2pass 2.1.0 → 2.3.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.
@@ -0,0 +1,462 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "open3"
5
+ require "time"
6
+ require "timeout"
7
+ require "yaml"
8
+
9
+ module TwoPass
10
+ class Broker
11
+ DEFAULT_ACTION_TIMEOUT_SECONDS = 10
12
+ DEFAULT_CACHE_TTL = 300
13
+ REDACTION = "[REDACTED]"
14
+
15
+ class Error < StandardError
16
+ attr_reader :code, :details
17
+
18
+ def initialize(code, message, details = {})
19
+ @code = code
20
+ @details = details
21
+ super(message)
22
+ end
23
+ end
24
+
25
+ def self.default_policy_path
26
+ File.join(TwoPass.shared_dir || TwoPass::VAULT_DIR, "broker-policy.yml")
27
+ end
28
+
29
+ # principal: the caller's verified identity (a device name, set by the hub
30
+ # server). When present it replaces any "actor" claimed in the request.
31
+ def initialize(policy_path: self.class.default_policy_path, principal: nil,
32
+ approvals: Approvals.new, clock: -> { Time.now })
33
+ @policy_path = policy_path
34
+ @principal = principal
35
+ @approvals = approvals
36
+ @clock = clock
37
+ end
38
+
39
+ # Everything `actor` may reveal without approval, for a sealed bundle:
40
+ # grants allowing get or list with allow_reveal, not expired, not gated.
41
+ # Purposes are ignored (the bundle serves every purpose).
42
+ def bundle_contents(actor)
43
+ grants = Array(policy.fetch("actors", {}).fetch(actor, {})["grants"]).select do |grant|
44
+ (operation_allowed?(grant, "get") || operation_allowed?(grant, "list")) &&
45
+ reveal_allowed?(grant) && grant_not_expired?(grant)
46
+ end
47
+ gated, free = grants.partition { |grant| gated?(grant) }
48
+
49
+ buckets = {}
50
+ missing = []
51
+ free.each do |grant|
52
+ vault = grant["vault"].to_s
53
+ env = optional_string(grant, "env")
54
+ entries = begin
55
+ TwoPass.send(:load_vault, vault, env: env)
56
+ rescue RuntimeError
57
+ missing << (env ? "#{vault} (#{env})" : vault)
58
+ next
59
+ end
60
+ ids = configured_ids(grant)
61
+ bucket = (buckets[[vault, env]] ||= {})
62
+ entries.each do |entry|
63
+ bucket[entry[:id]] = entry[:value] if ids == "*" || ids.include?(entry[:id])
64
+ end
65
+ end
66
+
67
+ vaults = buckets.map do |(vault, env), values|
68
+ {"vault" => vault, "env" => env, "entries" => values.sort.map { |id, value| {"id" => id, "value" => value} }}
69
+ end
70
+ {vaults: vaults.sort_by { |v| [v["vault"], v["env"].to_s] }, skipped_gated: gated.size, missing: missing.uniq}
71
+ end
72
+
73
+ def handle_json(input)
74
+ handle(JSON.parse(input))
75
+ rescue JSON::ParserError => e
76
+ error_response("invalid_json", e.message)
77
+ end
78
+
79
+ def handle(request)
80
+ request = deep_stringify(request)
81
+ operation = required_string(request, "operation")
82
+
83
+ case operation
84
+ when "list_ids"
85
+ list_ids(request)
86
+ when "metadata"
87
+ metadata(request)
88
+ when "get"
89
+ get(request)
90
+ when "list"
91
+ list(request)
92
+ when "use"
93
+ use(request)
94
+ else
95
+ raise Error.new("invalid_operation", "Unsupported broker operation: #{operation}")
96
+ end
97
+ rescue Error => e
98
+ error_response(e.code, e.message, e.details)
99
+ end
100
+
101
+ private
102
+
103
+ attr_reader :policy_path
104
+
105
+ def list_ids(request)
106
+ grants = authorized_grants(request, "list_ids")
107
+ vault_name = required_string(request, "vault")
108
+ env = optional_string(request, "env")
109
+ vault_ids = TwoPass.send(:load_vault, vault_name, env: env).map { |entry| entry[:id] }
110
+
111
+ ids = grants.flat_map do |grant|
112
+ grant_ids = configured_ids(grant)
113
+ grant_ids == "*" ? vault_ids : grant_ids
114
+ end
115
+
116
+ {
117
+ ok: true,
118
+ operation: "list_ids",
119
+ vault: vault_name,
120
+ env: env,
121
+ ids: (ids & vault_ids).sort
122
+ }
123
+ end
124
+
125
+ def metadata(request)
126
+ grant = authorized_grant_for_id(request, "metadata")
127
+ vault_name = required_string(request, "vault")
128
+ env = optional_string(request, "env")
129
+ id = required_string(request, "id")
130
+
131
+ {
132
+ ok: true,
133
+ operation: "metadata",
134
+ vault: vault_name,
135
+ env: env,
136
+ id: id,
137
+ available: secret_available?(vault_name, id, env: env),
138
+ reveal_allowed: reveal_allowed?(grant)
139
+ }
140
+ end
141
+
142
+ def get(request)
143
+ grant = authorized_grant_for_id(request, "get")
144
+
145
+ unless reveal_allowed?(grant)
146
+ raise Error.new("unauthorized", "Request is not authorized")
147
+ end
148
+
149
+ vault_name = required_string(request, "vault")
150
+ env = optional_string(request, "env")
151
+ id = required_string(request, "id")
152
+ cache_ttl = ensure_approved!([grant], request, "get", id)
153
+
154
+ {
155
+ ok: true,
156
+ operation: "get",
157
+ vault: vault_name,
158
+ env: env,
159
+ id: id,
160
+ value: TwoPass.send(:local_secret, vault_name, id, env: env),
161
+ cache_ttl: cache_ttl
162
+ }
163
+ end
164
+
165
+ # Returns id/value pairs for every secret the caller may reveal.
166
+ def list(request)
167
+ grants = authorized_grants(request, "list").select { |grant| reveal_allowed?(grant) }
168
+ raise Error.new("unauthorized", "Request is not authorized") if grants.empty?
169
+
170
+ cache_ttl = ensure_approved!(grants, request, "list", "*")
171
+ vault_name = required_string(request, "vault")
172
+ env = optional_string(request, "env")
173
+ entries = TwoPass.send(:load_vault, vault_name, env: env)
174
+ .select { |entry| grants.any? { |grant| id_allowed?(grant, entry[:id]) } }
175
+ .sort_by { |entry| entry[:id] }
176
+ .map { |entry| {id: entry[:id], value: entry[:value]} }
177
+
178
+ {
179
+ ok: true,
180
+ operation: "list",
181
+ vault: vault_name,
182
+ env: env,
183
+ entries: entries,
184
+ cache_ttl: cache_ttl
185
+ }
186
+ end
187
+
188
+ def use(request)
189
+ action_name = required_string(request, "action")
190
+ grant = prefer_ungated(authorized_grants(request, "use")).find do |candidate|
191
+ action_config(candidate, action_name)
192
+ end
193
+
194
+ unless grant
195
+ raise Error.new("unauthorized", "Request is not authorized")
196
+ end
197
+
198
+ ensure_approved!([grant], request, "use", action_name)
199
+ action = action_config(grant, action_name)
200
+ command = action_command(action)
201
+ timeout_seconds = action_timeout(action)
202
+ secret_env = secret_environment(action, grant, request)
203
+
204
+ stdout, stderr, status = nil
205
+ Timeout.timeout(timeout_seconds) do
206
+ stdout, stderr, status = Open3.capture3(secret_env, *command)
207
+ end
208
+
209
+ secret_values = secret_env.values
210
+ {
211
+ ok: true,
212
+ operation: "use",
213
+ vault: required_string(request, "vault"),
214
+ env: optional_string(request, "env"),
215
+ action: action_name,
216
+ success: status.success?,
217
+ status: status.exitstatus,
218
+ stdout: redact(stdout, secret_values),
219
+ stderr: redact(stderr, secret_values)
220
+ }
221
+ rescue Timeout::Error
222
+ error_response("action_timeout", "Broker action timed out")
223
+ rescue SystemCallError => e
224
+ error_response("action_error", e.message)
225
+ end
226
+
227
+ def policy
228
+ unless File.file?(policy_path)
229
+ raise Error.new("missing_policy", "Broker policy not found: #{policy_path}")
230
+ end
231
+
232
+ deep_stringify(YAML.safe_load_file(policy_path, aliases: false) || {})
233
+ rescue Psych::SyntaxError => e
234
+ raise Error.new("invalid_policy", e.message)
235
+ end
236
+
237
+ def authorized_grants(request, operation)
238
+ actor = actor_for(request)
239
+ vault = required_string(request, "vault")
240
+ env = optional_string(request, "env")
241
+ purpose = required_string(request, "purpose")
242
+ actor_policy = policy.fetch("actors", {}).fetch(actor, {})
243
+ grants = Array(actor_policy["grants"]).select do |grant|
244
+ grant_matches_context?(grant, vault, env, purpose) &&
245
+ operation_allowed?(grant, operation)
246
+ end
247
+
248
+ raise Error.new("unauthorized", "Request is not authorized") if grants.empty?
249
+
250
+ grants
251
+ end
252
+
253
+ def authorized_grant_for_id(request, operation)
254
+ id = required_string(request, "id")
255
+ grant = prefer_ungated(authorized_grants(request, operation)).find do |candidate|
256
+ id_allowed?(candidate, id)
257
+ end
258
+
259
+ raise Error.new("unauthorized", "Request is not authorized") unless grant
260
+
261
+ grant
262
+ end
263
+
264
+ # Grants that need no human approval are tried first.
265
+ def prefer_ungated(grants)
266
+ grants.each_with_index.sort_by { |grant, index| [gated?(grant) ? 1 : 0, index] }.map(&:first)
267
+ end
268
+
269
+ def gated?(grant)
270
+ grant["require_approval"] == true
271
+ end
272
+
273
+ # Returns how long the caller may cache the answer (seconds). Raises
274
+ # approval_required / approval_denied when a gated grant has no live
275
+ # approval for this exact scope.
276
+ def ensure_approved!(grants, request, operation, target)
277
+ ttl = grants.map { |grant| cache_ttl(grant) }.min
278
+ gated = grants.select { |grant| gated?(grant) }
279
+ return ttl if gated.empty?
280
+
281
+ now = @clock.call
282
+ scope = Approvals.scope(
283
+ principal: actor_for(request),
284
+ operation: operation,
285
+ vault: required_string(request, "vault"),
286
+ env: optional_string(request, "env"),
287
+ target: target,
288
+ purpose: required_string(request, "purpose")
289
+ )
290
+ remaining = @approvals.approved_remaining(scope, now: now)
291
+ return [ttl, remaining].min if remaining
292
+
293
+ approval_ttl = gated.map { |grant| positive_integer(grant, "approval_ttl", Approvals::DEFAULT_APPROVAL_TTL) }.min
294
+ entry = @approvals.request(scope, ttl: approval_ttl, now: now)
295
+ if entry["status"] == "denied"
296
+ raise Error.new("approval_denied", "Request was denied on the hub", approval_id: entry["id"])
297
+ end
298
+
299
+ raise Error.new(
300
+ "approval_required",
301
+ "Approval required. On the hub run: 2pass approve #{entry['id']}",
302
+ approval_id: entry["id"]
303
+ )
304
+ end
305
+
306
+ def cache_ttl(grant)
307
+ value = grant.fetch("cache_ttl", DEFAULT_CACHE_TTL)
308
+ unless value.is_a?(Integer) && value >= 0
309
+ raise Error.new("invalid_policy", "Grant cache_ttl must be a non-negative integer (seconds)")
310
+ end
311
+
312
+ value
313
+ end
314
+
315
+ def positive_integer(grant, key, default)
316
+ value = grant.fetch(key, default)
317
+ unless value.is_a?(Integer) && value.positive?
318
+ raise Error.new("invalid_policy", "Grant #{key} must be a positive integer (seconds)")
319
+ end
320
+
321
+ value
322
+ end
323
+
324
+ def actor_for(request)
325
+ @principal || required_string(request, "actor")
326
+ end
327
+
328
+ def grant_matches_context?(grant, vault, env, purpose)
329
+ grant["vault"].to_s == vault &&
330
+ optional_string(grant, "env") == env &&
331
+ list_includes?(grant["purposes"], purpose) &&
332
+ grant_not_expired?(grant)
333
+ end
334
+
335
+ def operation_allowed?(grant, operation)
336
+ list_includes?(grant["operations"], operation)
337
+ end
338
+
339
+ def id_allowed?(grant, id)
340
+ ids = configured_ids(grant)
341
+ ids == "*" || ids.include?(id)
342
+ end
343
+
344
+ def configured_ids(grant)
345
+ ids = grant["ids"]
346
+ return "*" if ids == "*"
347
+
348
+ Array(ids).map(&:to_s)
349
+ end
350
+
351
+ def reveal_allowed?(grant)
352
+ grant["allow_reveal"] == true
353
+ end
354
+
355
+ def grant_not_expired?(grant)
356
+ expires_at = optional_string(grant, "expires_at")
357
+ return true unless expires_at
358
+
359
+ Time.now.utc < Time.iso8601(expires_at).utc
360
+ rescue ArgumentError
361
+ raise Error.new("invalid_policy", "Grant expires_at must be an ISO8601 timestamp")
362
+ end
363
+
364
+ def action_config(grant, action_name)
365
+ return nil if action_name.to_s.empty?
366
+
367
+ grant.fetch("actions", {})[action_name.to_s]
368
+ end
369
+
370
+ def secret_environment(action, grant, request)
371
+ env_config = action.fetch("env", {})
372
+ unless env_config.is_a?(Hash) && env_config.any?
373
+ raise Error.new("invalid_policy", "Broker action must map at least one env var to a secret id")
374
+ end
375
+
376
+ vault_name = required_string(request, "vault")
377
+ env = optional_string(request, "env")
378
+
379
+ env_config.each_with_object({}) do |(env_name, secret_id), result|
380
+ secret_id = secret_id.to_s
381
+ unless id_allowed?(grant, secret_id)
382
+ raise Error.new("unauthorized", "Request is not authorized")
383
+ end
384
+
385
+ result[env_name.to_s] = TwoPass.send(:local_secret, vault_name, secret_id, env: env)
386
+ end
387
+ end
388
+
389
+ def action_command(action)
390
+ command = action["command"]
391
+ unless command.is_a?(Array) && command.any? && command.all? { |part| part.is_a?(String) && !part.empty? }
392
+ raise Error.new("invalid_policy", "Broker action command must be a non-empty array of strings")
393
+ end
394
+
395
+ command
396
+ end
397
+
398
+ def action_timeout(action)
399
+ timeout = action.fetch("timeout", DEFAULT_ACTION_TIMEOUT_SECONDS)
400
+ unless timeout.is_a?(Integer) && timeout.positive?
401
+ raise Error.new("invalid_policy", "Broker action timeout must be a positive integer")
402
+ end
403
+
404
+ timeout
405
+ end
406
+
407
+ def secret_available?(vault_name, id, env:)
408
+ TwoPass.send(:load_vault, vault_name, env: env).any? { |entry| entry[:id] == id }
409
+ end
410
+
411
+ def redact(output, secret_values)
412
+ secret_values
413
+ .compact
414
+ .reject(&:empty?)
415
+ .sort_by(&:length)
416
+ .reverse
417
+ .reduce(output.to_s) { |redacted, secret| redacted.gsub(secret, REDACTION) }
418
+ end
419
+
420
+ def required_string(hash, key)
421
+ value = hash[key]
422
+ if value.nil? || value.to_s.empty?
423
+ raise Error.new("invalid_request", "Missing required field: #{key}")
424
+ end
425
+
426
+ value.to_s
427
+ end
428
+
429
+ def optional_string(hash, key)
430
+ value = hash[key]
431
+ value.nil? || value.to_s.empty? ? nil : value.to_s
432
+ end
433
+
434
+ def list_includes?(list, value)
435
+ values = Array(list).map(&:to_s)
436
+ values.include?("*") || values.include?(value)
437
+ end
438
+
439
+ def deep_stringify(value)
440
+ case value
441
+ when Hash
442
+ value.each_with_object({}) do |(key, nested_value), result|
443
+ result[key.to_s] = deep_stringify(nested_value)
444
+ end
445
+ when Array
446
+ value.map { |item| deep_stringify(item) }
447
+ else
448
+ value
449
+ end
450
+ end
451
+
452
+ def error_response(code, message, details = {})
453
+ {
454
+ ok: false,
455
+ error: {
456
+ code: code,
457
+ message: message
458
+ }.merge(details)
459
+ }
460
+ end
461
+ end
462
+ end