jose_rs/authenticated.rs
1//! Values that arrived under authentication, and the header that came with them.
2//!
3//! The trust boundary in JOSE is not "trusted versus untrusted data" — after a
4//! signature check or an AEAD opening, everything is trusted *as far as the check
5//! reached*. The boundary is between:
6//!
7//! * **what was integrity-protected** — the JWS protected header, the JWE
8//! protected header, and the payload/plaintext they authenticated; and
9//! * **what was not** — JWE `unprotected`, the per-signature/per-recipient
10//! `header` member, and the JSON serialization's shared `unprotected` object.
11//! Those bytes travel in the clear and are attacker-chosen even when the
12//! document verifies perfectly.
13//!
14//! The concrete hazard is order of operations: an implementation that reads
15//! `unprotected.kid` to *choose* a key has made its own authentication decision
16//! depend on unauthenticated input, which is how "encrypt-then-sign" confusion and
17//! kid-confusion attacks work. This module cannot prevent a caller from ignoring
18//! that, but it removes the most common way to fall into it by accident —
19//! re-parsing the header after the fact, from whichever copy is nearest, and
20//! getting the unprotected one.
21//!
22//! [`Authenticated<T>`] carries the verified value, the authenticated header, and
23//! the unprotected metadata **as separate, differently-named fields**, and it is
24//! only constructible by the verification paths in this crate. There is no public
25//! constructor, so an `Authenticated` value always means what its name claims.
26//!
27//! ```
28//! use jose_rs::jwk;
29//! use jose_rs::jws::compact;
30//! use jose_rs::JoseHeader;
31//!
32//! let mut jwk = jwk::generate_ed25519()?;
33//! jwk.alg = Some("EdDSA".into());
34//! let mut header = JoseHeader::new("EdDSA");
35//! header.typ = Some("application+jwt".into());
36//! let token = compact::sign_with_jwk(&jwk, b"payload", &header)?;
37//!
38//! // One parse, and the authenticated header comes back with the payload.
39//! let outcome = compact::verify_with_jwk_authenticated(&jwk, &token)?;
40//! assert_eq!(outcome.value, b"payload");
41//! assert_eq!(outcome.protected.typ.as_deref(), Some("application+jwt"));
42//! // Nothing unauthenticated was carried in a compact JWS at all.
43//! assert!(outcome.unprotected.is_empty());
44//! # Ok::<(), jose_rs::JoseError>(())
45//! ```
46
47use crate::header::JoseHeader;
48use serde_json::Value;
49
50/// A value that arrived under signature or AEAD authentication.
51///
52/// Fields are public because they are the answer, not because they are
53/// interchangeable: [`protected`](Self::protected) was integrity-protected by the
54/// operation that produced this value, and [`unprotected`](Self::unprotected)
55/// explicitly was not. Use the protected header for any decision — algorithm, key
56/// identity, content type, `crit` — and treat the unprotected entries as
57/// display-only metadata.
58#[derive(Debug, Clone)]
59pub struct Authenticated<T> {
60 /// The verified payload, plaintext, or parsed claims.
61 pub value: T,
62 /// The protected header that was authenticated with this value.
63 ///
64 /// This is the header *the signature covered* (or the JWE protected header the
65 /// AEAD tag authenticated), parsed once by the verification path. It is not a
66 /// re-parse of whatever bytes the caller still has.
67 pub protected: JoseHeader,
68 /// Unauthenticated metadata carried by the document, verbatim.
69 ///
70 /// A compact JWS carries none, so this is usually empty. A flattened or general
71 /// JWS/JWE can carry several objects (the shared `unprotected` member plus a
72 /// `header` member per signature/recipient); each is one entry here, in the
73 /// order they appeared.
74 ///
75 /// **Never select a key, an algorithm, or a trust decision from these.** They
76 /// are not integrity-protected: a document that verifies perfectly can carry a
77 /// hostile `kid` here.
78 pub unprotected: Vec<Value>,
79 verified_key_index: Option<usize>,
80}
81
82impl<T> Authenticated<T> {
83 /// Construct an outcome.
84 ///
85 /// `pub(crate)`: the type's meaning is "a verification path produced this", and
86 /// a public constructor would let anyone mint that claim. Verification paths in
87 /// this crate call it; callers only ever receive the result.
88 pub(crate) fn new(value: T, protected: JoseHeader, unprotected: Vec<Value>) -> Self {
89 Self {
90 value,
91 protected,
92 unprotected,
93 verified_key_index: None,
94 }
95 }
96
97 /// Index of the JWK that verified this token, relative to the supplied set.
98 ///
99 /// This identifies the successful candidate even in a kid-less fallback.
100 /// It is not an identity or authorization claim. Single-key and JWE APIs
101 /// return `None`; [`Self::map`] preserves it.
102 pub fn verified_key_index(&self) -> Option<usize> {
103 self.verified_key_index
104 }
105
106 pub(crate) fn with_verified_key_index(mut self, index: usize) -> Self {
107 self.verified_key_index = Some(index);
108 self
109 }
110
111 /// Discard the header and keep the value.
112 pub fn into_value(self) -> T {
113 self.value
114 }
115
116 /// Transform the value, keeping the header context.
117 ///
118 /// Useful for parsing a verified payload into a domain type without losing the
119 /// authenticated header next to it.
120 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Authenticated<U> {
121 Authenticated {
122 value: f(self.value),
123 protected: self.protected,
124 unprotected: self.unprotected,
125 verified_key_index: self.verified_key_index,
126 }
127 }
128
129 /// The authenticated `alg` value.
130 ///
131 /// A convenience for the single most common header read after verification —
132 /// and the reason it exists as a method is so that read does not have to reach
133 /// for a header from somewhere else.
134 pub fn algorithm(&self) -> &str {
135 &self.protected.alg
136 }
137
138 /// The `kid` from the **authenticated** header only.
139 ///
140 /// Deliberately does not consult [`unprotected`](Self::unprotected), unlike a
141 /// `PlainHeader`-style getter that would search every object it can find.
142 pub fn kid(&self) -> Option<&str> {
143 self.protected.kid.as_deref()
144 }
145
146 /// `true` when the document carried any unauthenticated metadata.
147 ///
148 /// A caller that logs "this document tried to tell me something outside the
149 /// signature" can gate on this.
150 pub fn has_unprotected(&self) -> bool {
151 !self.unprotected.is_empty()
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 fn outcome() -> Authenticated<Vec<u8>> {
160 let mut protected = JoseHeader::new("ES256");
161 protected.kid = Some("signed-kid".into());
162 Authenticated::new(
163 b"payload".to_vec(),
164 protected,
165 vec![serde_json::json!({"kid": "unsigned-kid"})],
166 )
167 }
168
169 #[test]
170 fn the_kid_accessor_reads_the_authenticated_header_only() {
171 // The whole point of the type in one assertion: the document carries a
172 // second, unauthenticated `kid`, and the accessor must not see it.
173 let outcome = outcome();
174 assert_eq!(outcome.kid(), Some("signed-kid"));
175 assert_eq!(
176 outcome.unprotected[0].get("kid").and_then(Value::as_str),
177 Some("unsigned-kid"),
178 "the unauthenticated value is still *reported*, it is simply not authoritative"
179 );
180 assert!(outcome.has_unprotected());
181 }
182
183 #[test]
184 fn mapping_keeps_the_header_context() {
185 let parsed = outcome().map(|bytes| String::from_utf8(bytes).unwrap());
186 assert_eq!(parsed.value, "payload");
187 assert_eq!(parsed.algorithm(), "ES256");
188 assert_eq!(parsed.kid(), Some("signed-kid"));
189 assert_eq!(parsed.unprotected.len(), 1);
190 }
191
192 #[test]
193 fn a_compact_style_document_has_no_unprotected_metadata() {
194 let outcome = Authenticated::new(b"x".to_vec(), JoseHeader::new("EdDSA"), Vec::new());
195 assert!(!outcome.has_unprotected());
196 assert_eq!(outcome.clone().into_value(), b"x".to_vec());
197 }
198}