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).unwrap(),
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(
256 DecodingKey::from_secret(secret).unwrap(),
257 v,
258 |c: &Claims| c.vid.clone().or_else(|| Some(c.sub.clone())),
259 )
260 }
261
262 #[test]
263 fn valid_jwt_resolves_to_vid_via_claims_closure() {
264 let secret = b"test-secret";
265 let token = sign(
266 secret,
267 &Claims {
268 sub: "user-123".into(),
269 vid: Some("did:web:alice.example".into()),
270 exp: 10_000_000_000,
271 },
272 );
273 let auth = auth(secret);
274 assert_eq!(
275 auth.resolve(&token),
276 Some("did:web:alice.example".to_string())
277 );
278 }
279
280 #[test]
281 #[should_panic(expected = "at least one algorithm")]
282 fn empty_validation_algorithms_is_rejected_at_construction() {
283 let mut v = Validation::new(Algorithm::HS256);
284 v.algorithms.clear(); // pins nothing — must not be constructible
285 let _ = JwtBearerAuth::new(DecodingKey::from_secret(b"x").unwrap(), v, |c: &Claims| {
286 Some(c.sub.clone())
287 });
288 }
289
290 #[test]
291 fn token_with_unexpected_alg_is_rejected() {
292 // Auth pins HS256; a token signed with HS512 must not resolve.
293 let secret = b"test-secret";
294 let token = encode(
295 &Header::new(Algorithm::HS512),
296 &Claims {
297 sub: "did:web:eve.example".into(),
298 vid: None,
299 exp: 10_000_000_000,
300 },
301 &EncodingKey::from_secret(secret).unwrap(),
302 )
303 .unwrap();
304 assert_eq!(auth(secret).resolve(&token), None);
305 }
306
307 #[test]
308 fn jwt_without_vid_claim_falls_back_to_subject() {
309 let secret = b"test-secret";
310 let token = sign(
311 secret,
312 &Claims {
313 sub: "did:web:fallback.example".into(),
314 vid: None,
315 exp: 10_000_000_000,
316 },
317 );
318 let auth = auth(secret);
319 assert_eq!(
320 auth.resolve(&token),
321 Some("did:web:fallback.example".to_string())
322 );
323 }
324
325 #[test]
326 fn wrong_signature_returns_none() {
327 let token = sign(
328 b"correct-secret",
329 &Claims {
330 sub: "x".into(),
331 vid: None,
332 exp: 10_000_000_000,
333 },
334 );
335 let auth = auth(b"wrong-secret");
336 assert!(auth.resolve(&token).is_none());
337 }
338
339 #[test]
340 fn expired_jwt_returns_none() {
341 let token = sign(
342 b"test-secret",
343 &Claims {
344 sub: "x".into(),
345 vid: None,
346 exp: 1, // 1970
347 },
348 );
349 let auth = auth(b"test-secret");
350 assert!(auth.resolve(&token).is_none());
351 }
352
353 #[test]
354 fn malformed_jwt_returns_none() {
355 let auth = auth(b"test-secret");
356 assert!(auth.resolve("not-a-jwt").is_none());
357 }
358 }
359}