jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
Documentation
//! Pure-Rust JSON Object Signing and Encryption (JOSE) primitives.
//!
//! The crate provides JSON Web Signature (JWS), JSON Web Encryption (JWE),
//! JSON Web Key (JWK), and JSON Web Token (JWT) APIs backed by software keys
//! and optional PKCS#11 keys. Algorithms are represented by typed enums, and
//! higher-level JWK APIs bind key metadata to signing, verification,
//! encryption, and decryption operations.
//!
//! Optional crate features enable post-quantum algorithms, deprecated JOSE
//! algorithms needed for legacy interoperability, and PKCS#11 support.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod algorithm;
pub mod authenticated;
pub mod base64url;
pub mod capability;
/// Error and result types returned by JOSE operations.
pub mod error;
pub mod header;
pub mod jwe;
pub mod jwk;
/// JSON Web Signature compact and JSON serialization APIs.
pub mod jws;
pub mod jwt;
/// Strict, duplicate-rejecting JSON object member handling (internal).
pub(crate) mod member_map;
pub mod password;

#[cfg(test)]
mod security_tests;

pub use algorithm::{JweAlgorithm, JweEncryption, JwsAlgorithm};
pub use authenticated::Authenticated;
pub use error::{ErrorCategory, JoseError, Result};
pub use header::JoseHeader;
pub use jwk::JwkOp;
pub use password::Password;

/// Minimum RSA modulus size in bits required by RFC 7518 §3.3 / §4.2.
pub const MIN_RSA_BITS: usize = 2048;

/// Maximum RSA modulus size accepted or generated by this crate.
///
/// The ceiling bounds attacker-controlled big-integer allocation and private-key
/// validation work before an RSA key becomes usable. 8192-bit RSA remains well above
/// the security level of every JOSE algorithm implemented here.
pub const MAX_RSA_BITS: usize = 8192;

/// Maximum DER size accepted by key import entry points.
///
/// Supported 8192-bit RSA keys are only a few KiB. The wider 64 KiB envelope leaves
/// ample room for standard wrappers while bounding parser allocation before the key's
/// type and modulus can be inspected.
pub const MAX_KEY_DER_BYTES: usize = 64 * 1024;

/// Maximum token length (in bytes) accepted by the JWS and JWE decoders.
///
/// Caps memory allocation from an attacker-supplied oversized token — the
/// decoders refuse any input longer than this before any base64url or
/// JSON decoding runs. Set to 4 MiB: JOSE payloads have outgrown the
/// compact-token ceiling of RFC 7519 §2 — post-quantum signatures and
/// KEMs, and the proof systems that carry credentials over them, emit
/// payloads past the old 1 MiB bound, and a JWE wrapping one crosses it.
pub const MAX_TOKEN_BYTES: usize = 4 * 1024 * 1024;

/// The exact message raised when a signature fails to verify.
///
/// A constant rather than an inline literal because [`JoseError::category`]
/// classifies it by equality: substring matching over error text would classify any
/// message that *mentions* a verification failure as one.
pub const SIGNATURE_VERIFICATION_FAILED: &str = "signature verification failed";

/// Refuse to emit a serialized token (or JWS JSON member) of `len` bytes
/// that this crate's own decoders would reject under [`MAX_TOKEN_BYTES`].
///
/// Signing and encryption call this so that "every token this crate emits,
/// this crate can consume" holds for size as well as header content.
pub(crate) fn ensure_emit_size(len: usize) -> Result<()> {
    if len > MAX_TOKEN_BYTES {
        return Err(JoseError::InvalidToken(format!(
            "emitted token size {len} exceeds MAX_TOKEN_BYTES ({MAX_TOKEN_BYTES}); \
             this crate would refuse to decode it"
        )));
    }
    Ok(())
}

/// Enforce the one RSA modulus policy shared by all constructors and import formats.
pub(crate) fn ensure_rsa_bits(bits: usize) -> Result<()> {
    if bits < MIN_RSA_BITS {
        return Err(JoseError::Key(format!(
            "RSA key size {bits} bits is below the required minimum of {MIN_RSA_BITS}"
        )));
    }
    if bits > MAX_RSA_BITS {
        return Err(JoseError::Key(format!(
            "RSA key size {bits} bits exceeds the supported maximum of {MAX_RSA_BITS}"
        )));
    }
    Ok(())
}

/// Enforce the RSA policy from an unsigned big-endian modulus without first
/// constructing an attacker-sized big integer.
pub(crate) fn ensure_rsa_modulus_bytes(bytes: &[u8]) -> Result<()> {
    let bits = match bytes.iter().enumerate().find(|(_, byte)| **byte != 0) {
        Some((index, first)) => {
            (bytes.len() - index - 1) * 8 + (u8::BITS - first.leading_zeros()) as usize
        }
        None => 0,
    };
    ensure_rsa_bits(bits)
}

/// Bound a DER key container before ASN.1 or big-integer allocation begins.
pub(crate) fn ensure_key_der_size(len: usize) -> Result<()> {
    if len > MAX_KEY_DER_BYTES {
        return Err(JoseError::Key(format!(
            "DER key size {len} bytes exceeds MAX_KEY_DER_BYTES ({MAX_KEY_DER_BYTES})"
        )));
    }
    Ok(())
}