Skip to main content

jose4rs/
lib.rs

1//! # jose4rs
2//!
3//! A Rust implementation of the JOSE standards -- [JWS] (RFC 7515), [JWE]
4//! (RFC 7516), [JWK] (RFC 7517), and [JWT] (RFC 7519) -- ported from the Java
5//! [jose4j] library.
6//!
7//! [JWS]: https://tools.ietf.org/html/rfc7515
8//! [JWE]: https://tools.ietf.org/html/rfc7516
9//! [JWK]: https://tools.ietf.org/html/rfc7517
10//! [JWT]: https://tools.ietf.org/html/rfc7519
11//! [jose4j]: https://bitbucket.org/b_c/jose4j
12//!
13//! ## Modules
14//!
15//! - [`jwk`] -- JSON Web Keys and key sets, plus optional HTTPS JWKS fetching.
16//! - [`jws`] -- JSON Web Signature creation and verification.
17//! - [`jwe`] -- JSON Web Encryption encryption and decryption.
18//! - [`jwt`] -- JWT claims and a validating consumer.
19//! - [`jwa`] -- algorithm identifiers and algorithm constraints.
20//! - [`jwx`] -- shared JOSE header parameters and structure traits.
21//! - [`error`] -- the crate's error type.
22//!
23//! ## Design goals
24//!
25//! - **Minimal allocations** on the hot parse/verify/decrypt paths. Decoded
26//!   JOSE parts are referenced by offset into a single owned buffer rather
27//!   than copied.
28//! - **No panics on attacker-controlled input.** Malformed tokens and keys
29//!   return [`error::JoseError`]; panics are reserved for internal invariants.
30//! - **Backend flexibility.** Cryptography is provided by [aws-lc-rs] (default)
31//!   or [BoringSSL], selected by feature flag. ML-DSA is currently available
32//!   only with AWS-LC.
33//!
34//! [aws-lc-rs]: https://crates.io/crates/aws-lc-rs
35//! [BoringSSL]: https://github.com/google/boringssl
36//!
37//! ## Features
38//!
39//! | Feature | Effect |
40//! |---------|--------|
41//! | `aws-lc` (default) | Use the aws-lc-rs cryptography backend. Mutually exclusive with `boring`. |
42//! | `boring` | Use the `BoringSSL` cryptography backend. Mutually exclusive with `aws-lc`. |
43//! | `base64-simd` (default) | SIMD-accelerated base64. |
44//! | `base64` | Portable (non-SIMD) base64 fallback. |
45//! | `pq-ml-dsa` | ML-DSA signatures and AKP JWKs (RFC 9964); implies `aws-lc`. |
46//! | `jwks-https` | Blocking HTTPS JWKS fetching (bring your own transport). |
47//! | `jwks-https-async` | Async HTTPS JWKS fetching; implies `jwks-https`. |
48//!
49//! Exactly one cryptography backend (`aws-lc` or `boring`) must be enabled;
50//! selecting both or neither is a compile error.
51//!
52//! ## Example
53//!
54//! Verify a JWS and read its payload:
55//!
56//! ```no_run
57//! use jose4rs::jws::JsonWebSignature;
58//! use jose4rs::jwk::JsonWebKey;
59//! # use jose4rs::jwx::JsonWebStructure;
60//!
61//! # let compact = "eyJhbGc...";
62//! # let key_json = r#"{"kty":"oct","k":"..."}"#;
63//! let key = JsonWebKey::from_json(key_json)?;
64//! let mut jws = JsonWebSignature::from_compact_serialization(compact)?;
65//! let payload = jws.payload(&key)?; // verifies the signature first
66//! # Ok::<(), jose4rs::error::JoseError>(())
67//! ```
68
69// Pedantic clippy is enabled crate-wide; the lints below are opted out because
70// they are stylistic preferences or are dominated by FFI noise from the
71// aws-lc / boring wrappers (C `c_int` returns, length casts, raw-pointer
72// conversions), where the casts are intentional and SAFETY-documented.
73#![warn(clippy::pedantic)]
74#![allow(
75    // FFI-driven numeric/pointer casts in `src/crypto`; values are bounded by
76    // the underlying C API contracts.
77    clippy::cast_possible_truncation,
78    clippy::cast_possible_wrap,
79    clippy::cast_sign_loss,
80    clippy::cast_precision_loss,
81    clippy::borrow_as_ptr,
82    clippy::ptr_as_ptr,
83    clippy::ptr_cast_constness,
84    clippy::ref_as_ptr,
85    // Stylistic preferences we don't enforce.
86    clippy::must_use_candidate,
87    clippy::return_self_not_must_use,
88    clippy::similar_names,
89    clippy::many_single_char_names,
90    clippy::unreadable_literal,
91    clippy::too_many_lines,
92    clippy::struct_excessive_bools,
93    clippy::match_wildcard_for_single_variants,
94    clippy::trivially_copy_pass_by_ref,
95    clippy::needless_pass_by_value,
96    clippy::unused_self,
97    clippy::items_after_statements,
98    clippy::module_name_repetitions,
99    clippy::elidable_lifetime_names,
100    // Per-algorithm lookup tables keep one arm per variant for clarity, even
101    // when some bodies coincide; and some crypto fns return `Result` to match
102    // their erroring siblings even when a given path can't fail.
103    clippy::match_same_arms,
104    clippy::unnecessary_wraps
105)]
106
107// The two cryptography backends are mutually exclusive: both provide the same
108// FFI symbols, so enabling both would be ambiguous (and linking them together
109// is unsupported). Fail at compile time with a clear message rather than a
110// confusing cascade of duplicate-symbol / missing-import errors.
111#[cfg(all(feature = "aws-lc", feature = "boring"))]
112compile_error!(
113    "features `aws-lc` and `boring` are mutually exclusive; enable exactly one \
114     cryptography backend (e.g. `--no-default-features --features boring,base64-simd`)"
115);
116
117// At least one cryptography backend is required. Without one, no EVP/AEAD/RSA
118// symbols exist and the crate cannot build; say so directly.
119#[cfg(not(any(feature = "aws-lc", feature = "boring")))]
120compile_error!(
121    "no cryptography backend selected; enable exactly one of `aws-lc` (default) \
122     or `boring`"
123);
124
125mod base64;
126mod crypto;
127/// The crate error type, [`error::JoseError`].
128pub mod error;
129/// JOSE algorithms: identifiers and algorithm-constraint enforcement.
130pub mod jwa;
131/// JSON Web Encryption (JWE, RFC 7516) creation and decryption.
132pub mod jwe;
133/// JSON Web Keys (JWK, RFC 7517) and key sets (JWKS).
134pub mod jwk;
135/// JSON Web Signature (JWS, RFC 7515) creation and verification.
136pub mod jws;
137/// JSON Web Token (JWT, RFC 7519) claims and a validating consumer.
138pub mod jwt;
139/// Shared JOSE header parameters and the common structure trait.
140pub mod jwx;
141
142/// An index pair into a per-struct backing buffer, used to reference decoded
143/// JOSE parts without copying them.
144///
145/// A `BufferRef` owns nothing; it is only `{start_idx, end_idx}` into a buffer
146/// owned elsewhere (e.g. the `buffer: Vec<u8>` on [`jwe::JsonWebEncryption`] or
147/// [`jws::JsonWebSignature`]). The buffer is always passed in to [`BufferRef::get`]
148/// / [`BufferRef::get_mut`].
149///
150/// # Usage notes
151///
152/// * **Zero-copy, but re-fetch after growth.** The backing `Vec` may reallocate
153///   and move to a different memory block when it grows (e.g. another part is
154///   appended). Any `&[u8]` / `&mut [u8]` obtained from [`get`](BufferRef::get) /
155///   [`get_mut`](BufferRef::get_mut) borrows the *current* location, so it must
156///   not be held across a push/`extend_from_slice`/etc. that could reallocate.
157///   Re-fetch the slice after any such mutation.
158/// * **Indices, not pointers.** Because the struct stores offsets rather than
159///   raw pointers, the `BufferRef` itself stays valid across buffer growth -- only
160///   the borrowed slice it produces does not.
161/// * **`get_unchecked`.** `get`/`get_mut` use `get_unchecked` for speed; the
162///   invariant is that `start_idx <= end_idx <= buffer.len()` always holds for
163///   the buffer this `BufferRef` was created against.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub(crate) struct BufferRef {
166    start_idx: usize,
167    end_idx: usize,
168}
169
170impl BufferRef {
171    pub fn new(start_idx: usize, end_idx: usize) -> Self {
172        BufferRef { start_idx, end_idx }
173    }
174
175    pub fn is_empty(&self) -> bool {
176        self.end_idx == 0 || self.end_idx - self.start_idx == 0
177    }
178
179    pub fn len(&self) -> usize {
180        self.end_idx - self.start_idx
181    }
182
183    pub fn get<'a>(&self, s: &'a [u8]) -> &'a [u8] {
184        unsafe { s.get_unchecked(self.start_idx..self.end_idx) }
185    }
186
187    pub fn get_mut<'a>(&self, s: &'a mut [u8]) -> &'a mut [u8] {
188        unsafe { s.get_unchecked_mut(self.start_idx..self.end_idx) }
189    }
190}