vanishly 4.2.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c3c65b1352c41e4059c3d15e53f7bb267c844869fc6c4f111c7dd2e472da7555
4
+ data.tar.gz: 05fded67d8dbb68c85e325e143ea837ad00323501eb2dc91e47b552515f24254
5
+ SHA512:
6
+ metadata.gz: 746a79f951c013870b30f7d0b7a0570df23829a1944cd06fd01b8c4e472495d16643f66d80a4d4f7d2abd884af578a67439a6fb0dca737c215d519b10f2548a5
7
+ data.tar.gz: ba2fbd8260d2a3f313e776e0c5803693c9bd717c634ab5b031ac29b9788006aaa4cdcc13420c73305b052eb452baec142c1a54f0764cdede7a6721894d1253b3
data/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # vanishly (Ruby)
2
+
3
+ Client for [Vanishly](https://github.com/DennisPohlmann/Vanishly), one-time
4
+ secrets, for Ruby 3.1+, without dependencies besides OpenSSL.
5
+
6
+ Full documentation: [docs/CLIENTS.md](https://github.com/DennisPohlmann/Vanishly/blob/main/docs/CLIENTS.md). End-to-end encrypted (crypto format v1, the same as the web pages): the secret, the key and the passphrase never reach the server; the key is only in the link's `#` part.
7
+
8
+ ```bash
9
+ gem install vanishly
10
+ ```
11
+
12
+ ```ruby
13
+ require "vanishly"
14
+
15
+ c = Vanishly::Client.new("https://ots.example.com") # token: "vnly_..." with sign-in
16
+ res = c.create("s3cret", "", ttl: 3600, views: 1)
17
+ puts res["shareUrl"], res["receiptUrl"]
18
+ puts c.open(res["shareUrl"])["secret"]
19
+ ```
20
+
21
+ Every endpoint has a method (`receipt`, `burn`, `me`, `tokens`, `audit`,
22
+ ...); `request(method, path, body)` calls any other. API errors raise
23
+ `Vanishly::ApiError`.
@@ -0,0 +1,177 @@
1
+ require "json"
2
+ require "net/http"
3
+ require "uri"
4
+ require "erb"
5
+
6
+ module Vanishly
7
+ # An answer other than 2xx: status, error code, message and the whole body.
8
+ class ApiError < StandardError
9
+ attr_reader :status, :error, :body
10
+
11
+ def initialize(status, error, message, body)
12
+ super("#{status} #{error}: #{message}")
13
+ @status = status
14
+ @error = error
15
+ @body = body
16
+ end
17
+ end
18
+
19
+ LINK = %r{\A(https?://[^#]+?)/s/([A-Za-z0-9_-]{22})#([A-Za-z0-9_-]{43})\z}
20
+ OPTIONS = %w[ttl views confirmed recipients recipientGroups responsible responsibleGroups comment].freeze
21
+
22
+ # Splits https://host/s/<id>#<key> into [base, id, key].
23
+ def self.parse_link(link)
24
+ m = LINK.match(link.to_s.strip) or raise ArgumentError, "not a secret link: https://.../s/<id>#<key>"
25
+ [m[1], m[2], m[3]]
26
+ end
27
+
28
+ # One Vanishly server. token: a personal API token (vnly_...) or a provider token.
29
+ class Client
30
+ attr_reader :base_url, :recommended_version
31
+ attr_accessor :run_id, :comment, :on_behalf_of, :client_name, :timeout
32
+
33
+ def initialize(base_url, token: nil, run_id: nil, comment: nil, on_behalf_of: nil, timeout: 30)
34
+ raise ArgumentError, "base_url must start with https:// or http://" unless base_url.to_s.match?(%r{\Ahttps?://})
35
+
36
+ @base_url = base_url.sub(%r{/+\z}, "")
37
+ @token = token
38
+ @run_id = run_id
39
+ @comment = comment
40
+ @on_behalf_of = on_behalf_of
41
+ @client_name = "ruby"
42
+ @timeout = timeout
43
+ @recommended_version = nil
44
+ end
45
+
46
+ # Any API call; path below /api ("/v1/config"). raw: return the body as text.
47
+ def request(method, path, body = nil, query = nil, raw: false)
48
+ uri = URI("#{@base_url}/api#{path}")
49
+ q = (query || {}).reject { |_, v| v.nil? || v == "" }
50
+ uri.query = URI.encode_www_form(q) unless q.empty?
51
+ req = Net::HTTPGenericRequest.new(method.to_s.upcase, !body.nil?, true, uri)
52
+ req["Accept"] = "application/json"
53
+ req["User-Agent"] = "vanishly-#{@client_name}/#{VERSION}"
54
+ req["X-Vanishly-Client"] = "#{@client_name}/#{VERSION}"
55
+ req["Authorization"] = "Bearer #{@token}" if @token && !@token.empty?
56
+ req["X-Run-Id"] = @run_id if @run_id
57
+ req["X-Audit-Comment"] = ERB::Util.url_encode(@comment) if @comment
58
+ req["X-On-Behalf-Of"] = @on_behalf_of if @on_behalf_of
59
+ unless body.nil?
60
+ req["Content-Type"] = "application/json"
61
+ req.body = JSON.generate(body)
62
+ end
63
+ res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: @timeout, read_timeout: @timeout) { |h| h.request(req) }
64
+ @recommended_version = res["X-Vanishly-Client-Recommended"] if res["X-Vanishly-Client-Recommended"]
65
+ text = res.body.to_s.force_encoding("UTF-8")
66
+ unless res.is_a?(Net::HTTPSuccess)
67
+ b = begin
68
+ JSON.parse(text)
69
+ rescue JSON::ParserError
70
+ {}
71
+ end
72
+ b = {} unless b.is_a?(Hash)
73
+ raise ApiError.new(res.code.to_i, b["error"] || "http_error", b["message"] || res.message, b)
74
+ end
75
+ return text if raw
76
+
77
+ text.empty? ? nil : JSON.parse(text)
78
+ end
79
+
80
+ # Encrypts here and stores it (POST /v1/secrets); adds shareUrl and receiptUrl.
81
+ def create(secret, passphrase = "", **options)
82
+ key, payload = Crypto.encrypt_secret(secret, passphrase)
83
+ res = create_secret(payload.merge(opts(options)))
84
+ res["shareUrl"] = "#{@base_url}#{res['secretPath']}##{key}"
85
+ res["receiptUrl"] = res["receiptPath"] ? "#{@base_url}#{res['receiptPath']}##{key}" : nil
86
+ res
87
+ end
88
+
89
+ # Takes one view and decrypts here. Returns {"secret", "viewsLeft"}.
90
+ def open(link, passphrase = "")
91
+ base, id, key = Vanishly.parse_link(link)
92
+ raise ArgumentError, "the link belongs to #{base}, not to #{@base_url}" unless base == @base_url
93
+
94
+ pk = "".b
95
+ verifier = nil
96
+ unless passphrase.to_s.empty?
97
+ meta = secret_meta(id)
98
+ if meta["passphrase"]
99
+ pk = Crypto.unlock_key(passphrase, meta["salt"], meta["iterations"])
100
+ verifier = Crypto.verifier_for(pk, meta["salt"])
101
+ end
102
+ end
103
+ payload = reveal(id, verifier)
104
+ { "secret" => Crypto.decrypt_secret(payload, key, pk), "viewsLeft" => payload["viewsLeft"] }
105
+ end
106
+
107
+ def index = request("GET", "/v1")
108
+ def config = request("GET", "/v1/config")
109
+ def downloads = request("GET", "/v1/downloads")
110
+ def create_secret(payload) = request("POST", "/v1/secrets", payload)
111
+
112
+ # Server-side encryption (POST /v1/share): the server sees the secret.
113
+ def share(secret, passphrase = "", **options)
114
+ b = opts(options).merge("secret" => secret)
115
+ b["passphrase"] = passphrase unless passphrase.to_s.empty?
116
+ request("POST", "/v1/share", b)
117
+ end
118
+
119
+ # Server-side reveal (POST /v1/open): the server sees key and secret.
120
+ def open_on_server(link, passphrase = "")
121
+ b = { "link" => link }
122
+ b["passphrase"] = passphrase unless passphrase.to_s.empty?
123
+ request("POST", "/v1/open", b)
124
+ end
125
+
126
+ def secret_meta(id) = request("GET", "/v1/secrets/#{seg(id)}")
127
+ def reveal(id, verifier = nil) = request("POST", "/v1/secrets/#{seg(id)}/reveal", verifier ? { "verifier" => verifier } : {})
128
+ def receipt(id) = request("GET", "/v1/receipts/#{seg(id)}")
129
+ def burn(id) = request("POST", "/v1/receipts/#{seg(id)}/burn", {})
130
+ def me = request("GET", "/v1/me")
131
+ def my_secrets(**q) = request("GET", "/v1/me/secrets", nil, q)
132
+ def my_secret(ref) = request("GET", "/v1/me/secrets/#{seg(ref)}")
133
+ def burn_my_secret(ref) = request("POST", "/v1/me/secrets/#{seg(ref)}/burn", {})
134
+ def groups(q = "") = request("GET", "/v1/groups", nil, { q: q })
135
+ def people(q = "") = request("GET", "/v1/people", nil, { q: q })
136
+ def tokens = request("GET", "/v1/tokens")
137
+ def create_token(**body) = request("POST", "/v1/tokens", body)
138
+ def revoke_token(id) = request("POST", "/v1/tokens/#{seg(id)}/revoke", {})
139
+
140
+ # admin
141
+ def admin_status = request("GET", "/v1/admin/status")
142
+ def admin_tokens = request("GET", "/v1/admin/tokens")
143
+ def admin_revoke_token(id) = request("POST", "/v1/admin/tokens/#{seg(id)}/revoke", {})
144
+ # format: json, csv or jsonl (csv and jsonl come back as text)
145
+ def audit(**q) = request("GET", "/v1/admin/audit", nil, q, raw: %w[csv jsonl].include?(q[:format].to_s))
146
+ def audit_verify = request("GET", "/v1/admin/audit/verify")
147
+ def token_policies = request("GET", "/v1/admin/token-policies")
148
+ def set_token_policy(**body) = request("POST", "/v1/admin/token-policies", body)
149
+ def admin_secrets(**q) = request("GET", "/v1/admin/secrets", nil, q)
150
+ def admin_secret(ref) = request("GET", "/v1/admin/secrets/#{seg(ref)}")
151
+ def admin_burn(ref) = request("POST", "/v1/admin/secrets/#{seg(ref)}/burn", {})
152
+ def service_accounts = request("GET", "/v1/admin/service-accounts")
153
+ def create_service_account(**body) = request("POST", "/v1/admin/service-accounts", body)
154
+ def change_service_account(name, **body) = request("POST", "/v1/admin/service-accounts/#{seg(name)}", body)
155
+ def delete_service_account(name) = request("POST", "/v1/admin/service-accounts/#{seg(name)}/delete", {})
156
+ def service_account_tokens(name) = request("GET", "/v1/admin/service-accounts/#{seg(name)}/tokens")
157
+ def issue_service_account_token(name, **body) = request("POST", "/v1/admin/service-accounts/#{seg(name)}/tokens", body)
158
+ def rotate_service_account_token(name, id, **body) = request("POST", "/v1/admin/service-accounts/#{seg(name)}/tokens/#{seg(id)}/rotate", body)
159
+ def users = request("GET", "/v1/admin/users")
160
+ def create_user(**body) = request("POST", "/v1/admin/users", body)
161
+ def change_user(user, **body) = request("POST", "/v1/admin/users/#{seg(user)}", body)
162
+ def reset_user_password(user, **body) = request("POST", "/v1/admin/users/#{seg(user)}/password", body)
163
+ def delete_user(user) = request("POST", "/v1/admin/users/#{seg(user)}/delete", {})
164
+
165
+ private
166
+
167
+ def seg(s) = ERB::Util.url_encode(s.to_s)
168
+
169
+ def opts(options)
170
+ o = options.transform_keys(&:to_s)
171
+ bad = o.keys - OPTIONS
172
+ raise ArgumentError, "unknown option(s): #{bad.join(', ')}" unless bad.empty?
173
+
174
+ o.compact
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,88 @@
1
+ require "openssl"
2
+
3
+ module Vanishly
4
+ # Crypto format v1, the same as public/js/vanishly-crypto.js:
5
+ # key 32 random bytes, only ever in the URL fragment (#...)
6
+ # pk without passphrase empty, else PBKDF2-SHA256(passphrase, salt, iterations, 32)
7
+ # encKey HKDF-SHA256(ikm = key || pk, salt, info "vanishly v1 enc")
8
+ # verifier HKDF-SHA256(ikm = pk, salt, info "vanishly v1 auth"); the server keeps SHA-256(verifier)
9
+ # ciphertext AES-256-GCM(encKey, iv 12 bytes, aad "vanishly v1")
10
+ module Crypto
11
+ FORMAT_VERSION = 1
12
+ PBKDF2_ITERATIONS = 600_000
13
+ AAD = "vanishly v1".b
14
+
15
+ # Wrong key or passphrase, or damaged data.
16
+ class DecryptError < StandardError; end
17
+
18
+ module_function
19
+
20
+ def to_b64url(bytes)
21
+ [bytes].pack("m0").tr("+/", "-_").delete("=") # base64url, no padding (no base64 gem: not default since Ruby 3.4)
22
+ end
23
+
24
+ def from_b64url(str)
25
+ raise ArgumentError, "invalid base64url" unless str.is_a?(String) && str.match?(/\A[A-Za-z0-9_-]*\z/) && str.length % 4 != 1
26
+
27
+ (str.tr("-_", "+/") + ("=" * (-str.length % 4))).unpack1("m0")
28
+ end
29
+
30
+ def hkdf(ikm, salt, info)
31
+ OpenSSL::KDF.hkdf(ikm, salt: salt, info: info, length: 32, hash: "SHA256")
32
+ end
33
+
34
+ def pbkdf2(passphrase, salt, iterations)
35
+ OpenSSL::KDF.pbkdf2_hmac(passphrase.encode("UTF-8"), salt: salt, iterations: iterations, length: 32, hash: "SHA256")
36
+ end
37
+
38
+ # Stretches a passphrase once (pk); salt is the base64url value of the secret.
39
+ def unlock_key(passphrase, salt, iterations)
40
+ pbkdf2(passphrase, from_b64url(salt), iterations)
41
+ end
42
+
43
+ # The verifier the reveal API checks for a passphrase-protected secret.
44
+ def verifier_for(pk, salt)
45
+ to_b64url(hkdf(pk, from_b64url(salt), "vanishly v1 auth"))
46
+ end
47
+
48
+ # Returns [key, payload]: the key goes into the URL fragment, the payload to POST /v1/secrets.
49
+ def encrypt_secret(plaintext, passphrase = "", iterations: PBKDF2_ITERATIONS, key: nil, salt: nil, iv: nil)
50
+ key ||= OpenSSL::Random.random_bytes(32)
51
+ salt ||= OpenSSL::Random.random_bytes(16)
52
+ iv ||= OpenSSL::Random.random_bytes(12)
53
+ raise ArgumentError, "key, salt or iv has the wrong length" unless key.bytesize == 32 && salt.bytesize == 16 && iv.bytesize == 12
54
+
55
+ pk = passphrase.to_s.empty? ? "".b : pbkdf2(passphrase, salt, iterations)
56
+ c = OpenSSL::Cipher.new("aes-256-gcm").encrypt
57
+ c.key = hkdf(key + pk, salt, "vanishly v1 enc")
58
+ c.iv = iv
59
+ c.auth_data = AAD
60
+ ct = c.update(plaintext.encode("UTF-8")) + c.final + c.auth_tag(16)
61
+ payload = { "v" => FORMAT_VERSION, "ciphertext" => to_b64url(ct), "iv" => to_b64url(iv),
62
+ "salt" => to_b64url(salt), "iterations" => iterations }
63
+ payload["verifier"] = to_b64url(hkdf(pk, salt, "vanishly v1 auth")) unless pk.empty?
64
+ [to_b64url(key), payload]
65
+ end
66
+
67
+ # Decrypts what the reveal API returned; pk from unlock_key for a passphrase.
68
+ def decrypt_secret(payload, key, pk = "".b)
69
+ k = from_b64url(key)
70
+ raise ArgumentError, "the key must be 32 bytes" unless k.bytesize == 32
71
+
72
+ raw = from_b64url(payload.fetch("ciphertext"))
73
+ raise ArgumentError, "too short" if raw.bytesize < 16
74
+
75
+ c = OpenSSL::Cipher.new("aes-256-gcm").decrypt
76
+ c.key = hkdf(k + (pk || "".b), from_b64url(payload.fetch("salt")), "vanishly v1 enc")
77
+ c.iv = from_b64url(payload.fetch("iv"))
78
+ c.auth_tag = raw.byteslice(-16, 16)
79
+ c.auth_data = AAD
80
+ pt = (c.update(raw.byteslice(0, raw.bytesize - 16)) + c.final).force_encoding("UTF-8")
81
+ raise ArgumentError, "not UTF-8" unless pt.valid_encoding?
82
+
83
+ pt
84
+ rescue OpenSSL::Cipher::CipherError, ArgumentError, KeyError => e
85
+ raise DecryptError, "cannot decrypt: wrong key or passphrase, or damaged data (#{e.class})"
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,3 @@
1
+ module Vanishly
2
+ VERSION = "4.2.0"
3
+ end
data/lib/vanishly.rb ADDED
@@ -0,0 +1,5 @@
1
+ # Vanishly client: end-to-end encrypted one-time secrets (crypto format v1)
2
+ # and the whole Vanishly API (/api/v1).
3
+ require_relative "vanishly/version"
4
+ require_relative "vanishly/crypto"
5
+ require_relative "vanishly/client"
metadata ADDED
@@ -0,0 +1,48 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: vanishly
3
+ version: !ruby/object:Gem::Version
4
+ version: 4.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Dennis Pohlmann
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Crypto format v1 of Vanishly (AES-256-GCM, HKDF, PBKDF2) with OpenSSL,
13
+ and one method per API endpoint. No dependencies.
14
+ executables: []
15
+ extensions: []
16
+ extra_rdoc_files: []
17
+ files:
18
+ - README.md
19
+ - lib/vanishly.rb
20
+ - lib/vanishly/client.rb
21
+ - lib/vanishly/crypto.rb
22
+ - lib/vanishly/version.rb
23
+ homepage: https://github.com/DennisPohlmann/Vanishly
24
+ licenses:
25
+ - GPL-3.0-or-later
26
+ metadata:
27
+ source_code_uri: https://github.com/DennisPohlmann/Vanishly/tree/main/clients/ruby
28
+ documentation_uri: https://github.com/DennisPohlmann/Vanishly/blob/main/docs/CLIENTS.md
29
+ rubygems_mfa_required: 'true'
30
+ rdoc_options: []
31
+ require_paths:
32
+ - lib
33
+ required_ruby_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: '3.1'
38
+ required_rubygems_version: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ requirements: []
44
+ rubygems_version: 3.6.9
45
+ specification_version: 4
46
+ summary: 'Client for Vanishly: end-to-end encrypted one-time secrets and the whole
47
+ API'
48
+ test_files: []