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
//! Shared Base64url → UTF-8 → JSON decode pipeline for JWT segments.
//!
//! Both the header and claims parsers perform the same three-step decode
//! pipeline. This module extracts that logic to a single `inline` helper
//! so changes to the pipeline (e.g. adding size limits) need only happen
//! in one place.
use cratebase64url_decode;
use crateJsonValue;
// ---------------------------------------------------------------------------
// Size bound
// ---------------------------------------------------------------------------
/// Maximum accepted length, in bytes, of a single Base64url JWT segment.
///
/// Decoding allocates roughly `len * 3 / 4` bytes *before* the JSON parser
/// applies its own 10 MB input ceiling, so an unbounded segment is a
/// resource-amplification surface for a server that runs verification on
/// untrusted tokens. This ceiling caps the pre-JSON allocation. At 16 MiB it
/// is comfortably larger than any segment the JSON layer would accept
/// (`16 MiB` Base64url decodes to ~12 MiB, above the JSON parser's 10 MB
/// limit), so it never rejects a token the pipeline would otherwise have
/// parsed — it only bounds the pathological case.
const MAX_SEGMENT_LEN: usize = 16 * 1024 * 1024;
/// Ceiling on the Base64url **signature** segment.
///
/// The signature is raw bytes, not JSON, so it never reaches
/// [`decode_segment`] and was previously decoded with no bound at all — an
/// attacker could hand a verifier an arbitrarily long third segment and force
/// the allocation before any signature comparison. Every algorithm this crate
/// supports produces at most 512 bytes (RSA-4096), ≈683 Base64url characters;
/// 8 KiB is far above any legitimate value and far below a useful
/// amplification.
pub const MAX_SIGNATURE_SEGMENT_LEN: usize = 8 * 1024;
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// Segment decode failure category, mapped to caller-specific error types.
pub
// ---------------------------------------------------------------------------
// Decode helper
// ---------------------------------------------------------------------------
/// Decodes a Base64url JWT segment into a parsed [`JsonValue`].
///
/// Performs the standard three-step pipeline: length bound → Base64url
/// decode → UTF-8 validation → JSON parsing. A segment longer than
/// [`MAX_SEGMENT_LEN`] is rejected as [`SegmentDecodeError::InvalidBase64`]
/// before any decode allocation occurs.
pub