pq_crypto-jwt 0.2.2 → 0.2.3

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1e3f2795566f0f5c947da5064603b1307f6dabac8d3e3821091db761cf16b12e
4
- data.tar.gz: 4866374dafdfcaa976922b77e62e2d73640ee5b0a8c83b2c48ff0f44142df925
3
+ metadata.gz: a1ef792000099bbeefd1b4f1ad2a3b4e5e1e249bbb82f019c82d0fddffce4141
4
+ data.tar.gz: 69d4cf5300f40df6aac37963dcf08ef26e38c40052d404f0a959b6d205ae9253
5
5
  SHA512:
6
- metadata.gz: 2e16f7692d02822b00b5726935ae7f915bc59db28e79562ae7cc023284ca0d3369683244ddaa26045a7207e07e8e27f80796e06daa69dc1963bc0522d46cec7e
7
- data.tar.gz: 1d6e9af3f6fe60bdd2b461eaaf01dc5f3d4980ede10a3498994691dbe23c38e01c6ab49b41eff65ac637e5bf05bb2342a20675ce00b366dc7979cb224845f188
6
+ metadata.gz: 4f760084e0fa96d10cba90bd11f6eb0508620146c029a04510f89101b31c70fb239873176a6e9974b143eff930f4f54646b7c41cef724da2c20c797b4ee52d5b
7
+ data.tar.gz: f8ff2a669c988f448d2e11d9773ea8121b61a670bbcd7b9e9df35327027116ce188138ca87cf80f609a09b7450e20bd13baecf520bdaa7fa0e585d24da40ed55
data/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3
4
+
5
+ ### Breaking
6
+
7
+ - JWK `pub` / `priv` members and detached JWS segments must be unpadded base64url strings (RFC 7515, RFC 7517).
8
+ Padded, standard-alphabet and non-String values are rejected, so a key or signature has exactly one accepted
9
+ encoding. `PQCrypto::JWT::JWK.base64url_decode` raises `PQCrypto::JWT::Error` for them.
10
+ - `PQCrypto::JWT::MLDSA44/65/87` are frozen instances of `PQCrypto::JWT::JWA::MLDSA`, which includes
11
+ `JWT::JWA::SigningAlgorithm` like ruby-jwt's built-in algorithms. The `::ALG` / `::PQ_CRYPTO_ALGORITHM`
12
+ constants are replaced by `#alg` / `#pq_crypto_algorithm`.
13
+ - `JWT::JWK::AKP#parameters` returns a frozen snapshot and the cryptographic members are frozen copies. Metadata
14
+ still changes through `[]=`. JWK hashes returned by `JWK.from_public_key` / `JWK.from_seed` freeze their values.
15
+
16
+ ### Changed
17
+
18
+ - Streaming lives in the `PQCrypto::JWT::JWA::Streaming` mixin; `MLDSAStreaming` remains as an alias and the
19
+ per-algorithm require paths (`pq_crypto/jwt/jwa/ml_dsa_65` etc.) still load the gem.
20
+ - `JWK`, `JWKS` and `Keys` use `extend self` with a `private` section instead of per-method `private_class_method`.
21
+ - CI adds `jwt ~> 3.3.0` to the matrix and a RuboCop lint job.
22
+
23
+ ### Fixed
24
+
25
+ - `JWT::JWK::AKP#members` no longer includes `priv`. ruby-jwt's `JWT::JWK::Thumbprint` kid generator hashed the
26
+ private seed for private AKP JWKs, so they got a different `kid` than their public counterpart.
27
+ - `JWT::JWK::AKP` copies its cryptographic members on import, so mutating the caller's strings afterwards can no
28
+ longer desynchronize the exported `pub` from the already parsed public key.
29
+ - `JWKS.find` / `JWKS.find_all` return `nil` / `[]` for non-Hash containers instead of raising `TypeError`, and skip
30
+ entries whose `#to_hash` does not return a Hash.
31
+
3
32
  ## 0.2.2
4
33
 
5
34
  ### Fixed
data/README.md CHANGED
@@ -18,7 +18,7 @@ ML-KEM/JWE is **not included**. Full JWE support needs a separate standards-comp
18
18
  - `pq_crypto` `~> 0.6.1`
19
19
  - `jwt` `>= 3.1`, `< 4.0`
20
20
 
21
- The CI release matrix covers Ruby `3.1`, `3.2`, `3.3`, `3.4`, `4.0` crossed with `jwt ~> 3.1.0` and `jwt ~> 3.2.0` on Linux and macOS. A dedicated Node `jose` interop job runs on Node 24 with `JOSE_INTEROP=1`.
21
+ The CI release matrix covers Ruby `3.1`, `3.2`, `3.3`, `3.4`, `4.0` crossed with `jwt ~> 3.1.0`, `jwt ~> 3.2.0` and `jwt ~> 3.3.0` on Linux and macOS. A dedicated Node `jose` interop job runs on Node 24 with `JOSE_INTEROP=1`.
22
22
 
23
23
  `pq_crypto-jwt` is Ruby-only and does not ship its own native extension. Native ML-DSA work, seed-aware keys, PKCS#8/SPKI parsing, and streaming signing/verification are delegated to `pq_crypto`.
24
24
 
@@ -28,6 +28,12 @@ The CI release matrix covers Ruby `3.1`, `3.2`, `3.3`, `3.4`, `4.0` crossed with
28
28
  gem "pq_crypto-jwt", "~> 0.2"
29
29
  ```
30
30
 
31
+ ## Upgrading from 0.2.x
32
+
33
+ - JWK `pub` / `priv` members and detached JWS segments must be unpadded base64url strings (RFC 7515, RFC 7517). Padded or standard-alphabet Base64 values, which 0.2.x tolerated, are now rejected; re-encode them before import.
34
+ - `JWT::JWK::AKP#parameters` returns a frozen snapshot, and the `kty`, `alg`, `pub` and `priv` values are frozen. Change metadata through `akp[:kid] = "..."`.
35
+ - `PQCrypto::JWT::MLDSA44`, `MLDSA65` and `MLDSA87` are frozen algorithm objects instead of modules. Use `.alg` and `.pq_crypto_algorithm` instead of the internal `::ALG` and `::PQ_CRYPTO_ALGORITHM` constants. `require "pq_crypto/jwt/jwa/ml_dsa_65"` and the other per-algorithm paths still work.
36
+
31
37
  ## Register the algorithms
32
38
 
33
39
  `pq_crypto-jwt` does not register algorithms implicitly. Register once during boot:
@@ -109,6 +115,8 @@ jwk = PQCrypto::JWT::JWK.from_public_key(
109
115
  )
110
116
  ```
111
117
 
118
+ `pub` and `priv` must be unpadded base64url strings; padded or standard Base64 values are rejected.
119
+
112
120
  Private AKP JWK uses RFC 9964 seed format: `priv` is the 32 raw-byte ML-DSA seed encoded as base64url. It is not the expanded ML-DSA secret key, and helper APIs expect raw seed bytes, not hex or text encodings.
113
121
 
114
122
  ```ruby
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+
5
+ module PQCrypto
6
+ module JWT
7
+ module Base64URL
8
+ module_function
9
+
10
+ def encode(bytes)
11
+ Base64.urlsafe_encode64(String(bytes), padding: false)
12
+ end
13
+
14
+ def decode(value)
15
+ raise ArgumentError, "base64url value must be a String" unless value.is_a?(String)
16
+
17
+ bytes = value.b
18
+ unless /\A[A-Za-z0-9_-]*\z/n.match?(bytes)
19
+ raise ArgumentError, "base64url must use the unpadded URL-safe alphabet"
20
+ end
21
+
22
+ Base64.urlsafe_decode64(bytes)
23
+ end
24
+ end
25
+ private_constant :Base64URL
26
+ end
27
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+
5
+ module PQCrypto
6
+ module JWT
7
+ module JWA
8
+ class DetachedSigningInputIO
9
+ def initialize(encoded_header, payload_io, chunk_size: Streaming::DEFAULT_CHUNK_SIZE)
10
+ @chunk_size = Streaming.validate_chunk_size!(chunk_size)
11
+ @payload_io = payload_io
12
+ @buffer = "#{encoded_header}.".b
13
+ @carry = "".b
14
+ @eof = false
15
+ end
16
+
17
+ def read(length = nil, outbuf = nil)
18
+ raise ArgumentError, "negative length #{length} given" if length&.negative?
19
+ return emit(+"", outbuf) if length&.zero?
20
+
21
+ fill(length)
22
+ emit(take(length || buffer.bytesize), outbuf) unless buffer.empty?
23
+ end
24
+
25
+ def readpartial(maxlen, outbuf = nil)
26
+ result = read(maxlen, outbuf)
27
+ raise EOFError if result.nil? || result.empty?
28
+
29
+ result
30
+ end
31
+
32
+ def binmode = self
33
+ def binmode? = true
34
+ def close = nil
35
+
36
+ private
37
+
38
+ attr_reader :chunk_size, :payload_io
39
+ attr_accessor :buffer, :carry, :eof
40
+
41
+ def emit(result, outbuf) = outbuf ? outbuf.replace(result) : result
42
+
43
+ def take(length)
44
+ head = buffer.byteslice(0, length)
45
+ self.buffer = buffer.byteslice(head.bytesize..)
46
+ head
47
+ end
48
+
49
+ def fill(length)
50
+ feed until eof || (length && buffer.bytesize >= length)
51
+ end
52
+
53
+ def feed
54
+ chunk = payload_io.read(chunk_size)
55
+ if chunk.nil? || chunk.empty?
56
+ buffer << encode(carry)
57
+ self.eof = true
58
+ else
59
+ bytes = carry + chunk.b
60
+ size = bytes.bytesize
61
+ aligned = size - (size % 3)
62
+ buffer << encode(bytes.byteslice(0, aligned))
63
+ self.carry = bytes.byteslice(aligned..)
64
+ end
65
+ end
66
+
67
+ def encode(bytes) = Base64.urlsafe_encode64(bytes, padding: false)
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PQCrypto
4
+ module JWT
5
+ module JWA
6
+ class MLDSA
7
+ include ::JWT::JWA::SigningAlgorithm
8
+ include Streaming
9
+
10
+ attr_reader :alg, :pq_crypto_algorithm
11
+
12
+ def initialize(alg, pq_crypto_algorithm)
13
+ @alg = String(alg).dup.freeze
14
+ @pq_crypto_algorithm = pq_crypto_algorithm
15
+ freeze
16
+ end
17
+
18
+ def valid_alg?(alg_to_validate) = alg_to_validate == alg
19
+ def key_kind = :signature
20
+
21
+ def sign(data:, signing_key:)
22
+ ensure_key!(signing_key, PQCrypto::Signature::SecretKey, "signing")
23
+ raise ArgumentError, "data must be a String" unless data.is_a?(String)
24
+
25
+ signing_key.sign(data.b, context: EMPTY_CONTEXT)
26
+ rescue KeyTypeError, ArgumentError
27
+ raise
28
+ rescue StandardError => error
29
+ raise ::JWT::EncodeError, error.message
30
+ end
31
+
32
+ def verify(data:, signature:, verification_key:)
33
+ verification_key.is_a?(PQCrypto::Signature::PublicKey) &&
34
+ verification_key.algorithm == pq_crypto_algorithm &&
35
+ data.is_a?(String) && signature.is_a?(String) &&
36
+ signature_length_valid?(signature) &&
37
+ verification_key.verify(data.b, signature.b, context: EMPTY_CONTEXT)
38
+ rescue *VERIFY_ERRORS
39
+ false
40
+ end
41
+
42
+ private
43
+
44
+ def ensure_key!(key, klass, role)
45
+ raise KeyTypeError, "#{alg} #{role} requires #{klass}" unless key.is_a?(klass)
46
+
47
+ actual = key.algorithm
48
+ return if actual == pq_crypto_algorithm
49
+
50
+ raise KeyTypeError, "#{alg} #{role} requires #{pq_crypto_algorithm.inspect} key, got #{actual.inspect}"
51
+ end
52
+
53
+ def signature_length_valid?(signature)
54
+ expected = PQCrypto::Signature.details(pq_crypto_algorithm)[:signature_bytes]
55
+ expected.nil? || signature.bytesize == expected
56
+ rescue *VERIFY_ERRORS
57
+ false
58
+ end
59
+ end
60
+
61
+ MLDSA44 = MLDSA.new("ML-DSA-44", :ml_dsa_44)
62
+ MLDSA65 = MLDSA.new("ML-DSA-65", :ml_dsa_65)
63
+ MLDSA87 = MLDSA.new("ML-DSA-87", :ml_dsa_87)
64
+ end
65
+ end
66
+ end
@@ -1,21 +1,3 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../jwa"
4
- require_relative "ml_dsa_streaming"
5
-
6
- module PQCrypto
7
- module JWT
8
- module JWA
9
- module MLDSA44
10
- extend ::JWT::JWA::SigningAlgorithm
11
- extend PQCrypto::JWT::JWA::MLDSA
12
- extend PQCrypto::JWT::JWA::MLDSAStreaming
13
-
14
- ALG = "ML-DSA-44".freeze
15
- PQ_CRYPTO_ALGORITHM = :ml_dsa_44
16
-
17
- def self.alg = ALG
18
- end
19
- end
20
- end
21
- end
3
+ require_relative "../../jwt"
@@ -1,21 +1,3 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../jwa"
4
- require_relative "ml_dsa_streaming"
5
-
6
- module PQCrypto
7
- module JWT
8
- module JWA
9
- module MLDSA65
10
- extend ::JWT::JWA::SigningAlgorithm
11
- extend PQCrypto::JWT::JWA::MLDSA
12
- extend PQCrypto::JWT::JWA::MLDSAStreaming
13
-
14
- ALG = "ML-DSA-65".freeze
15
- PQ_CRYPTO_ALGORITHM = :ml_dsa_65
16
-
17
- def self.alg = ALG
18
- end
19
- end
20
- end
21
- end
3
+ require_relative "../../jwt"
@@ -1,21 +1,3 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../jwa"
4
- require_relative "ml_dsa_streaming"
5
-
6
- module PQCrypto
7
- module JWT
8
- module JWA
9
- module MLDSA87
10
- extend ::JWT::JWA::SigningAlgorithm
11
- extend PQCrypto::JWT::JWA::MLDSA
12
- extend PQCrypto::JWT::JWA::MLDSAStreaming
13
-
14
- ALG = "ML-DSA-87".freeze
15
- PQ_CRYPTO_ALGORITHM = :ml_dsa_87
16
-
17
- def self.alg = ALG
18
- end
19
- end
20
- end
21
- end
3
+ require_relative "../../jwt"
@@ -1,216 +1,3 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "base64"
4
- require "json"
5
-
6
- module PQCrypto
7
- module JWT
8
- module JWA
9
- module MLDSAStreaming
10
- DEFAULT_CHUNK_SIZE = 1 << 20
11
- STREAMING_DECODE_ERRORS = [JSON::ParserError, ArgumentError, TypeError, EncodingError].freeze
12
- STREAMING_VERIFY_ERRORS = [PQCrypto::Error, PQCrypto::JWT::Error].freeze
13
-
14
- def streaming_supported?
15
- PQCrypto::Signature.supported.include?(pq_crypto_algorithm)
16
- rescue PQCrypto::Error
17
- false
18
- end
19
-
20
- def sign_io(signing_key:, payload_io: nil, io: nil, header_fields: {}, chunk_size: DEFAULT_CHUNK_SIZE)
21
- ensure_streaming!
22
- ensure_key!(signing_key, PQCrypto::Signature::SecretKey, "signing")
23
- validate_chunk_size!(chunk_size)
24
- source = payload_io || io
25
- raise ArgumentError, "payload_io must respond to #read" unless source.respond_to?(:read)
26
-
27
- header = normalize_signing_header!(header_fields).merge("alg" => alg)
28
- encoded_header = base64url(JSON.generate(header))
29
- input = DetachedSigningInputIO.new(encoded_header, source, chunk_size: chunk_size)
30
- signature = signing_key.sign_io(input, chunk_size: chunk_size, context: EMPTY_CONTEXT)
31
- "#{encoded_header}..#{base64url(signature)}"
32
- rescue PQCrypto::JWT::Error, ArgumentError
33
- raise
34
- rescue StandardError => e
35
- raise ::JWT::EncodeError, e.message
36
- end
37
-
38
- def verify_io(verification_key:, token:, payload_io:, chunk_size: DEFAULT_CHUNK_SIZE, strict: false)
39
- ensure_streaming!
40
- ensure_key!(verification_key, PQCrypto::Signature::PublicKey, "verification")
41
- validate_chunk_size!(chunk_size)
42
- return streaming_decode_failure!(strict, "token must be a String") unless token.is_a?(String)
43
- return streaming_decode_failure!(strict, "payload_io must respond to #read") unless payload_io.respond_to?(:read)
44
-
45
- encoded_header, encoded_payload, encoded_signature, extra = token.split(".", -1)
46
- unless extra.nil? && encoded_payload == "" && encoded_signature
47
- return streaming_decode_failure!(strict, "compact detached JWS must have exactly three segments and an empty payload segment")
48
- end
49
-
50
- header = JSON.parse(Base64.urlsafe_decode64(encoded_header))
51
- return streaming_decode_failure!(strict, "unsupported streaming JWS protected header") unless supported_streaming_header?(header)
52
-
53
- signature = Base64.urlsafe_decode64(encoded_signature)
54
- return streaming_verify_failure!(strict, "invalid #{alg} signature length") unless signature_length_valid?(signature)
55
-
56
- input = DetachedSigningInputIO.new(encoded_header, payload_io, chunk_size: chunk_size)
57
- return streaming_verify_failure!(strict, "Streaming JWS verification failed") unless verification_key.verify_io(input, signature, chunk_size: chunk_size, context: EMPTY_CONTEXT)
58
-
59
- [payload_io.respond_to?(:pos) ? payload_io.pos : nil, header]
60
- rescue *STREAMING_DECODE_ERRORS => e
61
- streaming_decode_failure!(strict, e.message)
62
- rescue *STREAMING_VERIFY_ERRORS => e
63
- streaming_verify_failure!(strict, e.message)
64
- end
65
-
66
- def verify_io!(**kwargs)
67
- verify_io(**kwargs) || raise(::JWT::VerificationError, "Streaming JWS verification failed")
68
- true
69
- end
70
-
71
- private
72
-
73
- def ensure_streaming!
74
- return if streaming_supported?
75
-
76
- raise PQCrypto::JWT::UnsupportedFeature, "#{alg} does not support streaming JWS"
77
- end
78
-
79
- def base64url(bytes)
80
- Base64.urlsafe_encode64(String(bytes).b, padding: false)
81
- end
82
-
83
- def normalize_signing_header!(header_fields)
84
- unless header_fields.respond_to?(:to_hash)
85
- raise ArgumentError, "header_fields must be a Hash-like object"
86
- end
87
-
88
- header = header_fields.to_hash.each_with_object({}) { |(key, value), out| out[String(key)] = value }
89
- unsupported = %w[b64 crit] & header.keys
90
- unless unsupported.empty?
91
- raise ArgumentError, "unsupported protected header#{unsupported.size == 1 ? '' : 's'}: #{unsupported.join(', ')}"
92
- end
93
-
94
- header
95
- end
96
-
97
- def supported_streaming_header?(header)
98
- return false unless header.is_a?(Hash) && header["alg"] == alg
99
- return false if header.key?("crit")
100
- return false if header.key?("b64") && header["b64"] != true
101
-
102
- true
103
- end
104
-
105
- def validate_chunk_size!(chunk_size)
106
- return if chunk_size.is_a?(Integer) && chunk_size.positive?
107
-
108
- raise ArgumentError, "chunk_size must be a positive Integer"
109
- end
110
-
111
- def streaming_decode_failure!(strict, message)
112
- raise ::JWT::DecodeError, message if strict
113
-
114
- false
115
- end
116
-
117
- def streaming_verify_failure!(strict, message)
118
- raise ::JWT::VerificationError, message if strict
119
-
120
- false
121
- end
122
- end
123
-
124
- class DetachedSigningInputIO
125
- def initialize(encoded_header, payload_io, chunk_size: MLDSAStreaming::DEFAULT_CHUNK_SIZE)
126
- unless chunk_size.is_a?(Integer) && chunk_size.positive?
127
- raise ArgumentError, "chunk_size must be a positive Integer"
128
- end
129
-
130
- @prefix = "#{encoded_header}.".b
131
- @payload_io = payload_io
132
- @chunk_size = chunk_size
133
- @buffer = +""
134
- @carry = +""
135
- @prefix_done = false
136
- @payload_done = false
137
- end
138
-
139
- def read(length = nil, outbuf = nil)
140
- if length.nil?
141
- drain_until_eof
142
- return nil if @buffer.empty?
143
-
144
- result = @buffer
145
- @buffer = +""
146
- else
147
- raise ArgumentError, "negative length #{length} given" if length.negative?
148
- return replace_outbuf(outbuf, +"") if length.zero?
149
-
150
- fill(length)
151
- return nil if @buffer.empty?
152
-
153
- result = @buffer.byteslice(0, length)
154
- @buffer = @buffer.byteslice(result.bytesize..-1) || +""
155
- end
156
-
157
- replace_outbuf(outbuf, result)
158
- end
159
-
160
- def readpartial(maxlen, outbuf = nil)
161
- result = read(maxlen, outbuf)
162
- raise EOFError if result.nil? || result.empty?
163
-
164
- result
165
- end
166
-
167
- def binmode = self
168
- def binmode? = true
169
- def close = nil
170
-
171
- private
172
-
173
- def replace_outbuf(outbuf, result)
174
- outbuf&.replace(result)
175
- outbuf || result
176
- end
177
-
178
- def drain_until_eof
179
- consume_prefix
180
- feed_one_chunk until @payload_done
181
- end
182
-
183
- def fill(length)
184
- consume_prefix
185
- feed_one_chunk while @buffer.bytesize < length && !@payload_done
186
- end
187
-
188
- def consume_prefix
189
- return if @prefix_done
190
-
191
- @buffer << @prefix
192
- @prefix_done = true
193
- end
194
-
195
- def feed_one_chunk
196
- chunk = @payload_io.read(@chunk_size)
197
- if chunk.nil? || chunk.empty?
198
- @buffer << Base64.urlsafe_encode64(@carry, padding: false) unless @carry.empty?
199
- @carry = +""
200
- @payload_done = true
201
- return
202
- end
203
-
204
- bytes = @carry + chunk.b
205
- aligned = bytes.bytesize - (bytes.bytesize % 3)
206
- if aligned.positive?
207
- @buffer << Base64.urlsafe_encode64(bytes.byteslice(0, aligned), padding: false)
208
- @carry = bytes.byteslice(aligned..-1) || +""
209
- else
210
- @carry = bytes
211
- end
212
- end
213
- end
214
- end
215
- end
216
- end
3
+ require_relative "../../jwt"
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+
6
+ module PQCrypto
7
+ module JWT
8
+ module JWA
9
+ module Streaming
10
+ DEFAULT_CHUNK_SIZE = 1 << 20
11
+ DECODE_ERRORS = [JSON::ParserError, ArgumentError, TypeError, EncodingError].freeze
12
+ VERIFY_ERRORS = [PQCrypto::Error, PQCrypto::JWT::Error].freeze
13
+ UNSUPPORTED_HEADERS = %w[b64 crit].freeze
14
+ STREAMING_DECODE_ERRORS = DECODE_ERRORS
15
+ STREAMING_VERIFY_ERRORS = VERIFY_ERRORS
16
+
17
+ def self.validate_chunk_size!(chunk_size)
18
+ return chunk_size if chunk_size.is_a?(Integer) && chunk_size.positive?
19
+
20
+ raise ArgumentError, "chunk_size must be a positive Integer"
21
+ end
22
+
23
+ def streaming_supported?
24
+ PQCrypto::Signature.supported.include?(pq_crypto_algorithm)
25
+ rescue PQCrypto::Error
26
+ false
27
+ end
28
+
29
+ def sign_io(signing_key:, payload_io: nil, io: nil, header_fields: {}, chunk_size: DEFAULT_CHUNK_SIZE)
30
+ payload_io ||= io
31
+ validate_stream!(signing_key, PQCrypto::Signature::SecretKey, "signing", chunk_size)
32
+ raise ArgumentError, "payload_io must respond to #read" unless payload_io.respond_to?(:read)
33
+
34
+ encoded_header = base64url(JSON.generate(signing_header(header_fields)))
35
+ input = DetachedSigningInputIO.new(encoded_header, payload_io, chunk_size:)
36
+ "#{encoded_header}..#{base64url(signing_key.sign_io(input, chunk_size:, context: EMPTY_CONTEXT))}"
37
+ rescue PQCrypto::JWT::Error, ArgumentError
38
+ raise
39
+ rescue StandardError => error
40
+ raise ::JWT::EncodeError, error.message
41
+ end
42
+
43
+ def verify_io(verification_key:, token:, payload_io:, chunk_size: DEFAULT_CHUNK_SIZE, strict: false)
44
+ verify_detached!(verification_key, token, payload_io, chunk_size)
45
+ rescue ::JWT::DecodeError
46
+ raise if strict
47
+
48
+ false
49
+ end
50
+
51
+ def verify_io!(**kwargs)
52
+ verify_io(**kwargs) || raise(::JWT::VerificationError, "Streaming JWS verification failed")
53
+ true
54
+ end
55
+
56
+ private
57
+
58
+ def verify_detached!(verification_key, token, payload_io, chunk_size)
59
+ validate_stream!(verification_key, PQCrypto::Signature::PublicKey, "verification", chunk_size)
60
+ raise ::JWT::DecodeError, "token must be a String" unless token.is_a?(String)
61
+ raise ::JWT::DecodeError, "payload_io must respond to #read" unless payload_io.respond_to?(:read)
62
+
63
+ encoded_header, header, signature = decode_detached(token)
64
+ input = DetachedSigningInputIO.new(encoded_header, payload_io, chunk_size:)
65
+ unless verification_key.verify_io(input, signature, chunk_size:, context: EMPTY_CONTEXT)
66
+ raise ::JWT::VerificationError, "Streaming JWS verification failed"
67
+ end
68
+
69
+ [payload_position(payload_io), header]
70
+ rescue *DECODE_ERRORS => error
71
+ raise ::JWT::DecodeError, error.message
72
+ rescue *VERIFY_ERRORS => error
73
+ raise ::JWT::VerificationError, error.message
74
+ end
75
+
76
+ def decode_detached(token)
77
+ case token.split(".", -1)
78
+ in [encoded_header, "", encoded_signature]
79
+ header = JSON.parse(Base64URL.decode(encoded_header))
80
+ raise ::JWT::DecodeError, "unsupported streaming JWS protected header" unless streamable_header?(header)
81
+
82
+ signature = Base64URL.decode(encoded_signature)
83
+ raise ::JWT::VerificationError, "invalid #{alg} signature length" unless signature_length_valid?(signature)
84
+
85
+ [encoded_header, header, signature]
86
+ else
87
+ raise ::JWT::DecodeError,
88
+ "compact detached JWS must have exactly three segments and an empty payload segment"
89
+ end
90
+ end
91
+
92
+ def ensure_streaming!
93
+ raise UnsupportedFeature, "#{alg} does not support streaming JWS" unless streaming_supported?
94
+ end
95
+
96
+ def validate_stream!(key, klass, role, chunk_size)
97
+ ensure_streaming!
98
+ ensure_key!(key, klass, role)
99
+ Streaming.validate_chunk_size!(chunk_size)
100
+ end
101
+
102
+ def payload_position(payload_io)
103
+ payload_io.pos if payload_io.respond_to?(:pos)
104
+ end
105
+
106
+ def signing_header(header_fields)
107
+ raise ArgumentError, "header_fields must be a Hash-like object" unless header_fields.respond_to?(:to_hash)
108
+
109
+ converted = header_fields.to_hash
110
+ raise ArgumentError, "header_fields #to_hash must return a Hash" unless converted.is_a?(Hash)
111
+
112
+ header = converted.transform_keys { |key| String(key) }
113
+ unsupported = UNSUPPORTED_HEADERS & header.keys
114
+ unless unsupported.empty?
115
+ raise ArgumentError, "unsupported protected header#{'s' if unsupported.size > 1}: #{unsupported.join(', ')}"
116
+ end
117
+
118
+ header.merge("alg" => alg)
119
+ end
120
+
121
+ def streamable_header?(header)
122
+ header.is_a?(Hash) && header["alg"] == alg && !header.key?("crit") && header.fetch("b64", true) == true
123
+ end
124
+
125
+ def base64url(bytes) = Base64URL.encode(bytes)
126
+ end
127
+ end
128
+ end
129
+ end