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
@@ -10,41 +10,80 @@ module Vkit
10
10
  true
11
11
  end
12
12
 
13
+ # --format json on every command: one JSON envelope on stdout, logs on
14
+ # stderr (see Vkit::CLI::Output).
15
+ FORMAT_OPTION = {
16
+ type: :string, default: "human", enum: %w[human json],
17
+ desc: "Output format: human, or json (one JSON object on stdout, logs on stderr)"
18
+ }.freeze
19
+
13
20
  # LOGIN
14
21
  desc "login", "Authenticate with VaultKit control plane"
15
22
  option :endpoint, type: :string
16
23
  option :email, type: :string
24
+ option :password_prompt, type: :boolean, default: false,
25
+ desc: "Read the password from the terminal (/dev/tty), never from stdin"
26
+ option :setup, type: :boolean, default: false,
27
+ desc: "Ask an admin to approve a setup session (a 30-minute token that can only set VaultKit up)"
28
+ option :wait, type: :boolean, default: false,
29
+ desc: "With --setup: wait for the session an earlier `vkit login --setup` requested"
30
+ option :timeout, type: :numeric,
31
+ desc: "With --setup: stop waiting after this many seconds (default: until the request expires)"
32
+ option :browser, type: :boolean, default: true, desc: "With --setup: open the approval page (--no-browser to skip)"
33
+ option :format, **FORMAT_OPTION
17
34
  def login
35
+ if options[:setup] || options[:wait]
36
+ return Commands::SetupLoginCommand.new(
37
+ endpoint: options[:endpoint], wait: options[:wait], browser: options[:browser], timeout: options[:timeout]
38
+ ).call
39
+ end
40
+
18
41
  Commands::LoginCommand.new(
19
42
  endpoint: options[:endpoint],
20
- email: options[:email]
43
+ email: options[:email],
44
+ password_prompt: options[:password_prompt]
21
45
  ).call
22
46
  end
23
47
 
24
48
  desc "whoami", "Show current identity"
49
+ option :format, **FORMAT_OPTION
25
50
  def whoami
26
51
  Commands::WhoamiCommand.new.call
27
52
  end
28
53
 
54
+ desc "doctor", "Check that VaultKit is set up and working, and say how to fix what isn't"
55
+ option :dir, type: :string, default: ".", desc: "The policy project to compare the active bundle with"
56
+ option :format, **FORMAT_OPTION
57
+ def doctor
58
+ Commands::DoctorCommand.new.call(dir: options[:dir])
59
+ end
60
+
29
61
  desc "logout", "Clear stored credentials"
62
+ option :format, **FORMAT_OPTION
30
63
  def logout
31
64
  Commands::LogoutCommand.new.call
32
65
  end
33
66
 
34
67
  desc "reset", "Clear all stored credentials and configuration"
68
+ option :yes, type: :boolean, default: false, desc: "Don't ask for confirmation"
69
+ option :format, **FORMAT_OPTION
35
70
  def reset
36
- Commands::ResetCommand.new.call
71
+ Commands::ResetCommand.new.call(yes: options[:yes])
37
72
  end
38
73
 
39
74
  desc "init", "Initialize a new VaultKit project"
40
75
  option :dir, type: :string, default: ".", desc: "Target directory"
41
76
  option :with, type: :string, desc: "Comma-separated policy packs to install (e.g. starter,ai_safety)"
77
+ option :git, type: :boolean, default: true,
78
+ desc: "Run git init when the folder isn't in a git repository (--no-git to skip)"
79
+ option :format, **FORMAT_OPTION
42
80
  def init
43
81
  packs = options[:with]&.split(",")&.map(&:strip)
44
82
 
45
83
  Commands::InitCommand.new.call(
46
84
  dir: options[:dir],
47
- packs: packs
85
+ packs: packs,
86
+ git: options[:git]
48
87
  )
49
88
  end
50
89
 
@@ -66,12 +105,14 @@ module Vkit
66
105
  # APPROVALS
67
106
  desc "approval:list", "List all approval requests"
68
107
  option :state, type: :string, default: "pending", enum: %w[pending approved denied all]
108
+ option :format, **FORMAT_OPTION
69
109
  define_method("approval:list") do
70
110
  Commands::ApprovalCommand.new.call_list(state: options[:state])
71
111
  end
72
112
 
73
113
  desc "approval:approve ID", "Approve a pending request"
74
114
  option :ttl, type: :numeric, desc: "Grant lifetime in seconds (default and maximum: the policy's TTL)"
115
+ option :format, **FORMAT_OPTION
75
116
  define_method("approval:approve") do |id|
76
117
  Commands::ApprovalCommand.new.call_approve(
77
118
  id: id,
@@ -81,6 +122,7 @@ module Vkit
81
122
 
82
123
  desc "approval:deny ID", "Deny a pending request"
83
124
  option :reason, type: :string
125
+ option :format, **FORMAT_OPTION
84
126
  define_method("approval:deny") do |id|
85
127
  Commands::ApprovalCommand.new.call_deny(
86
128
  id: id,
@@ -105,7 +147,9 @@ module Vkit
105
147
  # FETCH
106
148
  desc "fetch --grant ID", "Fetch data from Funl using a valid grant"
107
149
  option :grant, type: :string, required: true
108
- option :format, type: :string, default: "json", enum: %w[json table]
150
+ # No default: without --format the rows print as JSON after a summary
151
+ # line, as they always have; --format json is the envelope.
152
+ option :format, type: :string, enum: %w[json table], desc: "json (one JSON object) or table; default: JSON rows"
109
153
  def fetch
110
154
  Commands::FetchCommand.new.call(
111
155
  grant_ref: options[:grant],
@@ -116,7 +160,8 @@ module Vkit
116
160
  desc "grant:revoke", "Revoke a grant"
117
161
  option :grant, type: :string, required: true
118
162
  option :reason, type: :string, required: true, desc: "Why it's revoked; recorded in the audit log"
119
- option :force, type: :boolean, default: false
163
+ option :force, type: :boolean, default: false, aliases: "--yes", desc: "Don't ask for confirmation"
164
+ option :format, **FORMAT_OPTION
120
165
  define_method("grant:revoke") do
121
166
  Commands::GrantRevokeCommand.new.call(
122
167
  grant_ref: options[:grant],
@@ -132,16 +177,24 @@ module Vkit
132
177
  option :id, required: true
133
178
  option :engine, required: true
134
179
  option :username, required: true
135
- option :password, required: true
180
+ option :password, type: :string,
181
+ desc: "Deprecated: ends up in shell history. Use --password-prompt or --password-env"
182
+ option :password_prompt, type: :boolean, default: false,
183
+ desc: "Type the password into the terminal (/dev/tty, echo off)"
184
+ option :password_env, type: :string, banner: "VAR_NAME",
185
+ desc: "Read the password from this environment variable"
136
186
  option :config, required: true
137
187
  option :region, required: true, desc: "EU | US | CA | APAC"
138
188
  option :environment, required: true, desc: "production | staging | development | sandbox"
189
+ option :format, **FORMAT_OPTION
139
190
  def add
140
191
  Commands::DatasourceCommand.new.add(
141
192
  id: options[:id],
142
193
  engine: options[:engine],
143
194
  username: options[:username],
144
195
  password: options[:password],
196
+ password_prompt: options[:password_prompt],
197
+ password_env: options[:password_env],
145
198
  config: options[:config],
146
199
  region: options[:region],
147
200
  environment: options[:environment]
@@ -149,11 +202,13 @@ module Vkit
149
202
  end
150
203
 
151
204
  desc "list", "List all datasources (admin only)"
205
+ option :format, **FORMAT_OPTION
152
206
  def list
153
207
  Commands::DatasourceCommand.new.list
154
208
  end
155
209
 
156
210
  desc "get ID", "Fetch a datasource by ID (admin only)"
211
+ option :format, **FORMAT_OPTION
157
212
  def get(id)
158
213
  Commands::DatasourceCommand.new.get(id)
159
214
  end
@@ -162,6 +217,7 @@ module Vkit
162
217
  # SCAN
163
218
  desc "scan DATASOURCE", "Scan datasource and diff against registry"
164
219
  option :mode, type: :string, default: "diff_only", enum: %w[diff_only apply]
220
+ option :format, **FORMAT_OPTION
165
221
  def scan(datasource)
166
222
  Commands::ScanCommand.new.call(
167
223
  datasource,
@@ -176,7 +232,9 @@ module Vkit
176
232
  desc "export", "Export runtime registry to datasets/registry.yaml"
177
233
  option :dir, type: :string, default: "."
178
234
  option :out, type: :string, desc: "Custom output path"
179
- option :force, type: :boolean, default: false
235
+ option :force, type: :boolean, default: false, aliases: "--yes",
236
+ desc: "Overwrite an existing registry.yaml without asking"
237
+ option :format, **FORMAT_OPTION
180
238
  def export
181
239
  Commands::RegistryExportCommand.new.call(
182
240
  dir: options[:dir],
@@ -205,7 +263,11 @@ module Vkit
205
263
  option :registry_dir, type: :string, default: "datasets"
206
264
  option :out, type: :string, default: "dist/policy_bundle.json"
207
265
  option :org, type: :string
208
- option :version, type: :string
266
+ option :version, type: :string,
267
+ desc: "Name the bundle (defaults to the git commit); the commit is still recorded from git"
268
+ option :allow_dirty, type: :boolean, default: false,
269
+ desc: "Bundle uncommitted changes anyway; the bundle is recorded as dirty"
270
+ option :format, **FORMAT_OPTION
209
271
 
210
272
  def bundle
211
273
  Commands::PolicyBundleCommand.new.call(
@@ -213,13 +275,15 @@ module Vkit
213
275
  registry_dir: options[:registry_dir],
214
276
  out: options[:out],
215
277
  org: options[:org],
216
- version: options[:version]
278
+ version: options[:version],
279
+ allow_dirty: options[:allow_dirty]
217
280
  )
218
281
  end
219
282
 
220
283
  desc "validate", "Validate a compiled policy bundle"
221
284
  option :bundle, type: :string, default: "dist/policy_bundle.json"
222
285
  option :schema, type: :string
286
+ option :format, **FORMAT_OPTION
223
287
 
224
288
  def validate
225
289
  Commands::PolicyValidateCommand.new.call(
@@ -232,19 +296,23 @@ module Vkit
232
296
  option :bundle, type: :string, default: "dist/policy_bundle.json"
233
297
  option :org, type: :string
234
298
  option :activate, type: :boolean, default: true
299
+ option :format, type: :string, default: "human", enum: %w[human json],
300
+ desc: "Output format (human, or json for automations)"
235
301
 
236
302
  def deploy
237
303
  Commands::PolicyDeployCommand.new.call(
238
304
  bundle_path: options[:bundle],
239
305
  org: options[:org],
240
- activate: options[:activate]
306
+ activate: options[:activate],
307
+ format: options[:format]
241
308
  )
242
309
  end
243
310
 
244
311
  desc "revoke", "Revoke a policy bundle version"
245
312
  option :bundle_version, type: :string, required: true
246
313
  option :reason, type: :string
247
- option :force, type: :boolean, default: false
314
+ option :force, type: :boolean, default: false, aliases: "--yes", desc: "Don't ask for confirmation"
315
+ option :format, **FORMAT_OPTION
248
316
 
249
317
  def revoke
250
318
  Commands::PolicyRevokeCommand.new.call(
@@ -258,6 +326,7 @@ module Vkit
258
326
  subcommand "pack", Class.new(Thor) {
259
327
 
260
328
  desc "list", "List policy packs"
329
+ option :format, **FORMAT_OPTION
261
330
  option :dir, type: :string, default: "."
262
331
  def list
263
332
  Commands::PolicyPackListCommand.new.call(
@@ -266,6 +335,7 @@ module Vkit
266
335
  end
267
336
 
268
337
  desc "add NAME", "Install a policy pack"
338
+ option :format, **FORMAT_OPTION
269
339
  option :dir, type: :string, default: "."
270
340
  option :force, type: :boolean, default: false
271
341
  def add(name)
@@ -277,6 +347,7 @@ module Vkit
277
347
  end
278
348
 
279
349
  desc "remove NAME", "Remove an installed policy pack"
350
+ option :format, **FORMAT_OPTION
280
351
  option :dir, type: :string, default: "."
281
352
  option :force, type: :boolean, default: false
282
353
  def remove(name)
@@ -288,6 +359,7 @@ module Vkit
288
359
  end
289
360
 
290
361
  desc "info NAME", "Show information about a policy pack"
362
+ option :format, **FORMAT_OPTION
291
363
  option :dir, type: :string, default: "."
292
364
  def info(name)
293
365
  Commands::PolicyPackInfoCommand.new.call(
@@ -299,8 +371,9 @@ module Vkit
299
371
  desc "upgrade [NAME]", "Upgrade installed policy packs (all if NAME omitted)"
300
372
  option :dir, type: :string, default: "."
301
373
  option :force, type: :boolean, default: false
302
- option :restore, type: :boolean, default: false,
374
+ option :restore, type: :boolean, default: false, aliases: "--yes",
303
375
  desc: "Restore an up-to-date pack's missing files without asking"
376
+ option :format, **FORMAT_OPTION
304
377
  def upgrade(name = nil)
305
378
  Commands::PolicyPackUpgradeCommand.new.call(
306
379
  pack_name: name,
@@ -332,6 +405,9 @@ module Vkit
332
405
 
333
406
  # agents tokens create
334
407
  desc "create", "Create a new agent token (automation identity)"
408
+ option :secret_file, type: :string, banner: "PATH",
409
+ desc: "Write the token to this file (mode 600) instead of printing it"
410
+ option :format, **FORMAT_OPTION
335
411
  option :name, required: true, desc: "Human-readable name (e.g. billing-bot)"
336
412
  option :expires_in, type: :string, desc: "Token lifetime (e.g. 1h, 24h, 30d)"
337
413
  option :role, type: :string, default: "agent", desc: "Role assigned to this token"
@@ -350,7 +426,8 @@ module Vkit
350
426
  role: options[:role],
351
427
  tenant: options[:tenant],
352
428
  clearance: options[:clearance],
353
- region: options[:region]
429
+ region: options[:region],
430
+ secret_file: options[:secret_file]
354
431
  )
355
432
  end
356
433
 
@@ -358,7 +435,8 @@ module Vkit
358
435
  desc "revoke", "Revoke an agent token"
359
436
  option :token, required: true, desc: "Token ID or prefix"
360
437
  option :reason, type: :string, required: true, desc: "Why it's revoked; recorded in the audit log"
361
- option :force, type: :boolean, default: false, desc: "Skip confirmation"
438
+ option :force, type: :boolean, default: false, aliases: "--yes", desc: "Skip confirmation"
439
+ option :format, **FORMAT_OPTION
362
440
  def revoke
363
441
  Commands::AgentTokensRevokeCommand.new.call(
364
442
  token: options[:token],
@@ -7,7 +7,18 @@ module Vkit
7
7
  module CLI
8
8
  module Commands
9
9
  class AgentTokensCreateCommand < BaseCommand
10
+ # secret_file: write the token there (mode 600) instead of printing
11
+ # it. Under --format json it's required, so the token never lands in
12
+ # an agent's transcript.
10
13
  def call(options)
14
+ secret_file = options[:secret_file]
15
+ if json? && secret_file.to_s.empty?
16
+ needs_input!("secret_file_required", "Creating an agent token under --format json needs --secret-file.",
17
+ ["Rerun with --secret-file <path> (a path the person chooses, outside the repository); " \
18
+ "the token is written there with mode 600 and never printed."])
19
+ end
20
+ refuse_existing!(secret_file) if secret_file
21
+
11
22
  with_auth do
12
23
  user = credential_store.user
13
24
  org = user["organization_slug"]
@@ -20,6 +31,7 @@ module Vkit
20
31
 
21
32
  token = response.fetch("token")
22
33
  secret = response.fetch("secret")
34
+ Vkit::CLI::Output.register_secret(secret)
23
35
 
24
36
  puts "🔐 AGENT TOKEN ISSUED (shown once)"
25
37
  puts
@@ -36,18 +48,70 @@ module Vkit
36
48
  puts "⏳ Expires At: #{token["expires_at"] || "never"}"
37
49
  puts
38
50
 
39
- puts "🔑 TOKEN"
40
- puts "────────────────────────────────────────"
41
- puts secret
42
- puts "────────────────────────────────────────"
43
- puts
51
+ if secret_file
52
+ write_secret(secret_file, secret)
53
+ puts "🔑 Token written to #{secret_file} (mode 600)"
54
+ puts
55
+ else
56
+ puts "🔑 TOKEN"
57
+ puts "────────────────────────────────────────"
58
+ puts secret
59
+ puts "────────────────────────────────────────"
60
+ puts
61
+ end
44
62
 
45
63
  puts "⚠️ Store this token securely. It cannot be retrieved again."
64
+
65
+ warn_if_tenant_scoped(org) unless token["tenant"]
66
+ respond(token.reject { |k, _| k == "secret" }
67
+ .merge(secret_file ? { "secret_file" => File.expand_path(secret_file) } : {}))
46
68
  end
47
69
  end
48
70
 
49
71
  private
50
72
 
73
+ # Checked before the token is issued, so a bad path doesn't lose it.
74
+ def refuse_existing!(path)
75
+ return unless File.exist?(path)
76
+
77
+ raise Vkit::CLI::CommandError.new("#{path} already exists; not overwriting it.", code: "secret_file_exists",
78
+ fix: ["Pass a --secret-file path that doesn't exist yet."])
79
+ end
80
+
81
+ def write_secret(path, secret)
82
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.write(secret) }
83
+ end
84
+
85
+ WARNING_NAMES = 5
86
+
87
+ # A token with no tenant can't read a tenant-scoped dataset at all:
88
+ # VaultKit answers it as if the dataset didn't exist. Say so when the
89
+ # org has any, so the operator isn't left guessing why.
90
+ def warn_if_tenant_scoped(org)
91
+ names = tenant_scoped_datasets(org)
92
+ return if names.empty?
93
+
94
+ shown = names.first(WARNING_NAMES).join(", ")
95
+ shown += ", and #{names.size - WARNING_NAMES} more" if names.size > WARNING_NAMES
96
+ count = names.size == 1 ? "1 dataset is" : "#{names.size} datasets are"
97
+
98
+ puts
99
+ puts "⚠️ This token has no tenant, and #{count} tenant-scoped in #{org}: #{shown}."
100
+ puts " VaultKit answers its requests for them as if they didn't exist (\"Dataset not found\")."
101
+ puts " To read them, create a token for one tenant with --tenant."
102
+ end
103
+
104
+ # Names of datasets with a tenant column, from the registry export.
105
+ # Nothing if the export can't be read: the token is already issued.
106
+ def tenant_scoped_datasets(org)
107
+ registry = authenticated_client.get("/api/v1/orgs/#{org}/registries/export")
108
+ return [] unless registry.is_a?(Hash)
109
+
110
+ registry.select { |_name, ds| ds.is_a?(Hash) && !ds["tenant_column"].to_s.empty? }.keys.sort
111
+ rescue StandardError
112
+ []
113
+ end
114
+
51
115
  def build_body(options)
52
116
  body = {
53
117
  name: options.fetch(:name),
@@ -26,6 +26,8 @@ module Vkit
26
26
  private
27
27
 
28
28
  def print_result(tokens, format)
29
+ return respond({ "tokens" => tokens }, ["vkit agents tokens create --name <name> --secret-file <path> --format json"]) if format == "json"
30
+
29
31
  if tokens.empty?
30
32
  puts "No tokens found."
31
33
  return
@@ -19,6 +19,7 @@ module Vkit
19
19
  token = resolve_token!(org, token_ref)
20
20
 
21
21
  unless options[:force]
22
+ confirmation_needed!("Revoking agent token #{token["prefix"]}", "--yes") if json?
22
23
  confirm!(token)
23
24
  end
24
25
 
@@ -35,6 +36,7 @@ module Vkit
35
36
  puts "📝 Reason: #{reason}"
36
37
  puts
37
38
  puts "✅ The token is no longer valid, and its grants are revoked."
39
+ respond({ "id" => token["id"], "name" => token["name"], "prefix" => token["prefix"], "revoked" => true })
38
40
  end
39
41
  end
40
42
 
@@ -16,6 +16,7 @@ module Vkit
16
16
  "/api/v1/orgs/#{org}/approvals?state=#{state}"
17
17
  )
18
18
 
19
+ respond({ "state" => state, "approvals" => rows })
19
20
  if rows.empty?
20
21
  puts empty_message_for(state)
21
22
  return
@@ -54,6 +55,8 @@ module Vkit
54
55
  body: body
55
56
  )
56
57
 
58
+ respond({ "id" => id }.merge(res.is_a?(Hash) ? res : {}),
59
+ res["grant_ref"] ? ["vkit fetch --grant #{res["grant_ref"]} --format json"] : [])
57
60
  if res["status"] == "pending"
58
61
  puts "✍️ Signed off on request #{id}"
59
62
  puts " → Approved by: #{ApprovalRoles.describe(Array(res["approved_roles"]))}"
@@ -72,6 +75,10 @@ module Vkit
72
75
  user = credential_store.user
73
76
  org = user["organization_slug"]
74
77
 
78
+ if reason.nil? && json?
79
+ needs_input!("reason_required", "Denying a request needs a reason; it's recorded in the audit log.",
80
+ ["Ask the person why it's denied, then rerun with --reason \"<why>\"."])
81
+ end
75
82
  reason ||= prompt_reason
76
83
  raise "Denial reason cannot be empty" if reason.to_s.empty?
77
84
 
@@ -80,6 +87,7 @@ module Vkit
80
87
  body: { reason: reason }
81
88
  )
82
89
 
90
+ respond({ "id" => id, "state" => "denied", "reason" => reason })
83
91
  puts "🚫 Denied request #{id}"
84
92
  puts " → Reason: #{reason}"
85
93
  end
@@ -17,6 +17,9 @@ module Vkit
17
17
 
18
18
  since_time = parse_since(since)
19
19
  seen = {}
20
+ # A stream: one JSON object per approval, as before, rather than
21
+ # a single envelope (which a watch never gets to the end of).
22
+ Vkit::CLI::Output.streamed! if json?
20
23
 
21
24
  if format == "table"
22
25
  puts "⏳ Watching approval queue (Ctrl+C to stop)…"
@@ -85,11 +88,9 @@ module Vkit
85
88
  end
86
89
 
87
90
  def print_json(obj, pretty:)
88
- if pretty
89
- puts JSON.pretty_generate(obj)
90
- else
91
- puts JSON.generate(obj)
92
- end
91
+ out = json? ? Vkit::CLI::Output.stdout : $stdout
92
+ out.puts(pretty ? JSON.pretty_generate(obj) : JSON.generate(obj))
93
+ out.flush
93
94
  end
94
95
 
95
96
  def normalize(a)
@@ -1,9 +1,15 @@
1
+ require "time"
1
2
  require_relative "../api/client"
3
+ require_relative "../errors"
4
+ require_relative "../output"
5
+ require_relative "../error_map"
2
6
 
3
7
  module Vkit
4
8
  module CLI
5
9
  module Commands
6
10
  class BaseCommand
11
+ NOT_LOGGED_IN = "Not logged in. Run `vkit login`."
12
+
7
13
  protected
8
14
 
9
15
  def with_auth
@@ -12,8 +18,9 @@ module Vkit
12
18
  store = credential_store
13
19
 
14
20
  unless store.logged_in?
15
- raise "Not logged in. Run `vkit login`."
21
+ raise not_logged_in
16
22
  end
23
+ check_setup_session!(store)
17
24
 
18
25
  yield
19
26
  end
@@ -22,8 +29,11 @@ module Vkit
22
29
  store = credential_store
23
30
 
24
31
  if requires_auth? && !store.logged_in?
25
- raise "Not logged in. Run `vkit login`."
32
+ raise not_logged_in
26
33
  end
34
+ check_setup_session!(store) if requires_auth?
35
+
36
+ Vkit::CLI::Output.register_secret(store.token)
27
37
 
28
38
  Vkit::CLI::API::Client.new(
29
39
  base_url: store.endpoint,
@@ -35,9 +45,53 @@ module Vkit
35
45
  true
36
46
  end
37
47
 
48
+ # A saved setup session's token past its expiry: say so without a
49
+ # round trip (the control plane would answer setup_token_expired).
50
+ def check_setup_session!(store)
51
+ return unless store.respond_to?(:setup_session)
52
+
53
+ expires_at = store.setup_session&.dig("expires_at")
54
+ return unless expires_at
55
+
56
+ expiry = Time.parse(expires_at.to_s)
57
+ return if expiry > Time.now
58
+
59
+ raise Vkit::CLI::CommandError.new(
60
+ "The setup session expired at #{expiry.localtime.strftime('%H:%M')}.",
61
+ code: "setup_session_expired", fix: [Vkit::CLI::ErrorMap::SETUP_EXPIRED_FIX]
62
+ )
63
+ rescue ArgumentError
64
+ nil
65
+ end
66
+
38
67
  def credential_store
39
68
  @credential_store ||= Vkit::Core::CredentialStore.new
40
69
  end
70
+
71
+ def not_logged_in(message = NOT_LOGGED_IN)
72
+ Vkit::CLI::CommandError.new(message, code: "not_logged_in", fix: [Vkit::CLI::ErrorMap::LOGIN_FIX])
73
+ end
74
+
75
+ def json?
76
+ Vkit::CLI::Output.json?
77
+ end
78
+
79
+ # Records the result for --format json (and returns it). Human
80
+ # output is printed by the command as before.
81
+ def respond(result, next_steps = [], exit_code: Vkit::CLI::Output::EXIT_OK)
82
+ Vkit::CLI::Output.respond(result: result, next_steps: next_steps, exit_code: exit_code)
83
+ end
84
+
85
+ def needs_input!(code, message, fix, next_steps: [], result: nil)
86
+ raise Vkit::CLI::NeedsInput.new(message, code: code, fix: fix, next_steps: next_steps, result: result)
87
+ end
88
+
89
+ # A yes/no question for the person. Under --format json there's no
90
+ # one to ask, so it's needs_input, naming the flag that answers it.
91
+ def confirmation_needed!(what, flag)
92
+ needs_input!("confirmation_required", "#{what} needs confirmation.",
93
+ ["Ask the person whether to go ahead; if they agree, rerun with #{flag}."])
94
+ end
41
95
  end
42
96
  end
43
97
  end