-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_jwt.sql
More file actions
733 lines (662 loc) · 28.2 KB
/
Copy pathdecode_jwt.sql
File metadata and controls
733 lines (662 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/**
* MIT License
*
* Copyright (c) 2023 Leandro Lima <leandro@lls-software.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
create schema if not exists jwt;
/**
* Converts bytea (binary string) data to a numeric representation.
*
* @param {bytea} bytea_data - The bytea binary string data to be converted into a numeric representation.
* @returns {numeric} - The numeric representation of the input binary string data.
*/
create or replace function jwt.bytea_to_numeric(bytea_data bytea)
returns numeric as
$$
declare
result numeric := 0; -- Initialized to hold the numeric result as we process bytes.
byte_value int; -- Temporarily holds the numeric value of an individual byte.
begin
-- A null input has no numeric value. Without this guard the loop bound
-- length(null) is null and the FOR raises, which would turn a malformed key
-- (e.g. an RSA JWK missing its `n` or `e`) into an error instead of letting
-- the verifier skip it and fail closed.
if bytea_data is null then
return null;
end if;
-- Loop through each byte in the bytea data.
for i in 1..length(bytea_data) loop
-- Extract the byte value at the current position.
byte_value := get_byte(bytea_data, i - 1);
-- Accumulate the result, shifting left by one byte (8 bits) before adding new value.
result := result * 256 + byte_value;
end loop;
-- Return the numeric representation of the bytea data.
return result;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Converts a numeric value to a bytea (binary string) representation.
*
* @param {numeric} value - The numeric value to be converted into a bytea binary string representation.
* @returns {bytea} - The bytea representation of the input numeric value.
*/
create or replace function jwt.numeric_to_bytea(value numeric)
returns bytea as
$$
declare
bytea_value bytea := '\x'; -- Initializes the result as an empty bytea string with the hex format introduced.
remainder integer; -- Stores the remainder of the numeric value after division by 256.
begin
-- Loop while there is value left to process.
while value > 0 loop
-- Get the remainder of the value when divided by 256, representing the rightmost byte value.
remainder := value % 256;
-- Prepend the byte to the result with new remainder value.
bytea_value := set_byte(('\x00' || bytea_value), 0, remainder);
-- Divide the value by 256, effectively shifting right by one byte (preparing for next loop iteration).
value := (value - remainder) / 256;
end loop;
-- Return the bytea representation of the numeric value.
return bytea_value;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Decodes a URL-safe base64-encoded string into a bytea (binary) value.
*
* @param {text} segment - The URL-safe base64-encoded string to be decoded into binary data.
* @returns {bytea} - The bytea (binary) value representing the decoded output from the input base64-encoded string.
*/
create or replace function jwt.urlsafe_b64decode(segment text)
returns bytea as
$$
begin
-- Replace URL-safe characters with standard base64 characters.
segment := replace(replace(segment, '-', '+'), '_', '/');
-- Apply padding to the segment to make length a multiple of 4 as required by base64.
segment := rpad(segment, (ceil(length(segment) / 4::float) * 4)::integer, '='::text);
-- Return the binary data decoded from the base64 string.
return decode(segment, 'base64');
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Converts a JSON Web Key (JWK) to a key object.
*
* @param {jsonb} jwk - The JWK to be converted.
* @returns {jsonb} - A key object derived from the JWK, in JSONB format.
*/
create or replace function jwt.jwk_to_key(jwk jsonb)
returns jsonb as
$$
select
case
when jwk ->> 'kty' = 'RSA' then
jsonb_build_object(
'alg', jwk ->> 'alg',
'kid', jwk ->> 'kid',
'e', bytea_to_numeric(urlsafe_b64decode(jwk ->> 'e')),
'n', bytea_to_numeric(urlsafe_b64decode(jwk ->> 'n'))
)
when jwk ->> 'kty' = 'oct' then
jsonb_build_object(
'alg', jwk ->> 'alg',
'kid', jwk ->> 'kid',
'k', jwk ->> 'k'
)
end;
$$ language sql
immutable
set search_path = jwt, public, pg_temp;
/**
* Calculates the bit length of a numeric value (how many bits are necessary to represent the number).
*
* @param {numeric} num - The numeric value for which the bit length is to be calculated.
* @returns {int} - The number of bits required to represent the input numeric value.
*/
create or replace function jwt.bit_length(num numeric)
returns int as
$$
begin
-- A value of 0 still occupies one bit (the zero bit).
if num = 0 then
return 1;
end if;
-- Calculate and return the number of bits needed to represent 'num'.
-- Logarithm base 2 of 'num', rounded down and incremented by 1.
return floor(ln(num) / ln(2)) + 1;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Performs modular exponentiation, which calculates (base ^ exponent) % modulus.
*
* @param {numeric} base - The base number to be raised to the power of the exponent.
* @param {int} exponent - The exponent to which the base number is to be raised.
* @param {numeric} modulus - The modulus to be applied after the exponentiation.
* @returns {numeric} - The result of (base ^ exponent) % modulus.
*/
create or replace function jwt.mod_exp(base numeric, exponent int, modulus numeric)
returns numeric as
$$
declare
result numeric := 1;
begin
-- Ensure the base is within the modulus for further calculations
base := base % modulus;
-- Loop while there is still exponent value left.
while exponent > 0 loop
-- If current exponent bit is 1, accumulate result.
if exponent % 2 = 1 then
result := (result * base) % modulus;
end if;
-- Divide exponent by 2 for the next iteration (bit shift right).
exponent := exponent / 2;
-- Square the base for the next iteration and apply modulus.
base := (base * base) % modulus;
end loop;
-- Return the result of the modular exponentiation.
return result;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Decrypts a bytea (binary string) value using RSA modular exponentiation.
*
* @param {bytea} value - The bytea (binary string) value to be decrypted.
* @param {int} e - The exponent in the RSA key.
* @param {numeric} n - The modulus in the RSA key.
* @returns {bytea} - The decrypted bytea (binary string) value.
*/
create or replace function jwt.decrypt_rsa(value bytea, e integer, n numeric)
returns bytea as
$$
begin
return numeric_to_bytea(
value := mod_exp(
base := bytea_to_numeric(value),
exponent := e,
modulus := n
)
);
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Calculates the expected signature for comparison against the decrypted signature for RSA.
*
* @param {text} message - The message to be hashed and compared against the decrypted signature.
* @param {text} hash_algorithm - The hash algorithm used for signing.
* @param {int} keylength - The RSA modulus length in bytes (matches the signature length).
* @returns {bytea} - The signature that is expected after correctly padding the decrypted message, or null if the modulus is too small to hold the signature.
*/
drop function if exists jwt.build_rsa_expected_signature(text, text);
create or replace function jwt.build_rsa_expected_signature(message text, hash_algorithm text, keylength integer)
returns bytea as
$$
declare
-- ASN.1 headers for different SHA hash algorithms.
sha_256_asn1 bytea := '\x3031300d060960864801650304020105000420';
sha_384_asn1 bytea := '\x3041300d060960864801650304020205000430';
sha_512_asn1 bytea := '\x3051300d060960864801650304020305000440';
-- Variables to store JWT segments.
padding_length integer; -- The length of the padding found in the decrypted signature.
expected_signature bytea; -- The signature that is expected after correctly padding the decrypted message.
hash_asn1_header bytea; -- The ASN.1 header for the hash algorithm used for signing.
-- Variables to process each key for verification.
cleartext bytea; -- DigestInfo (ASN.1 header || hash) embedded in the block.
cleartext_length integer; -- Actual length of the DigestInfo being verified.
begin
-- Select the appropriate ASN.1 header based on the algorithm.
if hash_algorithm = 'sha256' then
hash_asn1_header := sha_256_asn1;
elsif hash_algorithm = 'sha384' then
hash_asn1_header := sha_384_asn1;
elsif hash_algorithm = 'sha512' then
hash_asn1_header := sha_512_asn1;
else
raise exception 'Unsupported hash algorithm: %', hash_algorithm;
end if;
-- Check if the ASN.1 header is not null.
assert hash_asn1_header is not null;
-- Construct the cleartext to be hashed and compared against the decrypted signature.
cleartext := hash_asn1_header || digest(message, hash_algorithm);
assert cleartext is not null;
-- Get the length of the DigestInfo content.
cleartext_length := octet_length(cleartext);
assert cleartext_length is not null;
-- PKCS#1 v1.5 requires the modulus to hold the DigestInfo plus at least 11
-- bytes of overhead (the 0x00 0x01 prefix, a 0x00 separator and at least 8
-- padding bytes). Reject keys that are too small to carry this signature.
if keylength < cleartext_length + 11 then
return null;
end if;
-- Calculate the padding length based on the modulus size and DigestInfo length.
padding_length := keylength - cleartext_length - 3;
assert padding_length >= 8;
-- Construct the expected_signature for comparison against the decrypted signature.
expected_signature := '\x01'::bytea ||
('\x' || repeat('ff', padding_length))::bytea ||
'\x00'::bytea ||
cleartext;
assert expected_signature is not null;
return expected_signature;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Checks if the RSA signature of a JWT matches the expected signature.
*
* @param {bytea} expected_signature - The expected RSA signature.
* @param {bytea} signature - The RSA signature to validate.
* @param {numeric} n - The RSA modulus used for signature decryption.
* @param {integer} e - The RSA exponent used for signature decryption.
* @returns {bool} Returns true if the signature matches the expected signature, false otherwise.
*/
create or replace function jwt.rsa_signature_matches(
expected_signature bytea,
signature bytea,
n numeric,
e integer
)
returns bool as
$$
declare
-- Variables to store JWT segments.
decrypted_signature bytea; -- The clear text signature derived after decrypting.
begin
if expected_signature is null or signature is null or n is null or e is null then
return false;
end if;
-- Decrypt the signature using the key.
decrypted_signature := decrypt_rsa(signature, e, n);
if decrypted_signature is null then
return false;
end if;
-- Check the signature validity
return expected_signature = decrypted_signature;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Compares two bytea values without leaking, through timing, where they first
* differ.
*
* PostgreSQL's `=` operator on bytea returns as soon as it finds a differing
* byte, so the time it takes reveals the length of the matching prefix. For an
* HMAC tag (a secret derived from the key) that turns the comparison into an
* oracle an attacker could use to forge a signature one byte at a time.
*
* Rather than rely on a hand-written byte loop being constant-time in an
* interpreted language, this uses the double-HMAC technique: both operands are
* hashed with a fresh random key, so the subsequent equality test runs over
* values the attacker cannot predict and its timing reveals nothing about the
* inputs. The result is still exact because equal inputs hash equally under the
* same key.
*
* @param {bytea} a - The first value to compare.
* @param {bytea} b - The second value to compare.
* @returns {bool} - True when the two values are equal, false otherwise.
*/
create or replace function jwt.secure_compare(a bytea, b bytea)
returns boolean as
$$
declare
blinding_key bytea := gen_random_bytes(32);
begin
if a is null or b is null then
return false;
end if;
return hmac(a, blinding_key, 'sha256') = hmac(b, blinding_key, 'sha256');
end;
$$ language plpgsql
volatile
set search_path = jwt, public, pg_temp;
/**
* Validates the registered claims of an already signature-verified JWT.
*
* Time-based claims are only enforced when present: a token without an `exp`
* (or `nbf`) claim is not rejected by the corresponding check. The `aud` and
* `iss` claims are only checked when the caller supplies an expected value.
*
* @param {jsonb} claims - The decoded JWT claims.
* @param {text} audience - The expected audience; when non-null the token's `aud` (string or array) must contain it.
* @param {text} issuer - The expected issuer; when non-null the token's `iss` must equal it.
* @param {interval} leeway - Clock-skew tolerance applied to the `exp` and `nbf` checks.
* @param {bool} validate_exp - Whether to enforce the `exp` (expiration) claim when present.
* @param {bool} validate_nbf - Whether to enforce the `nbf` (not-before) claim when present.
* @param {timestamptz} validation_time - The reference time the claims are validated against.
* @returns {bool} - True when the claims are acceptable, false otherwise.
*/
create or replace function jwt.validate_claims(
claims jsonb,
audience text,
issuer text,
leeway interval,
validate_exp boolean,
validate_nbf boolean,
validation_time timestamptz
)
returns boolean as
$$
begin
if claims is null then
return false;
end if;
-- RFC 7519 defines the JWT Claims Set as a JSON object. A validly-signed
-- token whose payload decodes to a scalar or array carries no registered
-- claims to check, so the exp/nbf/aud/iss guards below would vacuously pass
-- and the bogus value would be returned to the caller. Reject any non-object
-- payload outright so the function fails closed.
if jsonb_typeof(claims) <> 'object' then
return false;
end if;
-- exp: reject once the current time passes the expiration (plus leeway).
-- A non-numeric claim, or a numeric value so large that it overflows the
-- timestamp range, is treated as an invalid token rather than allowed to
-- raise: the conversion is guarded so the function fails closed.
if validate_exp and claims ? 'exp' then
if jsonb_typeof(claims -> 'exp') <> 'number' then
return false;
end if;
begin
if validation_time > to_timestamp((claims ->> 'exp')::numeric) + leeway then
return false;
end if;
exception
when others then
return false;
end;
end if;
-- nbf: reject while the current time is before the not-before (minus leeway).
-- Guarded the same way as `exp` above so an out-of-range value fails closed.
if validate_nbf and claims ? 'nbf' then
if jsonb_typeof(claims -> 'nbf') <> 'number' then
return false;
end if;
begin
if validation_time < to_timestamp((claims ->> 'nbf')::numeric) - leeway then
return false;
end if;
exception
when others then
return false;
end;
end if;
-- aud: when an expected audience is supplied, the token's `aud` claim
-- (a string or an array of strings, per RFC 7519) must contain it. Any
-- other shape -- absent, JSON null, a number, an object, or an array that
-- does not hold the expected string -- is rejected. The `?` operator only
-- matches string array elements, so numeric members never satisfy it.
if audience is not null then
if jsonb_typeof(claims -> 'aud') = 'array' then
if not (claims -> 'aud' ? audience) then
return false;
end if;
elsif jsonb_typeof(claims -> 'aud') = 'string' then
if claims ->> 'aud' <> audience then
return false;
end if;
else
return false;
end if;
end if;
-- iss: when an expected issuer is supplied, the token's `iss` must match it.
if issuer is not null then
if claims ->> 'iss' is null or claims ->> 'iss' <> issuer then
return false;
end if;
end if;
return true;
end;
$$ language plpgsql
immutable
set search_path = jwt, public, pg_temp;
/**
* Decodes a JWT, verifies its signature against a set of keys and validates its
* registered claims.
*
* By default the `exp` (expiration) and `nbf` (not-before) claims are enforced
* when present; pass `validate_exp`/`validate_nbf` as false to disable them.
* Audience and issuer are only checked when an expected value is supplied.
*
* @param {text} token - The JWT to be decoded and verified.
* @param {jsonb} keys - The JSON array of keys provided in JSONB format, against which the JWT's signature will be verified.
* @param {text} audience - Optional expected audience; when supplied the token's `aud` claim must contain it.
* @param {text} issuer - Optional expected issuer; when supplied the token's `iss` claim must equal it.
* @param {interval} leeway - Clock-skew tolerance applied to the `exp` and `nbf` checks (default 0).
* @param {bool} validate_exp - Whether to enforce the `exp` claim when present (default true).
* @param {bool} validate_nbf - Whether to enforce the `nbf` claim when present (default true).
* @returns {jsonb} - The decoded JWT claims in JSONB format if the signature and claims are valid, null otherwise.
*/
-- Drop the previous two-argument signature so the defaulted version below is the
-- only candidate (keeping both would make two-argument calls ambiguous).
drop function if exists jwt.decode_jwt(text, jsonb);
create or replace function jwt.decode_jwt(
token text,
keys jsonb,
audience text default null,
issuer text default null,
leeway interval default '0 seconds',
validate_exp boolean default true,
validate_nbf boolean default true
)
returns jsonb as
$$
declare
-- Variables to store JWT segments.
segments text[]; -- The segments of the JWT (header, claims, signature).
header_segment text; -- The header segment of the JWT.
claims_segment text; -- The claims segment of the JWT.
crypto_segment text; -- The signature segment of the JWT.
message text; -- The message to be hashed and compared against the decrypted signature.
signature bytea; -- Binary representation of the signature part of the JWT.
signature_length integer; -- Length of the signature segment in bytes.
header jsonb; -- JSONB decoded from the header segment.
claims jsonb; -- JSONB decoded from the claims segment.
expected_signature bytea; -- The signature that is expected after correctly padding the decrypted message.
hash_algorithm text; -- The hash algorithm used for signing.
signature_family text; -- The signature family used for signing.
-- Variables to process each key for verification.
keyrecord jsonb; -- Temporary storage for an individual key record.
alg text; -- Holds the algorithm used for signing.
keylength integer; -- The expected signature length in bytes (RSA modulus size or HMAC output length).
validation_time timestamptz := now(); -- Reference time for the exp/nbf claim checks.
begin
-- Check if the token or keys are null; if so, return null (indicating validation failure).
if token is null or keys is null then
return null;
end if;
-- Split the token into its segments (header, claims, signature)
segments := string_to_array(token, '.');
assert segments is not null;
if array_length(segments, 1) <> 3 then
return null;
end if;
header_segment := segments[1];
claims_segment := segments[2];
crypto_segment := segments[3];
-- Check if any of the segments are null; if so, return null (indicating validation failure).
if header_segment is null or claims_segment is null or crypto_segment is null then
return null;
end if;
-- Construct the message to be hashed and compared against the decrypted signature.
message := header_segment || '.' || claims_segment;
assert message is not null;
-- Decode the signature segment from the JWT.
begin
signature := urlsafe_b64decode(crypto_segment);
signature_length := octet_length(signature);
exception
when others then
return null;
end;
assert signature is not null;
assert signature_length is not null;
-- Attempt to decode and parse the header segment into JSONB; return null on failure.
begin
header := convert_from(urlsafe_b64decode(header_segment), 'UTF-8')::jsonb;
exception
when others then
return null;
end;
assert header is not null;
-- Attempt to decode and parse the claims segment into JSONB; return null on failure.
begin
claims := convert_from(urlsafe_b64decode(claims_segment), 'UTF-8')::jsonb;
exception
when others then
return null;
end;
assert claims is not null;
-- Fetch algorithm from header and return null if it is not present.
alg := header ->> 'alg';
if alg is null then
return null;
end if;
-- Map the JWT algorithm to its hash function and signature family.
if alg = 'RS256' then
hash_algorithm := 'sha256';
signature_family := 'RS';
elsif alg = 'RS384' then
hash_algorithm := 'sha384';
signature_family := 'RS';
elsif alg = 'RS512' then
hash_algorithm := 'sha512';
signature_family := 'RS';
elsif alg = 'HS256' then
hash_algorithm := 'sha256';
keylength := 32;
signature_family := 'HS';
elsif alg = 'HS384' then
hash_algorithm := 'sha384';
keylength := 48;
signature_family := 'HS';
elsif alg = 'HS512' then
hash_algorithm := 'sha512';
keylength := 64;
signature_family := 'HS';
else
-- If the algorithm is not supported, return null (indicating validation failure).
return null;
end if;
-- Check if the hash algorithm and signature family are not null.
assert hash_algorithm is not null;
assert signature_family is not null;
if signature_family = 'RS' then
-- Loop through each key provided and try to validate the JWT signature.
for keyrecord in
select jsonb_array_elements
from jsonb_array_elements(keys)
where
jsonb_array_elements ->> 'alg' = alg
and (
jsonb_array_elements ->> 'kid' is null
or jsonb_array_elements ->> 'kid' = header ->> 'kid'
)
loop
-- The RSA exponent is constrained to int by mod_exp/decrypt_rsa, so
-- skip keys whose exponent falls outside that range instead of
-- letting the cast below raise (returning null rather than erroring).
if (keyrecord ->> 'e')::numeric > 2147483647 then
continue;
end if;
-- RSA does not tie the algorithm to a fixed key size, so derive the
-- modulus length (in bytes) from each key. A valid RSA signature is
-- exactly as long as the modulus, so skip keys whose size does not
-- match the provided signature.
keylength := octet_length(numeric_to_bytea((keyrecord ->> 'n')::numeric));
if signature_length <> keylength then
continue;
end if;
-- Calculate the expected signature for this key's modulus size.
expected_signature := build_rsa_expected_signature(message, hash_algorithm, keylength);
if expected_signature is null then
continue;
end if;
if rsa_signature_matches(
expected_signature := expected_signature,
signature := signature,
n := (keyrecord ->> 'n')::numeric,
e := (keyrecord ->> 'e')::integer) then
-- The signature is authentic; the token is only accepted if its
-- registered claims also pass validation.
if validate_claims(claims, audience, issuer, leeway,
validate_exp, validate_nbf, validation_time) then
return claims;
end if;
return null;
end if;
end loop;
elsif signature_family = 'HS' then
-- The HMAC signature length is fixed by the hash function.
assert keylength is not null;
if signature_length <> keylength then
return null;
end if;
-- Loop through each key provided and try to validate the JWT signature.
for keyrecord in
select jsonb_array_elements
from jsonb_array_elements(keys)
where
jsonb_array_elements ->> 'alg' = alg
and (
jsonb_array_elements ->> 'kid' is null
or jsonb_array_elements ->> 'kid' = header ->> 'kid'
)
loop
expected_signature := hmac(
message::bytea, -- data
urlsafe_b64decode((keyrecord ->> 'k')::text), -- key
hash_algorithm -- type
);
-- Compare the computed HMAC against the token's signature without
-- leaking, through timing, how many leading bytes matched.
if secure_compare(expected_signature, signature) then
-- The signature is authentic; the token is only accepted if its
-- registered claims also pass validation.
if validate_claims(claims, audience, issuer, leeway,
validate_exp, validate_nbf, validation_time) then
return claims;
end if;
return null;
end if;
end loop;
else
-- If the signature family is not supported, return null (indicating validation failure).
return null;
end if;
-- If none of the keys matched, return null (indicating validation failure).
return null;
end;
$$ language plpgsql
stable
set search_path = jwt, public, pg_temp;