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