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
@@ -17,6 +17,9 @@ module Vkit
17
17
  aql =
18
18
  if aql_str&.strip&.length&.positive?
19
19
  JSON.parse(aql_str)
20
+ elsif json? && $stdin.tty?
21
+ raise Vkit::CLI::CommandError.new("No AQL given.", code: "aql_required",
22
+ fix: ["Pass the request with --aql '<json>' or pipe it on stdin."])
20
23
  else
21
24
  JSON.parse(STDIN.read)
22
25
  end
@@ -43,6 +46,29 @@ module Vkit
43
46
 
44
47
  private
45
48
 
49
+ # A denial is the request's answer, not a CLI failure, but it's what
50
+ # the agent asked for not happening, so it's an error (exit 2, as
51
+ # before). Queued and granted are ok, with what to run next.
52
+ def respond_json(result)
53
+ status = result["status"]
54
+ if status == "denied"
55
+ raise Vkit::CLI::CommandError.new(
56
+ result["reason"].to_s.empty? ? "Request denied by policy" : result["reason"],
57
+ code: "request_denied", exit_code: 2,
58
+ fix: ["Policy denied this request; ask for fewer or less sensitive fields, or ask an admin " \
59
+ "about the policy (request_id #{result["request_id"]})."]
60
+ )
61
+ end
62
+
63
+ next_steps =
64
+ case status
65
+ when "granted" then ["vkit fetch --grant #{result["grant_ref"]} --format json"]
66
+ when "pending_approval", "queued" then ["vkit requests list --state pending --format json"]
67
+ else []
68
+ end
69
+ respond(result, next_steps)
70
+ end
71
+
46
72
  # Every response names its request; the console's Activity page
47
73
  # finds it by this id.
48
74
  def print_request_id(result)
@@ -66,10 +92,7 @@ module Vkit
66
92
  def handle_result(result, options)
67
93
  status = result["status"]
68
94
 
69
- if options[:format] == "json"
70
- puts JSON.pretty_generate(result)
71
- exit status == "denied" ? 2 : 0
72
- end
95
+ return respond_json(result) if options[:format] == "json"
73
96
 
74
97
  case status
75
98
  when "denied"
@@ -27,6 +27,8 @@ module Vkit
27
27
  private
28
28
 
29
29
  def render(rows, format)
30
+ return respond({ "requests" => rows }) if format == "json"
31
+
30
32
  if rows.empty?
31
33
  puts "📭 No requests found"
32
34
  return
@@ -2,17 +2,22 @@ module Vkit
2
2
  module CLI
3
3
  module Commands
4
4
  class ResetCommand < BaseCommand
5
- def call
6
- print "⚠️ This will clear all stored credentials. Continue? (y/N): "
7
- response = $stdin.gets.chomp
8
-
9
- unless response.downcase == 'y'
10
- puts "Cancelled"
11
- return
5
+ def call(yes: false)
6
+ unless yes
7
+ confirmation_needed!("Clearing all stored credentials", "--yes") if json?
8
+
9
+ print "⚠️ This will clear all stored credentials. Continue? (y/N): "
10
+ response = $stdin.gets.to_s.chomp
11
+
12
+ unless response.downcase == 'y'
13
+ puts "Cancelled"
14
+ return
15
+ end
12
16
  end
13
17
 
14
18
  credential_store.clear!
15
19
  puts "🧹 All credentials cleared"
20
+ respond({ "cleared" => true }, ["vkit login"])
16
21
  end
17
22
  end
18
23
  end
@@ -20,11 +20,111 @@ module Vkit
20
20
  )
21
21
 
22
22
  print_diff(response)
23
+ respond(json_result(org, datasource_name, mode, response), scan_next_steps(datasource_name, mode)) if json?
23
24
  end
24
25
  end
25
26
 
26
27
  private
27
28
 
29
+ # Every column of the scanned datasets, for review: the registry as
30
+ # the control plane has it, with the scan's changes on top (the diff
31
+ # only lists what changed). unknown: the classifier couldn't place
32
+ # it; unreviewed: nobody has set it yet (the starter pack masks those
33
+ # for agents).
34
+ def json_result(org, datasource, mode, response)
35
+ datasets = Array(response.dig("diff", "datasets"))
36
+ registry = registry_export(org)
37
+
38
+ {
39
+ "datasource" => datasource,
40
+ "mode" => mode,
41
+ "applied" => response["applied"] == true,
42
+ # Nothing to change: control planes from vaultkit#126 on say so
43
+ # (a setup token's apply on a set-up organization is then a no-op,
44
+ # not refused); older ones only by an empty diff.
45
+ "unchanged" => response["unchanged"] == true ||
46
+ datasets.none? { |d| (d["changes"] || {}).values.any? { |v| Array(v).any? } },
47
+ "scan_id" => response["scan_id"],
48
+ "columns_complete" => !registry.nil?,
49
+ "datasets" => datasets.map { |d| json_dataset(d, registry && registry[d["name"]]) },
50
+ "unreviewed_count" => datasets.sum { |d| unreviewed_for(d).size },
51
+ "suggestion_count" => datasets.sum { |d| suggestions_for(d).size }
52
+ }.compact
53
+ end
54
+
55
+ def registry_export(org)
56
+ export = authenticated_client.get("/api/v1/orgs/#{org}/registries/export")
57
+ export.is_a?(Hash) ? export : nil
58
+ rescue StandardError => e
59
+ warn "⚠️ Couldn't read the registry (#{e.message}); listing only the columns that changed."
60
+ nil
61
+ end
62
+
63
+ def json_dataset(dataset, registered)
64
+ changes = dataset["changes"] || {}
65
+ columns = {}
66
+
67
+ (registered && registered["fields"] || {}).each do |name, f|
68
+ columns[name] = column(name, f["type"], f["sensitivity"], f["category"])
69
+ end
70
+ Array(changes["added_fields"]).each do |f|
71
+ f = { "name" => f } unless f.is_a?(Hash)
72
+ columns[f["name"]] = column(f["name"], f["type"], f["sensitivity"], Array(f["tags"]).first, "added")
73
+ end
74
+ Array(changes["changed_fields"]).each do |f|
75
+ f = { "name" => f } unless f.is_a?(Hash)
76
+ to = f["to"] || {}
77
+ columns[f["name"]] = column(f["name"], to["type"], to["sensitivity"], Array(to["tags"]).first, "changed")
78
+ end
79
+ Array(changes["removed_fields"]).each do |f|
80
+ name = f.is_a?(Hash) ? f["name"] : f
81
+ columns[name] = (columns[name] || column(name, nil, nil, nil)).merge("change" => "removed")
82
+ end
83
+
84
+ unreviewed = unreviewed_for(dataset)
85
+ suggestions = suggestions_for(dataset).to_h { |s| [s["name"], s] }
86
+ unreviewed.each { |name| columns[name] ||= column(name, nil, "unknown", nil) }
87
+ suggestions.each_key { |name| columns[name] ||= column(name, nil, nil, nil) }
88
+
89
+ {
90
+ "name" => dataset["name"],
91
+ "changed" => changes.values.any? { |v| Array(v).any? },
92
+ "columns" => columns.values.map do |c|
93
+ c.merge("unreviewed" => unreviewed.include?(c["name"]),
94
+ "unknown" => c["sensitivity"] == "unknown" || unreviewed.include?(c["name"]),
95
+ "suggestion" => suggestion(suggestions[c["name"]]))
96
+ end
97
+ }
98
+ end
99
+
100
+ def column(name, type, sensitivity, category, change = nil)
101
+ { "name" => name, "type" => type, "sensitivity" => sensitivity, "category" => category, "change" => change }
102
+ end
103
+
104
+ def suggestion(s)
105
+ return nil unless s
106
+
107
+ {
108
+ "current" => classification(s["current"]),
109
+ "suggested" => classification(s["suggested"])
110
+ }
111
+ end
112
+
113
+ def classification(c)
114
+ c ||= {}
115
+ { "sensitivity" => c["sensitivity"], "category" => Array(c["tags"]).first, "tags" => Array(c["tags"]) }
116
+ end
117
+
118
+ def scan_next_steps(datasource, mode)
119
+ if mode == "apply"
120
+ # Between the two: review datasets/registry.yaml (each unknown
121
+ # column's sensitivity) and commit it.
122
+ ["vkit registry export --force --format json", "vkit policy bundle --format json"]
123
+ else
124
+ ["vkit scan #{datasource} --mode apply --format json"]
125
+ end
126
+ end
127
+
28
128
  def print_diff(response)
29
129
  diff = response["diff"] || {}
30
130
  datasets = diff["datasets"] || []
@@ -0,0 +1,274 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require "rbconfig"
5
+ require_relative "../../core/auth_client"
6
+ require_relative "../../core/credential_store"
7
+
8
+ module Vkit
9
+ module CLI
10
+ module Commands
11
+ # `vkit login --setup`: a setup session (device authorization, like
12
+ # `gh auth login`) for a coding agent that sets VaultKit up. vkit asks
13
+ # the control plane for one, shows the person a code and a console
14
+ # link, and polls until an admin approves or denies it there. The token
15
+ # it gets acts for that admin, only on setup endpoints, for 30 minutes,
16
+ # and is saved like a normal login, marked as a setup session.
17
+ #
18
+ # In a terminal it's one command that waits. Under --format json it's
19
+ # two, so an agent can show the person the code before it waits:
20
+ #
21
+ # vkit login --setup --format json # needs_input (exit 3): user_code, verification_url
22
+ # vkit login --setup --wait --format json # polls; ok with the login, or an error
23
+ #
24
+ # The requested session is kept between the two (with the saved login),
25
+ # so rerunning the first returns the same code rather than a new one.
26
+ class SetupLoginCommand < BaseCommand
27
+ DEFAULT_INTERVAL = 5
28
+ WAIT_COMMAND = "vkit login --setup --wait --format json"
29
+ APPROVE_FIX = "Ask the person to open the URL, check the code matches, and approve"
30
+
31
+ def requires_auth?
32
+ false
33
+ end
34
+
35
+ # wait: poll for a session an earlier `vkit login --setup` requested.
36
+ # timeout: stop waiting after this many seconds (still pending is
37
+ # needs_input again); default: until the session expires.
38
+ def initialize(endpoint: nil, wait: false, browser: true, timeout: nil)
39
+ @endpoint = endpoint
40
+ @wait = wait
41
+ @browser = browser
42
+ @timeout = timeout
43
+ end
44
+
45
+ def call
46
+ pending = credential_store.pending_setup
47
+
48
+ if @wait
49
+ raise not_started unless pending
50
+ else
51
+ pending = nil unless reusable?(pending)
52
+ pending ||= start(resolve_endpoint)
53
+ show(pending)
54
+ approval_needed!(pending, "An admin has to approve this setup session in the console.") if json?
55
+ end
56
+
57
+ wait_for_approval(pending)
58
+ end
59
+
60
+ private
61
+
62
+ def resolve_endpoint
63
+ @endpoint ||
64
+ ENV["VKIT_ENDPOINT"] ||
65
+ credential_store.stored_payload&.dig("endpoint") ||
66
+ (json? ? endpoint_needed! : prompt("VaultKit Control Plane URL"))
67
+ end
68
+
69
+ # A requested session that's still worth waiting for: same control
70
+ # plane, not expired. One the person may already be looking at.
71
+ def reusable?(pending)
72
+ return false unless pending
73
+ return false if @endpoint && @endpoint.chomp("/") != pending["endpoint"].to_s.chomp("/")
74
+
75
+ !expired?(pending)
76
+ end
77
+
78
+ def start(endpoint)
79
+ res = Vkit::Core::AuthClient.new(base_url: endpoint).start_setup_session
80
+ Vkit::CLI::Output.register_secret(res["device_code"])
81
+ pending = {
82
+ "endpoint" => endpoint,
83
+ "device_code" => res["device_code"],
84
+ "user_code" => res["user_code"],
85
+ "verification_url" => res["verification_url"],
86
+ "verification_url_complete" => res["verification_url_complete"] || res["verification_url"],
87
+ "interval" => (res["interval"] || DEFAULT_INTERVAL).to_i,
88
+ "expires_at" => (now + res["expires_in"].to_i).utc.iso8601
89
+ }
90
+ credential_store.save_pending_setup(pending)
91
+ @started = true
92
+ pending
93
+ end
94
+
95
+ def show(pending)
96
+ puts "🔐 An admin approves this setup session in the VaultKit console:"
97
+ puts " 1. Open #{pending['verification_url']}"
98
+ puts " 2. Check the code matches: #{pending['user_code']}"
99
+ puts " 3. Approve it (by #{clock(pending['expires_at'])}, when the request expires)"
100
+ puts " Only approve it if you just started it in your own terminal."
101
+ open_browser(pending["verification_url_complete"]) if @browser && @started
102
+ end
103
+
104
+ def wait_for_approval(pending)
105
+ Vkit::CLI::Output.register_secret(pending["device_code"])
106
+ client = Vkit::Core::AuthClient.new(base_url: pending["endpoint"])
107
+ interval = (pending["interval"] || DEFAULT_INTERVAL).to_i
108
+ give_up_at = @timeout ? now + @timeout.to_f : nil
109
+ puts "⏳ Waiting for an admin to approve it..."
110
+
111
+ loop do
112
+ expired!(pending) if expired?(pending)
113
+ still_waiting!(pending) if give_up_at && now + interval > give_up_at
114
+
115
+ sleep interval
116
+ status, body = client.poll_setup_session(pending["device_code"])
117
+ return finish(pending, body) if status == 200 && body["access_token"]
118
+
119
+ case status == 429 ? "rate_limited" : body["error"]
120
+ when "authorization_pending"
121
+ next
122
+ when "slow_down"
123
+ interval = (body["interval"] || interval + 5).to_i
124
+ credential_store.save_pending_setup(pending.merge("interval" => interval))
125
+ when "rate_limited"
126
+ sleep [body["retry_after"].to_i, 1].max
127
+ when "access_denied"
128
+ ended!(pending, "setup_session_denied", body,
129
+ "Ask the person whether they meant to deny it; to try again, run `vkit login --setup`.")
130
+ when "expired_token"
131
+ expired!(pending)
132
+ when "invalid_grant"
133
+ ended!(pending, "setup_session_invalid", body,
134
+ "Run `vkit login --setup` to request a new setup session.")
135
+ else
136
+ raise Vkit::CLI::CommandError.new(
137
+ "The control plane answered the setup session poll with HTTP #{status}: " \
138
+ "#{body['error_description'] || body['error']}",
139
+ code: "setup_poll_failed", fix: ["Rerun `#{WAIT_COMMAND}`; if it keeps failing, run `vkit login --setup` again."]
140
+ )
141
+ end
142
+ end
143
+ end
144
+
145
+ def finish(pending, body)
146
+ token = body["access_token"]
147
+ Vkit::CLI::Output.register_secret(token)
148
+ user = body["user"] || {}
149
+ org = body.dig("organization", "slug") || user["organization_slug"]
150
+ expires_at = body["expires_at"] || (now + body["expires_in"].to_i).utc.iso8601
151
+
152
+ previous = credential_store.stored_payload || {}
153
+ replaced = previous["token"] && !previous["setup"] ? previous.dig("user", "email") : nil
154
+
155
+ credential_store.save(
156
+ endpoint: pending["endpoint"],
157
+ token: token,
158
+ user: user,
159
+ setup: { "expires_at" => expires_at, "organization" => org }
160
+ )
161
+
162
+ puts "✅ Setup session approved by #{user['email']} for #{org}; it works until #{clock(expires_at)}."
163
+ puts " It can only connect datasources, scan schemas and deploy policies. " \
164
+ "Run `vkit logout` when setup is done to end it."
165
+ if replaced
166
+ puts " It replaced your saved login (#{replaced}); run `vkit login` afterwards to sign in as yourself again."
167
+ end
168
+
169
+ result = { "setup_session" => true, "email" => user["email"], "role" => user["role"],
170
+ "organization" => org, "endpoint" => pending["endpoint"], "auth" => "setup",
171
+ "expires_at" => expires_at, "allowed_endpoints" => Array(body["allowed_endpoints"]) }
172
+ result["replaced_login"] = replaced if replaced
173
+ respond(result, ["vkit whoami --format json", "vkit init --format json"])
174
+ end
175
+
176
+ def approval_needed!(pending, message)
177
+ needs_input!(
178
+ "setup_approval_required", message,
179
+ [APPROVE_FIX, "then run `#{WAIT_COMMAND}` to wait for it"],
180
+ next_steps: [WAIT_COMMAND],
181
+ result: {
182
+ "user_code" => pending["user_code"],
183
+ "verification_url" => pending["verification_url"],
184
+ "verification_url_complete" => pending["verification_url_complete"],
185
+ "expires_at" => pending["expires_at"],
186
+ "endpoint" => pending["endpoint"]
187
+ }
188
+ )
189
+ end
190
+
191
+ # --timeout passed with no answer yet.
192
+ def still_waiting!(pending)
193
+ approval_needed!(pending, "Still waiting for an admin to approve the setup session.") if json?
194
+
195
+ raise Vkit::CLI::CommandError.new(
196
+ "Still waiting for an admin to approve the setup session (code #{pending['user_code']}).",
197
+ code: "setup_approval_required", fix: ["#{APPROVE_FIX}, then run `vkit login --setup --wait`."]
198
+ )
199
+ end
200
+
201
+ def expired!(pending)
202
+ credential_store.clear_pending_setup!
203
+ raise Vkit::CLI::CommandError.new(
204
+ "The setup session request expired before an admin approved it.",
205
+ code: "setup_session_expired",
206
+ fix: ["Run `vkit login --setup` for a new code. #{APPROVE_FIX} within 10 minutes."],
207
+ next_steps: ["vkit login --setup --format json"]
208
+ )
209
+ end
210
+
211
+ def ended!(pending, code, body, fix)
212
+ credential_store.clear_pending_setup!
213
+ raise Vkit::CLI::CommandError.new(
214
+ body["error_description"] || body["error"].to_s, code: code, fix: [fix],
215
+ next_steps: ["vkit login --setup --format json"]
216
+ )
217
+ end
218
+
219
+ def not_started
220
+ Vkit::CLI::CommandError.new(
221
+ "There's no setup session waiting for approval.",
222
+ code: "setup_session_not_started",
223
+ fix: ["Run `vkit login --setup --format json` first; it returns the code to show the person."],
224
+ next_steps: ["vkit login --setup --format json"]
225
+ )
226
+ end
227
+
228
+ def endpoint_needed!
229
+ needs_input!("endpoint_required", "No control plane URL to request a setup session from.",
230
+ ["Ask the person for their VaultKit control plane URL and rerun with --endpoint <url>."])
231
+ end
232
+
233
+ def expired?(pending)
234
+ Time.parse(pending["expires_at"].to_s) <= now
235
+ rescue ArgumentError
236
+ true
237
+ end
238
+
239
+ def clock(iso)
240
+ Time.parse(iso.to_s).localtime.strftime("%H:%M")
241
+ rescue ArgumentError
242
+ iso.to_s
243
+ end
244
+
245
+ def now
246
+ Time.now
247
+ end
248
+
249
+ def prompt(label)
250
+ print "#{label}: "
251
+ $stdin.gets.to_s.strip
252
+ end
253
+
254
+ # Best effort: the code and link are printed either way.
255
+ def open_browser(url)
256
+ return if url.to_s.empty?
257
+
258
+ cmd =
259
+ case RbConfig::CONFIG["host_os"]
260
+ when /darwin/ then ["open", url]
261
+ when /linux|bsd/ then ["xdg-open", url]
262
+ when /mswin|mingw|cygwin/ then ["cmd", "/c", "start", "", url]
263
+ end
264
+ return unless cmd
265
+
266
+ pid = Process.spawn(*cmd, out: File::NULL, err: File::NULL)
267
+ Process.detach(pid)
268
+ rescue StandardError
269
+ nil
270
+ end
271
+ end
272
+ end
273
+ end
274
+ end
@@ -5,8 +5,16 @@ module Vkit
5
5
  def call
6
6
  user = fetch_user_from_server_or_fallback
7
7
 
8
+ setup = credential_store.respond_to?(:setup_session) ? credential_store.setup_session : nil
9
+
8
10
  puts "👤 #{user['email']} " \
9
11
  "(role: #{user['role']}, org: #{user['organization_slug']})"
12
+ puts " Setup session: setup only, until #{setup['expires_at']}" if setup
13
+ result = { "email" => user["email"], "role" => user["role"],
14
+ "organization" => user["organization_slug"], "endpoint" => credential_store.endpoint,
15
+ "verified" => !@cached }
16
+ result["setup_session"] = { "expires_at" => setup["expires_at"] } if setup
17
+ respond(result)
10
18
  end
11
19
 
12
20
  private
@@ -15,7 +23,7 @@ module Vkit
15
23
  token = credential_store.token
16
24
  endpoint = credential_store.endpoint
17
25
 
18
- raise "Not logged in" if token.nil? || endpoint.nil?
26
+ raise not_logged_in("Not logged in") if token.nil? || endpoint.nil?
19
27
 
20
28
  client = Vkit::Core::AuthClient.new(base_url: endpoint)
21
29
  server_user = client.whoami(token)
@@ -25,12 +33,18 @@ module Vkit
25
33
 
26
34
  server_user
27
35
  rescue => e
36
+ # An agent checks the session with whoami, so a cached identity
37
+ # would hide an expired or unreachable one.
38
+ raise if json?
39
+
28
40
  fallback_local_user(e)
29
41
  end
30
42
 
31
43
  def fallback_local_user(error)
32
44
  user = credential_store.user
33
- raise "Not logged in" if user.nil?
45
+ raise not_logged_in("Not logged in") if user.nil?
46
+
47
+ @cached = true
34
48
 
35
49
  warn "⚠️ Unable to verify identity with server"
36
50
  warn "⚠️ #{error.message}"
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "io/wait"
5
+ require "open3"
6
+ require_relative "../../version"
7
+
8
+ module Vkit
9
+ module CLI
10
+ module Doctor
11
+ # Starts an MCP server over stdio, asks for its tools (initialize,
12
+ # then tools/list), and stops it. Returns the tool names; raises
13
+ # Failed when it doesn't start, answer or list in time.
14
+ class McpProbe
15
+ class Failed < StandardError; end
16
+
17
+ PROTOCOL_VERSION = "2025-06-18"
18
+
19
+ def initialize(timeout: 20)
20
+ @timeout = timeout
21
+ end
22
+
23
+ def call(command, env)
24
+ secret = env["VAULTKIT_TOKEN"].to_s
25
+ stdin, stdout, stderr, wait = Open3.popen3(env, command)
26
+ errors = Thread.new { stderr.read.to_s rescue "" } # rubocop:disable Style/RescueModifier
27
+ deadline = now + @timeout
28
+
29
+ send_message(stdin, id: 1, method: "initialize",
30
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {},
31
+ clientInfo: { name: "vkit-doctor", version: Vkit::VERSION } })
32
+ reply(stdout, 1, deadline)
33
+ send_message(stdin, method: "notifications/initialized")
34
+ send_message(stdin, id: 2, method: "tools/list", params: {})
35
+ Array(reply(stdout, 2, deadline).dig("result", "tools")).map { |t| t["name"] }.compact
36
+ rescue Failed => e
37
+ raise Failed, scrub(with_stderr(e.message, errors, wait), secret)
38
+ rescue SystemCallError, IOError => e
39
+ raise Failed, scrub(with_stderr(e.message, errors, wait), secret)
40
+ ensure
41
+ stop(stdin, wait)
42
+ end
43
+
44
+ private
45
+
46
+ def send_message(io, **message)
47
+ io.puts(JSON.generate({ jsonrpc: "2.0" }.merge(message)))
48
+ io.flush
49
+ end
50
+
51
+ # The response with this id, skipping notifications and log lines.
52
+ def reply(io, id, deadline)
53
+ buffer = +""
54
+ loop do
55
+ left = deadline - now
56
+ raise Failed, "no answer within #{@timeout}s" if left <= 0
57
+ raise Failed, "no answer within #{@timeout}s" unless io.wait_readable(left)
58
+
59
+ chunk = io.read_nonblock(4096, exception: false)
60
+ raise Failed, "it exited before answering" if chunk.nil?
61
+ next if chunk == :wait_readable
62
+
63
+ buffer << chunk
64
+ while (line = buffer.slice!(/\A[^\n]*\n/))
65
+ message = JSON.parse(line) rescue next # rubocop:disable Style/RescueModifier
66
+ next unless message.is_a?(Hash) && message["id"] == id
67
+ raise Failed, message.dig("error", "message").to_s if message["error"]
68
+
69
+ return message
70
+ end
71
+ end
72
+ end
73
+
74
+ def with_stderr(message, errors, wait)
75
+ return message unless errors
76
+
77
+ stop_process(wait)
78
+ last = errors.join(2)&.value.to_s.lines.map(&:strip).reject(&:empty?).last
79
+ last ? "#{message} (#{last})" : message
80
+ end
81
+
82
+ def stop(stdin, wait)
83
+ stdin&.close unless stdin&.closed?
84
+ stop_process(wait)
85
+ rescue IOError
86
+ nil
87
+ end
88
+
89
+ def stop_process(wait)
90
+ return unless wait&.alive?
91
+
92
+ Process.kill("TERM", wait.pid)
93
+ Process.kill("KILL", wait.pid) unless wait.join(2)
94
+ rescue Errno::ESRCH
95
+ nil
96
+ end
97
+
98
+ def scrub(text, secret)
99
+ secret.length >= 4 ? text.gsub(secret, "[REDACTED]") : text
100
+ end
101
+
102
+ def now
103
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end