jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
Documentation

jose-rs

Pure-Rust JOSE (JSON Object Signing and Encryption) library covering JWS, JWE, JWK, and JWT standards. Built on kryptering for cryptographic operations, supporting both in-memory software keys and PKCS#11 HSM-backed keys.

Standards

Standard RFC Coverage
JWS 7515 Compact + Flattened JSON + General JSON serialization
JWE 7516 Compact + Flattened JSON + General JSON serialization (protected header required; decryption of a general JWE is scoped to a caller-named recipient — see Security notes)
JWK 7517 RSA / EC / oct / OKP / AKP key types (see Supported algorithms for curve coverage), JWK Sets, Thumbprints (RFC 7638), key generation
JWT 7519 Claims, validation (exp/nbf/iss/aud/sub), nested JWT
JWA 7518 Implemented signature, encryption, and key management algorithms

Supported algorithms

JWS signatures: HS256/384/512, RS256/384/512, PS256/384/512, ES256/384/512, Ed25519, Ed448, EdDSA (Ed25519 or Ed448)

Ed25519 and Ed448 are fully specified identifiers from RFC 9864 section 2.2. They require the corresponding OKP curve. Legacy EdDSA dispatches on that curve; its JWK pin and the matching fully specified pin are interchangeable. Application JWT algorithm allowlists remain exact: list only Ed448 to refuse legacy EdDSA headers. Protected bytes are never renamed or reserialized for verification. Ed448 uses pure signatures with an empty context, not Ed448ph, and needs no post-quantum feature. X448 remains unsupported in JOSE.

JWS post-quantum signatures (opt-in): ML-DSA-44 / ML-DSA-65 / ML-DSA-87 (FIPS 204 and RFC 9964), plus the five composite algorithms from draft-ietf-jose-pq-composite-sigs-07: ML-DSA-44-ES256, ML-DSA-65-ES256, ML-DSA-65-ES384, ML-DSA-87-ES384, and ML-DSA-44-Ed25519.

JWE key management: dir, A128KW/A192KW/A256KW, A128GCMKW/A192GCMKW/A256GCMKW, ECDH-ES and ECDH-ES+A128KW/+A192KW/+A256KW (P-256/P-384/P-521, X25519), PBES2-HS256+A128KW/PBES2-HS384+A192KW/PBES2-HS512+A256KW, RSA-OAEP-256 (RSA-OAEP with --features rsa-oaep)

JWE content encryption: A128GCM/A192GCM/A256GCM, A128CBC-HS256/A192CBC-HS384/A256CBC-HS512

Every ECDH mode needs a JWK — a curve cannot be named by a byte string — and generates its ephemeral key per message. ECDH-ES agrees the content key with exactly one recipient and conveys no key at all; ECDH-ES+A128KW/+A192KW/ +A256KW agree a key-encryption key and carry the content key wrapped under it, which is the form that can reach several recipients — still refused for more than one, because RFC 7516 gives a recipient element no protected header of its own to carry that recipient's epk in (ADR 0018). None of them provides origin authentication: anyone with the recipient's public key can produce a message the recipient will decrypt. See ADRs 0016, 0017 and 0018.

A128GCMKW/A192GCMKW/A256GCMKW wrap the content key with AES-GCM instead of RFC 3394, and carry the wrap's IV and authentication tag as iv and tag header members — the same names the envelope uses for the content encryption's own values, which are separate and must not be confused. Those two members are generated by this crate and cannot be supplied by a caller, for any algorithm (ADR 0020); for several recipients they run into the same problem epk has, so those messages are refused too.

PBES2-HS256+A128KW/+HS384+A192KW/+HS512+A256KW derive the wrapping key from a password, which is a type of its own here (jose_rs::jwe::Password) rather than a string or an oct key: a password is only ever an input to a key derivation, and an oct JWK holding one would also be valid input to A128KW. The derivation's inputs — the salt input p2s and the iteration count p2c — are generated by this crate and read only from the authenticated header. The count the sender picks is CPU the recipient spends, so both ends are bounded: 1 000 is refused-and-refuses, 8 192 is emitted (inside the 10 000 and 16 384 ceilings the current peers enforce on themselves), 1 000 000 is the most this crate will compute for someone else's message (ADR 0021).

Feature flags

For pure software consumers, disable the default PKCS#11 integration:

[dependencies]
jose-rs = { version = "0.14.0", default-features = false }
Feature Default Description
pkcs11 Yes PKCS#11 HSM key support via kryptering
post-quantum No ML-DSA and composite ML-DSA algorithms
deprecated No Legacy algorithms (RSA-OAEP with SHA-1, none)

Usage

JWT (sign and verify)

use jose_rs::{JoseHeader, jwt, JwsAlgorithm};
use jose_rs::jwt::{Claims, Validation};

// Create a signer (HMAC-SHA256)
let key = kryptering::SoftwareKey::from_symmetric_bytes(
    kryptering::KeyAlgorithm::Hmac,
    b"my-secret-key-32-bytes-long!!!!!",
).unwrap();
let signer = kryptering::SoftwareSigner::new(
    JwsAlgorithm::HS256.to_crypto().unwrap(),
    key.clone(),
).unwrap();

// Encode
let header = JoseHeader::jwt("HS256");
let mut claims = Claims::default();
claims.iss = Some("my-service".into());
claims.sub = Some("user-42".into());
let token = jwt::encode(&signer, &header, &claims).unwrap();

// Decode and validate
let verifier = kryptering::SoftwareVerifier::new(
    JwsAlgorithm::HS256.to_crypto().unwrap(),
    key,
).unwrap();
let validation = Validation::new().with_issuer("my-service");
let decoded = jwt::decode(&verifier, &token, &validation).unwrap();
assert_eq!(decoded.sub.as_deref(), Some("user-42"));

JWT Claims.exp, nbf, and iat use NumericDate with nanosecond precision. For integer assignments, use claims.exp = Some(seconds.into()); for exact fractions, use claims.exp = Some("4102444800.125".parse()?). Parse original JSON into Claims to preserve decimal precision rather than passing through floating-point values. Numeric encodings over 128 bytes, nonzero precision below a nanosecond, negative values (including negative zero), out-of-range values, and exponents outside i32 are rejected. Missing/null optional dates keep their existing absence semantics. Expiration is exclusive, while not-before and maximum-age boundaries are inclusive. Validation::validate_at accepts an explicit trusted clock for deterministic checks.

JWE (encrypt and decrypt)

use jose_rs::{JweAlgorithm, JweEncryption};

let cek = [0x42u8; 32]; // 256-bit key for A256GCM
let plaintext = b"sensitive data";

let token = jose_rs::jwe::encrypt(&cek, plaintext, JweAlgorithm::Dir, JweEncryption::A256GCM).unwrap();
let decrypted = jose_rs::jwe::decrypt(&cek, &token).unwrap();
assert_eq!(decrypted, plaintext);

The same message in the JSON Serialization (RFC 7516 §7.2) — same algorithms, same policy, same key material:

use jose_rs::jwe::{compact, json};
use jose_rs::{JweAlgorithm, JweEncryption};

let cek = [0x42u8; 32];
let flattened = json::encrypt_flattened(
    &cek, b"sensitive data", JweAlgorithm::Dir, JweEncryption::A256GCM,
).unwrap();
println!("{}", flattened.to_json().unwrap());
// {"protected":"…","iv":"…","ciphertext":"…","tag":"…"}

// The two serializations are interchangeable for the shapes both support.
let as_compact = flattened.to_compact().unwrap();
assert_eq!(compact::decrypt(&cek, &as_compact).unwrap(), b"sensitive data");
let from_compact = json::FlattenedJwe::from_compact(&as_compact).unwrap();
assert_eq!(json::decrypt_flattened(&cek, &from_compact).unwrap(), b"sensitive data");

JWK (key management)

use jose_rs::jwk;

// Generate keys
let rsa_jwk = jwk::generate_rsa(2048).unwrap();
let ec_jwk = jwk::generate_ec("P-256").unwrap();
let ed_jwk = jwk::generate_ed25519().unwrap();

// Convert to/from kryptering keys
let software_key = jwk::jwk_to_software_key(&ec_jwk).unwrap();
let roundtripped = jwk::software_key_to_jwk(&software_key).unwrap();

// DER formats are chosen explicitly, and a key is rebuilt and validated rather than
// trusted for what its bytes claim (ADRs 0023, 0024).
let rsa_from_pkcs1 = jwk::jwk_from_pkcs1_der(&std::fs::read("id_rsa.der")?).unwrap();
let ec_from_sec1 = jwk::jwk_from_sec1_der(&std::fs::read("id_ec.der")?).unwrap();

// PEM (RFC 7468): the type label decides the format, and other formats are
// refused by name rather than guessed from the bytes.
let from_file = jwk::jwk_from_pem(&std::fs::read_to_string("key.pem")?).unwrap();
let public_pem = jwk::public_pem_from_jwk(&ec_jwk).unwrap();   // "-----BEGIN PUBLIC KEY-----"
let private_pem = jwk::private_pem_from_jwk(&rsa_jwk).unwrap(); // needs a private JWK

// Thumbprint (RFC 7638)
let thumbprint = jwk::thumbprint::thumbprint_sha256(&ec_jwk).unwrap();
// Explicit SHA-384/SHA-512 are also available; SHA-256 remains the default.
let sha384 = jwk::thumbprint::thumbprint(
    &ec_jwk,
    jwk::thumbprint::ThumbprintHash::Sha384,
).unwrap();

HSM-backed signing

use jose_rs::{JoseHeader, jwt};
use jose_rs::jwt::Claims;

// The same JWT API works with HSM keys -- just pass an HSM-backed signer
let provider = kryptering::pkcs11::Pkcs11Provider::new(
    std::path::Path::new("/usr/lib/softhsm/libsofthsm2.so")
).unwrap();
let session = provider.open_session("1234").unwrap();
let signer = kryptering::pkcs11::Pkcs11Signer::new(
    &session, "my-rsa-key",
    kryptering::SignatureAlgorithm::RsaPkcs1v15(kryptering::HashAlgorithm::Sha256),
).unwrap();

let header = JoseHeader::jwt("RS256");
let claims = Claims::default();
let token = jwt::encode(&signer, &header, &claims).unwrap();

Examples

See the examples directory for complete, runnable examples covering all major JOSE operations:

  • generate_keys -- generate RSA, EC P-256, Ed25519, HMAC, and AES keys as JWK files
  • jwt_hmac -- JWT sign/verify with HMAC-SHA256
  • jwt_rsa -- JWT sign with RS256, verify with public key
  • jwt_ecdsa -- JWT sign with ES256, verify with public key
  • jwt_eddsa -- JWT sign with EdDSA (Ed25519), verify with public key
  • jwt_ml_dsa -- JWT sign/verify with pure ML-DSA
  • jwt_composite -- JWT sign/verify with draft-07 ML-DSA-65-ES384
  • jwe_aes_kw -- JWE encrypt/decrypt with AES Key Wrap + AES-GCM
  • jwe_rsa_oaep -- JWE encrypt with RSA-OAEP, decrypt with private key
  • jws_json -- JWS flattened and general JSON serialization (multi-signature)
  • jwk_thumbprint -- RFC 7638 JWK Thumbprint for all key types
  • nested_jwt -- sign a JWT then encrypt it inside a JWE

Run cargo run --example generate_keys first to create the key files, then run any other example.

Security notes

  • RSA timing advisory (RUSTSEC-2023-0071). The locked rsa 0.10.0 is in RustSec's patched range (>=0.10.0); .cargo/audit.toml contains no advisory ignores. This covers the underlying private-operation timing issue, including signing and decryption. PKCS#11 remains available for long-lived keys that should stay non-exportable; token security depends on the provider.

  • Trust-sensitive header fields. jku, x5u, and jwk headers are parsed by the library but never fetched or trusted — callers must never resolve jku/x5u URLs without an explicit allow-list (SSRF / key-substitution risk) and must never treat an inline jwk header as a verification key without first verifying it against a trusted key store. On the emit side, jku, jwk, x5u and x5c are refused by default when signing or encrypting; set allow_key_reference_headers on jws::SignOptions or jwe::JweEncryptOptions to emit them deliberately (e.g. an x5c chain from jws::x5::bind_cert_to_header). RFC 8725 §3.10 does not require this; it is a defensive default so that caller-controlled data forwarded into a header cannot mint key references under a trusted key.

  • Unambiguous emitted headers. Signing and encryption refuse a header whose extra map repeats a typed member (alg, enc, kid, crit, ...), which would otherwise serialize as a duplicate JSON member that last-key-wins parsers (e.g. panva/jose, confirmed by the interop matrix) read differently. On the decode side the same duplicates are rejected at parse time. JWS JSON unprotected headers must be a JSON object disjoint from the protected header (RFC 7515 §7.2.1) and may not carry crit or b64. JWS signing refuses JWE-only members (enc, zip, epk, apu, apv, iv, tag, p2s, p2c) in either header, since enc marks a JWE (RFC 7516 §9), and refuses a crit list that names a registered header parameter or repeats a name (RFC 7515 §4.1.11). JWE encryption refuses registered members it does not implement (zip, b64, epk, apu, apv, p2s, p2c, iv, tag) and any crit.

  • jwt::decode_unverified is for inspection only. It returns the header and claims without any cryptographic check. Production code paths must call jwt::decode with a real verifier and Validation.

  • Algorithm binding. jws/jwt verify functions reject tokens whose alg header does not match the verifier's algorithm and always reject alg: "none" — even with the deprecated feature enabled. A crit header is rejected if it names any parameter outside the union of the library's understood set (b64) and the caller-supplied understood_crit allow-list (RFC 7515 §4.1.11); an empty crit array is itself rejected. RFC 7797 unencoded payloads (b64: false) are supported via sign_with_options / verify_with_options, and b64, when present, must be listed in crit (RFC 7797 §6).

  • JWE JSON Serialization is protected-header-only. jwe::json::FlattenedJwe (RFC 7516 §7.2.2) and jwe::general::GeneralJwe (RFC 7516 §7.2.1) both require a protected member, because enc must be integrity protected. The unprotected header members (unprotected, header) are read, with the disjointness RFC 7516 §7.2.1 requires, under one rule: an unauthenticated alg is accepted only for a key that pins it (the JWK APIs), so the header value is checked against the key instead of believed; the raw-key APIs refuse it. enc, zip, crit and the key-agreement parameters can never sit unprotected. jose-rs never emits unprotected parameters (ADR 0013).

  • JWE critical extensions (crit) are refused unless you say what you implement. With the default (empty) list, any JWE carrying crit is rejected — jose-rs implements none of its own. JweEncryptOptions::with_understood_crit / JweDecryptOptions::with_understood_crit declare the parameters your code processes; the library then enforces the RFC's structure on both sides — non-empty, no duplicates, no registered member posing as an extension, each name actually present — and hands you the value in JoseHeader::extra without interpreting it. crit and the parameter it names must both be in the protected header: criticality asserted by bytes nobody authenticates is not criticality (ADR 0015). In the general serialization the header the content tag is validated under is protected ∪ unprotected ∪ recipients[i].header — per recipient — so "decrypt this" is not a complete instruction. jwe::general therefore takes either the element index or the key's own kid (zero matches and several matches are both errors) and never searches the array the way panva's generalDecrypt does. Recipient arrays are bounded at 32 elements, because their length is attacker-chosen and each element costs a key-management operation (ADR 0014). External additional authenticated data (aad) is supported: JweEncryptOptions::with_external_aad / JweDecryptOptions::with_external_aad bind out-of-band bytes to the ciphertext. They are authenticated, not confidential — do not put secrets there — and the compact serialization refuses the option rather than silently dropping it (ADR 0012). Unrecognized private members are ignored while processing but retained, so re-serializing does not drop them and to_compact() refuses rather than silently discarding them. The parser rejects duplicate JSON member names (which serde_json would otherwise resolve last-key-wins), non-string member values, non-canonical base64url and oversized input; the parsed protected header is available through peek_protected_header() for inspection only, and no return value attests to it until decryption succeeds — see ADR 0011, ADR 0012 (external AAD) and ADR 0013 (unprotected header members).

  • RSA minimum key size. Keys below 2048 bits are rejected at parse and at generation time (RFC 7518 §3.3 / §4.2).

  • AES-GCM nonce collision bound. Content encryption with A128GCM / A192GCM / A256GCM uses a 96-bit random nonce per RFC 7518 §5.3. Under a single CEK the collision probability reaches 2⁻³² after ~2³² messages (NIST SP 800-38D §8.3). For high-throughput senders, rotate CEKs well before that bound — the dir mode with a fresh CEK per message avoids the issue entirely.

  • Token size cap. The JWS and JWE decoders reject any input larger than jose_rs::MAX_TOKEN_BYTES (1 MiB) before allocating any base64url buffer, to bound DoS from oversized attacker-supplied tokens. Signing and encryption apply the same limit to what they emit, so the crate never produces a token it would refuse to decode.

  • Debug output redaction. Jwk's Debug implementation redacts private components (d, p, q, dp, dq, qi, k) — logging a private Jwk will not spill the private material.

  • CEK zeroization. Content Encryption Keys generated or recovered inside JWE encrypt/decrypt — including the MAC_KEY || ENC_KEY split used for AES-CBC-HS — are wrapped in zeroize::Zeroizing and wiped from the heap when they go out of scope. This does not extend to key material held inside the underlying cipher crates (which manage their own state), and the decrypted plaintext returned to the caller is not zeroized — if your plaintext is itself a secret, wrap it on the caller side.

  • Signing-side algorithm binding. Symmetric to the verify path, the jws/jwt sign functions reject a header whose alg does not match the signer's algorithm, refuse alg: "none", and refuse a crit naming an extension outside the understood allow-list. This prevents emitting malformed tokens whose header advertises a different algorithm than the one actually used.

  • JWT Best Current Practices (RFC 8725). Validation supports pinning the typ header (with_typ), capping token age via iat (with_max_age, which requires iat), rejecting future-dated iat by default, and restricting the accepted signing algorithms independently of the verifier (with_allowed_algorithms). These close the JWT-context confusion and replay-window gaps that fall outside JWS-layer verification.

  • JWK authorization (RFC 7517 §4.2/§4.3). Call Jwk::check_op before using a key. If the JWK's use or key_ops field is set, the call enforces it — a verify-only key cannot be used to sign, an enc-marked key cannot be used for signatures, and so on. Jwk also provides to_public_jwk() for safely exporting a key (it strips every private component — d, p, q, dp, dq, qi, k).

  • JWK alg / kty consistency. Importing a JWK whose alg contradicts its kty (e.g. alg: "RS256" on a kty: "oct" key, or alg: "ES256" on a P-384 curve) is rejected at conversion time with a clear error, rather than failing opaquely downstream.

  • HMAC key minimum length (RFC 7518 §3.2). JWK-based JWS operations enforce 32/48/64-byte minimums for HS256/384/512 against the actual operation, including keys without alg metadata. Bindings constructing software signers/verifiers should use jwk::jwk_to_signature_key(&jwk, alg, JwkOp::Sign /* or Verify */); it also checks algorithm pins, permissions, key type/curve, and private material for signing. Select alg under application policy and use the returned key only for that algorithm and operation. Generic jwk_to_software_key remains a material-conversion API: it checks pinned HMAC lengths but cannot authorize an unspecified operation, and still infers AES for unpinned 16/24/32-byte keys.

  • Private JWK fields zeroize on drop. Jwk's Drop impl calls zeroize::Zeroize on d, p, q, dp, dq, qi, and k when present, so private material is wiped from the heap before the allocation is returned to the allocator.

  • jwt::decode_unverified is #[deprecated]. Every call site now emits a compiler warning pointing users to jwt::decode. The function remains available for legitimate pre-verification inspection (e.g. reading a token's kid to select the right verifier).

  • JWK-first API (safer one-shot for every operation). Prefer the *_with_jwk functions over the manual "build a signer/verifier yourself" path:

    • Sign/verify: jws::compact::sign_with_jwk, jws::compact::verify_with_jwk, jwt::encode_with_jwk, jwt::decode_with_jwk, jwt::decode_with_jwkset.
    • Encrypt/decrypt: jwe::encrypt_with_jwk, jwe::decrypt_with_jwk.

    Signing and verification derive the algorithm from the JWK or token header as appropriate. JWE encryption and decryption require jwk.alg to be pinned explicitly: jwe::encrypt_with_jwk reads the key-management algorithm from the JWK, and jwe::decrypt_with_jwk rejects tokens whose header alg does not match that pinned value. This prevents algorithm-substitution when one key is reused across configurations.

    Each API enforces Jwk::check_op for the intended operation (Sign/Verify/Encrypt/Decrypt/WrapKey/UnwrapKey) and constructs the underlying signer/verifier or key-material form internally. decode_with_jwkset is the canonical OIDC flow: a token pinning a kid selects exactly that JWK, and a kid matching nothing in an addressable set is a hard error rather than a fall-through. Tokens carrying no kid — and tokens pinning one against a set whose JWKs are themselves all kid-less, which cannot be addressed by name — try each key in the set in turn. Because that fallback can accept a token under any key in the set, pair it with Validation::require_kid() when the set mixes keys of differing trust. For new symmetric JWKs, prefer jwk::generate_symmetric_for_alg(...) or jwk::generate_direct_symmetric(...) so alg and use are pinned at creation time.

Post-quantum and composite signatures (experimental)

ML-DSA support is available behind the opt-in post-quantum feature:

[dependencies]
jose-rs = { version = "0.14.0", features = ["post-quantum"] }

Enabling this pulls in the optional ml-dsa crate plus kryptering's post-quantum backend. The shared pkcs8 0.11 dependency supplies its key encoding. It enables pure ML-DSA-44, ML-DSA-65, and ML-DSA-87, as well as all five composite identifiers listed above.

JWK wire format (kty = "AKP")

Per RFC 9964, ML-DSA keys use the "AKP" ("Algorithm Key Pair") key type with two base64url members:

  • pub — the raw FIPS 204 encoded public key (1312 / 1952 / 2592 bytes for the three security levels).
  • priv — the 32-byte FIPS 204 seed (not an expanded private key). The expanded signing key is derived on demand via ML-DSA.KeyGen_internal(seed).

Jwk.priv is zeroized on Drop alongside the existing RSA/EC/oct private-component wipe. Jwk::to_public_jwk() strips priv and keeps pub, which is the correct shape for a JWK Set endpoint.

Composite algorithms use the same AKP members, with concatenated encodings defined by draft-ietf-jose-pq-composite-sigs-07 and RFC 10073:

  • pub = ML-DSA public || traditional public
  • priv = 32-byte ML-DSA seed || traditional private

ECDSA public components are X9.62 uncompressed points, ECDSA private components are the draft's exact DER ECPrivateKey form, and ECDSA signature components are variable-length canonical DER. Draft-03 raw ECDSA components are rejected without fallback.

The selected alg fixes the component algorithms, prehash, domain-separation label, aggregate key lengths, and signature-length bounds. Import rejects wrong lengths, malformed traditional public keys, and private/public mismatches. Generate composite keys atomically so neither component is reused independently:

use kryptering::CompositeMlDsaVariant;

let key = jose_rs::jwk::generate_composite_mldsa(
    CompositeMlDsaVariant::MlDsa65Es384,
).unwrap();
let header = jose_rs::JoseHeader::new("ML-DSA-65-ES384");
let token = jose_rs::jws::compact::sign_with_jwk(&key, b"payload", &header).unwrap();
let payload = jose_rs::jws::compact::verify_with_jwk(&key.to_public_jwk(), &token).unwrap();
assert_eq!(payload, b"payload");

Status and caveats

  • Pure ML-DSA is standardized. The AKP JWK and pure ML-DSA JOSE behavior follows RFC 9964. FIPS 204 defines the signature primitive.

  • Composite draft status. Composite names and encodings follow draft-ietf-jose-pq-composite-sigs-07. They may change before publication. Draft-07 replaced draft-03 semantics: rotate draft-03 ECDSA composite keys and their thumbprint-derived kid values rather than relabeling them.

  • ml-dsa crate history. The RustCrypto ml-dsa crate shipped three moderate-severity advisories during its 0.1.0 release-candidate series. jose now tracks the stable ml-dsa 0.1.0 (and pkcs8 0.11.0) releases via caret ranges, matching kryptering. All three advisories were fixed in release candidates earlier than the stable release, so cargo audit is clean against ml-dsa 0.1.0:

    Advisory Summary Patched from
    GHSA-hcp2-x6j4-29j7 Decompose timing side-channel during signing >= 0.1.0-rc.3
    GHSA-5x2r-hc65-25f9 Repeated hint indices (signature malleability) >= 0.1.0-rc.4
    GHSA-h37v-hp6w-2pp8 UseHint off-by-two >= 0.1.0-rc.5

    Because the dependency now uses a caret range (0.1.0), any future ml-dsa advisory will be reported by cargo audit; remediation may require a Cargo.lock update — consult cargo audit before bumping, and track RustCrypto/signatures for further ml-dsa releases.

  • Default signing mode is randomized (hedged). ML-DSA sign uses real randomness per FIPS 204 Algorithm 2, so repeated signatures over the same message and key are expected to differ while still verifying. The optional deterministic signing variant (equivalent to a zero rnd) is not currently exposed.

  • ML-DSA-87 test note. The expanded signing key (~5 KiB) exceeds the default 2 MiB debug-build test-thread stack; the ML-DSA-87 round-trip test spawns itself on a larger-stack thread. Release builds have smaller stack frames and are unaffected.

Development tooling

Verifying a change

The mechanical half of this repository's per-change definition of done is one command:

./scripts/gate.sh                # fmt + tests × 5 configs + clippy × 5 + strict rustdoc + capability drift
./scripts/gate.sh --quick        # default configuration only, while iterating
./scripts/gate.sh --with-interop # plus the interop matrix and every peer suite
just gate                        # same script, if you have `just`

It prints per-configuration test totals so "I ran the gate" is a checkable claim rather than an assertion. The rest of the checklist — RFC and errata review, an ADR that states a consequence, negative tests that fail for the reason they claim, peer evidence that also pins what the peer accepts, migration notes, staged-file review and human merge — lives in docs/definition-of-done.md, where it is labelled as judgement instead of pretending to be automated (ADR 0033).

Dependencies, MSRV and platform checks

docs/dependencies.md records the locked versions, the feature map, the unified RustCrypto trait family, the advisory posture, and the platform promises (no unsafe, no async, no network, no filesystem in the library). tests/dependency_policy.rs checks those claims against the manifest and the lock, so the page cannot rot into folklore; ./scripts/dependency-report.sh regenerates its inputs (ADRs 0036 and 0037).

Performance baselines

cargo run --release --example perf_baseline        # markdown table of the measured axes
cargo test --release --test perf_baselines         # shape invariants CI enforces

Numbers belong in the pull request that changes them, with the command line and machine class; the harness, the procedure and the machine-independent invariants live in docs/performance-baseline.md (ADR 0035).

Fuzzing and regression replay

Harnesses live in fuzz/ and need nightly plus cargo-fuzz to search. What runs on every commit is the mirror: tests/fuzz_regressions.rs replays the checked-in corpus (fuzz/seeds/, generated by cargo run --example fuzz_seeds) plus deterministic mutations through the same input sequences the harnesses use, and fails if a harness starts exercising an entry point the mirror does not (ADR 0034).

Dependency audit

The repository is wired for cargo-audit. Local run:

cargo install --locked cargo-audit
cargo audit --deny warnings

CI runs the same command on every push to main, every pull request that touches Cargo.toml / Cargo.lock, and on a daily schedule (.github/workflows/audit.yml). With the current lockfile, the command completes successfully without warnings.

.cargo/audit.toml has no advisory ignores. Every advisory and, with --deny warnings, every audit warning fails the local and CI check. The RustSec Marvin advisory lists rsa >=0.10.0 as patched. CI also runs daily and on manual dispatch.

Interop test vectors (RFC 7520)

tests/rfc7520.rs verifies examples from RFC 7520 — these are the canonical worked vectors every JOSE implementation is expected to reproduce, which gives the library a cross-implementation interop baseline:

  • JWS §4.1–4.4. RS256, PS384, ES512 verify; HS256 as a full byte-for-byte deterministic roundtrip (sign then byte-compare against the RFC's published compact serialization).
  • JWE §5.6, §5.8. Direct encryption with A128GCM and A128KW + A128GCM — decrypt the RFC's published JWE and check the recovered plaintext.
  • JWE §5.2. RSA-OAEP + A256GCM decrypt using the RFC's RSA-4096 key. Runs only under --features deprecated because RSA-OAEP uses SHA-1.

All vectors are embedded verbatim from rfcs/rfc7520.txt with their original indent-continuations intact; runtime whitespace-stripping eliminates transcription risk in 1000+-char RSA key material.

Fuzzing

fuzz/ is a cargo-fuzz project with 17 targets covering attacker-controlled parse, key import, selection, verification and decryption paths. See fuzz/README.md for the per-target breakdown and long-running campaign controls.

just fuzz-setup
just fuzz-build
just fuzz-one jwk_from_json 300
just fuzz 3600                              # all targets, detached in tmux

The manually dispatched CI workflow (.github/workflows/fuzz.yml) builds every target to catch compilation regressions; actual fuzzing runs belong in a longer-running campaign or OSS-Fuzz once the corpus stabilizes.

License

BSD-2-Clause

Migrating to 0.12

  • Claims.extra and JoseHeader.extra now use BTreeMap<String, Value>. Custom members serialize in sorted order; typed members retain struct order. Convert an existing HashMap with .into_iter().collect(). This is stable serialization, not JSON canonicalization or preservation of incoming order.
  • Add Ed448 to exhaustive JwsAlgorithm and KeyGeneration matches. generate_ed448() returns an unpinned key, like generate_ed25519().
  • Edwards JWK pins accept the same-curve EdDSA spelling (ADR 0043). Require exact header spelling with Validation::with_allowed_algorithms.
  • decode_with_jwkset_authenticated and decode_with_jwkset_policy_authenticated retain the authenticated header and report verified_key_index(). The latter enforces a candidate budget.
  • UnverifiedJwt::parse exposes explicitly untrusted header/claims for key discovery. Payload duplicates are rejected at every object depth before normalization, including embedded JWKS/JWK data (ADR 0047). Ordinary JWT claim parsing keeps its top-level-only duplicate policy. After application-owned async discovery, call .verify_with(...). decode_self_signed provides a synchronous selector. Self-signature proves key possession, not issuer identity; no trust establishment or fetching occurs.
  • Validation::signature_only() disables exp/nbf/future-iat checks. It still verifies the signature; builders can add issuer, audience, type and algorithm policy. without_exp(), without_nbf() and without_iat_future_check() disable individual checks. Defaults still check all three with 60-second leeway; use Validation::new().with_leeway(0) for exact time boundaries.
  • Authenticated<T> now has private provenance state. Receive it from a verification API; transform its value with .map(...). Direct construction and exhaustive struct destructuring from outside the crate are unsupported.

See tests/migration_features.rs for independent Ed448 vectors and regression coverage, and ADRs 0043–0046 for the policy and compatibility consequences.