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
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "../secret_input"
4
5
 
5
6
  module Vkit
6
7
  module CLI
@@ -8,30 +9,44 @@ module Vkit
8
9
  class DatasourceCommand < BaseCommand
9
10
  REDACT = "[REDACTED]"
10
11
 
11
- def add(id:, engine:, username:, password:, config:, region:, environment:)
12
+ # The password comes from the terminal (password_prompt) or an
13
+ # environment variable (password_env). --password still works but is
14
+ # deprecated: it ends up in shell history and agent transcripts.
15
+ #
16
+ # Adding an id that already exists with the same settings changes
17
+ # nothing and isn't an error; with different settings it's a 409
18
+ # datasource_exists (control planes from vaultkit#126 on compare
19
+ # them; older ones are taken to mean the same). The control plane has
20
+ # no way to change a stored credential, so a password source given
21
+ # for an existing id isn't read.
22
+ def add(id:, engine:, username:, config:, region:, environment:, password: nil,
23
+ password_prompt: false, password_env: nil)
24
+ warn_deprecated_password unless password.nil?
25
+ Vkit::CLI::Output.register_secret(password)
26
+
12
27
  with_auth do
13
28
  user = require_admin!
14
29
  org = user["organization_slug"]
15
-
16
- config_hash = config ? JSON.parse(config) : {}
17
-
18
- response = authenticated_client.post(
19
- "/api/v1/orgs/#{org}/datasources",
20
- body: {
21
- name: id,
22
- engine: engine,
23
- username: username,
24
- password: password,
25
- region: region.upcase,
26
- environment: environment,
27
- config: config_hash
28
- }
29
- )
30
-
30
+
31
+ config_hash = parse_config(config)
32
+ source = password_source(password, password_prompt, password_env)
33
+
34
+ body = { name: id, engine: engine, username: username, region: region.upcase,
35
+ environment: environment, config: config_hash }
36
+
37
+ existing = find(org, id)
38
+ return already_exists(confirm_existing(org, body, existing), source) if existing
39
+
40
+ password = read_password(source, id) unless source == :flag
41
+
42
+ response = authenticated_client.post("/api/v1/orgs/#{org}/datasources", body: body.merge(password: password))
43
+ return already_exists(response, source) if response["already_existed"]
44
+
31
45
  puts "✅ Datasource created:"
32
46
  print_datasource(response)
47
+ respond(redacted(response).merge("already_existed" => false), scan_next_steps(id))
33
48
  end
34
- end
49
+ end
35
50
 
36
51
  def list
37
52
  with_auth do
@@ -42,6 +57,7 @@ module Vkit
42
57
  "/api/v1/orgs/#{org}/datasources"
43
58
  )
44
59
 
60
+ respond({ "datasources" => rows.map { |ds| redacted(ds) } })
45
61
  puts "📦 Datasources (#{rows.size}):"
46
62
  rows.each do |ds|
47
63
  print_datasource(ds)
@@ -59,6 +75,7 @@ module Vkit
59
75
  "/api/v1/orgs/#{org}/datasources/#{name}"
60
76
  )
61
77
 
78
+ respond(redacted(ds))
62
79
  print_datasource(ds)
63
80
  end
64
81
  end
@@ -67,15 +84,115 @@ module Vkit
67
84
 
68
85
  def require_admin!
69
86
  user = credential_store.user
70
- raise "Not logged in. Run: vkit login" unless user
87
+ raise not_logged_in("Not logged in. Run: vkit login") unless user
71
88
 
72
89
  unless user["role"] == "admin"
73
- raise "⛔ Access denied: only admin users may manage datasources"
90
+ raise Vkit::CLI::CommandError.new(
91
+ "⛔ Access denied: only admin users may manage datasources", code: "admin_required",
92
+ fix: ["Ask an admin of the organization to add the datasource, or log in as one."]
93
+ )
74
94
  end
75
95
 
76
96
  user
77
97
  end
78
98
 
99
+ def parse_config(config)
100
+ config ? JSON.parse(config) : {}
101
+ rescue JSON::ParserError => e
102
+ raise Vkit::CLI::CommandError.new("--config isn't valid JSON: #{e.message}", code: "invalid_config",
103
+ fix: ["Pass --config as a JSON object, e.g. '{\"host\":\"db\",\"port\":5432,\"database\":\"app\"}'."])
104
+ end
105
+
106
+ # :flag, :prompt, :env, or nil when none was given.
107
+ def password_source(password, prompt, env)
108
+ given = [(:flag unless password.nil?), (:prompt if prompt), (:env if env)].compact
109
+ if given.length > 1
110
+ raise Vkit::CLI::CommandError.new("Give the password one way only.", code: "conflicting_password_sources",
111
+ fix: ["Use either --password-prompt or --password-env VAR_NAME, not both."])
112
+ end
113
+
114
+ @password_env = env
115
+ given.first
116
+ end
117
+
118
+ def read_password(source, id)
119
+ case source
120
+ when :prompt then Vkit::CLI::SecretInput.from_tty("Password for #{id}")
121
+ when :env then Vkit::CLI::SecretInput.from_env(@password_env)
122
+ else secret_required!
123
+ end.tap { |value| Vkit::CLI::Output.register_secret(value) }
124
+ end
125
+
126
+ # No password source: an agent can't supply one, and shouldn't, so it
127
+ # hands the command to the person.
128
+ def secret_required!
129
+ needs_input!(
130
+ "secret_required", "The datasource's password is needed and wasn't given.",
131
+ ["Ask the person to run this same command in their own terminal with --password-prompt " \
132
+ "and type the password there (or set an environment variable and pass --password-env VAR_NAME)."]
133
+ ) if json?
134
+
135
+ raise Vkit::CLI::CommandError.new(
136
+ "A password is required: use --password-prompt to type it, or --password-env VAR_NAME.",
137
+ code: "secret_required", fix: []
138
+ )
139
+ end
140
+
141
+ # nil when there's no datasource by that id.
142
+ def find(org, id)
143
+ authenticated_client.get("/api/v1/orgs/#{org}/datasources/#{id}")
144
+ rescue Vkit::CLI::API::APIError => e
145
+ raise unless e.status == 404
146
+
147
+ nil
148
+ end
149
+
150
+ # The id exists: send the settings (no credential) and let the
151
+ # control plane say whether they match. It answers 200
152
+ # already_existed when they do and 409 datasource_exists when they
153
+ # don't (raised as is). An older control plane answers neither (it
154
+ # refuses the duplicate some other way), so the existing one stands.
155
+ def confirm_existing(org, body, existing)
156
+ response = authenticated_client.post("/api/v1/orgs/#{org}/datasources", body: body)
157
+ response.is_a?(Hash) && response["already_existed"] ? response : existing
158
+ rescue Vkit::CLI::API::APIError => e
159
+ raise if e.code == "datasource_exists" || e.code.to_s.start_with?("setup_")
160
+
161
+ existing
162
+ end
163
+
164
+ def already_exists(existing, source)
165
+ puts "ℹ️ Datasource #{existing["name"]} already exists; left unchanged."
166
+ result = redacted(existing).merge("already_existed" => true, "credential_updated" => false)
167
+ if source
168
+ note = "The control plane can't change a stored credential, so the password given wasn't used."
169
+ puts " #{note}"
170
+ result["warning"] = note
171
+ end
172
+ respond(result, scan_next_steps(existing["name"]))
173
+ end
174
+
175
+ def scan_next_steps(id)
176
+ ["vkit scan #{id} --mode apply --format json", "vkit registry export --force --format json"]
177
+ end
178
+
179
+ def warn_deprecated_password
180
+ warn "⚠️ --password is deprecated: it ends up in shell history and agent transcripts. " \
181
+ "Use --password-prompt (type it) or --password-env VAR_NAME."
182
+ end
183
+
184
+ def redacted(ds)
185
+ {
186
+ "name" => ds["name"] || ds[:name],
187
+ "engine" => ds["engine"] || ds[:engine],
188
+ "config" => ds["config"] || ds[:config],
189
+ "region" => ds["region"] || ds[:region],
190
+ "environment" => ds["environment"] || ds[:environment],
191
+ "created_at" => ds["created_at"] || ds[:created_at],
192
+ "updated_at" => ds["updated_at"] || ds[:updated_at]
193
+ }.compact
194
+ end
195
+
79
196
  def print_datasource(ds)
80
197
  puts JSON.pretty_generate(
81
198
  {
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../doctor"
4
+ require_relative "../../core/credential_store"
5
+
6
+ module Vkit
7
+ module CLI
8
+ module Commands
9
+ # vkit doctor: runs Doctor's checks and reports them. Exits 0 only when
10
+ # none failed; under --format json a failure is status "error"
11
+ # (doctor_checks_failed) with the checks still in result.
12
+ class DoctorCommand < BaseCommand
13
+ ICONS = { "pass" => "✓", "warn" => "!", "fail" => "✗", "info" => "i" }.freeze
14
+
15
+ def initialize(runner: nil)
16
+ super()
17
+ @runner = runner
18
+ end
19
+
20
+ def call(dir: ".")
21
+ runner = @runner || Vkit::CLI::Doctor::Runner.new(store: credential_store, project_root: File.expand_path(dir))
22
+ runner.run
23
+ report = runner.to_h
24
+ print_report(report)
25
+
26
+ if runner.failed?
27
+ failed = report["checks"].select { |c| c["status"] == "fail" }
28
+ message = "#{failed.size} of #{report['checks'].size} checks failed: " \
29
+ "#{failed.map { |c| Vkit::CLI::Doctor::LABELS[c['name']] }.join(', ')}."
30
+ raise Vkit::CLI::CommandError.new(message, code: "doctor_checks_failed",
31
+ fix: [failed.map { |c| c["fix"] }.compact.uniq.join(" ")],
32
+ result: report) if json?
33
+
34
+ exit 1
35
+ end
36
+
37
+ respond(report)
38
+ end
39
+
40
+ private
41
+
42
+ def requires_auth?
43
+ false
44
+ end
45
+
46
+ def print_report(report)
47
+ width = Vkit::CLI::Doctor::LABELS.values.map(&:length).max
48
+ puts "vkit doctor"
49
+ puts
50
+ order = Vkit::CLI::Doctor::LABELS.keys
51
+ (report["checks"] + report["skipped"]).sort_by { |c| order.index(c["name"]) || order.size }.each do |c|
52
+ label = Vkit::CLI::Doctor::LABELS.fetch(c["name"], c["name"]).ljust(width)
53
+ if c.key?("status")
54
+ puts " #{ICONS[c['status']]} #{label} #{c['detail']}"
55
+ puts " #{' ' * width} #{c['status'] == 'info' ? '' : 'Fix: '}#{c['fix']}" if c["fix"] && c["status"] != "pass"
56
+ else
57
+ puts " - #{label} Skipped: #{c['reason']}"
58
+ puts " #{' ' * width} #{c['fix']}" if c["fix"]
59
+ end
60
+ end
61
+ counts = report["summary"]
62
+ puts
63
+ puts " #{counts['pass']} passed, #{counts['warn']} #{counts['warn'] == 1 ? 'warning' : 'warnings'}, " \
64
+ "#{counts['fail']} failed#{", #{counts['info']} info" if counts['info'].to_i.positive?}#{", #{report['skipped'].size} skipped" if report['skipped'].any?}"
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -6,7 +6,10 @@ module Vkit
6
6
  module CLI
7
7
  module Commands
8
8
  class FetchCommand < BaseCommand
9
- def call(grant_ref:, format: "json")
9
+ # format nil: the summary line, then the rows as JSON (as before).
10
+ # "json": the envelope, with rows and meta in result.
11
+ def call(grant_ref:, format: nil)
12
+ @grant_ref = grant_ref
10
13
  with_auth do
11
14
  user = credential_store.user
12
15
  org = user["organization_slug"]
@@ -25,6 +28,9 @@ module Vkit
25
28
  private
26
29
 
27
30
  def print_result(rows, meta, format)
31
+ return respond({ "grant" => @grant_ref, "rows" => rows, "meta" => meta }) if format == "json"
32
+
33
+ format ||= "json"
28
34
  puts "✅ OK — #{rows.size} rows"
29
35
 
30
36
  if meta.any?
@@ -16,6 +16,8 @@ module Vkit
16
16
  raise "Not authenticated. Please login." if org.nil? || org.empty?
17
17
 
18
18
  unless force
19
+ confirmation_needed!("Revoking grant #{grant_ref}", "--yes") if json?
20
+
19
21
  puts "⚠️ You are about to revoke grant: #{grant_ref}"
20
22
  puts " Organization: #{org}"
21
23
  puts " Reason: #{reason}"
@@ -35,6 +37,7 @@ module Vkit
35
37
  puts "✅ Grant revoked"
36
38
  puts " Grant: #{grant_ref}"
37
39
  puts " Revoked: #{response["revoked_at"]}"
40
+ respond({ "grant" => grant_ref, "revoked_at" => response["revoked_at"] })
38
41
  end
39
42
  end
40
43
  end
@@ -3,15 +3,28 @@
3
3
  require "fileutils"
4
4
  require_relative "base_command"
5
5
  require_relative "../policy_pack/manager"
6
+ require_relative "../../policy/git_state"
7
+ require_relative "../../policy/pack_integrity"
6
8
 
7
9
  module Vkit
8
10
  module CLI
9
11
  module Commands
10
12
  class InitCommand < BaseCommand
11
- def call(dir:, packs:)
13
+ # .vkit/packs.yaml records the installed packs, and vkit policy bundle
14
+ # checks them against it, so it's committed. Nothing else in .vkit/ is
15
+ # (nothing else is written there today).
16
+ GITIGNORE = <<~IGNORE
17
+ dist/
18
+ .vkit/*
19
+ !.vkit/packs.yaml
20
+ IGNORE
21
+
22
+ def call(dir:, packs:, git: true)
12
23
  dir = File.expand_path(dir)
24
+ already = initialized?(dir)
13
25
  FileUtils.mkdir_p(dir)
14
26
 
27
+ git_initialized = git ? init_git(dir) : false
15
28
  create_structure(dir)
16
29
 
17
30
  manager = Vkit::CLI::PolicyPack::Manager.new(
@@ -22,17 +35,24 @@ module Vkit
22
35
  installed = []
23
36
 
24
37
  # Default secure behavior
25
- if packs.nil? || packs.empty?
38
+ # (only for a new project: rerunning init leaves the packs as they are)
39
+ if (packs.nil? || packs.empty?) && already
40
+ packs = []
41
+ elsif packs.nil? || packs.empty?
26
42
  puts "\nℹ️ No packs specified. Installing 'starter' for secure defaults."
27
43
  packs = ["starter"]
28
44
  end
29
45
 
46
+ pack_results = []
30
47
  packs.each do |pack_name|
48
+ was_installed = manager.installed?(pack_name)
31
49
  count = manager.install_with_deps!(pack_name)
32
50
  total_policies += count
33
51
  installed << pack_name
34
52
 
35
53
  metadata = manager.pack_metadata(pack_name)
54
+ pack_results << { "name" => pack_name, "version" => metadata["version"], "policies_added" => count,
55
+ "already_installed" => was_installed }
36
56
  puts "✓ Installed #{pack_name} pack (v#{metadata['version']}) - #{count} policies"
37
57
  end
38
58
 
@@ -44,16 +64,54 @@ module Vkit
44
64
  puts "\nNext steps:"
45
65
  puts " 1. Review policies in config/policies/"
46
66
  puts " 2. Run: vkit scan <datasource> --mode apply"
47
- puts " 3. Run: vkit policy bundle"
48
- puts " 4. Run: vkit policy deploy"
67
+ puts " 3. Commit: git add -A && git commit -m \"Add VaultKit policies\""
68
+ puts " 4. Run: vkit policy bundle"
69
+ puts " 5. Run: vkit policy deploy"
49
70
 
71
+ respond(
72
+ { "dir" => dir, "already_existed" => already, "git_initialized" => git_initialized,
73
+ "packs" => pack_results, "policies_added" => total_policies },
74
+ init_next_steps(dir)
75
+ )
50
76
  rescue StandardError => e
77
+ raise if json?
78
+
51
79
  puts "❌ Error: #{e.message}"
52
80
  exit 1
53
81
  end
54
82
 
55
83
  private
56
84
 
85
+ # Initialised before: it has the pack record init writes.
86
+ def initialized?(dir)
87
+ File.exist?(File.join(dir, Vkit::Policy::PackIntegrity::TRACKING_PATH))
88
+ end
89
+
90
+ def init_next_steps(dir)
91
+ cd = File.expand_path(dir) == Dir.pwd ? [] : ["cd #{dir}"]
92
+ cd + [
93
+ "vkit datasource add --id <id> --engine <engine> --username <user> --config '<json>' " \
94
+ "--region <region> --environment <env> --password-prompt",
95
+ "vkit scan <datasource> --mode apply --format json",
96
+ "vkit registry export --force --format json"
97
+ ]
98
+ end
99
+
100
+ # A bundle's version is the commit its policies are in, so a new
101
+ # project starts as a repository. Never commits.
102
+ def init_git(dir)
103
+ return false if Vkit::Policy::GitState.new(dir).repo?
104
+
105
+ if system("git", "init", "--quiet", dir, out: File::NULL, err: File::NULL)
106
+ puts "✓ Initialized a git repository in #{dir}"
107
+ true
108
+ else
109
+ puts "⚠️ Couldn't run git init (is git installed?). vkit policy bundle needs a git repository " \
110
+ "or --version."
111
+ false
112
+ end
113
+ end
114
+
57
115
  def create_structure(dir)
58
116
  FileUtils.mkdir_p(File.join(dir, "config", "policies"))
59
117
  FileUtils.mkdir_p(File.join(dir, "datasets"))
@@ -79,12 +137,7 @@ module Vkit
79
137
  end
80
138
 
81
139
  gitignore_path = File.join(dir, ".gitignore")
82
- unless File.exist?(gitignore_path)
83
- File.write(
84
- gitignore_path,
85
- "dist/\n.vkit/\n"
86
- )
87
- end
140
+ File.write(gitignore_path, GITIGNORE) unless File.exist?(gitignore_path)
88
141
  end
89
142
  end
90
143
  end
@@ -1,4 +1,5 @@
1
1
  require "io/console"
2
+ require_relative "../secret_input"
2
3
  require_relative "../../core/auth_client"
3
4
  require_relative "../../core/credential_store"
4
5
  require "base64"
@@ -12,9 +13,10 @@ module Vkit
12
13
  false
13
14
  end
14
15
 
15
- def initialize(endpoint: nil, email: nil)
16
+ def initialize(endpoint: nil, email: nil, password_prompt: false)
16
17
  @endpoint = endpoint
17
18
  @email = email
19
+ @password_prompt = password_prompt
18
20
  end
19
21
 
20
22
  def call
@@ -22,7 +24,7 @@ module Vkit
22
24
  @endpoint ||
23
25
  ENV["VKIT_ENDPOINT"] ||
24
26
  credential_store.stored_payload&.dig("endpoint") ||
25
- prompt("VaultKit Control Plane URL")
27
+ (json? ? endpoint_needed! : prompt("VaultKit Control Plane URL"))
26
28
  client = Vkit::Core::AuthClient.new(base_url: endpoint)
27
29
 
28
30
  discovery = client.discover
@@ -47,8 +49,17 @@ module Vkit
47
49
  user: result[:user]
48
50
  )
49
51
 
52
+ Vkit::CLI::Output.register_secret(result[:token])
50
53
  puts "✅ Logged in as #{result[:user]['email']}"
54
+ respond(
55
+ { "email" => result[:user]["email"], "role" => result[:user]["role"],
56
+ "organization" => result[:user]["organization_slug"], "endpoint" => endpoint, "auth" => auth },
57
+ ["vkit init --format json", "vkit datasource add --id <id> --engine <engine> --username <user> " \
58
+ "--config '<json>' --region <region> --environment <env> --password-prompt"]
59
+ )
51
60
  rescue => e
61
+ raise if json?
62
+
52
63
  puts "❌ Login failed: #{e.message}"
53
64
  exit 1
54
65
  end
@@ -96,9 +107,22 @@ module Vkit
96
107
  "Sign-in was rejected"
97
108
  end
98
109
 
110
+ def endpoint_needed!
111
+ needs_input!("endpoint_required", "No control plane URL to log in to.",
112
+ ["Ask the person for their VaultKit control plane URL and rerun with --endpoint <url>."])
113
+ end
114
+
115
+ # Under --format json the password never goes through stdin (an
116
+ # agent's pipe): only the terminal, and only when asked for.
99
117
  def password_flow(client)
118
+ if json?
119
+ needs_input!("email_required", "Password login needs an email.", ["Rerun with --email <address>."]) unless @email
120
+ secret_needed! unless @password_prompt
121
+ end
122
+
100
123
  email = @email || prompt("Email")
101
- password = prompt_password("Password")
124
+ password = @password_prompt ? Vkit::CLI::SecretInput.from_tty("Password") : prompt_password("Password")
125
+ Vkit::CLI::Output.register_secret(password)
102
126
 
103
127
  res = client.password_login(email: email, password: password)
104
128
 
@@ -109,7 +133,11 @@ module Vkit
109
133
  end
110
134
 
111
135
  def token_flow(client)
112
- token = ENV["VAULTKIT_TOKEN"] || prompt_password("API Token")
136
+ token = ENV["VAULTKIT_TOKEN"]
137
+ token ||= Vkit::CLI::SecretInput.from_tty("API Token") if @password_prompt
138
+ secret_needed! if token.nil? && json?
139
+ token ||= prompt_password("API Token")
140
+ Vkit::CLI::Output.register_secret(token)
113
141
  user = client.whoami(token)
114
142
 
115
143
  {
@@ -118,6 +146,12 @@ module Vkit
118
146
  }
119
147
  end
120
148
 
149
+ def secret_needed!
150
+ needs_input!("secret_required", "Logging in needs a secret the person has to type.",
151
+ ["Ask the person to run `vkit login --password-prompt` in their own terminal " \
152
+ "and type it there, then rerun your command."])
153
+ end
154
+
121
155
  def prompt(label)
122
156
  print "#{label}: "
123
157
  STDIN.gets.strip
@@ -1,13 +1,25 @@
1
+ require "time"
2
+
1
3
  module Vkit
2
4
  module CLI
3
5
  module Commands
4
6
  class LogoutCommand < BaseCommand
7
+ SETUP_TOKEN_PREFIX = "vkit_setup_".freeze
8
+ # The control plane already ended it: nothing left to revoke.
9
+ SETUP_ALREADY_ENDED = %w[setup_token_expired setup_token_revoked setup_token_invalid].freeze
10
+
5
11
  # Always the saved login, even when VKIT_ENDPOINT/VKIT_TOKEN are set.
12
+ # A setup session's token is revoked on the control plane first
13
+ # (DELETE /api/setup_sessions/current); whatever that answers, the
14
+ # login is cleared here.
6
15
  def call
7
16
  saved = credential_store.stored_payload || {}
8
17
  token = saved["token"]
18
+ result = { "logged_out" => true }
9
19
 
10
- if token
20
+ if token && setup_token?(saved)
21
+ result.merge!(revoke_setup_session(saved))
22
+ elsif token
11
23
  begin
12
24
  client = Vkit::Core::AuthClient.new(
13
25
  base_url: saved["endpoint"]
@@ -22,6 +34,47 @@ module Vkit
22
34
 
23
35
  credential_store.clear_token!
24
36
  puts "🧹 Logged out"
37
+ respond(result, ["vkit login"])
38
+ end
39
+
40
+ private
41
+
42
+ def setup_token?(saved)
43
+ saved["setup"] || saved["token"].to_s.start_with?(SETUP_TOKEN_PREFIX)
44
+ end
45
+
46
+ def revoke_setup_session(saved)
47
+ Vkit::CLI::Output.register_secret(saved["token"])
48
+ Vkit::Core::AuthClient.new(base_url: saved["endpoint"]).end_setup_session(saved["token"])
49
+ puts "🔒 Setup session ended on the control plane"
50
+ { "setup_session_revoked" => true }
51
+ rescue Vkit::Core::AuthClient::HTTPError => e
52
+ return { "setup_session_revoked" => true, "already_ended" => true } if already_ended?(e)
53
+
54
+ revoke_failed(saved, "HTTP #{e.status}")
55
+ rescue StandardError => e
56
+ revoke_failed(saved, e.message)
57
+ end
58
+
59
+ def already_ended?(error)
60
+ error.status == 401 && SETUP_ALREADY_ENDED.include?(JSON.parse(error.body.to_s)["code"])
61
+ rescue JSON::ParserError
62
+ false
63
+ end
64
+
65
+ def revoke_failed(saved, reason)
66
+ expires_at = saved.dig("setup", "expires_at")
67
+ until_when = expires_at ? "until it expires at #{clock(expires_at)}" : "until it expires"
68
+ warning = "Couldn't end the setup session on the control plane (#{reason}). It's cleared here, but the " \
69
+ "token stays valid #{until_when}; an admin can revoke it on the console's Agents page."
70
+ warn "⚠️ #{warning}"
71
+ { "setup_session_revoked" => false, "warning" => warning, "expires_at" => expires_at }.compact
72
+ end
73
+
74
+ def clock(iso)
75
+ Time.parse(iso.to_s).localtime.strftime("%H:%M")
76
+ rescue ArgumentError
77
+ iso.to_s
25
78
  end
26
79
  end
27
80
  end