Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 53 additions & 47 deletions apps/auth-service/src/federation/providers/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -118,7 +103,8 @@ impl FederationApplication {
protocol: &GoogleProtocol,
) -> Result<VerifiedIdentity, ProviderError> {
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,
Expand Down Expand Up @@ -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<Utc>,
/// Time before which the token must not be accepted, which Google may send.
#[serde(default, with = "chrono::serde::ts_seconds_option")]
nbf: Option<DateTime<Utc>>,
/// Issuance time.
#[serde(with = "chrono::serde::ts_seconds")]
iat: DateTime<Utc>,
/// Nonce stored with the federation flow when it started.
nonce: String,
/// Authorized party; must be this client when present.
Expand All @@ -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<Utc>,
) -> Result<Self, GoogleError> {
if token.len() > MAX_TOKEN_BYTES {
return Err(GoogleError::TokenTooLong(token.len()));
Expand All @@ -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);
}
Expand All @@ -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<Utc> {
self.exp
}
fn not_before(&self) -> Option<DateTime<Utc>> {
self.nbf
}
fn issued_at(&self) -> DateTime<Utc> {
self.iat
}
fn nonce(&self) -> Option<&str> {
Some(&self.nonce)
}
}
54 changes: 35 additions & 19 deletions apps/auth-service/src/federation/tests/protocols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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");
Expand All @@ -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::<ClaimsError>()
.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();
Expand Down
2 changes: 1 addition & 1 deletion crates/auth-sdk/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/auth-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}
Expand Down
2 changes: 1 addition & 1 deletion crates/auth-sdk/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl<X: DeserializeOwned> ResourceValidator<X> {
) -> Result<AccessToken<S, X>, TokenError> {
let claims: AccessTokenClaims<X> = self
.issuer
.decode(token, TokenType::Access, self.resource.identifier())
.decode(token, TokenType::Access, self.resource.identifier(), None)
.await?;
AccessToken::from_claims(claims)?.into_scoped()
}
Expand Down
2 changes: 1 addition & 1 deletion crates/auth-sdk/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ async fn token_vectors() {
let resource = Resource::new(audience).expect("vector resource");
match issuer.resource(resource).validate::<Scopes>(token).await {
Ok(_) => case.assert::<AccessTokenClaims>(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())),
Expand Down
Loading