diff options
Diffstat (limited to 'app/models')
-rw-r--r-- | app/models/identity.rb | 5 | ||||
-rw-r--r-- | app/models/keyring.rb | 55 |
2 files changed, 60 insertions, 0 deletions
diff --git a/app/models/identity.rb b/app/models/identity.rb index 92f8f7a..b8c2245 100644 --- a/app/models/identity.rb +++ b/app/models/identity.rb @@ -136,6 +136,11 @@ class Identity < CouchRest::Model::Base write_attribute('keys', keys.merge(type => key.to_s)) end + def delete_key(type) + raise 'key not found' unless keys[type] + write_attribute('keys', keys.except(type)) + end + def cert_fingerprints read_attribute('cert_fingerprints') || Hash.new end diff --git a/app/models/keyring.rb b/app/models/keyring.rb new file mode 100644 index 0000000..66f7bfd --- /dev/null +++ b/app/models/keyring.rb @@ -0,0 +1,55 @@ +# +# Keyring +# +# A collection of cryptographic keys. +# + +class Keyring + class Error < RuntimeError + end + + class NotFound < Error + def initialize(type) + super "no such key: #{type}" + end + end + + def initialize(storage) + @storage = storage + end + + def create(type, value) + raise Error, "key already exists" if storage.keys[type].present? + storage.set_key type, {type: type, value: value, rev: new_rev}.to_json + storage.save + end + + def update(type, rev:, value:) + check_rev type, rev + storage.set_key type, {type: type, value: value, rev: new_rev}.to_json + storage.save + end + + def delete(type, rev:) + check_rev type, rev + storage.delete_key type + storage.save + end + + def key_of_type(type) + JSON.parse(storage.keys[type]) if storage.keys[type] + end + + protected + attr_reader :storage + + def check_rev(type, rev) + old = key_of_type(type) + raise NotFound, type unless old + raise Error, "wrong revision: #{rev}" unless old['rev'] == rev + end + + def new_rev + SecureRandom.urlsafe_base64(8) + end +end |