Skip to main content

jose_rs/
lib.rs

1//! Pure-Rust JSON Object Signing and Encryption (JOSE) primitives.
2//!
3//! The crate provides JSON Web Signature (JWS), JSON Web Encryption (JWE),
4//! JSON Web Key (JWK), and JSON Web Token (JWT) APIs backed by software keys
5//! and optional PKCS#11 keys. Algorithms are represented by typed enums, and
6//! higher-level JWK APIs bind key metadata to signing, verification,
7//! encryption, and decryption operations.
8//!
9//! Optional crate features enable post-quantum algorithms, deprecated JOSE
10//! algorithms needed for legacy interoperability, and PKCS#11 support.
11
12#![forbid(unsafe_code)]
13#![warn(missing_docs)]
14
15pub mod algorithm;
16pub mod authenticated;
17pub mod base64url;
18pub mod capability;
19/// Error and result types returned by JOSE operations.
20pub mod error;
21pub mod header;
22pub mod jwe;
23pub mod jwk;
24/// JSON Web Signature compact and JSON serialization APIs.
25pub mod jws;
26pub mod jwt;
27/// Strict, duplicate-rejecting JSON object member handling (internal).
28pub(crate) mod member_map;
29pub mod password;
30
31#[cfg(test)]
32mod security_tests;
33
34pub use algorithm::{JweAlgorithm, JweEncryption, JwsAlgorithm};
35pub use authenticated::Authenticated;
36pub use error::{ErrorCategory, JoseError, Result};
37pub use header::JoseHeader;
38pub use jwk::JwkOp;
39pub use password::Password;
40
41/// Minimum RSA modulus size in bits required by RFC 7518 §3.3 / §4.2.
42pub const MIN_RSA_BITS: usize = 2048;
43
44/// Maximum RSA modulus size accepted or generated by this crate.
45///
46/// The ceiling bounds attacker-controlled big-integer allocation and private-key
47/// validation work before an RSA key becomes usable. 8192-bit RSA remains well above
48/// the security level of every JOSE algorithm implemented here.
49pub const MAX_RSA_BITS: usize = 8192;
50
51/// Maximum DER size accepted by key import entry points.
52///
53/// Supported 8192-bit RSA keys are only a few KiB. The wider 64 KiB envelope leaves
54/// ample room for standard wrappers while bounding parser allocation before the key's
55/// type and modulus can be inspected.
56pub const MAX_KEY_DER_BYTES: usize = 64 * 1024;
57
58/// Maximum token length (in bytes) accepted by the JWS and JWE decoders.
59///
60/// Caps memory allocation from an attacker-supplied oversized token — the
61/// decoders refuse any input longer than this before any base64url or
62/// JSON decoding runs. Set to 4 MiB: JOSE payloads have outgrown the
63/// compact-token ceiling of RFC 7519 §2 — post-quantum signatures and
64/// KEMs, and the proof systems that carry credentials over them, emit
65/// payloads past the old 1 MiB bound, and a JWE wrapping one crosses it.
66pub const MAX_TOKEN_BYTES: usize = 4 * 1024 * 1024;
67
68/// The exact message raised when a signature fails to verify.
69///
70/// A constant rather than an inline literal because [`JoseError::category`]
71/// classifies it by equality: substring matching over error text would classify any
72/// message that *mentions* a verification failure as one.
73pub const SIGNATURE_VERIFICATION_FAILED: &str = "signature verification failed";
74
75/// Refuse to emit a serialized token (or JWS JSON member) of `len` bytes
76/// that this crate's own decoders would reject under [`MAX_TOKEN_BYTES`].
77///
78/// Signing and encryption call this so that "every token this crate emits,
79/// this crate can consume" holds for size as well as header content.
80pub(crate) fn ensure_emit_size(len: usize) -> Result<()> {
81    if len > MAX_TOKEN_BYTES {
82        return Err(JoseError::InvalidToken(format!(
83            "emitted token size {len} exceeds MAX_TOKEN_BYTES ({MAX_TOKEN_BYTES}); \
84             this crate would refuse to decode it"
85        )));
86    }
87    Ok(())
88}
89
90/// Enforce the one RSA modulus policy shared by all constructors and import formats.
91pub(crate) fn ensure_rsa_bits(bits: usize) -> Result<()> {
92    if bits < MIN_RSA_BITS {
93        return Err(JoseError::Key(format!(
94            "RSA key size {bits} bits is below the required minimum of {MIN_RSA_BITS}"
95        )));
96    }
97    if bits > MAX_RSA_BITS {
98        return Err(JoseError::Key(format!(
99            "RSA key size {bits} bits exceeds the supported maximum of {MAX_RSA_BITS}"
100        )));
101    }
102    Ok(())
103}
104
105/// Enforce the RSA policy from an unsigned big-endian modulus without first
106/// constructing an attacker-sized big integer.
107pub(crate) fn ensure_rsa_modulus_bytes(bytes: &[u8]) -> Result<()> {
108    let bits = match bytes.iter().enumerate().find(|(_, byte)| **byte != 0) {
109        Some((index, first)) => {
110            (bytes.len() - index - 1) * 8 + (u8::BITS - first.leading_zeros()) as usize
111        }
112        None => 0,
113    };
114    ensure_rsa_bits(bits)
115}
116
117/// Bound a DER key container before ASN.1 or big-integer allocation begins.
118pub(crate) fn ensure_key_der_size(len: usize) -> Result<()> {
119    if len > MAX_KEY_DER_BYTES {
120        return Err(JoseError::Key(format!(
121            "DER key size {len} bytes exceeds MAX_KEY_DER_BYTES ({MAX_KEY_DER_BYTES})"
122        )));
123    }
124    Ok(())
125}