Skip to main content

trust_tasks_https/
auth.rs

1//! Authentication seam: resolve an incoming HTTP request to a Verifiable
2//! Identifier.
3//!
4//! [`Auth`] is the trait the server uses to convert a bearer token into a
5//! VID. [`BearerAuth`] is a minimal `HashMap`-backed implementation
6//! suitable for demos and tests; real deployments would implement [`Auth`]
7//! against their identity provider, peer-certificate database, JWT
8//! verifier, etc.
9
10use std::collections::HashMap;
11
12/// Resolves bearer tokens to Verifiable Identifiers.
13///
14/// Implementations are consulted on every inbound request before the
15/// framework's [`TransportHandler`](trust_tasks_rs::TransportHandler) sees
16/// the document. Returning `None` means the request is unauthenticated;
17/// the server may still accept it (the framework falls back to in-band
18/// `issuer` + `proof`), or apply policy (e.g. require auth for non-bearer
19/// specs).
20pub trait Auth: Send + Sync + 'static {
21    /// Resolve `token` to a VID, or return `None` if the token is unknown.
22    fn resolve(&self, token: &str) -> Option<String>;
23}
24
25/// Static `HashMap`-backed [`Auth`] implementation. Constructed from a
26/// list of `(token, vid)` pairs.
27///
28/// ```rust,ignore
29/// use trust_tasks_https::BearerAuth;
30///
31/// let auth = BearerAuth::from_pairs([
32///     ("alice-token", "did:web:alice.example"),
33///     ("bob-token",   "did:web:bob.example"),
34/// ]);
35/// ```
36#[derive(Debug, Clone, Default)]
37pub struct BearerAuth {
38    tokens: HashMap<String, String>,
39}
40
41impl BearerAuth {
42    /// Empty bearer-auth table; every token resolves to `None`.
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    /// Build from `(token, vid)` pairs. Either argument can be anything
48    /// `Into<String>`-convertible.
49    pub fn from_pairs<I, T, V>(iter: I) -> Self
50    where
51        I: IntoIterator<Item = (T, V)>,
52        T: Into<String>,
53        V: Into<String>,
54    {
55        let mut auth = Self::new();
56        for (t, v) in iter {
57            auth.insert(t, v);
58        }
59        auth
60    }
61
62    /// Insert a single `(token, vid)` mapping, builder-style.
63    pub fn with(mut self, token: impl Into<String>, vid: impl Into<String>) -> Self {
64        self.insert(token, vid);
65        self
66    }
67
68    /// Insert a single `(token, vid)` mapping in place.
69    pub fn insert(&mut self, token: impl Into<String>, vid: impl Into<String>) {
70        self.tokens.insert(token.into(), vid.into());
71    }
72}
73
74impl Auth for BearerAuth {
75    fn resolve(&self, token: &str) -> Option<String> {
76        self.tokens.get(token).cloned()
77    }
78}
79
80/// JWT-bearer [`Auth`] adapter — available behind the `jwt` Cargo
81/// feature.
82#[cfg(feature = "jwt")]
83#[cfg_attr(docsrs, doc(cfg(feature = "jwt")))]
84pub use jwt::JwtBearerAuth;
85
86#[cfg(feature = "jwt")]
87#[cfg_attr(docsrs, doc(cfg(feature = "jwt")))]
88mod jwt {
89    use std::marker::PhantomData;
90
91    use jsonwebtoken::{decode, DecodingKey, Validation};
92    use serde::de::DeserializeOwned;
93
94    use super::Auth;
95
96    /// [`Auth`] adapter that decodes an inbound JWT bearer token under a
97    /// caller-supplied `DecodingKey` + [`Validation`], then delegates the
98    /// subject-VID extraction to a closure over the typed claims.
99    ///
100    /// Most Trust-Tasks consumers running on a JWT-based session model
101    /// (OIDC, Affinidi sessions, etc.) end up re-inventing this glue
102    /// inside their [`Auth`] impl — the wrapper exists so the same six
103    /// lines do not appear in every consumer.
104    ///
105    /// ```rust,ignore
106    /// use jsonwebtoken::{DecodingKey, Validation, Algorithm};
107    /// use serde::Deserialize;
108    /// use trust_tasks_https::JwtBearerAuth;
109    ///
110    /// #[derive(Deserialize)]
111    /// struct MyClaims {
112    ///     sub: String,
113    ///     /// Custom claim — your session JWT might carry the VID
114    ///     /// separately from the OIDC `sub`.
115    ///     vid: Option<String>,
116    /// }
117    ///
118    /// let auth = JwtBearerAuth::<MyClaims>::new(
119    ///     DecodingKey::from_secret(b"my-shared-secret"),
120    ///     Validation::new(Algorithm::HS256),
121    ///     |claims| claims.vid.clone().or(Some(claims.sub.clone())),
122    /// );
123    /// ```
124    ///
125    /// On any decode / signature / `Validation` failure the adapter
126    /// returns `None` from [`Auth::resolve`], producing an
127    /// unauthenticated request — the framework then falls back to
128    /// in-band `issuer` + `proof` per SPEC.md §4.8.1.
129    pub struct JwtBearerAuth<C: DeserializeOwned + Send + Sync + 'static> {
130        key: DecodingKey,
131        validation: Validation,
132        extract: Box<ExtractFn<C>>,
133        _phantom: PhantomData<fn() -> C>,
134    }
135
136    /// Caller-supplied subject-extraction closure: given the decoded
137    /// typed claims, return the VID string (or `None` to fall back to
138    /// unauthenticated, e.g. if the claim that names the VID is empty).
139    type ExtractFn<C> = dyn Fn(&C) -> Option<String> + Send + Sync;
140
141    impl<C: DeserializeOwned + Send + Sync + 'static> JwtBearerAuth<C> {
142        /// Build a [`JwtBearerAuth`] over the supplied verification key,
143        /// `jsonwebtoken` [`Validation`] policy, and a subject-extraction
144        /// closure over the typed claims.
145        pub fn new<F>(key: DecodingKey, validation: Validation, extract: F) -> Self
146        where
147            F: Fn(&C) -> Option<String> + Send + Sync + 'static,
148        {
149            // Guardrail against algorithm confusion: an empty `algorithms`
150            // list tells `jsonwebtoken` to accept a token's self-declared
151            // `alg`, enabling HS/RS key-confusion and `alg: none` forgeries.
152            // A verifier MUST pin the exact algorithm(s) it expects; this is a
153            // programming error, so fail loudly at construction rather than
154            // silently accept forged tokens.
155            assert!(
156                !validation.algorithms.is_empty(),
157                "JwtBearerAuth requires Validation to pin at least one algorithm; \
158                 an empty `algorithms` list disables algorithm checking and \
159                 exposes algorithm-confusion attacks"
160            );
161            Self {
162                key,
163                validation,
164                extract: Box::new(extract),
165                _phantom: PhantomData,
166            }
167        }
168    }
169
170    impl<C: DeserializeOwned + Send + Sync + 'static> std::fmt::Debug for JwtBearerAuth<C> {
171        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172            f.debug_struct("JwtBearerAuth")
173                .field("claims_type", &std::any::type_name::<C>())
174                .finish_non_exhaustive()
175        }
176    }
177
178    impl<C: DeserializeOwned + Send + Sync + 'static> Auth for JwtBearerAuth<C> {
179        fn resolve(&self, token: &str) -> Option<String> {
180            let data = decode::<C>(token, &self.key, &self.validation).ok()?;
181            (self.extract)(&data.claims)
182        }
183    }
184
185    #[cfg(test)]
186    mod tests {
187        use super::*;
188        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
189        use serde::{Deserialize, Serialize};
190
191        #[derive(Serialize, Deserialize)]
192        struct Claims {
193            sub: String,
194            vid: Option<String>,
195            exp: usize,
196        }
197
198        fn sign(secret: &[u8], claims: &Claims) -> String {
199            encode(
200                &Header::new(Algorithm::HS256),
201                claims,
202                &EncodingKey::from_secret(secret),
203            )
204            .unwrap()
205        }
206
207        fn auth(secret: &[u8]) -> JwtBearerAuth<Claims> {
208            let mut v = Validation::new(Algorithm::HS256);
209            v.validate_exp = true;
210            v.required_spec_claims.clear();
211            JwtBearerAuth::new(DecodingKey::from_secret(secret), v, |c: &Claims| {
212                c.vid.clone().or_else(|| Some(c.sub.clone()))
213            })
214        }
215
216        #[test]
217        fn valid_jwt_resolves_to_vid_via_claims_closure() {
218            let secret = b"test-secret";
219            let token = sign(
220                secret,
221                &Claims {
222                    sub: "user-123".into(),
223                    vid: Some("did:web:alice.example".into()),
224                    exp: 10_000_000_000,
225                },
226            );
227            let auth = auth(secret);
228            assert_eq!(
229                auth.resolve(&token),
230                Some("did:web:alice.example".to_string())
231            );
232        }
233
234        #[test]
235        #[should_panic(expected = "at least one algorithm")]
236        fn empty_validation_algorithms_is_rejected_at_construction() {
237            let mut v = Validation::new(Algorithm::HS256);
238            v.algorithms.clear(); // pins nothing — must not be constructible
239            let _ = JwtBearerAuth::new(DecodingKey::from_secret(b"x"), v, |c: &Claims| {
240                Some(c.sub.clone())
241            });
242        }
243
244        #[test]
245        fn token_with_unexpected_alg_is_rejected() {
246            // Auth pins HS256; a token signed with HS512 must not resolve.
247            let secret = b"test-secret";
248            let token = encode(
249                &Header::new(Algorithm::HS512),
250                &Claims {
251                    sub: "did:web:eve.example".into(),
252                    vid: None,
253                    exp: 10_000_000_000,
254                },
255                &EncodingKey::from_secret(secret),
256            )
257            .unwrap();
258            assert_eq!(auth(secret).resolve(&token), None);
259        }
260
261        #[test]
262        fn jwt_without_vid_claim_falls_back_to_subject() {
263            let secret = b"test-secret";
264            let token = sign(
265                secret,
266                &Claims {
267                    sub: "did:web:fallback.example".into(),
268                    vid: None,
269                    exp: 10_000_000_000,
270                },
271            );
272            let auth = auth(secret);
273            assert_eq!(
274                auth.resolve(&token),
275                Some("did:web:fallback.example".to_string())
276            );
277        }
278
279        #[test]
280        fn wrong_signature_returns_none() {
281            let token = sign(
282                b"correct-secret",
283                &Claims {
284                    sub: "x".into(),
285                    vid: None,
286                    exp: 10_000_000_000,
287                },
288            );
289            let auth = auth(b"wrong-secret");
290            assert!(auth.resolve(&token).is_none());
291        }
292
293        #[test]
294        fn expired_jwt_returns_none() {
295            let token = sign(
296                b"test-secret",
297                &Claims {
298                    sub: "x".into(),
299                    vid: None,
300                    exp: 1, // 1970
301                },
302            );
303            let auth = auth(b"test-secret");
304            assert!(auth.resolve(&token).is_none());
305        }
306
307        #[test]
308        fn malformed_jwt_returns_none() {
309            let auth = auth(b"test-secret");
310            assert!(auth.resolve("not-a-jwt").is_none());
311        }
312    }
313}