nanoflags 0.1.0 → 0.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.
@@ -1,59 +1,59 @@
1
- # frozen_string_literal: true
2
-
3
- require "tempfile"
4
-
5
- module NanoFlags
6
- # Persistence of the last good configuration, so that a restarting process can evaluate flags before (or without)
7
- # reaching the edge. A store is any object with +get+ (the stored text, or nil) and +set(text)+. A store sits
8
- # outside the trust boundary: a signed bundle read back from it is verified again before it is used.
9
- module Store
10
- # The last good bundle in a file (written atomically, mode 0600).
11
- class File
12
- def initialize(path)
13
- @path = path.to_s
14
- end
15
-
16
- def get
17
- ::File.exist?(@path) ? ::File.binread(@path).force_encoding(Encoding::UTF_8) : nil
18
- end
19
-
20
- def set(text)
21
- dir = ::File.dirname(@path)
22
- tmp = Tempfile.create([".nanoflags-", ".json"], dir, mode: ::File::BINARY)
23
- begin
24
- tmp.chmod(0o600)
25
- tmp.write(text)
26
- tmp.close
27
- ::File.rename(tmp.path, @path)
28
- rescue StandardError
29
- ::File.unlink(tmp.path) if ::File.exist?(tmp.path)
30
- raise
31
- end
32
- end
33
- end
34
-
35
- # In memory (tests).
36
- class Memory
37
- attr_accessor :text
38
-
39
- def get = @text
40
- def set(text) = (@text = text)
41
- end
42
-
43
- # Any ActiveSupport::Cache store (`Rails.cache`, a Redis or Memcached cache store), shared by every process that
44
- # uses it.
45
- class Cache
46
- def initialize(cache, key: "nanoflags.bundle")
47
- @cache = cache
48
- @key = key
49
- end
50
-
51
- def get
52
- v = @cache.read(@key)
53
- v.is_a?(String) ? v : nil
54
- end
55
-
56
- def set(text) = @cache.write(@key, text)
57
- end
58
- end
59
- end
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+
5
+ module NanoFlags
6
+ # Persistence of the last good configuration, so that a restarting process can evaluate flags before (or without)
7
+ # reaching the edge. A store is any object with +get+ (the stored text, or nil) and +set(text)+. A store sits
8
+ # outside the trust boundary: a signed bundle read back from it is verified again before it is used.
9
+ module Store
10
+ # The last good bundle in a file (written atomically, mode 0600).
11
+ class File
12
+ def initialize(path)
13
+ @path = path.to_s
14
+ end
15
+
16
+ def get
17
+ ::File.exist?(@path) ? ::File.binread(@path).force_encoding(Encoding::UTF_8) : nil
18
+ end
19
+
20
+ def set(text)
21
+ dir = ::File.dirname(@path)
22
+ tmp = Tempfile.create([".nanoflags-", ".json"], dir, mode: ::File::BINARY)
23
+ begin
24
+ tmp.chmod(0o600)
25
+ tmp.write(text)
26
+ tmp.close
27
+ ::File.rename(tmp.path, @path)
28
+ rescue StandardError
29
+ ::File.unlink(tmp.path) if ::File.exist?(tmp.path)
30
+ raise
31
+ end
32
+ end
33
+ end
34
+
35
+ # In memory (tests).
36
+ class Memory
37
+ attr_accessor :text
38
+
39
+ def get = @text
40
+ def set(text) = (@text = text)
41
+ end
42
+
43
+ # Any ActiveSupport::Cache store (`Rails.cache`, a Redis or Memcached cache store), shared by every process that
44
+ # uses it.
45
+ class Cache
46
+ def initialize(cache, key: "nanoflags.bundle")
47
+ @cache = cache
48
+ @key = key
49
+ end
50
+
51
+ def get
52
+ v = @cache.read(@key)
53
+ v.is_a?(String) ? v : nil
54
+ end
55
+
56
+ def set(text) = @cache.write(@key, text)
57
+ end
58
+ end
59
+ end
@@ -1,180 +1,180 @@
1
- # frozen_string_literal: true
2
-
3
- require "openssl"
4
-
5
- module NanoFlags
6
- # Bundle signature verification: Ed25519 over the canonical string
7
- # `"nanoflags-bundle-v1\n<environment id>\n<revision>\n<checksum>\n<sha256 hex of the bundle text>"`.
8
- #
9
- # Only PUBLIC keys are handled here; a JWK that carries a private member (`d`) is refused.
10
- #
11
- # @api private
12
- module Signature
13
- module_function
14
-
15
- # SubjectPublicKeyInfo prefix of a raw Ed25519 public key (RFC 8410).
16
- SPKI_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze
17
-
18
- # The signature a bundle was accepted with (kept so that a persisted copy can be verified again).
19
- Info = Struct.new(:signature, :kid, :environment_id, :revision, :checksum) do
20
- def to_h = { "signature" => signature, "kid" => kid, "environmentId" => environment_id, "revision" => revision, "checksum" => checksum }
21
-
22
- def self.from_h(h)
23
- return nil unless h.is_a?(Hash) && h["signature"].is_a?(String) && h["environmentId"].is_a?(String) && h["checksum"].is_a?(String)
24
-
25
- rev = h["revision"]
26
- rev = rev.to_i if rev.is_a?(Float) && rev == rev.floor
27
- return nil unless rev.is_a?(Integer)
28
-
29
- new(h["signature"], h["kid"].is_a?(String) && !h["kid"].empty? ? h["kid"] : nil, h["environmentId"], rev, h["checksum"])
30
- end
31
- end
32
-
33
- Key = Struct.new(:kid, :key)
34
-
35
- def base64url_decode(value)
36
- s = value.to_s.tr("-_", "+/").sub(/=+\z/, "")
37
- return nil unless s.match?(%r{\A[A-Za-z0-9+/]*\z}) && s.length % 4 != 1
38
-
39
- (s + ("=" * ((4 - (s.length % 4)) % 4))).unpack1("m0")
40
- rescue ArgumentError
41
- nil
42
- end
43
-
44
- def public_ed25519_jwk?(jwk)
45
- jwk.is_a?(Hash) && jwk["kty"] == "OKP" && jwk["crv"] == "Ed25519" && jwk["x"].is_a?(String) && !jwk["x"].empty? && !jwk.key?("d")
46
- end
47
-
48
- # The public Ed25519 JWKs among +jwks+ (anything else, including private keys, is skipped).
49
- def import_keys(jwks)
50
- Array(jwks).filter_map do |jwk|
51
- jwk = jwk.transform_keys(&:to_s) if jwk.is_a?(Hash)
52
- next unless public_ed25519_jwk?(jwk)
53
-
54
- raw = base64url_decode(jwk["x"])
55
- next unless raw && raw.bytesize == 32
56
-
57
- begin
58
- Key.new(jwk["kid"].is_a?(String) && !jwk["kid"].empty? ? jwk["kid"] : nil, OpenSSL::PKey.read(SPKI_PREFIX + raw))
59
- rescue OpenSSL::PKey::PKeyError
60
- nil
61
- end
62
- end
63
- end
64
-
65
- def canonical(environment_id, revision, checksum, bundle_text)
66
- "nanoflags-bundle-v1\n#{environment_id}\n#{revision}\n#{checksum}\n#{OpenSSL::Digest::SHA256.hexdigest(bundle_text.b)}"
67
- end
68
-
69
- # Whether +info.signature+ is a valid signature by one of +keys+ over the canonical string for +bundle_text+.
70
- # A key id narrows the candidates; an unknown key id matches no key.
71
- def verify(keys, info, bundle_text)
72
- sig = base64url_decode(info.signature)
73
- return false unless sig && sig.bytesize == 64
74
-
75
- msg = canonical(info.environment_id, info.revision, info.checksum, bundle_text).b
76
- keys.any? do |k|
77
- next false if info.kid && k.kid && k.kid != info.kid
78
-
79
- begin
80
- k.key.verify(nil, sig, msg)
81
- rescue OpenSSL::PKey::PKeyError
82
- false
83
- end
84
- end
85
- end
86
-
87
- # The exact source text of the top-level member +name+ of a JSON object (the last one when it repeats, like
88
- # JSON.parse), or nil. The edge embeds the stored, signed bundle text byte-for-byte; hashing that span avoids any
89
- # re-serialisation.
90
- def raw_member(text, name)
91
- t = text.b
92
- n = t.bytesize
93
- i = 0
94
- ws = -> { i += 1 while i < n && " \n\r\t".include?(t.getbyte(i).chr) }
95
- str = lambda do
96
- return nil if i >= n || t.getbyte(i) != 34
97
-
98
- start = i
99
- i += 1
100
- while i < n
101
- c = t.getbyte(i)
102
- if c == 92
103
- i += 2
104
- elsif c == 34
105
- i += 1
106
- return [start, i]
107
- else
108
- i += 1
109
- end
110
- end
111
- nil
112
- end
113
- value = lambda do
114
- ws.()
115
- return false if i >= n
116
-
117
- c = t.getbyte(i)
118
- return !str.().nil? if c == 34
119
-
120
- if c == 123 || c == 91
121
- depth = 0
122
- while i < n
123
- c = t.getbyte(i)
124
- if c == 34
125
- return false if str.().nil?
126
-
127
- next
128
- end
129
- if c == 123 || c == 91
130
- depth += 1
131
- elsif c == 125 || c == 93
132
- depth -= 1
133
- end
134
- i += 1
135
- return true if depth.zero?
136
- end
137
- return false
138
- end
139
- start = i
140
- i += 1 while i < n && !",}] \n\r\t".include?(t.getbyte(i).chr)
141
- i > start
142
- end
143
- ws.()
144
- return nil if i >= n || t.getbyte(i) != 123
145
-
146
- i += 1
147
- found = nil
148
- loop do
149
- ws.()
150
- return found if i < n && t.getbyte(i) == 125
151
-
152
- key = str.()
153
- return nil if key.nil?
154
-
155
- ws.()
156
- return nil if i >= n || t.getbyte(i) != 58
157
-
158
- i += 1
159
- ws.()
160
- start = i
161
- return nil unless value.()
162
-
163
- k = begin
164
- Engine::Json.parse(t.byteslice(key[0], key[1] - key[0]))
165
- rescue StandardError
166
- nil
167
- end
168
- found = t.byteslice(start, i - start).force_encoding(Encoding::UTF_8) if k == name
169
- ws.()
170
- if i < n && t.getbyte(i) == 44
171
- i += 1
172
- elsif i < n && t.getbyte(i) == 125
173
- return found
174
- else
175
- return nil
176
- end
177
- end
178
- end
179
- end
180
- end
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module NanoFlags
6
+ # Bundle signature verification: Ed25519 over the canonical string
7
+ # `"nanoflags-bundle-v1\n<environment id>\n<revision>\n<checksum>\n<sha256 hex of the bundle text>"`.
8
+ #
9
+ # Only PUBLIC keys are handled here; a JWK that carries a private member (`d`) is refused.
10
+ #
11
+ # @api private
12
+ module Signature
13
+ module_function
14
+
15
+ # SubjectPublicKeyInfo prefix of a raw Ed25519 public key (RFC 8410).
16
+ SPKI_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze
17
+
18
+ # The signature a bundle was accepted with (kept so that a persisted copy can be verified again).
19
+ Info = Struct.new(:signature, :kid, :environment_id, :revision, :checksum) do
20
+ def to_h = { "signature" => signature, "kid" => kid, "environmentId" => environment_id, "revision" => revision, "checksum" => checksum }
21
+
22
+ def self.from_h(h)
23
+ return nil unless h.is_a?(Hash) && h["signature"].is_a?(String) && h["environmentId"].is_a?(String) && h["checksum"].is_a?(String)
24
+
25
+ rev = h["revision"]
26
+ rev = rev.to_i if rev.is_a?(Float) && rev == rev.floor
27
+ return nil unless rev.is_a?(Integer)
28
+
29
+ new(h["signature"], h["kid"].is_a?(String) && !h["kid"].empty? ? h["kid"] : nil, h["environmentId"], rev, h["checksum"])
30
+ end
31
+ end
32
+
33
+ Key = Struct.new(:kid, :key)
34
+
35
+ def base64url_decode(value)
36
+ s = value.to_s.tr("-_", "+/").sub(/=+\z/, "")
37
+ return nil unless s.match?(%r{\A[A-Za-z0-9+/]*\z}) && s.length % 4 != 1
38
+
39
+ (s + ("=" * ((4 - (s.length % 4)) % 4))).unpack1("m0")
40
+ rescue ArgumentError
41
+ nil
42
+ end
43
+
44
+ def public_ed25519_jwk?(jwk)
45
+ jwk.is_a?(Hash) && jwk["kty"] == "OKP" && jwk["crv"] == "Ed25519" && jwk["x"].is_a?(String) && !jwk["x"].empty? && !jwk.key?("d")
46
+ end
47
+
48
+ # The public Ed25519 JWKs among +jwks+ (anything else, including private keys, is skipped).
49
+ def import_keys(jwks)
50
+ Array(jwks).filter_map do |jwk|
51
+ jwk = jwk.transform_keys(&:to_s) if jwk.is_a?(Hash)
52
+ next unless public_ed25519_jwk?(jwk)
53
+
54
+ raw = base64url_decode(jwk["x"])
55
+ next unless raw && raw.bytesize == 32
56
+
57
+ begin
58
+ Key.new(jwk["kid"].is_a?(String) && !jwk["kid"].empty? ? jwk["kid"] : nil, OpenSSL::PKey.read(SPKI_PREFIX + raw))
59
+ rescue OpenSSL::PKey::PKeyError
60
+ nil
61
+ end
62
+ end
63
+ end
64
+
65
+ def canonical(environment_id, revision, checksum, bundle_text)
66
+ "nanoflags-bundle-v1\n#{environment_id}\n#{revision}\n#{checksum}\n#{OpenSSL::Digest::SHA256.hexdigest(bundle_text.b)}"
67
+ end
68
+
69
+ # Whether +info.signature+ is a valid signature by one of +keys+ over the canonical string for +bundle_text+.
70
+ # A key id narrows the candidates; an unknown key id matches no key.
71
+ def verify(keys, info, bundle_text)
72
+ sig = base64url_decode(info.signature)
73
+ return false unless sig && sig.bytesize == 64
74
+
75
+ msg = canonical(info.environment_id, info.revision, info.checksum, bundle_text).b
76
+ keys.any? do |k|
77
+ next false if info.kid && k.kid && k.kid != info.kid
78
+
79
+ begin
80
+ k.key.verify(nil, sig, msg)
81
+ rescue OpenSSL::PKey::PKeyError
82
+ false
83
+ end
84
+ end
85
+ end
86
+
87
+ # The exact source text of the top-level member +name+ of a JSON object (the last one when it repeats, like
88
+ # JSON.parse), or nil. The edge embeds the stored, signed bundle text byte-for-byte; hashing that span avoids any
89
+ # re-serialisation.
90
+ def raw_member(text, name)
91
+ t = text.b
92
+ n = t.bytesize
93
+ i = 0
94
+ ws = -> { i += 1 while i < n && " \n\r\t".include?(t.getbyte(i).chr) }
95
+ str = lambda do
96
+ return nil if i >= n || t.getbyte(i) != 34
97
+
98
+ start = i
99
+ i += 1
100
+ while i < n
101
+ c = t.getbyte(i)
102
+ if c == 92
103
+ i += 2
104
+ elsif c == 34
105
+ i += 1
106
+ return [start, i]
107
+ else
108
+ i += 1
109
+ end
110
+ end
111
+ nil
112
+ end
113
+ value = lambda do
114
+ ws.()
115
+ return false if i >= n
116
+
117
+ c = t.getbyte(i)
118
+ return !str.().nil? if c == 34
119
+
120
+ if c == 123 || c == 91
121
+ depth = 0
122
+ while i < n
123
+ c = t.getbyte(i)
124
+ if c == 34
125
+ return false if str.().nil?
126
+
127
+ next
128
+ end
129
+ if c == 123 || c == 91
130
+ depth += 1
131
+ elsif c == 125 || c == 93
132
+ depth -= 1
133
+ end
134
+ i += 1
135
+ return true if depth.zero?
136
+ end
137
+ return false
138
+ end
139
+ start = i
140
+ i += 1 while i < n && !",}] \n\r\t".include?(t.getbyte(i).chr)
141
+ i > start
142
+ end
143
+ ws.()
144
+ return nil if i >= n || t.getbyte(i) != 123
145
+
146
+ i += 1
147
+ found = nil
148
+ loop do
149
+ ws.()
150
+ return found if i < n && t.getbyte(i) == 125
151
+
152
+ key = str.()
153
+ return nil if key.nil?
154
+
155
+ ws.()
156
+ return nil if i >= n || t.getbyte(i) != 58
157
+
158
+ i += 1
159
+ ws.()
160
+ start = i
161
+ return nil unless value.()
162
+
163
+ k = begin
164
+ Engine::Json.parse(t.byteslice(key[0], key[1] - key[0]))
165
+ rescue StandardError
166
+ nil
167
+ end
168
+ found = t.byteslice(start, i - start).force_encoding(Encoding::UTF_8) if k == name
169
+ ws.()
170
+ if i < n && t.getbyte(i) == 44
171
+ i += 1
172
+ elsif i < n && t.getbyte(i) == 125
173
+ return found
174
+ else
175
+ return nil
176
+ end
177
+ end
178
+ end
179
+ end
180
+ end
@@ -1,6 +1,6 @@
1
- # frozen_string_literal: true
2
-
3
- module NanoFlags
4
- # The version of this gem, reported to the edge as "ruby/<version>".
5
- VERSION = "0.1.0"
6
- end
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # The version of this gem, reported to the edge as "ruby/<version>".
5
+ VERSION = "0.2.0"
6
+ end