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,243 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "net/http"
5
+ require "openssl"
6
+ require_relative "errors"
7
+ require_relative "../core/auth_client"
8
+ require_relative "api/client"
9
+
10
+ module Vkit
11
+ module CLI
12
+ # Turns an exception into the envelope's error: a stable code, the
13
+ # message, and one sentence saying what to do. Only codes the CLI or the
14
+ # control plane can actually tell apart are used.
15
+ module ErrorMap
16
+ LOGIN_FIX = "Ask the person to run `vkit login` in their own terminal (it opens a browser or asks for " \
17
+ "their password), or set VKIT_ENDPOINT and VKIT_TOKEN, then rerun this command."
18
+
19
+ SETUP_EXPIRED_FIX = "Setup sessions last 30 minutes. Run `vkit login --setup` for a new one (with --format json " \
20
+ "it returns a code; ask the person to open the URL, check the code matches, and approve), " \
21
+ "then rerun this command."
22
+ SETUP_SCOPE_FIX = "A setup session can't do this; an admin must. Ask the person to sign in as themselves with " \
23
+ "`vkit login` and run it, or, if the organization is already set up and they want this " \
24
+ "session to change it, approve a new one with \"Allow this session to replace existing " \
25
+ "policies and datasources\" ticked."
26
+
27
+ # The control plane's codes for a setup token it refuses (401), by
28
+ # what vkit calls them.
29
+ SETUP_TOKEN_ERRORS = {
30
+ "setup_token_expired" => ["setup_session_expired", "The setup session has expired.", SETUP_EXPIRED_FIX],
31
+ "setup_token_revoked" => ["setup_session_revoked", "The setup session was revoked (in the console, or by " \
32
+ "`vkit logout`).",
33
+ "Ask the person whether to start another; if so, run `vkit login --setup`, then " \
34
+ "rerun this command."],
35
+ "setup_token_invalid" => ["setup_session_invalid", "The control plane doesn't know this setup token.",
36
+ "Run `vkit login --setup` for a new setup session, then rerun this command."],
37
+ "setup_approver_not_admin" => ["setup_approver_not_admin",
38
+ "The admin who approved this setup session is no longer an admin.",
39
+ "Ask an admin of the organization to approve a new setup session " \
40
+ "(`vkit login --setup`), then rerun this command."]
41
+ }.freeze
42
+
43
+ # 409s the control plane answers with a code.
44
+ CONFLICT_FIXES = {
45
+ "datasource_exists" => "A datasource with this id already exists with different settings, and it can't " \
46
+ "be changed from vkit. Add it under a new id, or rerun with the settings it already " \
47
+ "has (`vkit datasource get <id>`).",
48
+ "bundle_version_exists" => "This bundle version was already uploaded with other contents, and a version " \
49
+ "can only be uploaded once. Commit your policy changes and rebuild with " \
50
+ "`vkit policy bundle` (the version is the commit), or name a new one with " \
51
+ "--version <label>.",
52
+ "bundle_checksum_exists" => "These exact policies were already uploaded under another version (the " \
53
+ "message names it), so there's nothing new to deploy. If that version isn't " \
54
+ "active, an admin can activate it in the console; otherwise change the " \
55
+ "policies and rebuild."
56
+ }.freeze
57
+
58
+ UNREACHABLE = [
59
+ Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ECONNRESET, Errno::ETIMEDOUT,
60
+ Errno::EADDRNOTAVAIL, SocketError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError
61
+ ].freeze
62
+
63
+ USER_TOKEN_REASONS = { "Signature has expired" => "token_expired", "revoked token" => "token_revoked" }.freeze
64
+
65
+ # What the control plane passes on from funl when it can't reach or
66
+ # log in to a datasource (only vkit scan connects; datasource add
67
+ # doesn't). funl gives a refused connection and a failed login the same
68
+ # code, datasource_unavailable, so only its wording tells them apart,
69
+ # and a failed login looks like any other failed connection.
70
+ DATASOURCE_ERRORS = [
71
+ [/datasource_unavailable\): Couldn't reach the datasource/, "datasource_unreachable",
72
+ "Check the datasource's host and port in its config and that the database is running and reachable " \
73
+ "from VaultKit, then rerun the scan."],
74
+ [/datasource_unavailable\)/, "datasource_connection_failed",
75
+ "Check the datasource's username and password (and that the database accepts connections from " \
76
+ "VaultKit); a wrong password looks the same as other connection failures."],
77
+ [/\(permission_denied\)/, "datasource_permission_denied",
78
+ "Grant the datasource's database role read access to the tables it should scan, then rerun."],
79
+ [/\(query_failed\)/, "datasource_query_failed",
80
+ "The datasource rejected the scan's query; check its config (host, port, database) and that the " \
81
+ "role can read the schema, then rerun."],
82
+ [/\((datasource_busy|query_timeout)\)/, "datasource_busy",
83
+ "The datasource is overloaded or slow; wait a little and rerun."],
84
+ [/Failed to open TCP connection|Funl rejected|Funl error/, "query_runtime_unavailable",
85
+ "VaultKit's query runtime (funl) failed or couldn't be reached; ask whoever runs the control plane " \
86
+ "to check it, then rerun."]
87
+ ].freeze
88
+
89
+ module_function
90
+
91
+ def datasource_error(message)
92
+ DATASOURCE_ERRORS.each do |pattern, code, fix|
93
+ return error(code, message, fix) if message.match?(pattern)
94
+ end
95
+ nil
96
+ end
97
+
98
+ def map(e)
99
+ case e
100
+ when NeedsInput
101
+ command_error(e, "needs_input")
102
+ when CommandError
103
+ command_error(e, "error")
104
+ when API::APIError
105
+ api_error(e)
106
+ when Vkit::Core::AuthClient::HTTPError
107
+ api_error(auth_http_error(e))
108
+ when *UNREACHABLE
109
+ unreachable(e)
110
+ when Thor::Error
111
+ error("invalid_arguments", e.message,
112
+ "Fix the arguments as the message says; `vkit help <command>` lists a command's options.")
113
+ when Interrupt
114
+ error("interrupted", "Interrupted", "Rerun the command.").merge(exit_code: 130)
115
+ else
116
+ mapped_by_class(e) || error("command_failed", e.message.to_s.strip,
117
+ "Read the message, fix what it names, and rerun the command.")
118
+ end
119
+ end
120
+
121
+ # The fix to print under a human-mode error, for the errors whose fix
122
+ # matters more than the message (setup sessions, conflicts); nil for
123
+ # the rest, which print as they always have.
124
+ def human_fix(e)
125
+ code = e.respond_to?(:code) ? e.code.to_s : ""
126
+ mapped = map(e) if e.is_a?(API::APIError) || e.is_a?(CommandError)
127
+ return nil unless mapped
128
+
129
+ mapped_code = mapped[:code].to_s
130
+ relevant = [code, mapped_code].any? { |c| c.start_with?("setup_") } || CONFLICT_FIXES.key?(mapped_code)
131
+ relevant ? mapped[:fix] : nil
132
+ end
133
+
134
+ def error(code, message, fix, **extra)
135
+ { status: "error", code: code, message: message, fix: fix }.merge(extra)
136
+ end
137
+
138
+ # A CommandError's fix is lines (often commands); the envelope's is one
139
+ # sentence, so they're joined.
140
+ def command_error(e, status)
141
+ fix = e.fix.empty? ? "Read the message, fix what it names, and rerun the command." : e.fix.join("; ")
142
+ out = { status: status, code: e.code, message: e.message, fix: fix, next_steps: e.next_steps }
143
+ out[:exit_code] = e.exit_code if e.exit_code
144
+ out[:result] = e.result if e.result
145
+ out
146
+ end
147
+
148
+ def auth_http_error(e)
149
+ body = begin
150
+ JSON.parse(e.body.to_s)
151
+ rescue JSON::ParserError
152
+ e.body.to_s
153
+ end
154
+ API::APIError.from_body(e.status, body)
155
+ end
156
+
157
+ def unreachable(e)
158
+ error("control_plane_unreachable", "Couldn't reach the VaultKit control plane: #{e.message}",
159
+ "Check that the control plane is running and that the endpoint is right " \
160
+ "(`vkit whoami`, or VKIT_ENDPOINT), then rerun the command.")
161
+ end
162
+
163
+ # 401s carry the control plane's reason in code (token_expired,
164
+ # token_revoked). Everything else keeps the server's code when it sends
165
+ # one, so nothing is lost.
166
+ def api_error(e)
167
+ extra = e.request_id ? { request_id: e.request_id } : {}
168
+ message = e.error.is_a?(String) ? e.error : e.error.to_json
169
+
170
+ if (ds = datasource_error(message))
171
+ return ds.merge(extra)
172
+ end
173
+
174
+ if (setup = SETUP_TOKEN_ERRORS[e.code])
175
+ code, text, fix = setup
176
+ return error(code, "#{text} (#{message})", fix, **extra)
177
+ end
178
+
179
+ case e.status
180
+ when 401
181
+ # Agent tokens say why in code; a person's login (a Devise JWT)
182
+ # only in the message.
183
+ reason = e.code || USER_TOKEN_REASONS.find { |text, _| message.include?(text) }&.last
184
+ case reason
185
+ when "token_expired"
186
+ error("session_expired", "Your VaultKit session has expired.",
187
+ "Login sessions last an hour. #{LOGIN_FIX}", **extra)
188
+ when "token_revoked"
189
+ error("token_revoked", "This VaultKit token has been revoked.",
190
+ "Use a token that is still valid. #{LOGIN_FIX}", **extra)
191
+ else
192
+ error("not_authenticated", "The control plane didn't accept your credentials (#{message}).",
193
+ LOGIN_FIX, **extra)
194
+ end
195
+ when 403
196
+ return error("setup_scope_forbidden", message, SETUP_SCOPE_FIX, **extra) if e.code == "setup_scope_forbidden"
197
+
198
+ error(e.code || "forbidden", message,
199
+ "Your role isn't allowed to do this; ask an admin of the organization to do it or to change your role.",
200
+ **extra)
201
+ when 409
202
+ if (fix = CONFLICT_FIXES[e.code])
203
+ return error(e.code, message, fix, **extra)
204
+ end
205
+
206
+ error(e.code || "api_error", message,
207
+ "Read the control plane's message and fix what it names, then rerun the command.",
208
+ **extra.merge(http_status: e.status))
209
+ when 404
210
+ error(e.code || "not_found", message, "Check the name or ID you passed; list what exists first.", **extra)
211
+ else
212
+ error(e.code || "api_error", message,
213
+ "Read the control plane's message and fix what it names, then rerun the command.",
214
+ **extra.merge(http_status: e.status))
215
+ end
216
+ end
217
+
218
+ def mapped_by_class(e)
219
+ manager = Vkit::CLI::PolicyPack::Manager if defined?(Vkit::CLI::PolicyPack::Manager)
220
+ if manager && e.is_a?(manager::PackNotFound)
221
+ packs = manager.new.available_packs
222
+ return error("unknown_pack", e.message,
223
+ "Use one of the packs this CLI ships: #{packs.join(', ')} (`vkit policy pack list`).",
224
+ result: { "available_packs" => packs })
225
+ end
226
+ if manager && e.is_a?(manager::DependencyMissing)
227
+ return error("pack_dependency_missing", e.message, "Add the packs it needs first, then rerun this command.")
228
+ end
229
+ if defined?(Vkit::Policy::ValidationError) && e.is_a?(Vkit::Policy::ValidationError)
230
+ return error("policy_invalid", e.message, "Fix the policies or registry the message names, then rerun.")
231
+ end
232
+ if e.message.to_s.start_with?("Not a VaultKit project", "Directory does not exist")
233
+ return error("not_a_project", e.message, "Run `vkit init` first, or pass --dir <project folder>.")
234
+ end
235
+ if e.is_a?(JSON::ParserError)
236
+ return error("invalid_json", e.message, "Pass valid JSON.")
237
+ end
238
+
239
+ nil
240
+ end
241
+ end
242
+ end
243
+ end
@@ -2,5 +2,37 @@ module Vkit
2
2
  module CLI
3
3
  class Error < StandardError; end
4
4
  class ConfigError < Error; end
5
+
6
+ # An error with a stable code that scripts and agents can match on, and
7
+ # the commands that fix it.
8
+ class CommandError < Error
9
+ attr_reader :code, :fix, :next_steps, :exit_code, :result
10
+
11
+ # result: what the envelope's result carries alongside the error (for
12
+ # needs_input, what the person has to be shown).
13
+ def initialize(message, code:, fix: [], next_steps: [], exit_code: nil, result: nil)
14
+ super(message)
15
+ @code = code
16
+ @fix = Array(fix)
17
+ @next_steps = Array(next_steps)
18
+ @exit_code = exit_code
19
+ @result = result
20
+ end
21
+
22
+ def to_h
23
+ { "status" => "error", "code" => code, "error" => message, "fix" => fix }
24
+ end
25
+
26
+ def render
27
+ lines = ["❌ #{message}", " Code: #{code}"]
28
+ lines += [" Fix:", *fix.map { |f| " #{f}" }] unless fix.empty?
29
+ lines.join("\n")
30
+ end
31
+ end
32
+
33
+ # The command can't go on without something only the person can give: a
34
+ # secret, a confirmation, a choice. Under --format json it's reported as
35
+ # status "needs_input" (exit 3) instead of waiting on a prompt.
36
+ class NeedsInput < CommandError; end
5
37
  end
6
38
  end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "stringio"
5
+ require_relative "errors"
6
+
7
+ module Vkit
8
+ module CLI
9
+ # --format json: every command prints exactly one object to stdout,
10
+ #
11
+ # { "status": "ok" | "error" | "needs_input", "result": {...},
12
+ # "next": ["<command to run next>", ...],
13
+ # "error": { "code", "message", "fix" } }
14
+ #
15
+ # and everything else (progress, warnings, the human output) goes to
16
+ # stderr. Commands record their result with Output.respond; errors are
17
+ # raised and turned into the envelope here, by ErrorMap.
18
+ module Output
19
+ EXIT_OK = 0
20
+ EXIT_ERROR = 1
21
+ # The command needs something only the person can give (a secret, a
22
+ # confirmation). Distinct from errors so an agent can tell them apart.
23
+ EXIT_NEEDS_INPUT = 3
24
+
25
+ REDACTED = "[REDACTED]"
26
+
27
+ class << self
28
+ # The real stdout while a JSON command runs ($stdout is stderr then).
29
+ attr_reader :stdout
30
+
31
+ def json?
32
+ !!@json
33
+ end
34
+
35
+ # Whether argv asks for JSON, before Thor has parsed it, so even an
36
+ # unknown option or a missing argument comes back as an envelope.
37
+ def json_requested?(argv)
38
+ argv.each_with_index.any? do |arg, i|
39
+ break false if arg == "--"
40
+
41
+ arg == "--format=json" || (arg == "--format" && argv[i + 1] == "json")
42
+ end
43
+ end
44
+
45
+ # Records the command's result. exit_code is for the few commands
46
+ # whose exit codes scripts already rely on (vkit registry diff).
47
+ def respond(result: {}, next_steps: [], exit_code: EXIT_OK)
48
+ @response = { result: result, next_steps: Array(next_steps), exit_code: exit_code }
49
+ result
50
+ end
51
+
52
+ # The command wrote its own stream to stdout (vkit approvals:watch),
53
+ # so there's no envelope to add after it.
54
+ def streamed!
55
+ @streamed = true
56
+ end
57
+
58
+ # Values that must never appear in the envelope, however they got
59
+ # into a message: passwords, tokens.
60
+ def register_secret(value)
61
+ value = value.to_s
62
+ return if value.length < 4
63
+
64
+ (@secrets ||= []) << value unless (@secrets ||= []).include?(value)
65
+ end
66
+
67
+ # An exit code for an error, overriding the default of 1, for
68
+ # commands that already document theirs.
69
+ attr_writer :error_exit_code
70
+
71
+ # Runs the block (the command) in JSON mode, prints the envelope and
72
+ # exits with its code. Never returns.
73
+ def run_json(out: $stdout)
74
+ envelope, code = capture_json(out: out) { yield }
75
+ out.puts(JSON.generate(envelope)) if envelope
76
+ out.flush
77
+ exit code
78
+ end
79
+
80
+ # The envelope and exit code, without printing or exiting (for tests
81
+ # and run_json).
82
+ def capture_json(out: $stdout)
83
+ reset!
84
+ @json = true
85
+ @stdout = out
86
+ saved = $stdout
87
+ $stdout = $stderr
88
+
89
+ envelope, code =
90
+ begin
91
+ yield
92
+ success
93
+ rescue SystemExit => e
94
+ exited(e)
95
+ rescue Exception => e # rubocop:disable Lint/RescueException
96
+ raise if e.is_a?(NoMemoryError) || e.is_a?(SignalException) && !e.is_a?(Interrupt)
97
+
98
+ failure(e)
99
+ end
100
+
101
+ [@streamed && code.zero? ? nil : redact(envelope), code]
102
+ ensure
103
+ $stdout = saved
104
+ @json = false
105
+ end
106
+
107
+ def reset!
108
+ @response = nil
109
+ @streamed = false
110
+ @secrets = []
111
+ @error_exit_code = nil
112
+ end
113
+
114
+ private
115
+
116
+ def success
117
+ r = @response || { result: {}, next_steps: [], exit_code: EXIT_OK }
118
+ [envelope("ok", r[:result], r[:next_steps]), r[:exit_code]]
119
+ end
120
+
121
+ # A command that exits on its own: a recorded result means it was
122
+ # done; otherwise a non-zero exit is an error it already printed (to
123
+ # stderr, now).
124
+ def exited(e)
125
+ return success if @response
126
+ return [envelope("ok", {}, []), EXIT_OK] if e.success?
127
+
128
+ error = { "code" => "command_failed", "message" => "The command failed; see stderr for details.",
129
+ "fix" => "Read the message on stderr and fix what it names, then rerun the command." }
130
+ [envelope("error", {}, [], error), e.status]
131
+ end
132
+
133
+ def failure(e)
134
+ mapped = ErrorMap.map(e)
135
+ status = mapped.delete(:status)
136
+ code = status == "needs_input" ? EXIT_NEEDS_INPUT : (@error_exit_code || mapped.delete(:exit_code) || EXIT_ERROR)
137
+ mapped.delete(:exit_code)
138
+ next_steps = mapped.delete(:next_steps) || []
139
+ result = mapped.delete(:result) || {}
140
+ [envelope(status, result, next_steps, mapped.transform_keys(&:to_s)), code]
141
+ end
142
+
143
+ def envelope(status, result, next_steps, error = nil)
144
+ env = { "status" => status, "result" => result || {}, "next" => next_steps }
145
+ env["error"] = error if error
146
+ env
147
+ end
148
+
149
+ def redact(envelope)
150
+ return envelope if @secrets.empty?
151
+
152
+ json = JSON.generate(envelope)
153
+ @secrets.sort_by { |s| -s.length }.each do |s|
154
+ json = json.gsub(JSON.generate(s)[1..-2], REDACTED)
155
+ end
156
+ JSON.parse(json)
157
+ end
158
+ end
159
+ end
160
+ end
161
+ end
@@ -1,5 +1,6 @@
1
1
  require "json"
2
2
  require "json_schemer"
3
+ require_relative "output"
3
4
 
4
5
  module Vkit
5
6
  module CLI
@@ -15,6 +16,13 @@ module Vkit
15
16
 
16
17
  return if errors.empty?
17
18
 
19
+ if Vkit::CLI::Output.json?
20
+ raise Vkit::CLI::CommandError.new(
21
+ "Policy bundle validation failed:\n#{errors.map { |err| format_error(err, bundle) }.join("\n")}",
22
+ code: "bundle_invalid", fix: ["Fix the policies the errors name, then rebuild with `vkit policy bundle`."]
23
+ )
24
+ end
25
+
18
26
  puts "\n❌ Policy bundle validation failed\n\n"
19
27
 
20
28
  errors.each do |err|
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/console"
4
+ require_relative "errors"
5
+
6
+ module Vkit
7
+ module CLI
8
+ # Secrets come from the person's terminal or the environment, never from
9
+ # a command-line argument (shell history, agent transcripts) or stdin (an
10
+ # agent's pipe).
11
+ module SecretInput
12
+ TTY = "/dev/tty"
13
+
14
+ module_function
15
+
16
+ # Reads one line from the controlling terminal with echo off. The prompt
17
+ # goes to the terminal too, so nothing touches stdout or stderr.
18
+ def from_tty(label, tty_path: TTY)
19
+ File.open(tty_path, "r+") do |tty|
20
+ tty.print "#{label}: "
21
+ tty.flush
22
+ value = tty.respond_to?(:noecho) && tty.tty? ? tty.noecho(&:gets) : tty.gets
23
+ tty.puts
24
+ value.to_s.chomp
25
+ end
26
+ rescue Errno::ENXIO, Errno::ENOENT, Errno::EACCES, Errno::ENOTTY, Errno::EIO
27
+ raise Vkit::CLI::NeedsInput.new(
28
+ "There's no terminal to type the secret into.",
29
+ code: "secret_required",
30
+ fix: ["Ask the person to run this command with --password-prompt in their own terminal."]
31
+ )
32
+ end
33
+
34
+ # The value of an environment variable, by name. The name, not the
35
+ # value, is what errors mention.
36
+ def from_env(name)
37
+ value = ENV[name.to_s]
38
+ if value.nil? || value.empty?
39
+ raise Vkit::CLI::CommandError.new(
40
+ "Environment variable #{name} is not set (or is empty).",
41
+ code: "secret_env_missing",
42
+ fix: ["Set #{name} in the environment vkit runs in, or use --password-prompt."]
43
+ )
44
+ end
45
+
46
+ value
47
+ end
48
+ end
49
+ end
50
+ end
data/lib/vkit/cli.rb CHANGED
@@ -1,18 +1,28 @@
1
1
  require "thor"
2
2
  require_relative "version"
3
3
 
4
+ require_relative "cli/errors"
5
+ require_relative "cli/output"
6
+ require_relative "cli/error_map"
4
7
  require_relative "cli/commands"
5
8
  require_relative "cli/base_cli"
6
9
 
7
10
  module Vkit
8
11
  module CLI
9
12
  def self.start(argv = ARGV)
13
+ json = Output.json_requested?(argv)
14
+
10
15
  if %w[--version -v].include?(argv.first)
16
+ Output.run_json { Output.respond(result: { "version" => Vkit::VERSION }) } if json
11
17
  puts "vkit #{Vkit::VERSION}"
12
18
  exit 0
13
19
  end
14
20
 
15
- BaseCLI.start(argv)
21
+ return BaseCLI.start(argv) unless json
22
+
23
+ # debug: Thor raises its own errors (an unknown option, a missing
24
+ # argument) instead of printing them, so they come back as an envelope.
25
+ Output.run_json { BaseCLI.start(argv, debug: true) }
16
26
  end
17
27
  end
18
- end
28
+ end
@@ -2,12 +2,25 @@ require "net/http"
2
2
  require "uri"
3
3
  require "json"
4
4
  require "openssl"
5
+ require_relative "user_agent"
5
6
 
6
7
  module Vkit
7
8
  module Core
8
9
  class AuthClient
9
10
  DEFAULT_BASE_URL = ENV["VKIT_ENDPOINT"] || "http://localhost:3000"
10
11
 
12
+ # A non-2xx answer. The message is as it always was; status and body
13
+ # let --format json say why (an expired login is a 401).
14
+ class HTTPError < RuntimeError
15
+ attr_reader :status, :body
16
+
17
+ def initialize(status, body)
18
+ @status = status.to_i
19
+ @body = body
20
+ super("HTTP #{status}: #{body}")
21
+ end
22
+ end
23
+
11
24
  def initialize(base_url: DEFAULT_BASE_URL)
12
25
  @base_url = base_url.chomp("/")
13
26
  end
@@ -78,6 +91,48 @@ module Vkit
78
91
  http_request(uri, req, allow_non_200: true)
79
92
  end
80
93
 
94
+ # Setup sessions (device authorization, RFC 8628 style): ask for one,
95
+ # then poll until an admin approves or denies it in the console.
96
+ def start_setup_session
97
+ uri = uri_for("/api/setup_sessions")
98
+ req = Net::HTTP::Post.new(uri)
99
+ req["Content-Type"] = "application/json"
100
+ req["Accept"] = "application/json"
101
+ req.body = "{}"
102
+
103
+ parse_json(http_request(uri, req))
104
+ end
105
+
106
+ # [HTTP status, body]: 200 with the token once approved; 400 with
107
+ # error authorization_pending, slow_down, access_denied, expired_token
108
+ # or invalid_grant; 429 rate_limited.
109
+ def poll_setup_session(device_code)
110
+ uri = uri_for("/api/setup_sessions/token")
111
+ req = Net::HTTP::Post.new(uri)
112
+ req["Content-Type"] = "application/json"
113
+ req["Accept"] = "application/json"
114
+ req.body = JSON.dump(device_code: device_code)
115
+
116
+ res = http_request(uri, req, allow_non_200: true)
117
+ body = begin
118
+ JSON.parse(res.body.to_s)
119
+ rescue JSON::ParserError
120
+ { "error" => res.body.to_s }
121
+ end
122
+ [res.code.to_i, body]
123
+ end
124
+
125
+ # A setup token ending itself (DELETE /api/setup_sessions/current).
126
+ # Raises HTTPError when the control plane doesn't confirm it.
127
+ def end_setup_session(token)
128
+ uri = uri_for("/api/setup_sessions/current")
129
+ req = Net::HTTP::Delete.new(uri)
130
+ req["Authorization"] = "Bearer #{token}"
131
+ req["Accept"] = "application/json"
132
+
133
+ parse_json(http_request(uri, req))
134
+ end
135
+
81
136
  private
82
137
 
83
138
  def uri_for(path)
@@ -90,12 +145,13 @@ module Vkit
90
145
  end
91
146
 
92
147
  def http_request(uri, req, allow_non_200: false)
148
+ req["User-Agent"] = UserAgent.to_s
93
149
  res = build_http(uri).request(req)
94
150
 
95
151
  return res if allow_non_200
96
152
 
97
153
  unless res.is_a?(Net::HTTPSuccess)
98
- raise "HTTP #{res.code}: #{res.body}"
154
+ raise HTTPError.new(res.code, res.body)
99
155
  end
100
156
 
101
157
  res