diff --git a/apps/auth-service/src/federation/providers/google.rs b/apps/auth-service/src/federation/providers/google.rs index 19836a114..e3cd72bc3 100644 --- a/apps/auth-service/src/federation/providers/google.rs +++ b/apps/auth-service/src/federation/providers/google.rs @@ -4,13 +4,14 @@ use super::{ FederationApplication, FederationConfigError, IdentityStrategy, MAX_TOKEN_BYTES, Provider, ProviderEndpoints, ProviderError, VerifiedIdentity, }; -use chrono::Utc; +use chrono::{DateTime, Utc}; use serde::Deserialize; use sourceorigin_auth::{Jws, KeyCache, TokenError}; use sourceorigin_common::protocol::{ claims::Audience, jwt::Algorithm, oauth::{Prompt, Scope}, + registered::{ClaimsError, Expiry, RegisteredClaims, Validation}, }; use thiserror::Error; use url::Url; @@ -21,8 +22,6 @@ const SCOPES: &[&str] = &[ Scope::Email.as_str(), Scope::Profile.as_str(), ]; -/// Allowed clock skew when checking ID-token issuance. -const CLOCK_SKEW_SECONDS: i64 = 30; /// Display name proposed when the token carries no usable name. const FALLBACK_NAME: &str = "Google user"; /// The domain of Gmail addresses, which Google always hosts. @@ -43,24 +42,10 @@ pub(in crate::federation) enum GoogleError { /// The ID token's claims are missing or have the wrong type. #[error("Google ID token claims are invalid")] Claims(#[source] serde_json::Error), - /// The ID token was issued by someone other than Google. - #[error("Google ID token issuer {0:?} is not Google")] - UntrustedIssuer(String), - /// The ID token is for another client. - #[error("Google ID token is not for this client")] - WrongAudience, - /// The ID token also names clients other than this one. - #[error("Google ID token audience includes other clients")] - SharedAudience, - /// The ID token was issued for another sign-in attempt. - #[error("Google ID token nonce does not match this sign-in attempt")] - NonceMismatch, - /// The ID token has expired. - #[error("Google ID token has expired")] - Expired, - /// The ID token's issuance time is in the future. - #[error("Google ID token is issued in the future")] - IssuedInFuture, + /// The ID token is not Google's, not for this client alone, expired, not yet + /// valid, or for another sign-in attempt. + #[error("Google ID token claims are not accepted")] + Rejected(#[from] ClaimsError), /// The ID token was authorized for another client. #[error("Google ID token authorized party is another client")] AuthorizedPartyMismatch, @@ -118,7 +103,8 @@ impl FederationApplication { protocol: &GoogleProtocol, ) -> Result { let token: GoogleToken = Self::json(response).await?; - let claims = GoogleClaims::verify(&token.id_token, protocol, client_id, nonce).await?; + let claims = + GoogleClaims::verify(&token.id_token, protocol, client_id, nonce, Utc::now()).await?; let authoritative = claims.authoritative(); VerifiedIdentity::new( Provider::Google, @@ -149,10 +135,15 @@ pub(in crate::federation) struct GoogleClaims { aud: Audience, /// Stable Google account ID. sub: String, - /// Expiry, as a Unix timestamp. - exp: i64, - /// Issuance time, as a Unix timestamp. - iat: i64, + /// Expiry. + #[serde(with = "chrono::serde::ts_seconds")] + exp: DateTime, + /// Time before which the token must not be accepted, which Google may send. + #[serde(default, with = "chrono::serde::ts_seconds_option")] + nbf: Option>, + /// Issuance time. + #[serde(with = "chrono::serde::ts_seconds")] + iat: DateTime, /// Nonce stored with the federation flow when it started. nonce: String, /// Authorized party; must be this client when present. @@ -171,14 +162,16 @@ pub(in crate::federation) struct GoogleClaims { } impl GoogleClaims { - /// Verifies the signature against Google's published keys, then the issuer, - /// exclusive audience, nonce and times. Unlike the SDK's own ID tokens, expiry has - /// no leeway: the token came straight from Google's token endpoint. + /// Verifies the signature against Google's published keys, then, at `now`, the + /// shared check of the issuer, exclusive audience, times and nonce, and last the + /// authorized party. Unlike the SDK's own ID tokens, expiry has no leeway + /// ([`Expiry::Strict`]): the token came straight from Google's token endpoint. pub(in crate::federation) async fn verify( token: &str, protocol: &GoogleProtocol, client_id: &str, nonce: &str, + now: DateTime, ) -> Result { if token.len() > MAX_TOKEN_BYTES { return Err(GoogleError::TokenTooLong(token.len())); @@ -187,25 +180,14 @@ impl GoogleClaims { let algorithm = jws.require_algorithm(&[Algorithm::Rs256])?; protocol.keys.verify(&jws, algorithm).await?; let claims: Self = serde_json::from_slice(jws.payload()).map_err(GoogleError::Claims)?; - if !protocol.issuers.contains(&claims.iss.as_str()) { - return Err(GoogleError::UntrustedIssuer(claims.iss)); - } - if !claims.aud.contains(client_id) { - return Err(GoogleError::WrongAudience); - } - if claims.aud.iter().any(|audience| audience != client_id) { - return Err(GoogleError::SharedAudience); - } - if claims.nonce != nonce { - return Err(GoogleError::NonceMismatch); - } - let now = Utc::now().timestamp(); - if claims.exp <= now { - return Err(GoogleError::Expired); - } - if claims.iat > now + CLOCK_SKEW_SECONDS { - return Err(GoogleError::IssuedInFuture); + Validation { + issuers: protocol.issuers, + audience: Some(client_id), + nonce: Some(nonce), + expiry: Expiry::Strict, + now, } + .check(&claims)?; if claims.azp.as_deref().is_some_and(|azp| azp != client_id) { return Err(GoogleError::AuthorizedPartyMismatch); } @@ -231,3 +213,27 @@ impl GoogleClaims { .is_some_and(|hd| domain.eq_ignore_ascii_case(hd))) } } + +impl RegisteredClaims for GoogleClaims { + /// An ID token, which trusts no other audience (OIDC Core §3.1.3.7). + const EXCLUSIVE_AUDIENCE: bool = true; + + fn issuer(&self) -> &str { + &self.iss + } + fn audience(&self) -> &Audience { + &self.aud + } + fn expires_at(&self) -> DateTime { + self.exp + } + fn not_before(&self) -> Option> { + self.nbf + } + fn issued_at(&self) -> DateTime { + self.iat + } + fn nonce(&self) -> Option<&str> { + Some(&self.nonce) + } +} diff --git a/apps/auth-service/src/federation/tests/protocols.rs b/apps/auth-service/src/federation/tests/protocols.rs index c531bf0a3..9b59dad94 100644 --- a/apps/auth-service/src/federation/tests/protocols.rs +++ b/apps/auth-service/src/federation/tests/protocols.rs @@ -2,8 +2,10 @@ use super::*; use crate::federation::providers::{GoogleClaims, GoogleProtocol}; +use chrono::DateTime; use sourceorigin_auth::{KeyCache, KeySet}; use sourceorigin_common::protocol::jwt::{Algorithm, TokenType}; +use sourceorigin_common::protocol::registered::ClaimsError; use sourceorigin_crypto::Rs256Key; use tracing::Instrument; @@ -161,8 +163,8 @@ async fn google_key_fetch_is_a_client_span_of_its_request() { } /// ID-token verification rejects untrusted signatures, malformed claims, untrusted -/// issuers, other or additional audiences, another nonce, and tokens expired or -/// issued in the future. +/// issuers, other or additional audiences, another nonce, and tokens expired, not yet +/// valid or issued in the future, all at the time it is given. #[tokio::test] async fn google_signed_tokens_are_verified() { let rsa = Rs256Key::generate("google-test").expect("RSA key"); @@ -175,51 +177,65 @@ async fn google_signed_tokens_are_verified() { protocol.keys = KeyCache::fixed( KeySet::parse(&serde_json::to_vec(&rsa.jwks()).expect("JWKS")).expect("key set"), ); - let valid = serde_json::json!({"iss":"https://accounts.google.com","aud":"client","sub":"subject","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"nonce"}); + // Long past, so a check reading the system clock would refuse every token. + let now = DateTime::from_timestamp(1_767_225_600, 0).expect("time"); + let at = |seconds: i64| now.timestamp() + seconds; + let valid = serde_json::json!({"iss":"https://accounts.google.com","aud":"client","sub":"subject","iat":at(0),"exp":at(300),"nonce":"nonce"}); let verify = async |claims: &serde_json::Value| { let token = rsa.sign(TokenType::Id, claims).expect("signed token"); - GoogleClaims::verify(&token, &protocol, "client", "nonce").await + GoogleClaims::verify(&token, &protocol, "client", "nonce", now).await + }; + // The shared check's error, behind Google's. + let rejection = async |claims: &serde_json::Value| { + let error = verify(claims).await.err()?; + std::error::Error::source(&error)? + .downcast_ref::() + .cloned() }; assert!(verify(&valid).await.is_ok()); let untrusted = Rs256Key::generate("google-test").expect("untrusted key"); let token = untrusted.sign(TokenType::Id, &valid).expect("signed token"); assert_eq!( - GoogleClaims::verify(&token, &protocol, "client", "nonce") + GoogleClaims::verify(&token, &protocol, "client", "nonce", now) .await .map_err(|error| error.to_string()) .err() .as_deref(), Some("Google ID token failed verification") ); + let time = |seconds: i64| DateTime::from_timestamp(at(seconds), 0).expect("time"); for (field, value, error) in [ ( "nonce", serde_json::json!("other"), - "Google ID token nonce does not match this sign-in attempt", + ClaimsError::NonceMismatch, ), ( "iat", - serde_json::json!(Utc::now().timestamp() + 3600), - "Google ID token is issued in the future", + serde_json::json!(at(31)), + ClaimsError::IssuedInFuture(time(31)), + ), + // Google may send `nbf`, which gets the same leeway as `iat`. + ( + "nbf", + serde_json::json!(at(31)), + ClaimsError::NotYetValid(time(31)), ), // Expiry has no leeway: a token that expired a second ago is refused. ( "exp", - serde_json::json!(Utc::now().timestamp() - 1), - "Google ID token has expired", + serde_json::json!(at(-1)), + ClaimsError::Expired(time(-1)), ), ] { let mut claims = valid.clone(); claims[field] = value; - assert_eq!( - verify(&claims) - .await - .map_err(|error| error.to_string()) - .err() - .as_deref(), - Some(error), - "{field}" - ); + assert_eq!(rejection(&claims).await, Some(error), "{field}"); + } + for (field, value) in [("iat", at(30)), ("nbf", at(30))] { + let mut claims = valid.clone(); + claims[field] = serde_json::json!(value); + assert!(verify(&claims).await.is_ok(), "{field} within the leeway"); } for field in ["iss", "aud", "exp", "sub"] { let mut claims = valid.clone(); diff --git a/crates/auth-sdk/src/client.rs b/crates/auth-sdk/src/client.rs index e0f4fb5fb..01b0f51fa 100644 --- a/crates/auth-sdk/src/client.rs +++ b/crates/auth-sdk/src/client.rs @@ -968,7 +968,7 @@ impl Client { let client = self.config().client_id.as_str(); let claims: LogoutTokenClaims = self .issuer() - .decode(token, TokenType::Logout, client) + .decode(token, TokenType::Logout, client, None) .await?; LogoutToken::from_claims(claims) } diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index fb9c3c891..9278700ab 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -150,7 +150,7 @@ pub use token::{ /// by name, so this list is the SDK's contract. pub mod protocol { pub use sourceorigin_common::protocol::{ - challenge, claims, jwt, metadata, oauth, sdk, step_up, + challenge, claims, jwt, metadata, oauth, registered, sdk, step_up, }; pub use sourceorigin_common::{ClientId, DeliveryId, InvalidValue, SessionId, TokenId, UserId}; } diff --git a/crates/auth-sdk/src/resource.rs b/crates/auth-sdk/src/resource.rs index af5e6dd7a..aef8fadc1 100644 --- a/crates/auth-sdk/src/resource.rs +++ b/crates/auth-sdk/src/resource.rs @@ -213,7 +213,7 @@ impl ResourceValidator { ) -> Result, TokenError> { let claims: AccessTokenClaims = self .issuer - .decode(token, TokenType::Access, self.resource.identifier()) + .decode(token, TokenType::Access, self.resource.identifier(), None) .await?; AccessToken::from_claims(claims)?.into_scoped() } diff --git a/crates/auth-sdk/src/tests.rs b/crates/auth-sdk/src/tests.rs index af054b752..786557c00 100644 --- a/crates/auth-sdk/src/tests.rs +++ b/crates/auth-sdk/src/tests.rs @@ -178,7 +178,7 @@ async fn token_vectors() { let resource = Resource::new(audience).expect("vector resource"); match issuer.resource(resource).validate::(token).await { Ok(_) => case.assert::(Ok(issuer - .decode(token, TokenType::Access, audience) + .decode(token, TokenType::Access, audience, None) .await .expect("decode a token that validated"))), Err(error) => case.assert::<()>(Err(error.code())), diff --git a/crates/auth-sdk/src/token.rs b/crates/auth-sdk/src/token.rs index f371549fe..cdb5561bd 100644 --- a/crates/auth-sdk/src/token.rs +++ b/crates/auth-sdk/src/token.rs @@ -8,12 +8,13 @@ use sourceorigin_common::{ protocol::{ challenge::{BearerChallenge, BearerError}, claims::{ - AccessTokenClaims, Acr, Actor, Amr, Audience, Confirmation, IdTokenClaims, - LogoutTokenClaims, ProfileClaims, + AccessTokenClaims, Acr, Actor, Amr, Confirmation, IdTokenClaims, LogoutTokenClaims, + ProfileClaims, }, constants::{LEEWAY, MAX_LOGOUT_LIFETIME}, jwt::{Algorithm, Claim, TokenType}, oauth::Scopes, + registered::{ClaimsError, Expiry, RegisteredClaims, Validation}, sdk::{ErrorCategory, ErrorReason, SdkError}, step_up::StepUpRequirement, }, @@ -28,10 +29,13 @@ use thiserror::Error; /// use chrono::Utc; /// use sourceorigin_auth::{ /// KeyError, TokenError, -/// protocol::sdk::{ErrorCategory, ErrorReason, SdkError}, +/// protocol::{ +/// registered::ClaimsError, +/// sdk::{ErrorCategory, ErrorReason, SdkError}, +/// }, /// }; /// -/// let expired = TokenError::Expired(Utc::now()); +/// let expired = TokenError::Claims(ClaimsError::Expired(Utc::now())); /// assert_eq!( /// expired.code(), /// SdkError::new(ErrorCategory::InvalidToken, ErrorReason::Expired) @@ -82,31 +86,9 @@ pub enum TokenError { /// `sub` is neither an account ID nor the client. #[error("token subject {0:?} is not an account ID")] InvalidSubject(String), - /// `iss` is not the issuer. - #[error("token issuer is {found:?}, expected {expected:?}")] - WrongIssuer { - /// The configured issuer. - expected: String, - /// The token's `iss`. - found: String, - }, - /// `aud` does not contain the expected value. - #[error("token audience {found:?} does not contain {expected:?}")] - WrongAudience { - /// The resource or client this token must be for. - expected: String, - /// The token's `aud`. - found: Audience, - }, - /// `exp` has passed, beyond the leeway. - #[error("token expired at {0}")] - Expired(DateTime), - /// `nbf` is in the future, beyond the leeway. - #[error("token is not valid before {0}")] - NotYetValid(DateTime), - /// `iat` is in the future, beyond the leeway. - #[error("token is issued in the future, at {0}")] - IssuedInFuture(DateTime), + /// `iss`, `aud`, a time or the ID token's `nonce` fails the shared check. + #[error(transparent)] + Claims(#[from] ClaimsError), /// A logout token's `exp` is more than 10 minutes after its `iat`. #[error("logout token is valid from {issued_at} to {expires_at}, longer than 10 minutes")] LifetimeTooLong { @@ -118,9 +100,6 @@ pub enum TokenError { /// A logout token names neither `sub` nor `sid`, so no session to end. #[error("logout token names neither sub nor sid")] NoLogoutTarget, - /// The ID token's `nonce` is not the pending login's. - #[error("ID token nonce does not match this login")] - NonceMismatch, /// The ID token's `azp` names another client. #[error("ID token authorized party is {found:?}, expected {expected:?}")] WrongAuthorizedParty { @@ -167,6 +146,7 @@ impl TokenError { pub const fn code(&self) -> SdkError { let reason = match self { Self::Keys(error) => return error.code(), + Self::Claims(error) => error.reason(), Self::InsufficientScope { .. } => { return SdkError::category(ErrorCategory::InsufficientScope); } @@ -182,13 +162,7 @@ impl TokenError { Self::InvalidClaims(_) | Self::InvalidSubject(_) | Self::NoLogoutTarget => { ErrorReason::InvalidClaims } - Self::WrongIssuer { .. } => ErrorReason::IssuerMismatch, - Self::WrongAudience { .. } => ErrorReason::WrongAudience, - Self::Expired(_) => ErrorReason::Expired, - Self::NotYetValid(_) => ErrorReason::NotYetValid, - Self::IssuedInFuture(_) => ErrorReason::IssuedInFuture, Self::LifetimeTooLong { .. } => ErrorReason::LifetimeTooLong, - Self::NonceMismatch => ErrorReason::NonceMismatch, Self::WrongAuthorizedParty { .. } => ErrorReason::WrongAuthorizedParty, Self::AuthenticationTooOld { .. } => ErrorReason::AuthenticationTooOld, Self::SubjectMismatch { .. } => ErrorReason::SubjectMismatch, @@ -675,108 +649,6 @@ impl LogoutToken { } } -/// The registered claims every token type checks the same way. -pub(crate) trait RegisteredClaims: DeserializeOwned { - /// `iss`. - fn issuer(&self) -> &str; - /// `aud`. - fn audience(&self) -> &Audience; - /// `exp`. - fn expires_at(&self) -> DateTime; - /// `nbf`, if any. - fn not_before(&self) -> Option>; - /// `iat`. - fn issued_at(&self) -> DateTime; - - /// Whether `aud` must name the expected audience alone. ID tokens trust no other - /// audience (OIDC Core §3.1.3.7), so `azp` can only confirm this client, and auth - /// addresses each logout token to one client; access tokens may name several. - const EXCLUSIVE_AUDIENCE: bool; - - /// Checks `iss`, `aud` and the times, in the documented order. - fn check(&self, issuer: &str, audience: &str, now: DateTime) -> Result<(), TokenError> { - if self.issuer() != issuer { - return Err(TokenError::WrongIssuer { - expected: issuer.to_owned(), - found: self.issuer().to_owned(), - }); - } - let others = - Self::EXCLUSIVE_AUDIENCE && self.audience().iter().any(|value| value != audience); - if others || !self.audience().contains(audience) { - return Err(TokenError::WrongAudience { - expected: audience.to_owned(), - found: self.audience().clone(), - }); - } - // Checked: a far-future `exp` must not overflow, and never expires. - if self - .expires_at() - .checked_add_signed(LEEWAY) - .is_some_and(|deadline| now >= deadline) - { - return Err(TokenError::Expired(self.expires_at())); - } - if let Some(not_before) = self.not_before().filter(|nbf| *nbf > now + LEEWAY) { - return Err(TokenError::NotYetValid(not_before)); - } - if self.issued_at() > now + LEEWAY { - return Err(TokenError::IssuedInFuture(self.issued_at())); - } - Ok(()) - } -} - -/// Implements [`RegisteredClaims`] for claims types whose registered claims are their -/// `iss`, `aud`, `exp` and `iat` fields. Each names its `nbf` field, or `none` for a -/// type without one, so no type can leave the not-before check out by omission. -macro_rules! registered_claims { - (@not_before $claims:ident, none) => { - None - }; - (@not_before $claims:ident, $nbf:ident) => { - $claims.$nbf - }; - ($( - impl $([$($generics:tt)*])? for $claims:ty { - exclusive_audience: $exclusive:literal, not_before: $nbf:ident - } - )+) => {$( - impl$(<$($generics)*>)? RegisteredClaims for $claims { - const EXCLUSIVE_AUDIENCE: bool = $exclusive; - - fn issuer(&self) -> &str { - &self.iss - } - fn audience(&self) -> &Audience { - &self.aud - } - fn expires_at(&self) -> DateTime { - self.exp - } - fn not_before(&self) -> Option> { - registered_claims!(@not_before self, $nbf) - } - fn issued_at(&self) -> DateTime { - self.iat - } - } - )+}; -} - -registered_claims! { - impl [X: DeserializeOwned] for AccessTokenClaims { - exclusive_audience: false, not_before: nbf - } - impl for IdTokenClaims { - exclusive_audience: true, not_before: nbf - } - // `LogoutTokenClaims` has no `nbf`. - impl for LogoutTokenClaims { - exclusive_audience: true, not_before: none - } -} - impl Issuer { /// Algorithms both this SDK and the issuer accept. fn algorithms(&self) -> Vec { @@ -790,20 +662,29 @@ impl Issuer { .collect() } - /// Runs the shared checks on a token of type `typ` meant for `audience`, in the - /// order of the SDK design: framing, type, algorithm, key, signature, claims. - pub(crate) async fn decode( + /// Runs the shared checks on a token of type `typ` meant for `audience`, bound to + /// the login's `nonce` if it sent one, in the order of the SDK design: framing, + /// type, algorithm, key, signature, claims. + pub(crate) async fn decode( &self, token: &str, typ: TokenType, audience: &str, + nonce: Option<&str>, ) -> Result { let jws = Jws::parse(token)?; jws.require_type(typ)?; let algorithm = jws.require_algorithm(&self.algorithms())?; self.keys().verify(&jws, algorithm).await?; let claims: T = serde_json::from_slice(jws.payload()).map_err(TokenError::InvalidClaims)?; - claims.check(self.issuer(), audience, self.now())?; + Validation { + issuers: &[self.issuer()], + audience: Some(audience), + nonce, + expiry: Expiry::Lenient, + now: self.now(), + } + .check(&claims)?; Ok(claims) } @@ -816,10 +697,9 @@ impl Issuer { nonce: Option<&str>, max_age: Option, ) -> Result { - let claims: IdTokenClaims = self.decode(token, TokenType::Id, client.as_str()).await?; - if nonce.is_some_and(|nonce| claims.nonce.as_deref() != Some(nonce)) { - return Err(TokenError::NonceMismatch); - } + let claims: IdTokenClaims = self + .decode(token, TokenType::Id, client.as_str(), nonce) + .await?; if let Some(azp) = claims.azp.as_ref().filter(|azp| *azp != client) { return Err(TokenError::WrongAuthorizedParty { expected: client.clone(), diff --git a/crates/common/src/protocol/constants.rs b/crates/common/src/protocol/constants.rs index 2fbbbdf1d..f70c34b87 100644 --- a/crates/common/src/protocol/constants.rs +++ b/crates/common/src/protocol/constants.rs @@ -7,7 +7,8 @@ use std::time::Duration; super::sdk_constants! { /// Clock skew tolerated on `exp`, `nbf`, `iat` and `auth_time`. Auth tolerates the - /// same on `iat` alone, and none on `exp` or `max_age`. + /// same on `nbf` and `iat` alone, and none on `exp` or `max_age` + /// (`registered::Expiry`). pub const LEEWAY: TimeDelta = TimeDelta::seconds(30); /// Longest a logout token may be valid: auth signs each delivery attempt for two /// minutes, so a longer-lived token was not made for one attempt. diff --git a/crates/common/src/protocol/mod.rs b/crates/common/src/protocol/mod.rs index 56252361f..e3eafc478 100644 --- a/crates/common/src/protocol/mod.rs +++ b/crates/common/src/protocol/mod.rs @@ -71,6 +71,8 @@ pub mod jwt; pub mod metadata; /// OAuth and OpenID Connect vocabulary shared by clients and the provider. pub mod oauth; +/// The one check of a token's registered claims, and its leeway policy. +pub mod registered; /// Whether a browser request comes from a site's own pages. pub mod same_origin; /// Error codes shared by the SDKs and their test vectors. diff --git a/crates/common/src/protocol/registered/mod.rs b/crates/common/src/protocol/registered/mod.rs new file mode 100644 index 000000000..1b3383fd9 --- /dev/null +++ b/crates/common/src/protocol/registered/mod.rs @@ -0,0 +1,273 @@ +//! The one check of a token's registered claims (RFC 7519 §4.1) and `nonce`, which +//! auth runs on its own tokens and Google's, and the SDKs on auth's. +//! +//! The leeway policy: `nbf` and `iat` always allow [`LEEWAY`], since the issuer's +//! clock may run ahead of the verifier's. `exp` allows it only where [`Expiry`] +//! says, since lenience there only extends a token's life. +//! +//! [`LEEWAY`]: crate::protocol::constants::LEEWAY +//! [`Expiry`]: crate::protocol::registered::Expiry +//! +//! ``` +//! use chrono::{TimeDelta, Utc}; +//! use sourceorigin_common::protocol::{ +//! claims::IdTokenClaims, +//! registered::{ClaimsError, Expiry, Validation}, +//! }; +//! +//! let claims: IdTokenClaims = serde_json::from_str(r#"{ +//! "iss": "https://auth.sourceorigin.dev", +//! "sub": "01936f3e-8c00-7000-8000-000000000001", +//! "aud": "notes-web", +//! "iat": 1767225540, +//! "exp": 1767225840, +//! "nonce": "n-0S6_WzA2Mj" +//! }"#)?; +//! let validation = Validation { +//! issuers: &["https://auth.sourceorigin.dev"], +//! audience: Some("notes-web"), +//! nonce: Some("n-0S6_WzA2Mj"), +//! expiry: Expiry::Lenient, +//! now: claims.iat + TimeDelta::minutes(1), +//! }; +//! assert_eq!(validation.check(&claims), Ok(())); +//! +//! // Ten seconds past `exp`, within the leeway an SDK allows, but not auth. +//! let late = Validation { now: claims.exp + TimeDelta::seconds(10), ..validation }; +//! assert_eq!(late.check(&claims), Ok(())); +//! let strict = Validation { expiry: Expiry::Strict, ..late }; +//! assert_eq!(strict.check(&claims), Err(ClaimsError::Expired(claims.exp))); +//! # Ok::<(), serde_json::Error>(()) +//! ``` + +use super::{ + claims::{AccessTokenClaims, Audience, IdTokenClaims, LogoutTokenClaims}, + constants::LEEWAY, + sdk::ErrorReason, +}; +use chrono::{DateTime, TimeDelta, Utc}; +use thiserror::Error; + +/// How [`Validation::check`] reads `exp`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Expiry { + /// Expired [`LEEWAY`] after `exp`: the SDKs, whose clock may run ahead of + /// auth's. + Lenient, + /// Expired at `exp`: auth, which ends its own tokens when it said they end, and + /// Google's ID tokens, which come straight from Google's token endpoint. + Strict, + /// Never expired: an `id_token_hint`, which still names its account once expired + /// (RP-Initiated Logout 1.0 §2). + Ignored, +} + +impl Expiry { + /// How long after `exp` a token still verifies, or `None` if it always does. + const fn leeway(self) -> Option { + match self { + Self::Lenient => Some(LEEWAY), + Self::Strict => Some(TimeDelta::zero()), + Self::Ignored => None, + } + } +} + +/// What a token's registered claims must say, checked at `now`. +#[derive(Clone, Copy, Debug)] +pub struct Validation<'a> { + /// The accepted `iss` values: one, except Google, which spells its issuer two ways. + pub issuers: &'a [&'a str], + /// The recipient `aud` must name, or `None` for any: auth's `UserInfo` endpoint + /// accepts every access token auth issued, whoever it is for. + pub audience: Option<&'a str>, + /// The `nonce` the token must carry, when the sign-in sent one. + pub nonce: Option<&'a str>, + /// How `exp` is read. + pub expiry: Expiry, + /// The time to check at, from the caller's clock, so tests can pin it. + pub now: DateTime, +} + +impl Validation<'_> { + /// Checks `iss`, `aud`, `exp`, `nbf`, `iat` and `nonce`, in that order, so a + /// token with several faults gets the first one's error. + /// + /// # Errors + /// The first claim that fails, as [`ClaimsError`]. + pub fn check(&self, claims: &T) -> Result<(), ClaimsError> { + if !self.issuers.contains(&claims.issuer()) { + return Err(ClaimsError::WrongIssuer { + expected: self.issuers.iter().map(ToString::to_string).collect(), + found: claims.issuer().to_owned(), + }); + } + if let Some(audience) = self.audience { + let found = claims.audience(); + let others = T::EXCLUSIVE_AUDIENCE && found.iter().any(|value| value != audience); + if others || !found.contains(audience) { + return Err(ClaimsError::WrongAudience { + expected: audience.to_owned(), + found: found.clone(), + }); + } + } + // Checked: a far-future `exp` must not overflow, and never expires. + let expired = self.expiry.leeway().is_some_and(|leeway| { + claims + .expires_at() + .checked_add_signed(leeway) + .is_some_and(|deadline| self.now >= deadline) + }); + if expired { + return Err(ClaimsError::Expired(claims.expires_at())); + } + let future = self.now + LEEWAY; + if let Some(not_before) = claims.not_before().filter(|nbf| *nbf > future) { + return Err(ClaimsError::NotYetValid(not_before)); + } + if claims.issued_at() > future { + return Err(ClaimsError::IssuedInFuture(claims.issued_at())); + } + if self + .nonce + .is_some_and(|nonce| claims.nonce() != Some(nonce)) + { + return Err(ClaimsError::NonceMismatch); + } + Ok(()) + } +} + +/// Why [`Validation::check`] refused a token's claims. +#[derive(Clone, Debug, Error, PartialEq, Eq)] +pub enum ClaimsError { + /// `iss` is none of the accepted issuers. + #[error("token issuer is {found:?}, expected one of {expected:?}")] + WrongIssuer { + /// The accepted issuers. + expected: Vec, + /// The token's `iss`. + found: String, + }, + /// `aud` does not name the expected recipient, or names others where it must + /// name that one alone. + #[error("token audience {found:?} does not contain {expected:?}")] + WrongAudience { + /// The resource or client this token must be for. + expected: String, + /// The token's `aud`. + found: Audience, + }, + /// `exp` has passed, beyond any leeway. + #[error("token expired at {0}")] + Expired(DateTime), + /// `nbf` is in the future, beyond the leeway. + #[error("token is not valid before {0}")] + NotYetValid(DateTime), + /// `iat` is in the future, beyond the leeway. + #[error("token is issued in the future, at {0}")] + IssuedInFuture(DateTime), + /// The ID token's `nonce` is not the sign-in's. + #[error("ID token nonce does not match this login")] + NonceMismatch, +} + +impl ClaimsError { + /// The shared SDK error reason. + #[must_use] + pub const fn reason(&self) -> ErrorReason { + match self { + Self::WrongIssuer { .. } => ErrorReason::IssuerMismatch, + Self::WrongAudience { .. } => ErrorReason::WrongAudience, + Self::Expired(_) => ErrorReason::Expired, + Self::NotYetValid(_) => ErrorReason::NotYetValid, + Self::IssuedInFuture(_) => ErrorReason::IssuedInFuture, + Self::NonceMismatch => ErrorReason::NonceMismatch, + } + } +} + +/// A token's registered claims and `nonce`, as [`Validation::check`] reads them. +pub trait RegisteredClaims { + /// Whether `aud` must name the expected recipient alone. ID tokens trust no + /// other audience (OIDC Core §3.1.3.7), so `azp` can only confirm the client, + /// and auth addresses each logout token to one client; access tokens may name + /// several. + const EXCLUSIVE_AUDIENCE: bool; + + /// `iss`. + fn issuer(&self) -> &str; + /// `aud`. + fn audience(&self) -> &Audience; + /// `exp`. + fn expires_at(&self) -> DateTime; + /// `nbf`, if any. + fn not_before(&self) -> Option>; + /// `iat`. + fn issued_at(&self) -> DateTime; + /// `nonce`, if any. + fn nonce(&self) -> Option<&str>; +} + +/// Implements [`RegisteredClaims`] for claims types whose registered claims are their +/// `iss`, `aud`, `exp` and `iat` fields. Each names its `nbf` and `nonce` fields, or +/// `none` for a type without one, so no type can leave a check out by omission. +macro_rules! registered_claims { + (@nbf $claims:ident, none) => { + None + }; + (@nbf $claims:ident, $field:ident) => { + $claims.$field + }; + (@nonce $claims:ident, none) => { + None + }; + (@nonce $claims:ident, $field:ident) => { + $claims.$field.as_deref() + }; + ($( + impl $([$($generics:tt)*])? for $claims:ty { + exclusive_audience: $exclusive:literal, not_before: $nbf:ident, nonce: $nonce:ident + } + )+) => {$( + impl$(<$($generics)*>)? RegisteredClaims for $claims { + const EXCLUSIVE_AUDIENCE: bool = $exclusive; + + fn issuer(&self) -> &str { + &self.iss + } + fn audience(&self) -> &Audience { + &self.aud + } + fn expires_at(&self) -> DateTime { + self.exp + } + fn not_before(&self) -> Option> { + registered_claims!(@nbf self, $nbf) + } + fn issued_at(&self) -> DateTime { + self.iat + } + fn nonce(&self) -> Option<&str> { + registered_claims!(@nonce self, $nonce) + } + } + )+}; +} + +registered_claims! { + impl [X] for AccessTokenClaims { + exclusive_audience: false, not_before: nbf, nonce: none + } + impl for IdTokenClaims { + exclusive_audience: true, not_before: nbf, nonce: nonce + } + // A logout token has no `nbf`, and never a `nonce`. + impl for LogoutTokenClaims { + exclusive_audience: true, not_before: none, nonce: none + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/common/src/protocol/registered/tests.rs b/crates/common/src/protocol/registered/tests.rs new file mode 100644 index 000000000..7db10e15a --- /dev/null +++ b/crates/common/src/protocol/registered/tests.rs @@ -0,0 +1,159 @@ +//! The leeway policy, the order of the checks, and the audience rules. Every check +//! runs at a fixed instant long past, so a check reading the system clock would fail. +use super::*; +use serde_json::{Value, json}; + +/// The instant every check here runs at. +const NOW: i64 = 1_767_225_600; +/// The issuer every token here names. +const ISSUER: &str = "https://auth.example"; + +/// ID token claims issued a minute before [`NOW`] and valid for five more, with the +/// `changes` applied. +fn id_token(changes: &Value) -> IdTokenClaims { + let mut claims = json!({"iss": ISSUER, "sub": "user", "aud": "client", "iat": NOW - 60, + "exp": NOW + 300, "nonce": "nonce"}); + for (claim, value) in changes.as_object().expect("changes") { + claims[claim] = value.clone(); + } + serde_json::from_value(claims).expect("ID token claims") +} + +/// What an SDK checks an ID token against. +fn validation() -> Validation<'static> { + Validation { + issuers: &[ISSUER], + audience: Some("client"), + nonce: Some("nonce"), + expiry: Expiry::Lenient, + now: DateTime::from_timestamp(NOW, 0).expect("time"), + } +} + +/// `exp` allows the leeway only where `Expiry` says, and `nbf` and `iat` always do, +/// each up to its boundary. +#[test] +fn leeway_follows_the_policy() { + let seconds = LEEWAY.num_seconds(); + let at = |offset: i64| DateTime::from_timestamp(NOW + offset, 0).expect("time"); + for (expiry, exp, result) in [ + (Expiry::Lenient, NOW - seconds + 1, Ok(())), + ( + Expiry::Lenient, + NOW - seconds, + Err(ClaimsError::Expired(at(-seconds))), + ), + (Expiry::Strict, NOW + 1, Ok(())), + (Expiry::Strict, NOW, Err(ClaimsError::Expired(at(0)))), + (Expiry::Ignored, NOW - 3600, Ok(())), + ] { + let check = Validation { + expiry, + ..validation() + }; + assert_eq!( + check.check(&id_token(&json!({"exp": exp}))), + result, + "{expiry:?}" + ); + } + for expiry in [Expiry::Lenient, Expiry::Strict, Expiry::Ignored] { + let check = Validation { + expiry, + ..validation() + }; + for (claim, error) in [ + ("nbf", ClaimsError::NotYetValid as fn(_) -> _), + ("iat", ClaimsError::IssuedInFuture), + ] { + assert_eq!( + check.check(&id_token(&json!({claim: NOW + seconds}))), + Ok(()) + ); + assert_eq!( + check.check(&id_token(&json!({claim: NOW + seconds + 1}))), + Err(error(at(seconds + 1))), + "{claim}" + ); + } + } +} + +/// A token with several faults gets the first one's error, and a far-future `exp` +/// never overflows into an expiry. +#[test] +fn checks_run_in_order() { + let faults = [ + ("iss", json!("https://other.example")), + ("aud", json!("other")), + ("exp", json!(NOW - 3600)), + ("nbf", json!(NOW + 3600)), + ("iat", json!(NOW + 3600)), + ("nonce", json!("other")), + ]; + let reasons = [ + ErrorReason::IssuerMismatch, + ErrorReason::WrongAudience, + ErrorReason::Expired, + ErrorReason::NotYetValid, + ErrorReason::IssuedInFuture, + ErrorReason::NonceMismatch, + ]; + for (first, reason) in reasons.into_iter().enumerate() { + let changes = Value::Object( + faults[first..] + .iter() + .map(|(claim, value)| ((*claim).to_owned(), value.clone())) + .collect(), + ); + let result = validation().check(&id_token(&changes)); + assert_eq!(result.map_err(|error| error.reason()), Err(reason)); + } + let far = id_token(&json!({"exp": DateTime::::MAX_UTC.timestamp()})); + assert_eq!(validation().check(&far), Ok(())); +} + +/// Any accepted issuer passes; an ID token must name its client alone, an access +/// token among others, and no audience is checked when none is expected. A nonce is +/// required only when expected. +#[test] +fn issuers_audiences_and_nonces() { + let google = Validation { + issuers: &["https://accounts.google.com", "accounts.google.com"], + ..validation() + }; + let claims = id_token(&json!({"iss": "accounts.google.com"})); + assert_eq!(google.check(&claims), Ok(())); + assert!(matches!( + validation().check(&claims), + Err(ClaimsError::WrongIssuer { found, .. }) if found == "accounts.google.com" + )); + + let shared = id_token(&json!({"aud": ["client", "other"]})); + assert!(matches!( + validation().check(&shared), + Err(ClaimsError::WrongAudience { .. }) + )); + let access: AccessTokenClaims = serde_json::from_value(json!({"iss": ISSUER, + "sub": "user", "aud": ["client", "other"], "client_id": "client", + "jti": "01936f3e-8c00-7000-8000-000000000003", "scope": "openid", + "iat": NOW - 60, "exp": NOW + 300})) + .expect("access token claims"); + let unbound = Validation { + nonce: None, + ..validation() + }; + assert_eq!(unbound.check(&access), Ok(())); + let anyone = Validation { + audience: None, + ..unbound + }; + assert_eq!(anyone.check(&id_token(&json!({"aud": "other"}))), Ok(())); + + let no_nonce = id_token(&json!({"nonce": null})); + assert_eq!(anyone.check(&no_nonce), Ok(())); + assert_eq!( + validation().check(&no_nonce), + Err(ClaimsError::NonceMismatch) + ); +} diff --git a/docs/dev/architecture/sdk.md b/docs/dev/architecture/sdk.md index d794e6b6f..b0f7998a5 100644 --- a/docs/dev/architecture/sdk.md +++ b/docs/dev/architecture/sdk.md @@ -114,7 +114,7 @@ Checks run in this order, and the first failure is reported. Each failure is an for ID and logout tokens. An ID or logout token's `aud` must name no other client, since the SDK trusts no other audience (OIDC Core §3.1.3.7) (`wrong_audience`). -10. Time, with a 30-second leeway, matching auth's own `iat` skew: +10. Time, with a 30-second leeway, matching auth's skew on `nbf` and `iat`: - expired when `now >= exp + 30` (`expired`); - not yet valid when `nbf > now + 30`, for both token types (`not_yet_valid`); - issued in the future when `iat > now + 30` (`issued_in_future`). @@ -128,6 +128,11 @@ Checks run in this order, and the first failure is reported. Each failure is an delivery attempt for two minutes; - `sub` or `sid` is present (`invalid_claims`). +In Rust, steps 8 to 10 and the `nonce` are one check, `Validation::check` in +`sourceorigin_common::protocol::registered`, at the time the issuer's clock gives. +Auth runs the same check on Google's ID tokens, with `Expiry::Strict`: no leeway +on `exp`. + Scope and step-up requirements are checked after validation, and fail with their own categories. diff --git a/docs/dev/extending/federation-providers.md b/docs/dev/extending/federation-providers.md index d961279df..b737ce1ef 100644 --- a/docs/dev/extending/federation-providers.md +++ b/docs/dev/extending/federation-providers.md @@ -140,7 +140,10 @@ In `apps/auth-service/src/federation/providers/mod.rs`: 3. Add `Provider::GitLab => Ok(Self::gitlab())` to `ProviderEndpoints::new`. 4. Add a `GitLab(GitLabProtocol)` variant to `IdentityStrategy`, then its arms: - in `IdentityStrategy::extend_authorization`: an OpenID Connect provider - sends the flow's `nonce`, as `GoogleProtocol::extend_authorization` does; + sends the flow's `nonce`, as `GoogleProtocol::extend_authorization` does, + and its claims type implements `RegisteredClaims`, so the shared + `Validation::check` reads its issuer, audience, times and nonce, as + `GoogleClaims::verify` does; - in `FederationApplication::exchange`: call `gitlab_identity`. 5. Add the `Provider::GitLab` arm to `ProviderPicture::parse`: the host its pictures are on, and how to ask for the stored size, if it can. Nothing else diff --git a/docs/dev/security/boundaries.md b/docs/dev/security/boundaries.md index f8089bec1..cbf94c012 100644 --- a/docs/dev/security/boundaries.md +++ b/docs/dev/security/boundaries.md @@ -197,8 +197,10 @@ own calls to exchange the code and read the identity **What is checked:** the flow is bound to the browser that started it by a cookie, and the code exchange uses PKCE. Google's ID token is checked for its -signature against Google's keys, its issuer, an audience of auth's client alone -and the flow's nonce (`federation/providers/google.rs`). From GitHub, auth reads +signature against Google's keys, its issuer, an audience of auth's client alone, +its times and the flow's nonce (`federation/providers/google.rs`), by the check +the Rust SDK runs on auth's tokens (`protocol::registered` in +`sourceorigin-common`), with no leeway on `exp`. From GitHub, auth reads the numeric account ID and, if shared, the verified primary email (`federation/providers/github.rs`). diff --git a/packages/auth/src/protocol.ts b/packages/auth/src/protocol.ts index 3ca345369..b7cf0fe9d 100644 --- a/packages/auth/src/protocol.ts +++ b/packages/auth/src/protocol.ts @@ -774,7 +774,8 @@ export const ERROR_REASONS: readonly ErrorReason[] = ["issuer_mismatch", "invali /** * Clock skew tolerated on `exp`, `nbf`, `iat` and `auth_time`. Auth tolerates the - * same on `iat` alone, and none on `exp` or `max_age`. + * same on `nbf` and `iat` alone, and none on `exp` or `max_age` + * (`registered::Expiry`). * * In milliseconds. */