vaultkit 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +163 -30
  3. data/bin/vkit +8 -0
  4. data/lib/vkit/cli/api/client.rb +15 -3
  5. data/lib/vkit/cli/base_cli.rb +92 -14
  6. data/lib/vkit/cli/commands/agent_tokens_create_command.rb +69 -5
  7. data/lib/vkit/cli/commands/agent_tokens_list_command.rb +2 -0
  8. data/lib/vkit/cli/commands/agent_tokens_revoke_command.rb +2 -0
  9. data/lib/vkit/cli/commands/approval_command.rb +8 -0
  10. data/lib/vkit/cli/commands/approval_watch_command.rb +6 -5
  11. data/lib/vkit/cli/commands/base_command.rb +56 -2
  12. data/lib/vkit/cli/commands/datasource_command.rb +137 -20
  13. data/lib/vkit/cli/commands/doctor_command.rb +69 -0
  14. data/lib/vkit/cli/commands/fetch_command.rb +7 -1
  15. data/lib/vkit/cli/commands/grant_revoke_command.rb +3 -0
  16. data/lib/vkit/cli/commands/init_command.rb +63 -10
  17. data/lib/vkit/cli/commands/login_command.rb +38 -4
  18. data/lib/vkit/cli/commands/logout_command.rb +54 -1
  19. data/lib/vkit/cli/commands/policy_bundle_command.rb +114 -26
  20. data/lib/vkit/cli/commands/policy_deploy_command.rb +113 -7
  21. data/lib/vkit/cli/commands/policy_pack_add_command.rb +16 -1
  22. data/lib/vkit/cli/commands/policy_pack_info_command.rb +10 -2
  23. data/lib/vkit/cli/commands/policy_pack_list_command.rb +4 -0
  24. data/lib/vkit/cli/commands/policy_pack_remove_command.rb +3 -0
  25. data/lib/vkit/cli/commands/policy_pack_upgrade_command.rb +35 -1
  26. data/lib/vkit/cli/commands/policy_revoke_command.rb +4 -0
  27. data/lib/vkit/cli/commands/policy_validate_command.rb +4 -1
  28. data/lib/vkit/cli/commands/registry_diff_command.rb +14 -2
  29. data/lib/vkit/cli/commands/registry_export_command.rb +30 -1
  30. data/lib/vkit/cli/commands/request_command.rb +27 -4
  31. data/lib/vkit/cli/commands/requests_list_command.rb +2 -0
  32. data/lib/vkit/cli/commands/reset_command.rb +12 -7
  33. data/lib/vkit/cli/commands/scan_command.rb +100 -0
  34. data/lib/vkit/cli/commands/setup_login_command.rb +274 -0
  35. data/lib/vkit/cli/commands/whoami_command.rb +16 -2
  36. data/lib/vkit/cli/doctor/mcp_probe.rb +108 -0
  37. data/lib/vkit/cli/doctor.rb +698 -0
  38. data/lib/vkit/cli/error_map.rb +243 -0
  39. data/lib/vkit/cli/errors.rb +32 -0
  40. data/lib/vkit/cli/output.rb +161 -0
  41. data/lib/vkit/cli/policy_bundle_validator.rb +8 -0
  42. data/lib/vkit/cli/secret_input.rb +50 -0
  43. data/lib/vkit/cli.rb +12 -2
  44. data/lib/vkit/core/auth_client.rb +57 -1
  45. data/lib/vkit/core/credential_store.rb +38 -1
  46. data/lib/vkit/core/user_agent.rb +30 -0
  47. data/lib/vkit/policy/approval_groups.rb +47 -0
  48. data/lib/vkit/policy/bundle_compiler.rb +15 -3
  49. data/lib/vkit/policy/git_state.rb +114 -0
  50. data/lib/vkit/policy/match_check.rb +7 -1
  51. data/lib/vkit/policy/packs/ai_safety/metadata.yaml +2 -2
  52. data/lib/vkit/policy/packs/ai_safety/policies/01_require_approval_agents_sensitive_prod.yaml +3 -3
  53. data/lib/vkit/policy/packs/ai_safety/policies/04_require_approval_agents_financial_prod.yaml +23 -0
  54. data/lib/vkit/policy/packs/financial_compliance/metadata.yaml +2 -2
  55. data/lib/vkit/policy/packs/financial_compliance/policies/01_require_approval_financial_prod.yaml +3 -2
  56. data/lib/vkit/policy/policy_validator.rb +74 -1
  57. data/lib/vkit/policy/schema/policy_bundle.schema.json +14 -2
  58. data/lib/vkit/version.rb +1 -1
  59. metadata +41 -2
@@ -4,20 +4,26 @@ require "json"
4
4
  require "fileutils"
5
5
  require_relative "../../policy/bundle_compiler"
6
6
  require_relative "../../policy/validation_error"
7
+ require_relative "../../policy/git_state"
8
+ require_relative "../../policy/pack_integrity"
9
+ require_relative "../errors"
7
10
 
8
11
  module Vkit
9
12
  module CLI
10
13
  module Commands
11
14
  class PolicyBundleCommand < BaseCommand
12
- def call(policies_dir:, registry_dir:, out:, org:, version:)
15
+ def call(policies_dir:, registry_dir:, out:, org:, version:, allow_dirty: false)
16
+ inputs = [policies_dir, registry_dir, Vkit::Policy::PackIntegrity::TRACKING_PATH]
13
17
  policies_dir = File.expand_path(policies_dir)
14
18
  registry_dir = File.expand_path(registry_dir)
15
19
  out = File.expand_path(out)
16
20
 
17
- raise "Policies dir not found: #{policies_dir}" unless Dir.exist?(policies_dir)
18
- raise "Registry dir not found: #{registry_dir}" unless Dir.exist?(registry_dir)
21
+ missing_dir!("Policies", policies_dir, "--policies-dir") unless Dir.exist?(policies_dir)
22
+ missing_dir!("Registry", registry_dir, "--registry-dir") unless Dir.exist?(registry_dir)
19
23
 
20
- version ||= git_sha
24
+ git = Vkit::Policy::GitState.new(Dir.pwd)
25
+ source = source_for(git, version, inputs, allow_dirty)
26
+ version ||= source[:commit_sha]
21
27
 
22
28
  with_auth do
23
29
  derived_org = credential_store.user["organization_slug"]
@@ -43,11 +49,8 @@ module Vkit
43
49
  bundle_version: version,
44
50
  policies_dir: policies_dir,
45
51
  registry_dir: registry_dir,
46
- source: {
47
- repo: git_repo,
48
- ref: git_ref,
49
- commit_sha: version
50
- }
52
+ source: source,
53
+ created_at: created_at(git, source, inputs)
51
54
  )
52
55
 
53
56
  FileUtils.mkdir_p(File.dirname(out))
@@ -59,14 +62,116 @@ module Vkit
59
62
  puts " Checksum: #{bundle.dig("bundle", "checksum")}"
60
63
  puts " Output: #{out}"
61
64
  print_policy_summary(bundle, policies_dir)
65
+
66
+ respond(
67
+ { "org" => bundle.dig("bundle", "org_slug"), "bundle_version" => bundle.dig("bundle", "bundle_version"),
68
+ "checksum" => bundle.dig("bundle", "checksum"), "output" => out, "dirty" => source[:dirty] == true,
69
+ "policies" => bundle["policies"].length,
70
+ "packs" => Array(bundle.dig("bundle", "installed_packs")).map do |p|
71
+ { "name" => p["name"], "version" => p["version"], "policies" => Array(p["policy_ids"]).length }
72
+ end },
73
+ ["vkit policy deploy --bundle #{relative(out)} --format json"]
74
+ )
62
75
  end
76
+ rescue Vkit::CLI::CommandError => e
77
+ raise if json?
78
+
79
+ puts e.render
80
+ exit 1
63
81
  rescue Vkit::Policy::ValidationError => e
82
+ raise if json?
83
+
64
84
  puts e.message
65
85
  exit 1
66
86
  end
67
87
 
68
88
  private
69
89
 
90
+ # Message as before; the code is for --format json.
91
+ def missing_dir!(what, dir, flag)
92
+ raise "#{what} dir not found: #{dir}" unless json?
93
+
94
+ raise Vkit::CLI::CommandError.new(
95
+ "#{what} dir not found: #{dir}", code: "not_a_project",
96
+ fix: ["Run this from a VaultKit project (`vkit init`), or pass #{flag} <dir>."]
97
+ )
98
+ end
99
+
100
+ # The bundle's source block. commit_sha is the commit the policies are
101
+ # in, from git only; --version only names the bundle. Refuses to bundle
102
+ # what can't be traced to a commit, unless told to.
103
+ def source_for(git, version, inputs, allow_dirty)
104
+ unless git.repo?
105
+ raise not_versioned unless version
106
+
107
+ return {}
108
+ end
109
+
110
+ head = git.head
111
+ raise not_versioned unless head || version
112
+
113
+ source = { repo: git.remote_url, ref: git.branch, commit_sha: head }
114
+ changed = git.uncommitted(inputs)
115
+ return source if changed.empty?
116
+ raise not_committed(changed, inputs) unless allow_dirty
117
+
118
+ warn_dirty(changed)
119
+ source.merge(dirty: true)
120
+ end
121
+
122
+ # The bundle's created_at, from what it's built from rather than the
123
+ # clock, so bundling the same commit again gives the same checksum and
124
+ # redeploying it answers already_deployed (a version is uploaded only
125
+ # once, with one checksum). A clean commit uses its commit time.
126
+ # Uncommitted inputs (--allow-dirty) or no repo (--version) use the
127
+ # newest input file's modification time, at least the commit's.
128
+ def created_at(git, source, inputs)
129
+ committed = git.commit_time(source[:commit_sha]) if source[:commit_sha]
130
+ return committed if committed && !source[:dirty]
131
+
132
+ [committed, newest_mtime(inputs)].compact.max || Time.now
133
+ end
134
+
135
+ def newest_mtime(inputs)
136
+ inputs.flat_map { |path| File.directory?(path) ? Dir.glob(File.join(path, "**", "*"), File::FNM_DOTMATCH) : [path] }
137
+ .select { |path| File.file?(path) }
138
+ .map { |path| File.mtime(path) }
139
+ .max
140
+ end
141
+
142
+ def not_versioned
143
+ Vkit::CLI::CommandError.new(
144
+ "This policy project isn't in a git repository, so the bundle would have no version.",
145
+ code: "bundle_not_versioned",
146
+ fix: ["git init && git add -A && git commit -m \"Add VaultKit policies\"",
147
+ "or name the bundle: vkit policy bundle --version <label>"]
148
+ )
149
+ end
150
+
151
+ def not_committed(changed, inputs)
152
+ ignored = changed.select { |c| c[:ignored] }.map { |c| c[:path] }
153
+ fix = ["git add -A -- #{inputs.join(' ')}"]
154
+ fix << "git add -f -- #{ignored.join(' ')}" if ignored.any?
155
+ if ignored.include?(Vkit::Policy::PackIntegrity::TRACKING_PATH)
156
+ fix << "and in .gitignore, replace .vkit/ with two lines: .vkit/* and !.vkit/packs.yaml"
157
+ end
158
+ # Only the commit: agents following setup.md never bundle dirty, so
159
+ # --allow-dirty is left to `vkit help policy bundle`.
160
+ fix << "git commit -m \"Update VaultKit policies\""
161
+ files = changed.map { |c| " #{c[:path]}#{' (ignored by .gitignore)' if c[:ignored]}" }
162
+
163
+ Vkit::CLI::CommandError.new(
164
+ "These files aren't committed, so the bundle's version wouldn't match its policies:\n#{files.join("\n")}",
165
+ code: "bundle_not_committed",
166
+ fix: fix
167
+ )
168
+ end
169
+
170
+ def warn_dirty(changed)
171
+ puts "⚠️ Bundling uncommitted changes (--allow-dirty). The bundle is recorded as dirty:"
172
+ changed.each { |c| puts " #{c[:path]}" }
173
+ end
174
+
70
175
  # Per-pack counts on every bundle, so a pack that contributes nothing
71
176
  # is visible even when nothing errors.
72
177
  def print_policy_summary(bundle, policies_dir)
@@ -84,23 +189,6 @@ module Vkit
84
189
  def relative(path)
85
190
  path.delete_prefix(Dir.pwd + File::SEPARATOR)
86
191
  end
87
-
88
- def git_sha
89
- out = `git rev-parse HEAD 2>/dev/null`.strip
90
- return nil if out.empty?
91
-
92
- out
93
- end
94
-
95
- def git_repo
96
- out = `git config --get remote.origin.url 2>/dev/null`.strip
97
- out.empty? ? nil : out
98
- end
99
-
100
- def git_ref
101
- out = `git rev-parse --abbrev-ref HEAD 2>/dev/null`.strip
102
- out.empty? ? nil : out
103
- end
104
192
  end
105
193
  end
106
194
  end
@@ -4,12 +4,13 @@ require "json"
4
4
  require "digest"
5
5
  require_relative "../../policy/pack_integrity"
6
6
  require_relative "../../policy/bundle_compiler"
7
+ require_relative "../../policy/approval_groups"
7
8
 
8
9
  module Vkit
9
10
  module CLI
10
11
  module Commands
11
12
  class PolicyDeployCommand < BaseCommand
12
- def call(bundle_path:, org:, activate:)
13
+ def call(bundle_path:, org:, activate:, format: "human")
13
14
  with_auth do
14
15
  bundle_path = File.expand_path(bundle_path)
15
16
  raise "Bundle not found: #{bundle_path}" unless File.exist?(bundle_path)
@@ -35,20 +36,125 @@ module Vkit
35
36
  bundle = JSON.parse(File.read(bundle_path))
36
37
  Vkit::Policy::PackIntegrity.check_bundle!(bundle)
37
38
 
38
- response = upload(org_slug, bundle, activate)
39
-
40
- puts "🚀 Policy bundle deployed"
41
- puts " Org: #{org_slug}"
42
- puts " Version: #{response['bundle_version']}"
43
- puts " State: #{response['state']}"
39
+ response =
40
+ begin
41
+ upload(org_slug, bundle, activate)
42
+ rescue Vkit::CLI::API::APIError => e
43
+ raise conflict(e) if NEW_CONFLICT_CODES.include?(e.code)
44
+ raise unless json?
45
+
46
+ already_deployed(org_slug, bundle, e)
47
+ end
48
+ response = reuploaded(org_slug, response) if response["already_existed"]
49
+ return respond(response) if response["already_deployed"] || response["already_existed"]
50
+
51
+ warnings = deploy_warnings(org_slug, bundle, response)
52
+
53
+ if format == "json"
54
+ respond({ "org" => org_slug, "bundle_version" => response["bundle_version"],
55
+ "state" => response["state"], "checksum" => response["checksum"],
56
+ "warnings" => warnings, "already_deployed" => false })
57
+ else
58
+ print_deployed(org_slug, response, warnings)
59
+ end
44
60
  end
45
61
  rescue Vkit::Policy::ValidationError => e
62
+ raise if json?
63
+
46
64
  puts e.message
47
65
  exit 1
48
66
  end
49
67
 
50
68
  private
51
69
 
70
+ # The 409s a control plane from vaultkit#126 on answers with a code.
71
+ # Uploading the same bundle again isn't one of them: that's a 200
72
+ # with already_existed (see #reuploaded).
73
+ NEW_CONFLICT_CODES = %w[bundle_version_exists bundle_checksum_exists].freeze
74
+
75
+ # The same bundle (version and checksum) uploaded before: nothing
76
+ # was uploaded. With --activate the control plane also activates it
77
+ # if it wasn't active, and doesn't say which, so "already deployed"
78
+ # means it is the active bundle now without a new upload.
79
+ def reuploaded(org_slug, response)
80
+ version = response["bundle_version"]
81
+ active = response["state"] == "active"
82
+ if active
83
+ puts "✓ Bundle #{version} was already uploaded and is the active one; nothing new to deploy."
84
+ else
85
+ puts "✓ Bundle #{version} was already uploaded (state: #{response['state']}); nothing new to upload."
86
+ end
87
+ { "org" => org_slug, "bundle_version" => version, "state" => response["state"],
88
+ "checksum" => response["checksum"], "warnings" => [], "already_deployed" => active,
89
+ "already_existed" => true }
90
+ end
91
+
92
+ # The conflicting version and its state come with the 409.
93
+ def conflict(error)
94
+ Vkit::CLI::CommandError.new(
95
+ error.error.to_s, code: error.code, fix: [Vkit::CLI::ErrorMap::CONFLICT_FIXES.fetch(error.code)],
96
+ result: { "conflicting_version" => error.body["bundle_version"], "state" => error.body["state"] }.compact
97
+ )
98
+ end
99
+
100
+ # Each bundle version can be uploaded once. The control plane says
101
+ # so with a 409 (a 500 in production, where its catch-all answers
102
+ # first) and has no endpoint for the active bundle's checksum, only
103
+ # its version (GET /setup, admins). So: the same version active, from
104
+ # a clean commit, is already deployed; anything else is an error.
105
+ def already_deployed(org_slug, bundle, error)
106
+ raise error unless [409, 500].include?(error.status)
107
+
108
+ version = bundle.dig("bundle", "bundle_version")
109
+ active = active_version(org_slug)
110
+
111
+ if active == version && bundle.dig("bundle", "source", "dirty") != true
112
+ puts "✓ Bundle #{version} is already the active one; nothing to deploy."
113
+ return { "org" => org_slug, "bundle_version" => version, "state" => "active",
114
+ "checksum" => bundle.dig("bundle", "checksum"), "warnings" => [], "already_deployed" => true }
115
+ end
116
+
117
+ raise error unless error.status == 409 || active
118
+
119
+ raise Vkit::CLI::CommandError.new(
120
+ "Bundle version #{version} was already uploaded#{" (the active one is #{active})" if active}, " \
121
+ "and a version can only be deployed once.",
122
+ code: "bundle_version_exists",
123
+ fix: ["Commit your policy changes and rebuild with `vkit policy bundle` (the version is the commit), " \
124
+ "or name a new one with --version <label>."]
125
+ )
126
+ end
127
+
128
+ def active_version(org_slug)
129
+ setup = authenticated_client.get("/api/v1/orgs/#{org_slug}/setup")
130
+ setup.is_a?(Hash) ? setup.dig("active_policy", "version") : nil
131
+ rescue StandardError
132
+ nil
133
+ end
134
+
135
+ def print_deployed(org_slug, response, warnings)
136
+ puts "🚀 Policy bundle deployed"
137
+ puts " Org: #{org_slug}"
138
+ puts " Version: #{response['bundle_version']}"
139
+ puts " State: #{response['state']}"
140
+ return if warnings.empty?
141
+
142
+ puts
143
+ warnings.each { |w| puts "⚠️ #{w['message']}" }
144
+ end
145
+
146
+ # The control plane returns one warning per approval group nobody is
147
+ # in. Older control planes don't, so the same rule is applied here to
148
+ # the groups they list. A failure to list them never fails the deploy.
149
+ def deploy_warnings(org_slug, bundle, response)
150
+ return Array(response["warnings"]) if response.is_a?(Hash) && response.key?("warnings")
151
+
152
+ listed = authenticated_client.get("/api/v1/orgs/#{org_slug}/approval_groups")
153
+ Vkit::Policy::ApprovalGroups.warnings(bundle, listed.is_a?(Hash) ? listed["groups"] : [])
154
+ rescue StandardError
155
+ []
156
+ end
157
+
52
158
  # A control plane from before vaultkitcli#47 doesn't know installed_packs'
53
159
  # policy_ids and rejects the bundle on schema. The ids were checked
54
160
  # above, so send the bundle without them (re-checksummed) instead.
@@ -13,14 +13,29 @@ module Vkit
13
13
  project_root: dir
14
14
  )
15
15
 
16
+ meta = manager.pack_metadata(pack_name)
17
+
18
+ # Adding an installed pack again changes nothing, so it's not an
19
+ # error (an agent may rerun a setup step).
20
+ if manager.installed?(pack_name)
21
+ version = manager.installed_packs.dig(pack_name, "version")
22
+ puts "✓ #{pack_name} is already installed (v#{version})"
23
+ return respond({ "pack" => pack_name, "version" => version, "already_existed" => true,
24
+ "policies_added" => 0 }, ["vkit policy bundle --format json"])
25
+ end
26
+
16
27
  count = manager.install!(pack_name, force: force)
17
- meta = manager.pack_metadata(pack_name)
18
28
 
19
29
  puts "✅ Installed #{pack_name}"
20
30
  puts " Version: v#{meta['version']}"
21
31
  puts " Policies: #{count} added"
22
32
  puts "\nRun 'vkit policy bundle' to compile."
33
+ respond({ "pack" => pack_name, "version" => meta["version"], "already_existed" => false,
34
+ "policies_added" => count },
35
+ ["git add -A && git commit -m \"Add #{pack_name} policy pack\"", "vkit policy bundle --format json"])
23
36
  rescue StandardError => e
37
+ raise if json?
38
+
24
39
  puts "❌ Error: #{e.message}"
25
40
  exit 1
26
41
  end
@@ -16,6 +16,7 @@ module Vkit
16
16
  puts "\nPolicy Pack: #{meta['name']}"
17
17
  puts "Version: v#{meta['version']}"
18
18
  puts "Layer: #{meta['layer'] || 'n/a'}"
19
+ puts "Description: #{meta['description']}" if meta["description"]
19
20
 
20
21
  deps = Array(meta["dependencies"])
21
22
  puts "Dependencies: #{deps.empty? ? 'none' : deps.join(', ')}"
@@ -31,13 +32,20 @@ module Vkit
31
32
  puts " - #{p['id']}"
32
33
  end
33
34
 
34
- if manager.installed?(pack_name)
35
- entry = manager.installed_packs[pack_name]
35
+ entry = manager.installed_packs[pack_name]
36
+ if entry
36
37
  puts "\nInstalled: yes (v#{entry['version']})"
37
38
  else
38
39
  puts "\nInstalled: no"
39
40
  end
41
+
42
+ respond({ "name" => meta["name"], "version" => meta["version"], "layer" => meta["layer"],
43
+ "description" => meta["description"], "dependencies" => deps, "priority_band" => band, "policies" => policies.map { |p| p["id"] },
44
+ "installed" => !entry.nil?, "installed_version" => entry && entry["version"] },
45
+ entry ? [] : ["vkit policy pack add #{pack_name} --format json"])
40
46
  rescue StandardError => e
47
+ raise if json?
48
+
41
49
  puts "❌ Error: #{e.message}"
42
50
  exit 1
43
51
  end
@@ -13,6 +13,8 @@ module Vkit
13
13
 
14
14
  packs = manager.list_status
15
15
 
16
+ respond({ "packs" => packs.map { |p| p.merge("drift" => !!p["drift"]) } })
17
+
16
18
  if packs.empty?
17
19
  puts "No policy packs available."
18
20
  return
@@ -38,6 +40,8 @@ module Vkit
38
40
  end
39
41
  end
40
42
  rescue StandardError => e
43
+ raise if json?
44
+
41
45
  puts "❌ Error: #{e.message}"
42
46
  exit 1
43
47
  end
@@ -18,7 +18,10 @@ module Vkit
18
18
  puts "✅ Removed #{pack_name}"
19
19
  puts " Files deleted: #{removed}"
20
20
  puts "\nRun 'vkit policy bundle' to recompile."
21
+ respond({ "pack" => pack_name, "files_deleted" => removed }, ["vkit policy bundle --format json"])
21
22
  rescue StandardError => e
23
+ raise if json?
24
+
22
25
  puts "❌ Error: #{e.message}"
23
26
  exit 1
24
27
  end
@@ -29,6 +29,7 @@ module Vkit
29
29
  end
30
30
 
31
31
  print_summary(results)
32
+ respond_json(results, pack_name) if json?
32
33
 
33
34
  if results.any? { |r| %i[failed missing].include?(r[:status]) }
34
35
  if results.any? { |r| r[:status] == :missing }
@@ -40,12 +41,45 @@ module Vkit
40
41
 
41
42
  puts "\nRun 'vkit policy bundle' to recompile."
42
43
  rescue StandardError => e
44
+ raise if json?
45
+
43
46
  puts "❌ Error: #{e.message}"
44
47
  exit 1
45
48
  end
46
49
 
47
50
  private
48
51
 
52
+ # Missing files left unrestored are a question for the person
53
+ # (restore them?); a failed upgrade is an error.
54
+ def respond_json(results, pack_name)
55
+ rows = results.map { |r| json_row(r) }
56
+ failed = results.find { |r| r[:status] == :failed }
57
+ if failed
58
+ raise Vkit::CLI::CommandError.new("#{failed[:name]}: #{failed[:error]}", code: "pack_upgrade_failed",
59
+ fix: ["Fix what the message names, then rerun the upgrade."])
60
+ end
61
+ if results.any? { |r| r[:status] == :missing }
62
+ needs_input!("confirmation_required",
63
+ "Installed pack files are missing: #{rows.select { |r| r["status"] == "missing" }
64
+ .flat_map { |r| r["missing_files"] }.join(", ")}",
65
+ ["Ask the person whether to restore them from the pack; if they agree, rerun " \
66
+ "`vkit policy pack upgrade #{pack_name || "<pack>"} --restore`."])
67
+ end
68
+
69
+ respond({ "packs" => rows }, ["vkit policy bundle --format json"])
70
+ end
71
+
72
+ def json_row(r)
73
+ row = { "name" => r[:name], "status" => r[:status].to_s }
74
+ row["from"] = r[:old] if r[:old]
75
+ row["to"] = r[:new] if r[:new]
76
+ row["version"] = r[:version] if r[:version]
77
+ row["policies_updated"] = r[:policies] if r[:policies]
78
+ row["missing_files"] = Array(r[:files]).map { |f| f["path"] } if r[:files]
79
+ row["error"] = r[:error] if r[:error]
80
+ row
81
+ end
82
+
49
83
  def upgrade_single(manager, pack, force)
50
84
  summarize(pack, manager.upgrade!(pack, force: force))
51
85
  rescue => e
@@ -72,7 +106,7 @@ module Vkit
72
106
  puts "⚠️ #{r[:name]} #{r[:version]} is installed, but #{r[:files].length} of its files are missing:"
73
107
  r[:files].each { |f| puts " #{f["path"]} (#{f["policy_id"]})" }
74
108
 
75
- return unless restore || confirm?(input, "Restore them from the pack? [Y/n] ")
109
+ return unless restore || (!json? && confirm?(input, "Restore them from the pack? [Y/n] "))
76
110
 
77
111
  manager.restore!(r[:name])
78
112
  r[:status] = :restored
@@ -12,6 +12,8 @@ module Vkit
12
12
  raise "Not authenticated. Please login." if org.nil? || org.empty?
13
13
 
14
14
  unless force
15
+ confirmation_needed!("Revoking policy bundle #{bundle_version}", "--yes") if json?
16
+
15
17
  puts "⚠️ You are about to revoke policy bundle version: #{bundle_version}"
16
18
  puts " Organization: #{org}"
17
19
  puts " Reason: #{reason || 'Bundle revoked via CLI'}"
@@ -32,6 +34,8 @@ module Vkit
32
34
  puts " Version: #{response["bundle_version"]}"
33
35
  puts " Checksum: #{response["checksum"]}"
34
36
  puts " Revoked: #{response["revoked_at"]}"
37
+ respond({ "bundle_version" => response["bundle_version"], "checksum" => response["checksum"],
38
+ "revoked_at" => response["revoked_at"] })
35
39
  end
36
40
  end
37
41
  end
@@ -5,7 +5,7 @@ require_relative "../../policy/pack_integrity"
5
5
  module Vkit
6
6
  module CLI
7
7
  module Commands
8
- class PolicyValidateCommand
8
+ class PolicyValidateCommand < BaseCommand
9
9
  def call(bundle_path:, schema_path:)
10
10
  bundle_path = File.expand_path(bundle_path)
11
11
  raise "Bundle not found: #{bundle_path}" unless File.exist?(bundle_path)
@@ -21,7 +21,10 @@ module Vkit
21
21
  Vkit::Policy::PackIntegrity.check_bundle!(JSON.parse(File.read(bundle_path)))
22
22
 
23
23
  puts "✅ Policy bundle is valid"
24
+ respond({ "valid" => true, "bundle" => bundle_path }, ["vkit policy deploy --format json"])
24
25
  rescue Vkit::Policy::ValidationError => e
26
+ raise if json?
27
+
25
28
  puts e.message
26
29
  exit 1
27
30
  end
@@ -12,12 +12,19 @@ module Vkit
12
12
  DEFAULT_PATH = File.join("datasets", "registry.yaml")
13
13
 
14
14
  def call(dir:, format: "human")
15
+ # Exit codes, json or not: 0 no differences, 1 differences, 2 error.
16
+ Vkit::CLI::Output.error_exit_code = 2 if json?
15
17
  ensure_project!(dir)
16
18
 
17
19
  dir = File.expand_path(dir)
18
20
  path = File.join(dir, DEFAULT_PATH)
19
21
 
20
22
  unless File.exist?(path)
23
+ if json?
24
+ raise Vkit::CLI::CommandError.new("No local registry.yaml found.", code: "registry_not_found",
25
+ fix: ["Run `vkit registry export --format json` to create it."])
26
+ end
27
+
21
28
  puts "❌ No local registry.yaml found."
22
29
  exit 2
23
30
  end
@@ -42,8 +49,11 @@ module Vkit
42
49
  )
43
50
 
44
51
  if format == "json"
45
- puts JSON.pretty_generate(diff)
46
- exit diff["datasets"].empty? ? 0 : 1
52
+ changed = !diff["datasets"].empty?
53
+ respond(diff.merge("changed" => changed),
54
+ [],
55
+ exit_code: changed ? 1 : 0)
56
+ return
47
57
  else
48
58
  Vkit::Core::RegistryDiffPrinter.print(diff)
49
59
  exit diff["datasets"].empty? ? 0 : 1
@@ -51,6 +61,8 @@ module Vkit
51
61
  end
52
62
 
53
63
  rescue StandardError => e
64
+ raise if json?
65
+
54
66
  puts "❌ Error: #{e.message}"
55
67
  exit 2
56
68
  end
@@ -16,7 +16,10 @@ module Vkit
16
16
  dir = File.expand_path(dir)
17
17
  path = out ? File.expand_path(out, dir) : File.join(dir, DEFAULT_PATH)
18
18
 
19
- if File.exist?(path) && !force
19
+ existed = File.exist?(path)
20
+ if existed && !force
21
+ overwrite_needed!(dir, path) if json?
22
+
20
23
  decision = handle_existing_registry(dir: dir, path: path)
21
24
  return if decision == :abort
22
25
  end
@@ -33,8 +36,18 @@ module Vkit
33
36
 
34
37
  puts "✅ Registry exported to:"
35
38
  puts " #{relative(dir, path)}"
39
+
40
+ respond(
41
+ { "path" => path, "overwritten" => existed,
42
+ "datasets" => registry_data.is_a?(Hash) ? registry_data.keys.sort : [] },
43
+ # After reviewing datasets/registry.yaml and committing it.
44
+ ["git add datasets/registry.yaml && git commit -m \"Review VaultKit registry\"",
45
+ "vkit policy bundle --format json"]
46
+ )
36
47
  end
37
48
  rescue StandardError => e
49
+ raise if json?
50
+
38
51
  puts "❌ Error: #{e.message}"
39
52
  exit 1
40
53
  end
@@ -42,9 +55,25 @@ module Vkit
42
55
  private
43
56
 
44
57
  def ensure_project!(dir)
58
+ raise not_a_project if json? && !Dir.exist?(File.join(dir, ".vkit"))
45
59
  raise "Not a VaultKit project (missing .vkit/)" unless Dir.exist?(File.join(dir, ".vkit"))
46
60
  end
47
61
 
62
+ def not_a_project
63
+ Vkit::CLI::CommandError.new("Not a VaultKit project (missing .vkit/)", code: "not_a_project",
64
+ fix: ["Run `vkit init` first, or pass --dir <project>."])
65
+ end
66
+
67
+ # Overwriting replaces any review already done in the file, so it's
68
+ # the person's call (vkit init's placeholder file included).
69
+ def overwrite_needed!(dir, path)
70
+ needs_input!("overwrite_confirmation_required",
71
+ "#{relative(dir, path)} already exists and exporting would replace it.",
72
+ ["Check `vkit registry diff --format json`; if replacing the file is fine " \
73
+ "(it's still vkit init's placeholder, or the person agrees), rerun with --force."],
74
+ next_steps: ["vkit registry diff --format json"])
75
+ end
76
+
48
77
  def handle_existing_registry(dir:, path:)
49
78
  puts "\n⚠️ Existing registry.yaml detected at:"
50
79
  puts " #{relative(dir, path)}\n\n"