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.
- checksums.yaml +4 -4
- data/README.md +421 -7
- data/bin/2pass +331 -6
- data/lib/2pass/approvals.rb +128 -0
- data/lib/2pass/broker.rb +462 -0
- data/lib/2pass/bundle.rb +289 -0
- data/lib/2pass/device.rb +207 -0
- data/lib/2pass/device_cache.rb +85 -0
- data/lib/2pass/device_registry.rb +131 -0
- data/lib/2pass/encryption.rb +277 -0
- data/lib/2pass/envelope.rb +323 -0
- data/lib/2pass/locked_json_file.rb +33 -0
- data/lib/2pass/policy.rb +128 -0
- data/lib/2pass/remote.rb +387 -0
- data/lib/2pass/replay_cache.rb +27 -0
- data/lib/2pass/server.rb +84 -0
- data/lib/2pass/version.rb +1 -1
- data/lib/2pass.rb +296 -19
- metadata +15 -2
data/lib/2pass/remote.rb
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "open3"
|
|
5
|
+
require "shellwords"
|
|
6
|
+
|
|
7
|
+
module TwoPass
|
|
8
|
+
# Client side: a device that trusts one or more hubs sends `get` / `list` /
|
|
9
|
+
# `use` there instead of reading local vault files.
|
|
10
|
+
#
|
|
11
|
+
# With several hubs (e.g. two primary machines sharing vaults through
|
|
12
|
+
# iCloud), requests go to the hub that answered last, then the others. Only
|
|
13
|
+
# an unreachable hub triggers failover; a hub that answers "no" is final, so
|
|
14
|
+
# a refusal on one hub can't be bypassed through another.
|
|
15
|
+
module Remote
|
|
16
|
+
DEFAULT_PURPOSE = "cli"
|
|
17
|
+
DEFAULT_WAIT = 120
|
|
18
|
+
POLL_INTERVAL = 3
|
|
19
|
+
AGENT_PATTERN = /\A[a-z0-9][a-z0-9._-]{0,62}\z/i
|
|
20
|
+
UNREACHABLE = "unreachable"
|
|
21
|
+
CONNECT_TIMEOUT = 5
|
|
22
|
+
|
|
23
|
+
TrustedHub = Data.define(:identity, :command) do
|
|
24
|
+
def name = identity.name
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
class Error < StandardError
|
|
28
|
+
attr_reader :code
|
|
29
|
+
|
|
30
|
+
def initialize(message, code: nil)
|
|
31
|
+
@code = code
|
|
32
|
+
super(message)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Runs a command (normally ssh) that speaks the envelope protocol over
|
|
37
|
+
# stdin/stdout, e.g. `ssh hub 2pass serve --stdio`.
|
|
38
|
+
class CommandTransport
|
|
39
|
+
def initialize(command)
|
|
40
|
+
@command = command
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def call(request_json)
|
|
44
|
+
stdout, stderr, status = Open3.capture3(*@command, stdin_data: request_json)
|
|
45
|
+
if stdout.strip.empty?
|
|
46
|
+
detail = stderr.strip.empty? ? "exit status #{status.exitstatus}" : stderr.strip
|
|
47
|
+
raise Error.new("Unable to reach the hub (#{@command.join(' ')}): #{detail}", code: UNREACHABLE)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
stdout
|
|
51
|
+
rescue Errno::ENOENT => e
|
|
52
|
+
raise Error.new("Unable to run hub command: #{e.message}", code: UNREACHABLE)
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
class Client
|
|
57
|
+
def initialize(identity:, hub:, transport:)
|
|
58
|
+
@identity = identity
|
|
59
|
+
@hub = hub
|
|
60
|
+
@transport = transport
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def call(body)
|
|
64
|
+
request_json, pending = Envelope.seal_request(body, identity: @identity, hub: @hub)
|
|
65
|
+
envelope = JSON.parse(@transport.call(request_json))
|
|
66
|
+
|
|
67
|
+
unless envelope.is_a?(Hash) && envelope["type"] == "response"
|
|
68
|
+
error = envelope.is_a?(Hash) ? envelope["error"] : nil
|
|
69
|
+
message = error.is_a?(Hash) ? error["message"] : nil
|
|
70
|
+
code = error.is_a?(Hash) ? error["code"] : nil
|
|
71
|
+
raise Error.new("Hub rejected the request: #{message || 'unexpected reply'}", code: code)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
Envelope.open_response(envelope, identity: @identity, hub: @hub, pending: pending)
|
|
75
|
+
rescue JSON::ParserError
|
|
76
|
+
raise Error, "Hub returned an invalid reply"
|
|
77
|
+
rescue Envelope::Error => e
|
|
78
|
+
raise Error, "Hub reply rejected: #{e.message}"
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Like call, but raises when the hub answered with ok: false. While the
|
|
82
|
+
# hub says approval_required, keeps retrying (fresh request each time)
|
|
83
|
+
# for up to `wait` seconds.
|
|
84
|
+
def call!(body, wait: 0, sleeper: ->(seconds) { sleep(seconds) }, clock: -> { Time.now })
|
|
85
|
+
deadline = clock.call + wait
|
|
86
|
+
announced = nil
|
|
87
|
+
|
|
88
|
+
loop do
|
|
89
|
+
response = call(body)
|
|
90
|
+
return response if response["ok"]
|
|
91
|
+
|
|
92
|
+
error = response["error"] || {}
|
|
93
|
+
if error["code"] == "approval_required" && clock.call < deadline
|
|
94
|
+
if announced != error["approval_id"]
|
|
95
|
+
announced = error["approval_id"]
|
|
96
|
+
$stderr.puts "Waiting up to #{wait}s for approval on the hub: 2pass approve #{announced}"
|
|
97
|
+
end
|
|
98
|
+
sleeper.call(POLL_INTERVAL)
|
|
99
|
+
next
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
raise Error.new("Hub: #{error['message'] || 'request failed'}", code: error["code"])
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
class << self
|
|
108
|
+
# A hub this device can send requests to (has a transport command).
|
|
109
|
+
def configured?
|
|
110
|
+
hub_settings.any? { |h| Array(h["command"]).any? }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Trusts at least one primary, for requests or only to verify bundles.
|
|
114
|
+
def trusts_hubs?
|
|
115
|
+
hub_settings.any?
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def trusted_identities
|
|
119
|
+
hub_settings.map { |settings| identity_from(settings) }
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Reachable trusted hubs, the one that answered last first.
|
|
123
|
+
def hubs
|
|
124
|
+
list = hub_settings.select { |h| Array(h["command"]).any? }.map do |settings|
|
|
125
|
+
TrustedHub.new(identity: identity_from(settings), command: Array(settings["command"]))
|
|
126
|
+
end
|
|
127
|
+
raise Error, "No hub configured. Run: 2pass hub trust <token> --ssh 2pass-hub" if list.empty?
|
|
128
|
+
|
|
129
|
+
last = last_hub_fingerprint
|
|
130
|
+
list.each_with_index.sort_by { |hub, index| [hub.identity.fingerprint == last ? 0 : 1, index] }.map(&:first)
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Pins a hub's keys on this device (in addition to any already trusted).
|
|
134
|
+
# `confirm` gets the hub pairing code.
|
|
135
|
+
def trust(token, ssh: nil, command: nil, name: nil, confirm:)
|
|
136
|
+
Device.local_identity # the device needs an identity to talk to a hub
|
|
137
|
+
argv = transport_command(ssh: ssh, command: command)
|
|
138
|
+
identity = Device.parse_token(token)
|
|
139
|
+
name ||= identity.name
|
|
140
|
+
Device.validate_name!(name)
|
|
141
|
+
|
|
142
|
+
existing = hub_settings
|
|
143
|
+
if (same = existing.find { |h| h["fingerprint"] == identity.fingerprint })
|
|
144
|
+
raise Error, "This hub is already trusted as #{same['name']}"
|
|
145
|
+
end
|
|
146
|
+
if existing.any? { |h| h["name"] == name }
|
|
147
|
+
raise Error, "A hub named #{name} is already trusted. Pick another name with --name."
|
|
148
|
+
end
|
|
149
|
+
raise Error, "Pairing cancelled: the hub pairing code was not confirmed" unless confirm.call(identity.pairing_code, name)
|
|
150
|
+
|
|
151
|
+
pin(identity, name: name, command: argv)
|
|
152
|
+
if argv
|
|
153
|
+
"Trusting hub #{name} (#{identity.pairing_code}) via: #{argv.join(' ')}"
|
|
154
|
+
else
|
|
155
|
+
"Trusting #{name} (#{identity.pairing_code}) for bundles only (no connection)."
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Saves a primary's keys (bundles only, no command) after its pairing
|
|
160
|
+
# code was confirmed at first bundle import. Picks a free name.
|
|
161
|
+
def pin_bundle_signer(identity)
|
|
162
|
+
return if hub_settings.any? { |h| h["fingerprint"] == identity.fingerprint }
|
|
163
|
+
|
|
164
|
+
taken = hub_settings.map { |h| h["name"] }
|
|
165
|
+
name = identity.name
|
|
166
|
+
name = "#{identity.name}-#{(2..).find { |i| !taken.include?("#{identity.name}-#{i}") }}" if taken.include?(name)
|
|
167
|
+
pin(identity, name: name, command: nil)
|
|
168
|
+
name
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def remove(name)
|
|
172
|
+
remaining = hub_settings.reject { |h| h["name"] == name }
|
|
173
|
+
raise Error, "No trusted hub named #{name}" if remaining.size == hub_settings.size
|
|
174
|
+
|
|
175
|
+
save_hubs(remaining)
|
|
176
|
+
DeviceCache.new(identity: Device.local_identity).clear
|
|
177
|
+
"No longer trusting hub #{name}. Cleared cached answers."
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def describe
|
|
181
|
+
return "No primary trusted yet." unless trusts_hubs?
|
|
182
|
+
|
|
183
|
+
last = last_hub_fingerprint
|
|
184
|
+
rows = hub_settings.map do |h|
|
|
185
|
+
command = Array(h["command"]).any? ? Array(h["command"]).join(" ") : "(bundles only)"
|
|
186
|
+
[h["name"], Device.pairing_code(h["fingerprint"]), command, h["fingerprint"] == last ? "yes" : ""]
|
|
187
|
+
end
|
|
188
|
+
Terminal::Table.new(headings: ["Hub", "Pairing code", "Command", "Used last"], rows: rows).to_s
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# Pings every trusted hub, reachable or not.
|
|
192
|
+
def ping(transport_factory: nil)
|
|
193
|
+
return "No hub to connect to: this device only uses bundles." unless configured?
|
|
194
|
+
|
|
195
|
+
me = Device.local_identity
|
|
196
|
+
hubs.map do |hub|
|
|
197
|
+
client = Client.new(identity: me, hub: hub.identity, transport: transport_for(hub, transport_factory))
|
|
198
|
+
response = client.call!({"operation" => "ping"})
|
|
199
|
+
"#{hub.name}: accepts this device as #{response['device']} (approval expires #{response['expires_at'] || 'never'})"
|
|
200
|
+
rescue Error => e
|
|
201
|
+
"#{hub.name}: #{e.message}"
|
|
202
|
+
end.join("\n")
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def get(vault, id, env:, purpose:, **options)
|
|
206
|
+
with_bundle_fallback(options, ->(bundle) { bundle.value(vault, env, id) }) do
|
|
207
|
+
cached_call(request("get", vault, env, purpose, options[:agent], "id" => id), **options).fetch("value")
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def list(vault, env:, purpose:, **options)
|
|
212
|
+
with_bundle_fallback(options, ->(bundle) { bundle.entries(vault, env) }) do
|
|
213
|
+
response = cached_call(request("list", vault, env, purpose, options[:agent]), **options)
|
|
214
|
+
response.fetch("entries").map { |entry| {id: entry.fetch("id"), value: entry.fetch("value")} }
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# Runs a policy-defined action on the hub; never cached.
|
|
219
|
+
def use(vault, action, env:, purpose:, **options)
|
|
220
|
+
body = request("use", vault, env, purpose, options[:agent], "action" => action.to_s)
|
|
221
|
+
with_revocation_check(options) do
|
|
222
|
+
with_failover(options) { |client| client.call!(body, wait: wait_for(options)) }
|
|
223
|
+
end
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def cache(identity: Device.local_identity)
|
|
227
|
+
DeviceCache.new(identity: identity)
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
def clear_cache
|
|
231
|
+
DeviceCache.new(identity: Device.local_identity).clear
|
|
232
|
+
"Cleared the local cache of hub answers."
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def agent_from_env
|
|
236
|
+
ENV["TWOPASS_AGENT"].to_s.empty? ? nil : ENV["TWOPASS_AGENT"]
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
private
|
|
240
|
+
|
|
241
|
+
# Ask a reachable hub when one is configured; use the installed bundle
|
|
242
|
+
# when there is none, or when every hub is unreachable.
|
|
243
|
+
def with_bundle_fallback(options, from_bundle)
|
|
244
|
+
if configured? || options[:client]
|
|
245
|
+
begin
|
|
246
|
+
return yield
|
|
247
|
+
rescue Error => e
|
|
248
|
+
raise unless e.code == UNREACHABLE && Bundle.present?
|
|
249
|
+
end
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
from_bundle.call(Bundle.current!)
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
# Answers the hub allowed to be cached are served locally until they
|
|
256
|
+
# expire; otherwise ask the hub and store the answer for its cache_ttl.
|
|
257
|
+
def cached_call(body, **options)
|
|
258
|
+
cache = options.fetch(:cache) { self.cache } unless options[:no_cache]
|
|
259
|
+
key = body # the same answer is valid whichever trusted hub gave it
|
|
260
|
+
if cache && (hit = cache.fetch(key))
|
|
261
|
+
return hit
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
response = with_revocation_check(options, cache) do
|
|
265
|
+
with_failover(options) { |client| client.call!(body, wait: wait_for(options)) }
|
|
266
|
+
end
|
|
267
|
+
cache&.store(key, response.except("cache_ttl"), ttl: response["cache_ttl"])
|
|
268
|
+
response
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
# A hub that no longer accepts this device means cached answers must go.
|
|
272
|
+
# Applies even with --no-cache: the device no longer has any right to
|
|
273
|
+
# what it cached.
|
|
274
|
+
def with_revocation_check(options, cache = nil)
|
|
275
|
+
yield
|
|
276
|
+
rescue Error => e
|
|
277
|
+
(cache || options.fetch(:cache) { self.cache })&.clear if e.code == "unauthenticated"
|
|
278
|
+
raise
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
# Runs the block with a client for each trusted hub in turn until one is
|
|
282
|
+
# reachable. options[:client] pins a single client (tests);
|
|
283
|
+
# options[:transport_factory] builds transports from a TrustedHub.
|
|
284
|
+
def with_failover(options)
|
|
285
|
+
return yield(options[:client]) if options[:client]
|
|
286
|
+
|
|
287
|
+
me = Device.local_identity
|
|
288
|
+
failures = []
|
|
289
|
+
hubs.each do |hub|
|
|
290
|
+
client = Client.new(identity: me, hub: hub.identity, transport: transport_for(hub, options[:transport_factory]))
|
|
291
|
+
begin
|
|
292
|
+
result = yield(client)
|
|
293
|
+
remember_last_hub(hub.identity.fingerprint)
|
|
294
|
+
return result
|
|
295
|
+
rescue Error => e
|
|
296
|
+
raise unless e.code == UNREACHABLE
|
|
297
|
+
|
|
298
|
+
failures << "#{hub.name}: #{e.message}"
|
|
299
|
+
end
|
|
300
|
+
end
|
|
301
|
+
raise Error.new("No trusted hub could be reached:\n #{failures.join("\n ")}", code: UNREACHABLE)
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
def transport_for(hub, factory)
|
|
305
|
+
factory ? factory.call(hub) : CommandTransport.new(hub.command)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
# Legacy configs have a single `hub:`; newer ones a `hubs:` list.
|
|
309
|
+
def hub_settings
|
|
310
|
+
config = Encryption.config
|
|
311
|
+
Array(config["hubs"]) + (config["hub"] ? [config["hub"]] : [])
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
def pin(identity, name:, command:)
|
|
315
|
+
save_hubs(hub_settings + [{
|
|
316
|
+
"name" => name,
|
|
317
|
+
"fingerprint" => identity.fingerprint,
|
|
318
|
+
"sign_public_key" => Device.b64(identity.sign_public_key),
|
|
319
|
+
"box_public_key" => Device.b64(identity.box_public_key),
|
|
320
|
+
"command" => command
|
|
321
|
+
}.compact])
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
def save_hubs(list)
|
|
325
|
+
config = Encryption.config.except("hub")
|
|
326
|
+
Encryption.save_config(list.empty? ? config.except("hubs") : config.merge("hubs" => list))
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
def identity_from(settings)
|
|
330
|
+
identity = Device::PublicIdentity.new(
|
|
331
|
+
name: settings["name"].to_s,
|
|
332
|
+
sign_public_key: Device.unb64(settings["sign_public_key"]),
|
|
333
|
+
box_public_key: Device.unb64(settings["box_public_key"])
|
|
334
|
+
)
|
|
335
|
+
unless identity.fingerprint == settings["fingerprint"]
|
|
336
|
+
raise Error, "Keys for hub #{settings['name']} in #{Encryption.config_path} do not match its fingerprint"
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
identity
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def last_hub_path
|
|
343
|
+
File.join(TwoPass::VAULT_DIR, "last-hub")
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
def last_hub_fingerprint
|
|
347
|
+
File.file?(last_hub_path) ? File.read(last_hub_path).strip : nil
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
def remember_last_hub(fingerprint)
|
|
351
|
+
return if last_hub_fingerprint == fingerprint
|
|
352
|
+
|
|
353
|
+
Encryption.write_atomic(last_hub_path, fingerprint)
|
|
354
|
+
rescue SystemCallError
|
|
355
|
+
nil # only an ordering hint
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
def wait_for(options)
|
|
359
|
+
options.fetch(:wait, DEFAULT_WAIT).to_i
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
def request(operation, vault, env, purpose, agent, extra = {})
|
|
363
|
+
if agent && !AGENT_PATTERN.match?(agent.to_s)
|
|
364
|
+
raise Error, "Invalid agent name #{agent.inspect}: use letters, digits, '.', '_' or '-'"
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
{
|
|
368
|
+
"operation" => operation,
|
|
369
|
+
"vault" => vault.to_s,
|
|
370
|
+
"env" => env&.to_s,
|
|
371
|
+
"purpose" => (purpose || DEFAULT_PURPOSE).to_s,
|
|
372
|
+
"agent" => agent&.to_s
|
|
373
|
+
}.compact.merge(extra)
|
|
374
|
+
end
|
|
375
|
+
|
|
376
|
+
def transport_command(ssh:, command:)
|
|
377
|
+
if ssh && command
|
|
378
|
+
raise Error, "Use either --ssh or --command, not both"
|
|
379
|
+
elsif ssh
|
|
380
|
+
["ssh", "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=#{CONNECT_TIMEOUT}", ssh, "2pass", "serve", "--stdio"]
|
|
381
|
+
elsif command
|
|
382
|
+
Shellwords.split(command)
|
|
383
|
+
end # neither: trusted for bundles only
|
|
384
|
+
end
|
|
385
|
+
end
|
|
386
|
+
end
|
|
387
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TwoPass
|
|
4
|
+
# Request ids the hub has already accepted, kept long enough to cover the
|
|
5
|
+
# timestamp window.
|
|
6
|
+
class ReplayCache
|
|
7
|
+
def self.default_path
|
|
8
|
+
File.join(TwoPass::VAULT_DIR, "replay-cache.json")
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def initialize(path: self.class.default_path, retention: Envelope::MAX_SKEW * 2)
|
|
12
|
+
@path = path
|
|
13
|
+
@retention = retention
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Returns false if the id was already seen, otherwise records it.
|
|
17
|
+
def check_and_store(id, now: Time.now)
|
|
18
|
+
LockedJsonFile.update(@path) do |seen|
|
|
19
|
+
seen.reject! { |_id, ts| !ts.is_a?(Integer) || ts < now.to_i - @retention }
|
|
20
|
+
next false if seen.key?(id)
|
|
21
|
+
|
|
22
|
+
seen[id] = now.to_i
|
|
23
|
+
true
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
data/lib/2pass/server.rb
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module TwoPass
|
|
6
|
+
# Hub side of `2pass serve`: one envelope in, one envelope out.
|
|
7
|
+
#
|
|
8
|
+
# The caller's identity comes only from the verified envelope. The request
|
|
9
|
+
# body is handed to the broker with the device name as the actor, so access
|
|
10
|
+
# is whatever broker-policy.yml grants that device (nothing by default).
|
|
11
|
+
class Server
|
|
12
|
+
MAX_REQUEST_BYTES = 1_048_576
|
|
13
|
+
|
|
14
|
+
def initialize(identity:, registry: DeviceRegistry.new, replay_cache: ReplayCache.new,
|
|
15
|
+
policy_path: Broker.default_policy_path, clock: -> { Time.now })
|
|
16
|
+
@identity = identity
|
|
17
|
+
@registry = registry
|
|
18
|
+
@replay_cache = replay_cache
|
|
19
|
+
@policy_path = policy_path
|
|
20
|
+
@clock = clock
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def handle_json(input)
|
|
24
|
+
if input.bytesize > MAX_REQUEST_BYTES
|
|
25
|
+
return rejection("request_too_large", "Request is too large")
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
envelope = JSON.parse(input)
|
|
29
|
+
return rejection("invalid_request", "Request must be a JSON object") unless envelope.is_a?(Hash)
|
|
30
|
+
|
|
31
|
+
now = @clock.call
|
|
32
|
+
request = Envelope.open_request(
|
|
33
|
+
envelope, hub_identity: @identity, registry: @registry, replay_cache: @replay_cache, now: now
|
|
34
|
+
)
|
|
35
|
+
Envelope.seal_response(dispatch(request), hub_identity: @identity, request: request, now: now)
|
|
36
|
+
rescue JSON::ParserError
|
|
37
|
+
rejection("invalid_json", "Request is not valid JSON")
|
|
38
|
+
rescue Envelope::Rejected => e
|
|
39
|
+
rejection(e.code, e.message)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def dispatch(request)
|
|
45
|
+
device = request.device
|
|
46
|
+
case request.body["operation"]
|
|
47
|
+
when "ping"
|
|
48
|
+
{ok: true, operation: "ping", device: device["name"], expires_at: device["expires_at"]}
|
|
49
|
+
else
|
|
50
|
+
result = Broker.new(policy_path: @policy_path, principal: principal(request), clock: @clock)
|
|
51
|
+
.handle(request.body)
|
|
52
|
+
cap_cache_ttl(result, device)
|
|
53
|
+
end
|
|
54
|
+
rescue StandardError => e
|
|
55
|
+
{ok: false, error: {code: "hub_error", message: e.message}}
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# "laptop" for the device itself, "laptop/claude" for an agent on it. The
|
|
59
|
+
# agent label is chosen by the device: it scopes grants, approvals and
|
|
60
|
+
# cache entries, but is not a boundary against code running as the same
|
|
61
|
+
# OS user as the device key.
|
|
62
|
+
def principal(request)
|
|
63
|
+
agent = request.body["agent"]
|
|
64
|
+
return request.device["name"] if agent.nil? || agent.to_s.empty?
|
|
65
|
+
raise ArgumentError, "Invalid agent name" unless Remote::AGENT_PATTERN.match?(agent.to_s)
|
|
66
|
+
|
|
67
|
+
"#{request.device['name']}/#{agent}"
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Never let a device cache an answer past its own approval.
|
|
71
|
+
def cap_cache_ttl(result, device)
|
|
72
|
+
return result unless result.is_a?(Hash) && result[:cache_ttl]
|
|
73
|
+
return result unless device["expires_at"]
|
|
74
|
+
|
|
75
|
+
remaining = Time.iso8601(device["expires_at"]).to_i - @clock.call.to_i
|
|
76
|
+
result.merge(cache_ttl: [result[:cache_ttl], remaining].min)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Unauthenticated, unencrypted error for requests the hub could not verify.
|
|
80
|
+
def rejection(code, message)
|
|
81
|
+
JSON.generate(ok: false, error: {code: code, message: message})
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
data/lib/2pass/version.rb
CHANGED