vaultkit 1.5.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 (53) 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 +37 -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 +8 -2
  49. data/lib/vkit/policy/git_state.rb +114 -0
  50. data/lib/vkit/policy/policy_validator.rb +20 -0
  51. data/lib/vkit/policy/schema/policy_bundle.schema.json +4 -0
  52. data/lib/vkit/version.rb +1 -1
  53. metadata +40 -2
@@ -0,0 +1,698 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+ require "net/http"
6
+ require "open3"
7
+ require "time"
8
+ require "uri"
9
+ require_relative "../version"
10
+ require_relative "../core/user_agent"
11
+ require_relative "../policy/git_state"
12
+ require_relative "../policy/pack_integrity"
13
+ require_relative "api/client"
14
+ require_relative "error_map"
15
+ require_relative "output"
16
+ require_relative "doctor/mcp_probe"
17
+
18
+ module Vkit
19
+ module CLI
20
+ # vkit doctor: whether VaultKit is set up and working from here, and
21
+ # how to fix what isn't. Each check is { name, status, detail, fix };
22
+ # a check that needs an earlier one that failed (or was skipped) is
23
+ # skipped, with the reason, instead of failing for the same cause.
24
+ #
25
+ # Everything the checks touch is passed in, so tests can fake the
26
+ # control plane, RubyGems, git and the MCP server.
27
+ module Doctor
28
+ PASS = "pass"
29
+ WARN = "warn"
30
+ FAIL = "fail"
31
+ # Something doctor couldn't check and that isn't a problem in itself
32
+ # (an older control plane that doesn't report it), or worth knowing
33
+ # without being a warning. Never a pass, never a failure.
34
+ INFO = "info"
35
+ STATUSES = [PASS, WARN, FAIL, INFO].freeze
36
+ UPGRADE_FIX = "Upgrade the control plane."
37
+
38
+ ROLE_SAFETY_ISSUE = "https://github.com/vaultkit-inc/vaultkit/issues/125"
39
+ RUBYGEMS_LATEST = "https://rubygems.org/api/v1/versions/vaultkit/latest.json"
40
+ MCP_TOOLS = %w[vaultkit_discover vaultkit_query vaultkit_check_approval].freeze
41
+ AGENT_ENV = %w[VAULTKIT_BASE_URL VAULTKIT_ORG VAULTKIT_TOKEN].freeze
42
+ # What a policy bundle is compiled from (see vkit policy bundle).
43
+ BUNDLE_INPUTS = ["config/policies", "datasets", Vkit::Policy::PackIntegrity::TRACKING_PATH].freeze
44
+ # A login this close to expiring is worth a warning: the next few
45
+ # commands would fail part way.
46
+ EXPIRY_WARNING_SECONDS = 10 * 60
47
+
48
+ LABELS = {
49
+ "cli_version" => "CLI version",
50
+ "control_plane" => "Control plane",
51
+ "login" => "Login",
52
+ "datasources" => "Datasources",
53
+ "datasource_role" => "Datasource role",
54
+ "schema" => "Schema",
55
+ "policy_bundle" => "Policy bundle",
56
+ "approval_routing" => "Approval routing",
57
+ "agent_token" => "Agent token",
58
+ "mcp_server" => "MCP server"
59
+ }.freeze
60
+
61
+ Check = Struct.new(:name, :status, :detail, :fix, :extra, keyword_init: true) do
62
+ def failed?
63
+ status == FAIL
64
+ end
65
+
66
+ def to_h
67
+ { "name" => name, "status" => status, "detail" => detail, "fix" => fix }.merge(extra || {})
68
+ end
69
+ end
70
+
71
+ # A check that didn't run, and why (an earlier check failed, or it's
72
+ # optional and there's nothing to check).
73
+ Skip = Struct.new(:reason, :fix)
74
+
75
+ # GET a URL with no credentials: [status, body]. Raises what Net::HTTP
76
+ # raises when the host can't be reached.
77
+ HTTP_GET = lambda do |url, timeout|
78
+ uri = URI(url)
79
+ req = Net::HTTP::Get.new(uri)
80
+ req["User-Agent"] = Vkit::Core::UserAgent.to_s
81
+ req["Accept"] = "application/json"
82
+ res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
83
+ open_timeout: timeout, read_timeout: timeout) do |http|
84
+ http.request(req)
85
+ end
86
+ [res.code.to_i, res.body.to_s]
87
+ end
88
+
89
+ class Runner
90
+ attr_reader :checks, :skipped
91
+
92
+ # store: the CLI's credentials (Vkit::Core::CredentialStore).
93
+ # client_for: ->(base_url, token) { an API client }.
94
+ # http_get: ->(url, timeout) { [status, body] }, for requests without
95
+ # credentials (RubyGems, the control plane's health check).
96
+ # mcp_probe: ->(command, env) { tool names }, raising on failure.
97
+ def initialize(store:, env: ENV.to_h, project_root: Dir.pwd, now: -> { Time.now },
98
+ client_for: ->(base, token) { API::Client.new(base_url: base, token: token) },
99
+ http_get: HTTP_GET, mcp_probe: McpProbe.new, which: nil)
100
+ @store = store
101
+ @env = env
102
+ @project_root = project_root
103
+ @now = now
104
+ @client_for = client_for
105
+ @http_get = http_get
106
+ @mcp_probe = mcp_probe
107
+ @which = which || ->(cmd) { find_executable(cmd) }
108
+ end
109
+
110
+ def run
111
+ @checks = []
112
+ @skipped = []
113
+ @ran = {}
114
+ @skip_reasons = {}
115
+
116
+ step("cli_version") { cli_version }
117
+ step("control_plane") { control_plane }
118
+ step("login", after: %w[control_plane]) { login }
119
+ step("datasources", after: %w[login]) { datasources }
120
+ step("datasource_role", after: %w[datasources]) { datasource_role }
121
+ step("schema", after: %w[datasources]) { schema }
122
+ step("policy_bundle", after: %w[login]) { policy_bundle }
123
+ step("approval_routing", after: %w[login]) { approval_routing }
124
+ step("agent_token") { agent_token }
125
+ step("mcp_server", after: %w[agent_token]) { mcp_server }
126
+
127
+ self
128
+ end
129
+
130
+ def failed?
131
+ @checks.any?(&:failed?)
132
+ end
133
+
134
+ def to_h
135
+ counts = STATUSES.to_h { |s| [s, @checks.count { |c| c.status == s }] }
136
+ { "ok" => !failed?, "summary" => counts, "checks" => @checks.map(&:to_h), "skipped" => @skipped }
137
+ end
138
+
139
+ private
140
+
141
+ # Runs a check unless one it needs failed or was skipped. A check
142
+ # that raises something unexpected fails with the error, so one bug
143
+ # never hides the other checks.
144
+ def step(name, after: [])
145
+ blocker = after.find { |n| !@ran.key?(n) || @ran[n].failed? }
146
+ if blocker
147
+ # A check skipped because of a skipped one gives the root cause.
148
+ reason = @ran.key?(blocker) ? "#{LABELS[blocker]} failed." : @skip_reasons.fetch(blocker)
149
+ @skip_reasons[name] = reason
150
+ @skipped << { "name" => name, "reason" => reason }
151
+ return
152
+ end
153
+
154
+ result = begin
155
+ yield
156
+ rescue StandardError => e
157
+ mapped = ErrorMap.map(e)
158
+ check(FAIL, mapped[:message].to_s, mapped[:fix])
159
+ end
160
+
161
+ if result.is_a?(Skip)
162
+ @skip_reasons[name] = result.reason
163
+ @skipped << { "name" => name, "reason" => result.reason, "fix" => result.fix }.compact
164
+ return
165
+ end
166
+
167
+ result.name = name
168
+ @ran[name] = result
169
+ @checks << result
170
+ end
171
+
172
+ # An older control plane that lacks the endpoint or fields a check
173
+ # reads: reported, never passed.
174
+ def too_old(what)
175
+ check(INFO, "Can't check #{what}: the control plane is too old to report it.", UPGRADE_FIX)
176
+ end
177
+
178
+ def not_found?(error)
179
+ error.is_a?(API::APIError) && error.status == 404
180
+ end
181
+
182
+ def check(status, detail, fix = nil, **extra)
183
+ Check.new(status: status, detail: detail, fix: fix, extra: extra.empty? ? nil : extra.transform_keys(&:to_s))
184
+ end
185
+
186
+ # 1. This CLI's version, and whether RubyGems has a newer one. Being
187
+ # offline only means the newer-version check is left out.
188
+ def cli_version
189
+ latest = begin
190
+ status, body = @http_get.call(RUBYGEMS_LATEST, 3)
191
+ status == 200 ? JSON.parse(body)["version"] : nil
192
+ rescue StandardError, Timeout::Error
193
+ nil
194
+ end
195
+
196
+ current = Gem::Version.new(Vkit::VERSION)
197
+ if latest.nil? || !Gem::Version.correct?(latest)
198
+ return check(PASS, "vkit #{Vkit::VERSION} (couldn't reach RubyGems to check for a newer version).")
199
+ end
200
+
201
+ if Gem::Version.new(latest) > current
202
+ return check(WARN, "vkit #{Vkit::VERSION}; #{latest} is available.", "gem update vaultkit")
203
+ end
204
+
205
+ check(PASS, "vkit #{Vkit::VERSION} (the latest).")
206
+ end
207
+
208
+ # 2. The control plane answers at the configured URL. Its health
209
+ # check needs no login, so this tells "down" from "logged out".
210
+ def control_plane
211
+ endpoint = begin
212
+ @store.endpoint
213
+ rescue Vkit::CLI::Error => e
214
+ return check(FAIL, e.message, "Set both VKIT_ENDPOINT and VKIT_TOKEN, or unset the one that's set.")
215
+ end
216
+
217
+ if endpoint.to_s.strip.empty?
218
+ return check(FAIL, "No control plane is configured: not logged in, and VKIT_ENDPOINT isn't set.",
219
+ "vkit login --endpoint <control plane URL>")
220
+ end
221
+
222
+ @endpoint = endpoint.chomp("/")
223
+ status = health_status(@endpoint)
224
+ return check(PASS, "Reachable at #{@endpoint}.") if status == 200
225
+
226
+ check(FAIL, "#{@endpoint} answered HTTP #{status} to its health check (/up).",
227
+ "Check that this is the control plane's URL and that it's healthy (its logs), then rerun.")
228
+ rescue *ErrorMap::UNREACHABLE, Timeout::Error => e
229
+ check(FAIL, "Couldn't reach the control plane at #{@endpoint}: #{e.message}",
230
+ "Check that the control plane is running and the URL is right " \
231
+ "(`vkit login --endpoint <url>`, or VKIT_ENDPOINT), then rerun.")
232
+ end
233
+
234
+ # /up is Rails' health check. Behind a proxy that doesn't pass it on,
235
+ # the CLI's login discovery (/auth/cli) answers instead.
236
+ def health_status(endpoint)
237
+ status, = @http_get.call("#{endpoint}/up", 5)
238
+ return status unless status == 404
239
+
240
+ @http_get.call("#{endpoint}/auth/cli", 5).first
241
+ end
242
+
243
+ # 3. Logged in, as a person or a setup session, and until when.
244
+ def login
245
+ token = @store.token
246
+ Output.register_secret(token)
247
+ @client = @client_for.call(@endpoint, token)
248
+ me = @client.get("/auth/whoami")
249
+
250
+ if me["type"] == "agent"
251
+ return check(FAIL, "vkit is signed in with an agent token (#{me.dig('agent', 'name')}) from VKIT_TOKEN, " \
252
+ "so every vkit command runs as that agent.",
253
+ "Unset VKIT_TOKEN and VKIT_ENDPOINT (use VAULTKIT_TOKEN for the agent), then `vkit login`.")
254
+ end
255
+
256
+ user = me["user"] || {}
257
+ @org = user["organization_slug"]
258
+ @role = user["role"]
259
+ who = "#{user['email']} (#{@role}, org #{@org})"
260
+ via = @env["VKIT_TOKEN"].to_s.strip.empty? ? "" : " via VKIT_ENDPOINT/VKIT_TOKEN"
261
+
262
+ if (setup = me["setup_session"])
263
+ expires_at = parse_time(setup["expires_at"])
264
+ return expiry_check("Setup session#{via} (setup only), approved by #{user['email']} for org #{@org}",
265
+ expires_at,
266
+ "`vkit login --setup` for a new setup session.")
267
+ end
268
+
269
+ expiry_check("Signed in#{via} as #{who}", jwt_expiry(token), "`vkit login` to sign in again.")
270
+ end
271
+
272
+ def expiry_check(what, expires_at, renew)
273
+ return check(PASS, "#{what}.") unless expires_at
274
+
275
+ left = expires_at - @now.call
276
+ when_text = "#{expires_at.localtime.strftime('%H:%M')} (#{duration(left)})"
277
+ extra = { expires_at: expires_at.utc.iso8601 }
278
+ if left <= 0
279
+ return check(FAIL, "#{what}; the session expired at #{when_text}.", "Run #{renew}", **extra)
280
+ end
281
+ if left < EXPIRY_WARNING_SECONDS
282
+ return check(WARN, "#{what}; the session expires at #{when_text}.", "Run #{renew}", **extra)
283
+ end
284
+
285
+ check(PASS, "#{what}; the session expires at #{when_text}.", **extra)
286
+ end
287
+
288
+ # 4. At least one datasource, and the control plane can connect to
289
+ # each. There's no connection test yet, so this runs vkit scan in
290
+ # diff_only mode: it reads the schema (never data) and changes
291
+ # nothing in the registry.
292
+ def datasources
293
+ list = begin
294
+ @client.get(org_path("/datasources"))
295
+ rescue API::APIError => e
296
+ raise unless e.status == 403 && e.code != "setup_scope_forbidden"
297
+
298
+ return Skip.new("Only org admins can see datasources; you're signed in as #{@role}.",
299
+ "Ask an org admin to run `vkit doctor`.")
300
+ end
301
+ names = Array(list).map { |d| d["name"] }.compact
302
+
303
+ if names.empty?
304
+ return check(FAIL, "No datasources in #{@org}.",
305
+ "vkit datasource add --id <name> --engine postgres --username <role> --password-prompt " \
306
+ "--config '<json>' --region <region> --environment <environment>, then rerun.")
307
+ end
308
+
309
+ @scans = {}
310
+ failures = {}
311
+ names.each do |name|
312
+ @scans[name] = @client.post(org_path("/datasources/#{name}/scan"),
313
+ body: { datasource: name, mode: "diff_only" })
314
+ rescue StandardError => e
315
+ failures[name] = ErrorMap.map(e)
316
+ end
317
+
318
+ return check(PASS, "#{count(names.size, 'datasource')} (#{names.join(', ')}); VaultKit connected to " \
319
+ "each and read its schema.") if failures.empty?
320
+
321
+ broken = failures.map { |name, f| "#{name}: #{f[:message]} (#{f[:code]})" }.join("; ")
322
+ fix = failures.values.map { |f| f[:fix] }.uniq.join(" ")
323
+ if @scans.empty?
324
+ return check(FAIL, "VaultKit couldn't connect to any datasource. #{broken}", fix)
325
+ end
326
+
327
+ check(WARN, "Connected to #{@scans.keys.join(', ')}, but not to every datasource. #{broken}", fix)
328
+ end
329
+
330
+ # 5. The datasource's database role is safe (read-only, not a
331
+ # superuser or the table owner). The control plane can't tell yet.
332
+ def datasource_role
333
+ return Skip.new("No datasource could be reached.") if @scans.nil? || @scans.empty?
334
+
335
+ check(WARN, "Not verified: VaultKit can't yet check which database role #{@scans.keys.join(', ')} " \
336
+ "#{@scans.size == 1 ? 'connects' : 'connect'} as (#{ROLE_SAFETY_ISSUE}).",
337
+ "Use a dedicated read-only role, not a superuser or the table owner. See #{ROLE_SAFETY_ISSUE}")
338
+ end
339
+
340
+ # 6. Each reachable datasource's schema is in the registry, current,
341
+ # and classified.
342
+ def schema
343
+ return Skip.new("No datasource could be reached.") if @scans.nil? || @scans.empty?
344
+
345
+ registry = @client.get(org_path("/registries/export"))
346
+ registry = {} unless registry.is_a?(Hash)
347
+
348
+ unscanned = []
349
+ drifted = []
350
+ unknown = []
351
+ datasets = 0
352
+ columns = 0
353
+
354
+ @scans.each do |name, scan|
355
+ entries = registry.select { |_, d| d.is_a?(Hash) && d["datasource"] == name }
356
+ if entries.empty?
357
+ unscanned << name
358
+ next
359
+ end
360
+
361
+ datasets += entries.size
362
+ entries.each do |dataset, d|
363
+ (d["fields"] || {}).each do |field, f|
364
+ columns += 1
365
+ unknown << "#{dataset}.#{field}" if f["sensitivity"].to_s.empty? || f["sensitivity"] == "unknown"
366
+ end
367
+ end
368
+
369
+ Array(scan.dig("diff", "datasets")).each do |d|
370
+ drifted << "#{name}/#{d['name']}" if (d["changes"] || {}).values.any? { |v| Array(v).any? }
371
+ Array(d["unreviewed"]).each { |f| unknown << "#{d['name']}.#{f}" }
372
+ end
373
+ end
374
+ unknown.uniq!
375
+
376
+ if unscanned.any?
377
+ return check(FAIL, "#{unscanned.join(', ')} #{unscanned.size == 1 ? 'has' : 'have'} never been scanned " \
378
+ "into the registry, so policies can't see #{unscanned.size == 1 ? 'its' : 'their'} " \
379
+ "columns.",
380
+ unscanned.map { |n| "vkit scan #{n} --mode apply" }.join("; ") +
381
+ "; then vkit registry export, review datasets/registry.yaml, and commit it.")
382
+ end
383
+
384
+ problems = []
385
+ fixes = []
386
+ if drifted.any?
387
+ problems << "the schema changed since the last applied scan (#{list(drifted)})"
388
+ fixes << "Review the changes with `vkit scan <datasource>`, then `vkit scan <datasource> --mode apply` " \
389
+ "and `vkit registry export`."
390
+ end
391
+ if unknown.any?
392
+ problems << "#{count(unknown.size, 'column')} #{unknown.size == 1 ? 'has' : 'have'} no classification " \
393
+ "(#{list(unknown)})"
394
+ fixes << "Set each one's sensitivity in datasets/registry.yaml, then " \
395
+ "`vkit policy bundle && vkit policy deploy`."
396
+ end
397
+ summary = "#{count(datasets, 'dataset')}, #{count(columns, 'column')} in the registry"
398
+ return check(WARN, "#{summary}, but #{problems.join('; and ')}.", fixes.join(" ")) if problems.any?
399
+
400
+ check(PASS, "#{summary}, all classified; the schema matches the last scan.")
401
+ end
402
+
403
+ # 7. A bundle is active, and it's what `vkit policy bundle` would
404
+ # build from this repository's HEAD. Bundle versions are the
405
+ # commit the policies were bundled from (vaultkitcli#58), so the
406
+ # active one matches when it's HEAD, or an earlier commit whose
407
+ # policies, registry and pack list are the same as HEAD's.
408
+ # Nothing is compiled or written, and a dirty tree doesn't matter:
409
+ # the comparison is between commits.
410
+ def policy_bundle
411
+ version = active_bundle_version
412
+ return too_old("the active policy bundle") if version == :unknown
413
+
414
+ if version.nil?
415
+ return check(FAIL, "No policy bundle is active in #{@org}, so no request is allowed.",
416
+ "vkit policy bundle && vkit policy deploy")
417
+ end
418
+
419
+ shown = short(version)
420
+ git = Vkit::Policy::GitState.new(@project_root)
421
+ unless Dir.exist?(File.join(@project_root, "config/policies"))
422
+ return check(WARN, "#{shown} is active. This isn't a VaultKit policy project, so it wasn't compared " \
423
+ "with your policies.",
424
+ "Run `vkit doctor` from the policy project's folder to compare.")
425
+ end
426
+
427
+ head = git.repo? ? git.head : nil
428
+ unless head
429
+ return check(WARN, "#{shown} is active. This policy project has no git commits, so it couldn't be " \
430
+ "compared.",
431
+ "Commit the project, then `vkit policy bundle && vkit policy deploy`.")
432
+ end
433
+
434
+ note = uncommitted_note(git)
435
+ if version == head
436
+ return check(PASS, "#{shown} is active: this repository's HEAD.#{note}")
437
+ end
438
+
439
+ unless git.commit?(version)
440
+ return check(WARN, "#{shown} is active, but it isn't a commit in this repository (named with --version, " \
441
+ "or bundled from another clone or an unfetched branch), so it couldn't be compared " \
442
+ "with HEAD (#{short(head)}).#{note}",
443
+ "git fetch, or deploy from here: vkit policy bundle && vkit policy deploy")
444
+ end
445
+
446
+ unless git.changed_between?(version, head, BUNDLE_INPUTS)
447
+ return check(PASS, "#{shown} is active; HEAD (#{short(head)}) has the same policies and registry.#{note}")
448
+ end
449
+
450
+ behind = git.commits_between(version, head)
451
+ check(FAIL, "#{shown} is active, but the policies or registry changed after it" \
452
+ "#{behind&.positive? ? " (HEAD is #{count(behind, 'commit')} ahead)" : ''}; HEAD " \
453
+ "(#{short(head)}) isn't deployed.#{note}",
454
+ "vkit policy bundle && vkit policy deploy")
455
+ end
456
+
457
+ # The active bundle's version (nil: none is active): GET
458
+ # /approval_groups names it for any member; GET /setup (admins) is
459
+ # asked only if that fails. :unknown when the control plane has
460
+ # neither (builds from before 2026-10-27) or doesn't say.
461
+ def active_bundle_version
462
+ groups = begin
463
+ approval_groups
464
+ rescue StandardError
465
+ nil
466
+ end
467
+ return groups["policy_bundle_version"] if groups.is_a?(Hash) && groups.key?("policy_bundle_version")
468
+
469
+ setup = begin
470
+ @client.get(org_path("/setup"))
471
+ rescue API::APIError => e
472
+ return :unknown if not_found?(e) && (groups || not_found?(@approval_groups_error))
473
+
474
+ raise
475
+ end
476
+ return :unknown unless setup.is_a?(Hash) && setup.key?("active_policy")
477
+
478
+ setup.dig("active_policy", "version")
479
+ end
480
+
481
+ def uncommitted_note(git)
482
+ changed = git.uncommitted(BUNDLE_INPUTS)
483
+ return "" if changed.empty?
484
+
485
+ " Uncommitted changes (#{list(changed.map { |c| c[:path] })}) aren't in any bundle yet."
486
+ rescue StandardError
487
+ ""
488
+ end
489
+
490
+ # 7b. Who approves each approval group's requests. A group nobody is
491
+ # in falls back to org admins (vaultkit#127), which is worth
492
+ # knowing but not a problem (info). Only an error fails; a control
493
+ # plane that doesn't report active_member_count and
494
+ # admin_fallback (or has no GET /approval_groups) is too old to
495
+ # tell, which is never a pass.
496
+ def approval_groups
497
+ return @approval_groups if defined?(@approval_groups)
498
+
499
+ @approval_groups = @client.get(org_path("/approval_groups"))
500
+ rescue StandardError => e
501
+ @approval_groups_error = e
502
+ @approval_groups = nil
503
+ raise
504
+ end
505
+
506
+ ROUTING_FIELDS = %w[active_member_count admin_fallback].freeze
507
+
508
+ def approval_routing
509
+ if @approval_groups_error
510
+ return too_old("approval routing") if not_found?(@approval_groups_error)
511
+
512
+ raise @approval_groups_error
513
+ end
514
+
515
+ response = approval_groups
516
+ return too_old("approval routing") unless response.is_a?(Hash) && response.key?("groups")
517
+
518
+ groups = Array(response["groups"])
519
+ return check(PASS, "No policy routes requests to an approval group.") if groups.empty?
520
+ return too_old("approval routing") unless groups.all? { |g| ROUTING_FIELDS.all? { |f| g.key?(f) } }
521
+
522
+ described = []
523
+ fallback = []
524
+ groups.each do |g|
525
+ name = g["name"].to_s
526
+ described << "#{name} (#{count(g['active_member_count'].to_i, 'member')})"
527
+ fallback << name if g["admin_fallback"] == true
528
+ end
529
+
530
+ detail = "#{count(groups.size, 'group')}: #{described.join(', ')}."
531
+ return check(PASS, detail) if fallback.empty?
532
+
533
+ notes = fallback.map { |name| "#{name} has no members, so org admins approve its requests." }
534
+ check(INFO, "#{detail} #{notes.join(' ')}", "To have someone else approve, add them to " \
535
+ "#{fallback.join(', ')} in the console (Team).")
536
+ end
537
+
538
+ # 8. The agent's own credentials, as the SDK and vaultkit-mcp read
539
+ # them, work; and vkit itself isn't running as the agent. Tokens
540
+ # are never printed, nor any part of one.
541
+ def agent_token
542
+ Output.register_secret(@env["VAULTKIT_TOKEN"])
543
+ Output.register_secret(@env["VKIT_TOKEN"])
544
+
545
+ problems = []
546
+ fixes = []
547
+ if vkit_token_is_agent?
548
+ problems << "VKIT_TOKEN is an agent token, so every vkit command runs as the agent"
549
+ fixes << "Unset VKIT_TOKEN (and VKIT_ENDPOINT) and use VAULTKIT_TOKEN for the agent."
550
+ end
551
+
552
+ missing = AGENT_ENV.select { |k| @env[k].to_s.strip.empty? }
553
+ if missing.any?
554
+ problems << "#{missing.join(', ')} #{missing.size == 1 ? "isn't" : "aren't"} set"
555
+ fixes << "Create a token with `vkit agents tokens create --name <agent> --secret-file <path>`, and set " \
556
+ "VAULTKIT_BASE_URL, VAULTKIT_ORG and VAULTKIT_TOKEN (the file's contents) in the agent's " \
557
+ "environment (for an MCP host, its server config's env block)."
558
+ return check(FAIL, "#{problems.join('; ')}.", fixes.join(" "))
559
+ end
560
+
561
+ base = @env["VAULTKIT_BASE_URL"].strip.chomp("/")
562
+ org = @env["VAULTKIT_ORG"].strip
563
+ agent = @client_for.call(base, @env["VAULTKIT_TOKEN"].strip)
564
+ me = begin
565
+ agent.get("/auth/whoami")
566
+ rescue StandardError => e
567
+ mapped = ErrorMap.map(e)
568
+ problems << "VAULTKIT_TOKEN didn't work at #{base}: #{mapped[:message]}"
569
+ fixes << (mapped[:code] == "control_plane_unreachable" ? "Check VAULTKIT_BASE_URL." : agent_token_fix)
570
+ return check(FAIL, "#{problems.join('; ')}.", fixes.join(" "))
571
+ end
572
+
573
+ # Before whoami said type (early 2026), it answered only for people,
574
+ # with { user }; anything else can't be told apart.
575
+ return too_old("the agent token") if !me.key?("type") && !me.key?("user")
576
+
577
+ if me["type"] != "agent"
578
+ problems << "VAULTKIT_TOKEN is a person's login, not an agent token: the agent would act as them " \
579
+ "and stop working within the hour"
580
+ fixes << agent_token_fix
581
+ return check(FAIL, "#{problems.join('; ')}.", fixes.join(" "))
582
+ end
583
+
584
+ name = me.dig("agent", "name")
585
+ visible = begin
586
+ Array(agent.get("/api/v1/orgs/#{org}/aql/datasets")["datasets"]).size
587
+ rescue API::APIError => e
588
+ raise unless e.status == 404
589
+
590
+ problems << "VAULTKIT_ORG (#{org}) isn't the organization agent #{name}'s token belongs to"
591
+ fixes << "Set VAULTKIT_ORG to the token's organization slug."
592
+ return check(FAIL, "#{problems.join('; ')}.", fixes.join(" "))
593
+ end
594
+
595
+ return check(FAIL, "#{problems.join('; ')}.", fixes.join(" ")) if problems.any?
596
+
597
+ check(PASS, "Agent #{name} (#{me.dig('agent', 'role')}) is set up for #{org} at #{base}, and can see " \
598
+ "#{count(visible, 'dataset')}.")
599
+ end
600
+
601
+ def agent_token_fix
602
+ "Create an agent token with `vkit agents tokens create --name <agent> --secret-file <path>` and put " \
603
+ "its contents in VAULTKIT_TOKEN."
604
+ end
605
+
606
+ # VKIT_TOKEN set to an agent token: the same value as VAULTKIT_TOKEN,
607
+ # or one the control plane says is an agent's.
608
+ def vkit_token_is_agent?
609
+ token = @env["VKIT_TOKEN"].to_s.strip
610
+ return false if token.empty?
611
+ return true if token == @env["VAULTKIT_TOKEN"].to_s.strip
612
+
613
+ base = [@env["VKIT_ENDPOINT"], @env["VAULTKIT_BASE_URL"], @endpoint].map { |v| v.to_s.strip }
614
+ .find { |v| !v.empty? }
615
+ return false unless base
616
+
617
+ @client_for.call(base.chomp("/"), token).get("/auth/whoami")["type"] == "agent"
618
+ rescue StandardError
619
+ false
620
+ end
621
+
622
+ # 9. Optional: the Python SDK's MCP server starts with the agent's
623
+ # environment and lists VaultKit's tools.
624
+ def mcp_server
625
+ command = @which.call("vaultkit-mcp")
626
+ unless command
627
+ return Skip.new("Optional: vaultkit-mcp (the Python SDK's MCP server) isn't installed.",
628
+ "pip install 'vaultkit[mcp]' to give an MCP host (Claude, Cursor) VaultKit's tools.")
629
+ end
630
+
631
+ tools = @mcp_probe.call(command, @env)
632
+ missing = MCP_TOOLS - tools
633
+ if missing.any?
634
+ return check(FAIL, "vaultkit-mcp started but doesn't list #{missing.join(', ')} " \
635
+ "(it lists: #{tools.empty? ? 'nothing' : tools.join(', ')}).",
636
+ "pip install --upgrade 'vaultkit[mcp]'")
637
+ end
638
+
639
+ check(PASS, "vaultkit-mcp (#{command}) starts and lists #{MCP_TOOLS.join(', ')}.")
640
+ rescue McpProbe::Failed => e
641
+ check(FAIL, "vaultkit-mcp didn't start: #{e.message}",
642
+ "Run vaultkit-mcp in a terminal with the same VAULTKIT_* variables to see why; " \
643
+ "pip install --upgrade 'vaultkit[mcp]' if it's out of date.")
644
+ end
645
+
646
+ def org_path(suffix)
647
+ "/api/v1/orgs/#{@org}#{suffix}"
648
+ end
649
+
650
+ # A login JWT's exp claim (read, not verified: the control plane
651
+ # verifies it). nil for anything that isn't a JWT.
652
+ def jwt_expiry(token)
653
+ payload = token.to_s.split(".")[1]
654
+ return nil unless payload
655
+
656
+ exp = JSON.parse(Base64.urlsafe_decode64(payload + "=" * (-payload.length % 4)))["exp"]
657
+ exp.is_a?(Numeric) ? Time.at(exp) : nil
658
+ rescue ArgumentError, JSON::ParserError
659
+ nil
660
+ end
661
+
662
+ def parse_time(value)
663
+ value && Time.parse(value.to_s)
664
+ rescue ArgumentError
665
+ nil
666
+ end
667
+
668
+ def duration(seconds)
669
+ minutes = (seconds.abs / 60).round
670
+ text = minutes < 90 ? count(minutes, "minute") : format("%g hours", (minutes / 60.0).round(1))
671
+ seconds.negative? ? "#{text} ago" : "in #{text}"
672
+ end
673
+
674
+ def short(version)
675
+ version.to_s.match?(/\A\h{40}\z/) ? version[0, 12] : version.to_s
676
+ end
677
+
678
+ def count(n, noun)
679
+ "#{n} #{noun}#{'s' unless n == 1}"
680
+ end
681
+
682
+ def list(items, max = 5)
683
+ return items.join(", ") if items.size <= max
684
+
685
+ "#{items.first(max).join(', ')} and #{items.size - max} more"
686
+ end
687
+
688
+ def find_executable(cmd)
689
+ @env.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |dir|
690
+ path = File.join(dir, cmd)
691
+ return path if File.file?(path) && File.executable?(path)
692
+ end
693
+ nil
694
+ end
695
+ end
696
+ end
697
+ end
698
+ end