Skip to main content

wabot_addon_auth_jwt/
lib.rs

1//! # wabot-addon-auth-jwt
2//!
3//! JWT signing and the guard middleware that verifies them. Port of
4//! `wabot-ts/src/addon/auth/jwt` (`JwtConfig`, `JwtSigner`,
5//! `JwtGuardMiddleware`, `@jwtGuard`).
6//!
7//! ```ignore
8//! c.register_instance::<JwtConfig>(Arc::new(JwtConfig::from_env()?));
9//! register_singletons!(&c, JwtSigner, JwtGuard);
10//! // controllers that read Auth must be transient:
11//! register_transients!(&c, AccountController);
12//! ```
13//!
14//! ```ignore
15//! #[middleware(JwtGuard)]
16//! #[get("/me")]
17//! async fn me(&self) -> RestResult<Profile> {
18//!     let claims: Claims = self.auth.require_as()?;
19//!     …
20//! }
21//! ```
22//!
23//! ## Audiences and cookies
24//!
25//! Every session is signed with the same secret, so a token minted for
26//! one kind of user would otherwise work on another's endpoints. The
27//! `aud` claim is what separates them, and [`jwt_guard!`] declares a
28//! guard that requires one:
29//!
30//! ```ignore
31//! jwt_guard!(AdminGuard, audience = "admin", cookie = "admin_session");
32//! ```
33//!
34//! Separate cookie names let sessions of different user types coexist
35//! in one browser without overwriting each other.
36
37use std::sync::Arc;
38
39use async_trait::async_trait;
40use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use wabot_core::audit::{audit_actor_resolver, set_audit_actor};
45use wabot_core::auth::Auth;
46use wabot_core::injection::Container;
47use wabot_feature_rest_controller::{Middleware, RestError, RestResult};
48
49#[doc(hidden)]
50/// Socket.IO handshake guard. Behind the `socket` feature so a
51/// REST-only app doesn't compile socketioxide.
52#[cfg(feature = "socket")]
53pub mod handshake;
54#[cfg(feature = "socket")]
55pub use handshake::{JwtHandshakeGuard, JwtHandshakeOptions};
56#[cfg(feature = "socket")]
57#[doc(hidden)]
58pub use wabot_feature_socket_controller::{
59    socketioxide::extract::SocketRef as __SocketRef, HandshakeMiddleware as __HandshakeMiddleware,
60    SocketResult as __SocketResult,
61};
62
63/// Refresh tokens and sessions.
64pub mod refresh;
65pub use refresh::{
66    register_refresh_token_repository, InMemoryRefreshTokenRepository, Jwt, RefreshError,
67    RefreshToken, RefreshTokenData, RefreshTokenRepository, Session, SessionOptions,
68};
69
70pub use async_trait::async_trait as __async_trait;
71#[doc(hidden)]
72pub use wabot_core::injection::{
73    Container as __Container, IsSingleton, IsSingleton as __IsSingleton,
74};
75#[doc(hidden)]
76pub use wabot_feature_rest_controller::axum::http::request::Parts;
77#[doc(hidden)]
78pub use wabot_feature_rest_controller::{Middleware as __Middleware, RestResult as __RestResult};
79
80#[derive(Debug, Error)]
81pub enum JwtError {
82    #[error("{0} is not set")]
83    MissingEnv(&'static str),
84    #[error("unsupported JWT algorithm `{0}`")]
85    UnsupportedAlgorithm(String),
86    #[error("token signing failed: {0}")]
87    Signing(String),
88}
89
90/// Env var names, matching the TS config.
91pub mod env_names {
92    pub const SECRET: &str = "JWT_SECRET";
93    pub const ALGORITHM: &str = "JWT_ALGORITHM";
94    pub const ACCESS_EXPIRATION_SECONDS: &str = "JWT_ACCESS_EXPIRATION_SECONDS";
95    pub const REFRESH_EXPIRATION_SECONDS: &str = "JWT_REFRESH_EXPIRATION_SECONDS";
96    pub const COOKIE_NAME: &str = "JWT_COOKIE_NAME";
97    /// Comma-separated origins allowed to authenticate a socket
98    /// handshake with a cookie.
99    pub const COOKIE_ALLOWED_ORIGINS: &str = "JWT_COOKIE_ALLOWED_ORIGINS";
100}
101
102/// Secret, algorithm and lifetimes. Register one before the guard.
103#[derive(Clone)]
104pub struct JwtConfig {
105    encoding: EncodingKey,
106    decoding: DecodingKey,
107    pub algorithm: Algorithm,
108    pub access_expiration_seconds: u64,
109    /// How long a refresh token lives. Two weeks by default: long
110    /// enough that a browser session survives normal use, short enough
111    /// that an abandoned one lapses.
112    pub refresh_expiration_seconds: u64,
113    /// Cookie the guard falls back to when there's no `Authorization`
114    /// header. Default `wabot_jwt`.
115    pub cookie_name: String,
116    /// Origins allowed to authenticate a **socket handshake** with a
117    /// cookie. Empty by default, which refuses cookie handshake auth
118    /// outright — see [`handshake`] for why that has to fail closed.
119    pub cookie_allowed_origins: Vec<String>,
120}
121
122impl std::fmt::Debug for JwtConfig {
123    // Never let the key reach a log line.
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("JwtConfig")
126            .field("algorithm", &self.algorithm)
127            .field("access_expiration_seconds", &self.access_expiration_seconds)
128            .field("cookie_name", &self.cookie_name)
129            .finish_non_exhaustive()
130    }
131}
132
133impl JwtConfig {
134    /// HMAC config from a shared secret.
135    pub fn new(secret: impl AsRef<[u8]>) -> Self {
136        let secret = secret.as_ref();
137        Self {
138            encoding: EncodingKey::from_secret(secret),
139            decoding: DecodingKey::from_secret(secret),
140            algorithm: Algorithm::HS256,
141            access_expiration_seconds: 10 * 60,
142            refresh_expiration_seconds: 14 * 24 * 60 * 60,
143            cookie_name: "wabot_jwt".to_string(),
144            cookie_allowed_origins: Vec::new(),
145        }
146    }
147
148    /// Read `JWT_SECRET` + the optional knobs. Errors when the secret
149    /// is missing — a framework that quietly invented one would be
150    /// worse than a boot failure.
151    pub fn from_env() -> Result<Self, JwtError> {
152        use wabot_core::env;
153
154        let secret =
155            env::require(env_names::SECRET).map_err(|_| JwtError::MissingEnv(env_names::SECRET))?;
156        let mut config = Self::new(secret);
157        if let Some(algorithm) = env::string(env_names::ALGORITHM) {
158            config.algorithm = parse_algorithm(&algorithm)?;
159        }
160        config.access_expiration_seconds = env::or(
161            env_names::ACCESS_EXPIRATION_SECONDS,
162            config.access_expiration_seconds,
163        );
164        config.refresh_expiration_seconds = env::or(
165            env_names::REFRESH_EXPIRATION_SECONDS,
166            config.refresh_expiration_seconds,
167        );
168        config.cookie_name = env::string_or(env_names::COOKIE_NAME, config.cookie_name);
169        config.cookie_allowed_origins = env::list(env_names::COOKIE_ALLOWED_ORIGINS);
170        Ok(config)
171    }
172
173    pub fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
174        self.algorithm = algorithm;
175        self
176    }
177
178    pub fn with_access_expiration_seconds(mut self, seconds: u64) -> Self {
179        self.access_expiration_seconds = seconds;
180        self
181    }
182
183    pub fn with_refresh_expiration_seconds(mut self, seconds: u64) -> Self {
184        self.refresh_expiration_seconds = seconds;
185        self
186    }
187
188    pub fn with_cookie_name(mut self, name: impl Into<String>) -> Self {
189        self.cookie_name = name.into();
190        self
191    }
192
193    /// Origins allowed to authenticate a socket handshake with a
194    /// cookie. Without one, cookie handshake auth is refused.
195    pub fn with_cookie_allowed_origins<S: Into<String>>(
196        mut self,
197        origins: impl IntoIterator<Item = S>,
198    ) -> Self {
199        self.cookie_allowed_origins = origins.into_iter().map(Into::into).collect();
200        self
201    }
202
203    /// The decoding key, for guards in sibling modules. Only the
204    /// handshake guard needs it, and that is feature-gated.
205    #[cfg(feature = "socket")]
206    pub(crate) fn decoding_key(&self) -> &DecodingKey {
207        &self.decoding
208    }
209}
210
211fn parse_algorithm(name: &str) -> Result<Algorithm, JwtError> {
212    use std::str::FromStr;
213    Algorithm::from_str(name).map_err(|_| JwtError::UnsupportedAlgorithm(name.to_string()))
214}
215
216impl wabot_core::injection::IsSingleton for JwtConfig {
217    fn register_in(c: &Container) {
218        c.register_singleton_factory::<JwtConfig, _>(|_| {
219            Arc::new(JwtConfig::from_env().unwrap_or_else(|e| {
220                panic!("JwtConfig: {e}. Register one explicitly if you don't use env vars.")
221            }))
222        });
223    }
224}
225
226/// A signed token and when it expires. TS analogue: `JwtTokenDto`.
227#[derive(Debug, Clone, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct JwtToken {
230    pub token: String,
231    /// Unix seconds.
232    pub expiration: i64,
233}
234
235/// Options for one signing call.
236#[derive(Debug, Default, Clone)]
237pub struct SignOptions {
238    /// `aud` claim to stamp, so only guards declaring the same
239    /// audience accept the token.
240    pub audience: Option<String>,
241}
242
243/// Signs access tokens from a set of claims.
244pub struct JwtSigner {
245    config: Arc<JwtConfig>,
246}
247
248impl JwtSigner {
249    pub fn new(config: Arc<JwtConfig>) -> Self {
250        Self { config }
251    }
252
253    /// Sign `claims`, stamping `exp` (and `aud` when asked).
254    ///
255    /// The caller's claims are serialized to an object and the
256    /// registered claims merged in, so a domain type never has to know
257    /// about JWT mechanics.
258    pub fn sign(
259        &self,
260        claims: &impl Serialize,
261        options: &SignOptions,
262    ) -> Result<JwtToken, JwtError> {
263        let mut value =
264            serde_json::to_value(claims).map_err(|e| JwtError::Signing(e.to_string()))?;
265        let object = value
266            .as_object_mut()
267            .ok_or_else(|| JwtError::Signing("claims must serialize to a JSON object".into()))?;
268
269        let expiration =
270            chrono::Utc::now().timestamp() + self.config.access_expiration_seconds as i64;
271        object.insert("exp".into(), serde_json::json!(expiration));
272        if let Some(audience) = &options.audience {
273            object.insert("aud".into(), serde_json::json!(audience));
274        }
275
276        let token = jsonwebtoken::encode(
277            &Header::new(self.config.algorithm),
278            &value,
279            &self.config.encoding,
280        )
281        .map_err(|e| JwtError::Signing(e.to_string()))?;
282
283        Ok(JwtToken { token, expiration })
284    }
285
286    /// Sign with no audience.
287    pub fn sign_access_token(&self, claims: &impl Serialize) -> Result<JwtToken, JwtError> {
288        self.sign(claims, &SignOptions::default())
289    }
290}
291
292impl wabot_core::injection::IsSingleton for JwtSigner {
293    fn register_in(c: &Container) {
294        c.register_singleton_factory::<JwtSigner, _>(|c2| Arc::new(JwtSigner::new(c2.resolve())));
295    }
296}
297
298/// Per-endpoint guard settings. TS analogue: `IJwtGuardOptions`.
299#[derive(Debug, Default, Clone)]
300pub struct JwtGuardOptions {
301    /// Cookie names to try in order; empty falls back to
302    /// `JwtConfig::cookie_name`.
303    pub cookies: Vec<String>,
304    /// Required `aud` claim. `None` accepts any valid token.
305    pub audience: Option<String>,
306}
307
308/// Verifies tokens and fills the request's [`Auth`]. Stateless and
309/// shared — it writes into the *request's* container, which the
310/// middleware receives as an argument.
311pub struct JwtVerifier {
312    config: Arc<JwtConfig>,
313}
314
315impl JwtVerifier {
316    pub fn new(config: Arc<JwtConfig>) -> Self {
317        Self { config }
318    }
319
320    /// Extract, verify, and assign. The rejection message is
321    /// deliberately uniform — a caller must not learn *why* a token
322    /// was refused.
323    pub fn authenticate(
324        &self,
325        parts: &Parts,
326        container: &Container,
327        options: &JwtGuardOptions,
328    ) -> RestResult<()> {
329        let token = self.extract(parts, options)?;
330
331        let mut validation = Validation::new(self.config.algorithm);
332        match &options.audience {
333            Some(audience) => validation.set_audience(&[audience]),
334            // jsonwebtoken validates `aud` when the token carries one;
335            // a guard without an audience must accept those too.
336            None => validation.validate_aud = false,
337        }
338
339        let data =
340            jsonwebtoken::decode::<serde_json::Value>(&token, &self.config.decoding, &validation)
341                .map_err(|e| {
342                tracing::debug!(error = %e, "jwt rejected");
343                RestError::Unauthorized("Invalid token".into())
344            })?;
345
346        // Enforce the audience ourselves rather than trusting the
347        // library's: jsonwebtoken skips the check when the token
348        // carries no `aud` at all, which would let a token minted
349        // without an audience pass a guard that requires one.
350        if let Some(expected) = &options.audience {
351            if !claims_match_audience(&data.claims, expected) {
352                tracing::debug!(expected, "jwt rejected: audience mismatch");
353                return Err(RestError::Unauthorized("Invalid token".into()));
354            }
355        }
356
357        // Attribute the rest of this request to whoever the token
358        // names, so an audited write far downstream can say who asked
359        // for it. The resolver is the app's — the framework will not
360        // guess which claim is the user id.
361        set_audit_actor(audit_actor_resolver(container).from_auth(&data.claims));
362
363        Auth::of(container)
364            .assign(data.claims)
365            .map_err(|e| RestError::Unauthorized(e.to_string()))
366    }
367
368    /// `Authorization: Bearer …`, else the first cookie present.
369    fn extract(&self, parts: &Parts, options: &JwtGuardOptions) -> RestResult<String> {
370        if let Some(header) = parts.headers.get("authorization") {
371            let value = header
372                .to_str()
373                .map_err(|_| RestError::Unauthorized("Invalid Authorization header".into()))?;
374            let mut split = value.split(' ');
375            let scheme = split.next().unwrap_or_default();
376            let token = split.next().unwrap_or_default();
377            if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() || split.next().is_some()
378            {
379                return Err(RestError::Unauthorized(
380                    "Authorization header must be: Bearer <token>".into(),
381                ));
382            }
383            return Ok(token.to_string());
384        }
385
386        let names: Vec<&str> = if options.cookies.is_empty() {
387            vec![self.config.cookie_name.as_str()]
388        } else {
389            options.cookies.iter().map(String::as_str).collect()
390        };
391        for name in names {
392            if let Some(token) = cookie_value(parts, name) {
393                return Ok(token);
394            }
395        }
396        Err(RestError::Unauthorized(
397            "Missing authentication token".into(),
398        ))
399    }
400}
401
402impl wabot_core::injection::IsSingleton for JwtVerifier {
403    fn register_in(c: &Container) {
404        // So a controller holding `Arc<Auth>` still resolves on
405        // endpoints this guard doesn't cover.
406        Auth::register_default(c);
407        if !c.is_registered::<JwtConfig>() {
408            <JwtConfig as wabot_core::injection::IsSingleton>::register_in(c);
409        }
410        c.register_singleton_factory::<JwtVerifier, _>(|c2| {
411            Arc::new(JwtVerifier::new(c2.resolve()))
412        });
413    }
414}
415
416/// True when the token's `aud` claim matches `expected`. The claim is
417/// a string or an array of strings per RFC 7519; a missing claim never
418/// matches.
419pub(crate) fn claims_match_audience(claims: &serde_json::Value, expected: &str) -> bool {
420    match claims.get("aud") {
421        Some(serde_json::Value::String(actual)) => actual == expected,
422        Some(serde_json::Value::Array(values)) => values
423            .iter()
424            .any(|v| v.as_str().is_some_and(|s| s == expected)),
425        _ => false,
426    }
427}
428
429/// Read one cookie out of the request's `cookie` fields.
430///
431/// Every field is read, not the first: over HTTP/2 a browser may send one
432/// field per cookie (RFC 9113 §8.2.3), and Safari does.
433pub fn cookie_value(parts: &Parts, name: &str) -> Option<String> {
434    let fields = parts
435        .headers
436        .get_all("cookie")
437        .iter()
438        .filter_map(|field| field.to_str().ok());
439    for pair in fields.flat_map(|field| field.split(';')) {
440        let Some((key, value)) = pair.trim().split_once('=') else {
441            continue;
442        };
443        if key.trim() == name {
444            return Some(value.trim().to_string());
445        }
446    }
447    None
448}
449
450/// The default guard: any valid token, from the `Authorization` header
451/// or `JwtConfig::cookie_name`.
452pub struct JwtGuard {
453    verifier: Arc<JwtVerifier>,
454}
455
456impl JwtGuard {
457    pub fn new(verifier: Arc<JwtVerifier>) -> Self {
458        Self { verifier }
459    }
460}
461
462#[async_trait]
463impl Middleware for JwtGuard {
464    async fn handle(&self, parts: &Parts, container: &Container) -> RestResult<()> {
465        self.verifier
466            .authenticate(parts, container, &JwtGuardOptions::default())
467    }
468}
469
470impl wabot_core::injection::IsSingleton for JwtGuard {
471    fn register_in(c: &Container) {
472        if !c.is_registered::<JwtVerifier>() {
473            <JwtVerifier as wabot_core::injection::IsSingleton>::register_in(c);
474        }
475        c.register_singleton_factory::<JwtGuard, _>(|c2| Arc::new(JwtGuard::new(c2.resolve())));
476    }
477}
478
479/// Declare a guard with an audience and/or its own cookie names.
480///
481/// `#[middleware(T)]` names a type, so what TS passes to a decorator
482/// factory becomes a named guard type here:
483///
484/// ```ignore
485/// jwt_guard!(AdminGuard, audience = "admin", cookie = "admin_session");
486/// jwt_guard!(EitherGuard, cookies = ["staff_session", "admin_session"]);
487///
488/// register_singletons!(&c, AdminGuard);
489///
490/// #[middleware(AdminGuard)]
491/// #[get("/admin")]
492/// async fn admin(&self) -> RestResult<Report> { … }
493/// ```
494#[macro_export]
495macro_rules! jwt_guard {
496    (
497        $name:ident
498        $(, audience = $audience:expr)?
499        $(, cookie = $one:expr)?
500        $(, cookies = [$($cookie:expr),* $(,)?])?
501        $(,)?
502    ) => {
503        pub struct $name {
504            verifier: ::std::sync::Arc<$crate::JwtVerifier>,
505            options: $crate::JwtGuardOptions,
506        }
507
508        impl $name {
509            pub fn new(verifier: ::std::sync::Arc<$crate::JwtVerifier>) -> Self {
510                #[allow(unused_mut)]
511                let mut options = $crate::JwtGuardOptions::default();
512                $( options.audience = ::std::option::Option::Some($audience.to_string()); )?
513                $( options.cookies = ::std::vec![$one.to_string()]; )?
514                $( options.cookies = ::std::vec![$($cookie.to_string()),*]; )?
515                Self { verifier, options }
516            }
517        }
518
519        #[$crate::__async_trait]
520        impl $crate::__Middleware for $name {
521            async fn handle(
522                &self,
523                parts: &$crate::Parts,
524                container: &$crate::__Container,
525            ) -> $crate::__RestResult<()> {
526                self.verifier.authenticate(parts, container, &self.options)
527            }
528        }
529
530        impl $crate::IsSingleton for $name {
531            fn register_in(c: &$crate::__Container) {
532                if !c.is_registered::<$crate::JwtVerifier>() {
533                    <$crate::JwtVerifier as $crate::IsSingleton>::register_in(c);
534                }
535                c.register_singleton_factory::<$name, _>(|c2| {
536                    ::std::sync::Arc::new($name::new(c2.resolve()))
537                });
538            }
539        }
540    };
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546    use serde::{Deserialize, Serialize};
547    use wabot_feature_rest_controller::axum::http::Request;
548
549    #[derive(Debug, Serialize, Deserialize, PartialEq)]
550    struct Claims {
551        sub: String,
552        role: String,
553    }
554
555    fn claims() -> Claims {
556        Claims {
557            sub: "u-1".into(),
558            role: "admin".into(),
559        }
560    }
561
562    fn config() -> Arc<JwtConfig> {
563        Arc::new(JwtConfig::new("test-secret-value"))
564    }
565
566    fn parts_with(headers: &[(&str, &str)]) -> Parts {
567        let mut builder = Request::builder().uri("/");
568        for (name, value) in headers {
569            builder = builder.header(*name, *value);
570        }
571        builder.body(()).unwrap().into_parts().0
572    }
573
574    fn authenticate(headers: &[(&str, &str)], options: &JwtGuardOptions) -> RestResult<Arc<Auth>> {
575        let container = Container::new().create_child();
576        JwtVerifier::new(config()).authenticate(&parts_with(headers), &container, options)?;
577        Ok(Auth::of(&container))
578    }
579
580    fn bearer(token: &str) -> Vec<(&'static str, String)> {
581        vec![("authorization", format!("Bearer {token}"))]
582    }
583
584    fn as_refs<'a>(headers: &'a [(&'static str, String)]) -> Vec<(&'static str, &'a str)> {
585        headers.iter().map(|(k, v)| (*k, v.as_str())).collect()
586    }
587
588    #[test]
589    fn a_signed_token_round_trips_through_the_guard() {
590        let token = JwtSigner::new(config())
591            .sign_access_token(&claims())
592            .unwrap();
593        let headers = bearer(&token.token);
594        let auth = authenticate(&as_refs(&headers), &JwtGuardOptions::default()).unwrap();
595
596        let recovered: Claims = auth.require_as().unwrap();
597        assert_eq!(recovered, claims());
598        assert!(token.expiration > chrono::Utc::now().timestamp());
599    }
600
601    /// The point of attribution: a write far downstream can name the
602    /// person who asked for it, without every layer passing an id.
603    #[tokio::test]
604    async fn a_verified_token_attributes_the_request_to_its_subject() {
605        use wabot_core::audit::{
606            audit_actor, register_audit_actor_resolver, AuditActor, AuditActorResolver,
607        };
608        use wabot_core::log_context::{run_with_log_context, LogContext};
609
610        struct SubjectIsTheUser;
611        impl AuditActorResolver for SubjectIsTheUser {
612            fn from_auth(&self, claims: &serde_json::Value) -> AuditActor {
613                AuditActor::user().with_id(claims["sub"].as_str().unwrap_or("anonymous"))
614            }
615        }
616
617        let token = JwtSigner::new(config())
618            .sign_access_token(&claims())
619            .unwrap();
620        let headers = bearer(&token.token);
621
622        run_with_log_context(LogContext::new(), async {
623            let container = Container::new().create_child();
624            register_audit_actor_resolver(&container, Arc::new(SubjectIsTheUser));
625            JwtVerifier::new(config())
626                .authenticate(
627                    &parts_with(&as_refs(&headers)),
628                    &container,
629                    &JwtGuardOptions::default(),
630                )
631                .unwrap();
632
633            let actor = audit_actor().expect("the guard attributed the request");
634            assert_eq!(actor.kind, "user");
635            assert_eq!(actor.id.as_deref(), Some("u-1"));
636        })
637        .await;
638    }
639
640    #[tokio::test]
641    async fn a_rejected_token_attributes_nothing() {
642        use wabot_core::audit::audit_actor;
643        use wabot_core::log_context::{run_with_log_context, LogContext};
644
645        run_with_log_context(LogContext::new(), async {
646            let container = Container::new().create_child();
647            let _ = JwtVerifier::new(config()).authenticate(
648                &parts_with(&[("authorization", "Bearer not-a-token")]),
649                &container,
650                &JwtGuardOptions::default(),
651            );
652            assert!(
653                audit_actor().is_none(),
654                "an unauthenticated request must not be attributed to anyone"
655            );
656        })
657        .await;
658    }
659
660    #[test]
661    fn a_token_signed_with_another_secret_is_rejected() {
662        let other = Arc::new(JwtConfig::new("a-different-secret"));
663        let token = JwtSigner::new(other).sign_access_token(&claims()).unwrap();
664        let headers = bearer(&token.token);
665        assert!(matches!(
666            authenticate(&as_refs(&headers), &JwtGuardOptions::default()),
667            Err(RestError::Unauthorized(_))
668        ));
669    }
670
671    #[test]
672    fn a_tampered_token_is_rejected() {
673        let token = JwtSigner::new(config())
674            .sign_access_token(&claims())
675            .unwrap();
676        let mut segments: Vec<String> = token.token.split('.').map(String::from).collect();
677        segments[1].push('x');
678        let headers = bearer(&segments.join("."));
679        assert!(matches!(
680            authenticate(&as_refs(&headers), &JwtGuardOptions::default()),
681            Err(RestError::Unauthorized(_))
682        ));
683    }
684
685    #[test]
686    fn an_expired_token_is_rejected() {
687        // Well past jsonwebtoken's default 60s leeway.
688        let mut value = serde_json::to_value(claims()).unwrap();
689        value["exp"] = serde_json::json!(chrono::Utc::now().timestamp() - 3600);
690        let expired = jsonwebtoken::encode(
691            &Header::new(Algorithm::HS256),
692            &value,
693            &EncodingKey::from_secret(b"test-secret-value"),
694        )
695        .unwrap();
696
697        let headers = bearer(&expired);
698        assert!(matches!(
699            authenticate(&as_refs(&headers), &JwtGuardOptions::default()),
700            Err(RestError::Unauthorized(_))
701        ));
702    }
703
704    #[test]
705    fn the_audience_separates_sessions_signed_with_one_secret() {
706        let admin = JwtSigner::new(config())
707            .sign(
708                &claims(),
709                &SignOptions {
710                    audience: Some("admin".into()),
711                },
712            )
713            .unwrap();
714        let headers = bearer(&admin.token);
715        let headers = as_refs(&headers);
716
717        let admin_guard = JwtGuardOptions {
718            audience: Some("admin".into()),
719            ..Default::default()
720        };
721        let customer_guard = JwtGuardOptions {
722            audience: Some("customer".into()),
723            ..Default::default()
724        };
725
726        assert!(authenticate(&headers, &admin_guard).is_ok());
727        assert!(
728            authenticate(&headers, &customer_guard).is_err(),
729            "a token minted for one audience must not work on another's endpoints"
730        );
731        assert!(
732            authenticate(&headers, &JwtGuardOptions::default()).is_ok(),
733            "a guard without an audience accepts any valid token"
734        );
735    }
736
737    #[test]
738    fn a_token_without_an_audience_fails_a_guard_that_requires_one() {
739        let token = JwtSigner::new(config())
740            .sign_access_token(&claims())
741            .unwrap();
742        let headers = bearer(&token.token);
743        assert!(authenticate(
744            &as_refs(&headers),
745            &JwtGuardOptions {
746                audience: Some("admin".into()),
747                ..Default::default()
748            }
749        )
750        .is_err());
751    }
752
753    #[test]
754    fn the_cookie_is_the_fallback_when_there_is_no_header() {
755        let token = JwtSigner::new(config())
756            .sign_access_token(&claims())
757            .unwrap();
758        let cookie = format!("other=x; wabot_jwt={}; more=y", token.token);
759        let auth = authenticate(&[("cookie", &cookie)], &JwtGuardOptions::default()).unwrap();
760        assert!(auth.is_assigned());
761    }
762
763    /// Safari over HTTP/2 sends each cookie in a field of its own, and
764    /// only the first was read: with any other cookie ahead of it, a
765    /// signed-in browser was refused as tokenless.
766    #[test]
767    fn the_cookie_is_found_in_any_of_several_fields() {
768        let token = JwtSigner::new(config())
769            .sign_access_token(&claims())
770            .unwrap();
771        let session = format!("wabot_jwt={}", token.token);
772        let auth = authenticate(
773            &[("cookie", "_ga=GA1.1"), ("cookie", &session)],
774            &JwtGuardOptions::default(),
775        )
776        .unwrap();
777        assert!(auth.is_assigned());
778    }
779
780    #[test]
781    fn named_cookies_let_two_sessions_share_a_browser() {
782        let staff = JwtSigner::new(config())
783            .sign_access_token(&claims())
784            .unwrap();
785        let cookie = format!("admin_session=not-a-token; staff_session={}", staff.token);
786
787        assert!(authenticate(
788            &[("cookie", &cookie)],
789            &JwtGuardOptions {
790                cookies: vec!["staff_session".into()],
791                ..Default::default()
792            }
793        )
794        .is_ok());
795
796        assert!(
797            authenticate(
798                &[("cookie", &cookie)],
799                &JwtGuardOptions {
800                    cookies: vec!["admin_session".into()],
801                    ..Default::default()
802                }
803            )
804            .is_err(),
805            "the admin cookie holds a bogus token"
806        );
807    }
808
809    #[test]
810    fn a_malformed_authorization_header_does_not_fall_through_to_cookies() {
811        let token = JwtSigner::new(config())
812            .sign_access_token(&claims())
813            .unwrap();
814        let cookie = format!("wabot_jwt={}", token.token);
815        let result = authenticate(
816            &[("authorization", "Basic abc123"), ("cookie", &cookie)],
817            &JwtGuardOptions::default(),
818        );
819        assert!(
820            matches!(result, Err(RestError::Unauthorized(_))),
821            "a present-but-wrong header must be an error, not a silent cookie fallback"
822        );
823    }
824
825    #[test]
826    fn no_credential_at_all_is_unauthorized() {
827        assert!(matches!(
828            authenticate(&[], &JwtGuardOptions::default()),
829            Err(RestError::Unauthorized(_))
830        ));
831    }
832
833    #[test]
834    fn an_array_audience_claim_matches_any_member() {
835        let mut value = serde_json::to_value(claims()).unwrap();
836        value["aud"] = serde_json::json!(["admin", "staff"]);
837        value["exp"] = serde_json::json!(chrono::Utc::now().timestamp() + 600);
838        let token = jsonwebtoken::encode(
839            &Header::new(Algorithm::HS256),
840            &value,
841            &EncodingKey::from_secret(b"test-secret-value"),
842        )
843        .unwrap();
844        let headers = bearer(&token);
845        let headers = as_refs(&headers);
846
847        for audience in ["admin", "staff"] {
848            assert!(authenticate(
849                &headers,
850                &JwtGuardOptions {
851                    audience: Some(audience.into()),
852                    ..Default::default()
853                }
854            )
855            .is_ok());
856        }
857        assert!(authenticate(
858            &headers,
859            &JwtGuardOptions {
860                audience: Some("customer".into()),
861                ..Default::default()
862            }
863        )
864        .is_err());
865    }
866
867    #[test]
868    fn config_never_prints_its_key() {
869        let printed = format!("{:?}", JwtConfig::new("super-secret-value"));
870        assert!(!printed.contains("super-secret"), "got: {printed}");
871        assert!(printed.contains("HS256"));
872    }
873}