2pass 2.2.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.
data/lib/2pass.rb CHANGED
@@ -10,6 +10,18 @@ require "rubygems/version"
10
10
  require "terminal-table"
11
11
 
12
12
  require_relative "2pass/version"
13
+ require_relative "2pass/encryption"
14
+ require_relative "2pass/device"
15
+ require_relative "2pass/device_registry"
16
+ require_relative "2pass/envelope"
17
+ require_relative "2pass/locked_json_file"
18
+ require_relative "2pass/approvals"
19
+ require_relative "2pass/device_cache"
20
+ require_relative "2pass/replay_cache"
21
+ require_relative "2pass/server"
22
+ require_relative "2pass/remote"
23
+ require_relative "2pass/bundle"
24
+ require_relative "2pass/policy"
13
25
 
14
26
  module TwoPass
15
27
  VAULT_DIR = "#{Dir.home}/.2pass"
@@ -17,8 +29,12 @@ module TwoPass
17
29
  class << self
18
30
  def create_symlink(vault_name, target_path, env: nil)
19
31
  FileUtils.mkdir_p(VAULT_DIR)
20
- symlink_path = vault_file_path(vault_name, env: env)
21
32
  expanded_target_path = File.expand_path(target_path)
33
+ symlink_path = if expanded_target_path.end_with?(Encryption::FILE_SUFFIX)
34
+ encrypted_vault_file_path(vault_name, env: env)
35
+ else
36
+ vault_file_path(vault_name, env: env)
37
+ end
22
38
 
23
39
  unless File.exist?(expanded_target_path)
24
40
  raise "Target vault file does not exist: #{expanded_target_path}"
@@ -46,14 +62,184 @@ module TwoPass
46
62
  puts "Created symlink: #{symlink_path} -> #{expanded_target_path}"
47
63
  end
48
64
 
65
+ # Saves in the vault's current format. A new vault is created encrypted
66
+ # when a master key is configured (`2pass key init`), plaintext otherwise.
67
+ # A new vault goes to the shared folder when one is set, so the other
68
+ # primary machines see it.
49
69
  def save_vault(vault_name, data, env: nil)
50
70
  FileUtils.mkdir_p(VAULT_DIR)
51
- file_path = vault_file_path(vault_name, env: env)
52
- File.write(file_path, YAML.dump(data))
71
+ file_path, format = existing_vault_file(vault_name, env: env)
72
+ format ||= Encryption.enabled? ? :encrypted : :plain
73
+ new_dir = shared_dir || VAULT_DIR
74
+
75
+ if format == :encrypted
76
+ file_path ||= encrypted_vault_file_path(vault_name, env: env, dir: new_dir)
77
+ Encryption.write_atomic(
78
+ file_path,
79
+ Encryption.encrypt(YAML.dump(data), vault: vault_name, env: env)
80
+ )
81
+ else
82
+ File.write(file_path || vault_file_path(vault_name, env: env, dir: new_dir), YAML.dump(data))
83
+ end
84
+ end
85
+
86
+ # Folder shared by the primary machines (e.g. in iCloud Drive) holding
87
+ # vaults, devices.yml and broker-policy.yml. Keys, approvals and the replay
88
+ # cache always stay in ~/.2pass.
89
+ def shared_dir
90
+ dir = Encryption.config["shared_dir"]
91
+ dir && File.expand_path(dir)
92
+ end
93
+
94
+ SHARED_FILES = %w[devices.yml broker-policy.yml].freeze
95
+
96
+ def share_state(dir)
97
+ dir = File.expand_path(dir)
98
+ raise "Shared folder does not exist: #{dir}" unless File.directory?(dir)
99
+
100
+ moved = []
101
+ SHARED_FILES.each do |file|
102
+ local = File.join(VAULT_DIR, file)
103
+ shared = File.join(dir, file)
104
+ next unless File.file?(local) && !File.symlink?(local)
105
+
106
+ if File.exist?(shared)
107
+ raise "Both #{local} and #{shared} exist. Merge them by hand, delete the local one, then run this again."
108
+ end
109
+ FileUtils.mv(local, shared)
110
+ moved << file
111
+ end
112
+
113
+ Encryption.save_config(Encryption.config.merge("shared_dir" => dir))
114
+ message = +"This machine now reads vaults, approved devices and the broker policy from #{dir}."
115
+ message << "\nMoved: #{moved.join(', ')}." if moved.any?
116
+ message << "\nRun the same command on your other primary machine(s), pointing at the same synced folder."
117
+ if Encryption.enabled?
118
+ message << "\nWarning: vault encryption is on, but devices.yml and the policy are not signed yet;"
119
+ message << "\nanyone able to write to the shared folder could approve a device."
120
+ end
121
+ message
122
+ end
123
+
124
+ def init_device(name: nil, key_store: nil)
125
+ Device.init(name: name, key_store: key_store)
126
+ Device.describe_local
127
+ end
128
+
129
+ # Approves a device on the hub. `confirm` receives the pairing code and must
130
+ # return true only if a human checked it matches the code on the device.
131
+ # Approves a device on the hub and makes sure broker-policy.yml has an
132
+ # entry for it. Access is never granted implicitly: `grants` (vault/env
133
+ # specs) or the `choose` callback (interactive pick) decide what it gets.
134
+ def approve_device(token, name: nil, expires_in: nil, confirm:, grants: [], choose: nil)
135
+ identity = Device.parse_token(token)
136
+ targets = grants.map { |spec| Policy.parse_target(spec) }
137
+ missing = targets - Policy.available_targets
138
+ raise "Vault not found on this machine: #{missing.join(', ')}" if missing.any?
139
+ unless confirm.call(identity.pairing_code, name || identity.name)
140
+ raise "Pairing cancelled: the pairing code was not confirmed"
141
+ end
142
+
143
+ entry = DeviceRegistry.new.approve(identity, name: name, expires_in_days: parse_expiry(expires_in))
144
+ message = +"Approved #{entry['name']} (#{identity.pairing_code}), expires #{entry['expires_at'] || 'never'}."
145
+ message << "\n#{update_policy_for(entry['name'], targets, choose)}"
146
+ if Device.configured?
147
+ message << "\n\nOn #{entry['name']}, trust this machine with:"
148
+ message << "\n 2pass hub trust #{Device.local_identity.pairing_token}"
149
+ message << "\nand check it shows pairing code #{Device.local_identity.public_identity.pairing_code}."
150
+ message << "\nThat is enough for bundles (2pass bundle export #{entry['name']}). To let it connect here"
151
+ message << "\ninstead, add --ssh 2pass-hub (a Host alias in its ~/.ssh/config; see README)."
152
+ else
153
+ message << "\nThis hub has no device identity yet; run `2pass device init` here before devices can trust it."
154
+ end
155
+ message
156
+ end
157
+
158
+ def grant_access(actor, specs)
159
+ added = Policy.new.grant(actor, specs.map { |spec| Policy.parse_target(spec) })
160
+ return "#{actor} already had read access to #{specs.join(', ')}." if added.empty?
161
+
162
+ "Granted #{actor} read access to #{added.join(', ')} (all secrets, get/list)."
163
+ end
164
+
165
+ def update_policy_for(actor, targets, choose)
166
+ policy = Policy.new
167
+ path = Broker.default_policy_path
168
+ if policy.actor?(actor)
169
+ added = targets.any? ? policy.grant(actor, targets) : []
170
+ text = +"#{path} already has an entry for #{actor} (#{policy.grants(actor).size} grant(s)); left as is."
171
+ text = +"Added to the existing entry for #{actor}: #{added.join(', ')}." if added.any?
172
+ return text
173
+ end
174
+
175
+ targets = choose.call(actor, Policy.available_targets) if targets.empty? && choose
176
+ added = policy.grant(actor, Array(targets))
177
+ if added.any?
178
+ "New policy entry for #{actor}: read access to #{added.join(', ')} (all secrets, get/list)."
179
+ else
180
+ "New policy entry for #{actor}, with no access yet. Grant some with: 2pass policy grant #{actor} <vault[:env]>"
181
+ end
182
+ end
183
+
184
+ def revoke_device(name)
185
+ DeviceRegistry.new.revoke(name)
186
+ "Revoked #{name}. Rotate any secret this device was able to read."
187
+ end
188
+
189
+ def renew_device(name, expires_in: nil)
190
+ entry = DeviceRegistry.new.renew(name, expires_in_days: parse_expiry(expires_in))
191
+ "Renewed #{name}, expires #{entry['expires_at'] || 'never'}."
53
192
  end
54
193
 
55
- def list_content(vault_name, env: nil, format: :table)
56
- vault = load_vault(vault_name, env: env)
194
+ def init_encryption(key_store: nil)
195
+ store = Encryption.init(key_store: key_store || Encryption.default_key_store)
196
+ message = +"Master key created in #{store.description}."
197
+ message << "\nNew vaults will be encrypted. Encrypt existing ones with: 2pass migrate encrypt <vault_name> [env]"
198
+ message << "\nBack up this key now: without it, encrypted vaults cannot be recovered."
199
+ message
200
+ end
201
+
202
+ # Converts a plaintext vault to an encrypted one, verifies the result, then
203
+ # removes the local plaintext entry unless keep_plaintext is set.
204
+ def encrypt_vault(vault_name, env: nil, keep_plaintext: false)
205
+ plain_path = vault_file_path(vault_name, env: env)
206
+ encrypted_path = encrypted_vault_file_path(vault_name, env: env)
207
+
208
+ raise "Encryption is not configured. Run: 2pass key init" unless Encryption.enabled?
209
+ raise "Vault is already encrypted: #{encrypted_path}" if File.exist?(encrypted_path) || File.symlink?(encrypted_path)
210
+ raise missing_vault_error_message(vault_name, plain_path, env: env) unless File.exist?(plain_path)
211
+
212
+ data = load_vault(vault_name, env: env)
213
+ Encryption.write_atomic(encrypted_path, Encryption.encrypt(YAML.dump(data), vault: vault_name, env: env))
214
+
215
+ decrypted = YAML.load(Encryption.decrypt(File.read(encrypted_path), vault: vault_name, env: env), symbolize_names: true)
216
+ unless decrypted == data
217
+ FileUtils.rm_f(encrypted_path)
218
+ raise "Verification failed after encrypting #{vault_name}; plaintext vault left untouched"
219
+ end
220
+
221
+ message = +"Encrypted #{data.size} secret(s) into #{encrypted_path}"
222
+ if keep_plaintext
223
+ message << "\nPlaintext copy kept at #{plain_path}. Remove it once you no longer need it."
224
+ elsif File.symlink?(plain_path)
225
+ target = File.expand_path(File.readlink(plain_path), File.dirname(plain_path))
226
+ File.unlink(plain_path)
227
+ message << "\nRemoved symlink #{plain_path}."
228
+ message << "\nThe plaintext file it pointed to still exists: #{target}"
229
+ message << "\nDelete it (and from any synced location) once other devices no longer depend on it."
230
+ else
231
+ File.delete(plain_path)
232
+ message << "\nRemoved plaintext file #{plain_path}."
233
+ end
234
+ message
235
+ end
236
+
237
+ def list_content(vault_name, env: nil, format: :table, purpose: nil, **remote_options)
238
+ vault = if Remote.trusts_hubs?
239
+ Remote.list(vault_name, env: env, purpose: purpose, **remote_options)
240
+ else
241
+ load_vault(vault_name, env: env)
242
+ end
57
243
  if format == :table
58
244
  rows = vault
59
245
  .sort_by { |hash| hash[:id] }
@@ -80,6 +266,10 @@ module TwoPass
80
266
  end
81
267
 
82
268
  def add_secret(vault_name, id, value, env: nil)
269
+ if Remote.trusts_hubs?
270
+ raise "This device reads secrets from its primaries (hub or bundle); add secrets on a primary."
271
+ end
272
+
83
273
  new_secret = {
84
274
  id: id,
85
275
  value: value
@@ -93,14 +283,18 @@ module TwoPass
93
283
  save_vault(vault_name, data, env: env)
94
284
  end
95
285
 
96
- def get_secret(vault_name, id, env: nil)
97
- vault = load_vault(vault_name, env: env)
98
- entry = vault.find { |hash| hash[:id] == id }
99
- if entry
100
- entry[:value]
101
- else
102
- raise "Entry not found"
286
+ def get_secret(vault_name, id, env: nil, purpose: nil, **remote_options)
287
+ return Remote.get(vault_name, id, env: env, purpose: purpose, **remote_options) if Remote.trusts_hubs?
288
+
289
+ local_secret(vault_name, id, env: env)
290
+ end
291
+
292
+ def use_action(vault_name, action, env: nil, purpose: nil, **remote_options)
293
+ unless Remote.configured?
294
+ raise "`use` runs actions on a hub this device can reach (bundles can't run actions). Locally, use `2pass broker`."
103
295
  end
296
+
297
+ Remote.use(vault_name, action, env: env, purpose: purpose, **remote_options)
104
298
  end
105
299
 
106
300
  def update_cli
@@ -121,15 +315,30 @@ module TwoPass
121
315
 
122
316
  private
123
317
 
318
+ # Reads a secret from this machine's own vault files (never the hub).
319
+ def local_secret(vault_name, id, env: nil)
320
+ entry = load_vault(vault_name, env: env).find { |hash| hash[:id] == id }
321
+ raise "Entry not found" unless entry
322
+
323
+ entry[:value]
324
+ end
325
+
124
326
  def load_vault(vault_name, env: nil, allow_missing: false)
125
- file_path = self.vault_file_path(vault_name, env: env)
126
- unless File.exist?(file_path)
327
+ file_path, format = existing_vault_file(vault_name, env: env)
328
+ unless file_path
127
329
  return [] if allow_missing
128
330
 
129
- raise missing_vault_error_message(vault_name, file_path, env: env)
331
+ raise missing_vault_error_message(vault_name, vault_file_path(vault_name, env: env), env: env)
130
332
  end
131
333
 
132
- YAML.load_file(file_path, symbolize_names: true) || []
334
+ if format == :encrypted
335
+ plaintext = Encryption.decrypt(File.read(file_path), vault: vault_name, env: env)
336
+ YAML.load(plaintext, symbolize_names: true) || []
337
+ else
338
+ YAML.load_file(file_path, symbolize_names: true) || []
339
+ end
340
+ rescue Encryption::Error => e
341
+ raise "#{e.message} (#{file_path})"
133
342
  rescue Errno::EACCES, Errno::EPERM => e
134
343
  raise permission_error_message(file_path, e)
135
344
  rescue Psych::SyntaxError => e
@@ -137,10 +346,35 @@ module TwoPass
137
346
  []
138
347
  end
139
348
 
349
+ # Returns [path, :encrypted | :plain] for the vault on disk, or nil.
350
+ # When both exist (e.g. `migrate encrypt --keep-plaintext`), the encrypted
351
+ # file wins and a reminder about the plaintext copy goes to STDERR.
352
+ # Looks in ~/.2pass first (files and `link` symlinks), then in the shared
353
+ # folder when one is set (`2pass hub share`).
354
+ def existing_vault_file(vault_name, env: nil)
355
+ [VAULT_DIR, shared_dir].compact.uniq.each do |dir|
356
+ plain_path = vault_file_path(vault_name, env: env, dir: dir)
357
+ encrypted_path = encrypted_vault_file_path(vault_name, env: env, dir: dir)
358
+
359
+ if File.exist?(encrypted_path)
360
+ if File.exist?(plain_path)
361
+ $stderr.puts "Warning: plaintext copy of an encrypted vault still exists: #{plain_path}"
362
+ end
363
+ return [encrypted_path, :encrypted]
364
+ elsif File.exist?(plain_path)
365
+ return [plain_path, :plain]
366
+ end
367
+ end
368
+ nil
369
+ end
370
+
140
371
  def missing_vault_error_message(vault_name, file_path, env: nil)
141
372
  link_args = [vault_name, "<path-to-vault>", env].compact.join(" ")
142
373
  add_args = [vault_name, "<id>", "<value>", env].compact.join(" ")
143
374
 
375
+ encrypted_path = encrypted_vault_file_path(vault_name, env: env)
376
+ file_path = encrypted_path if File.symlink?(encrypted_path)
377
+
144
378
  if File.symlink?(file_path)
145
379
  target = File.expand_path(File.readlink(file_path), File.dirname(file_path))
146
380
  message = +"Vault symlink is broken: #{file_path} -> #{target}"
@@ -161,13 +395,26 @@ module TwoPass
161
395
  message
162
396
  end
163
397
 
164
- def vault_file_path(vault_name, env: nil)
398
+ def vault_file_path(vault_name, env: nil, dir: VAULT_DIR)
165
399
  [
166
- VAULT_DIR,
400
+ dir,
167
401
  [vault_name, env].compact.join(".")
168
402
  ].join("/") + ".yml"
169
403
  end
170
404
 
405
+ def parse_expiry(value)
406
+ return DeviceRegistry::DEFAULT_EXPIRY_DAYS if value.nil?
407
+ return nil if value.to_s == "never"
408
+
409
+ Integer(value.to_s, 10)
410
+ rescue ArgumentError
411
+ raise "Invalid --expires-in value #{value.inspect}: use a number of days or 'never'"
412
+ end
413
+
414
+ def encrypted_vault_file_path(vault_name, env: nil, dir: VAULT_DIR)
415
+ vault_file_path(vault_name, env: env, dir: dir) + Encryption::FILE_SUFFIX
416
+ end
417
+
171
418
  def permission_error_message(file_path, error)
172
419
  message = +"Unable to read vault file: #{file_path}\n#{error.class}: #{error.message}"
173
420
  symlink_target = nil
@@ -219,3 +466,5 @@ module TwoPass
219
466
  end
220
467
  end
221
468
  end
469
+
470
+ require_relative "2pass/broker"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: 2pass
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.0
4
+ version: 2.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Olivier
@@ -99,6 +99,19 @@ files:
99
99
  - bin/console
100
100
  - bin/setup
101
101
  - lib/2pass.rb
102
+ - lib/2pass/approvals.rb
103
+ - lib/2pass/broker.rb
104
+ - lib/2pass/bundle.rb
105
+ - lib/2pass/device.rb
106
+ - lib/2pass/device_cache.rb
107
+ - lib/2pass/device_registry.rb
108
+ - lib/2pass/encryption.rb
109
+ - lib/2pass/envelope.rb
110
+ - lib/2pass/locked_json_file.rb
111
+ - lib/2pass/policy.rb
112
+ - lib/2pass/remote.rb
113
+ - lib/2pass/replay_cache.rb
114
+ - lib/2pass/server.rb
102
115
  - lib/2pass/version.rb
103
116
  homepage: https://2pass.xyz
104
117
  licenses:
@@ -118,7 +131,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
118
131
  - !ruby/object:Gem::Version
119
132
  version: '0'
120
133
  requirements: []
121
- rubygems_version: 4.0.3
134
+ rubygems_version: 4.0.23
122
135
  specification_version: 4
123
136
  summary: A CLI app for managing secrets
124
137
  test_files: []