108 lines
3.9 KiB
Rust
108 lines
3.9 KiB
Rust
//! Google Sign-In: verification of Google ID tokens.
|
|||
|
|
//!
|
||
|
|
//! The frontend obtains an ID token with Google Identity Services (button or
|
||
|
|
//! One Tap) and posts it to `POST /v1/auth/google`. The token is a JWT signed
|
||
|
|
//! by Google; it is verified here against Google's published keys (JWKS,
|
||
|
|
//! cached), the configured client ids (audience) and the issuer.
|
||
|
|
|
||
|
|
use std::time::{Duration, Instant};
|
||
|
|
|
||
|
|
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
||
|
|
use serde::Deserialize;
|
||
|
|
use tokio::sync::RwLock;
|
||
|
|
|
||
|
|
use crate::error::ApiError;
|
||
|
|
|
||
|
|
const ISSUERS: [&str; 2] = ["accounts.google.com", "https://accounts.google.com"];
|
||
|
|
const JWKS_MAX_AGE: Duration = Duration::from_secs(3600);
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
pub struct GoogleClaims {
|
||
|
|
/// Stable Google account id.
|
||
|
|
pub sub: String,
|
||
|
|
pub email: Option<String>,
|
||
|
|
#[serde(default)]
|
||
|
|
pub email_verified: bool,
|
||
|
|
pub name: Option<String>,
|
||
|
|
pub locale: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Clone, Deserialize)]
|
||
|
|
struct Jwk {
|
||
|
|
kid: String,
|
||
|
|
n: String,
|
||
|
|
e: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
struct JwkSet {
|
||
|
|
keys: Vec<Jwk>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct GoogleVerifier {
|
||
|
|
client_ids: Vec<String>,
|
||
|
|
jwks_url: String,
|
||
|
|
http: reqwest::Client,
|
||
|
|
cache: RwLock<Option<(Instant, Vec<Jwk>)>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl GoogleVerifier {
|
||
|
|
pub fn new(client_ids: Vec<String>, jwks_url: String) -> Self {
|
||
|
|
let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("static configuration");
|
||
|
|
Self { client_ids, jwks_url, http, cache: RwLock::new(None) }
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn enabled(&self) -> bool {
|
||
|
|
!self.client_ids.is_empty()
|
||
|
|
}
|
||
|
|
|
||
|
|
async fn fetch_keys(&self) -> Result<Vec<Jwk>, ApiError> {
|
||
|
|
let set: JwkSet = self
|
||
|
|
.http
|
||
|
|
.get(&self.jwks_url)
|
||
|
|
.send()
|
||
|
|
.await
|
||
|
|
.and_then(|r| r.error_for_status())
|
||
|
|
.map_err(|e| ApiError::Internal(format!("fetching Google keys: {e}")))?
|
||
|
|
.json()
|
||
|
|
.await
|
||
|
|
.map_err(|e| ApiError::Internal(format!("parsing Google keys: {e}")))?;
|
||
|
|
Ok(set.keys)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The key with `kid`; the key set is refetched when it is stale or the
|
||
|
|
/// key is unknown (Google rotates its keys).
|
||
|
|
async fn key(&self, kid: &str) -> Result<Jwk, ApiError> {
|
||
|
|
if let Some((fetched, keys)) = self.cache.read().await.as_ref()
|
||
|
|
&& fetched.elapsed() < JWKS_MAX_AGE
|
||
|
|
&& let Some(k) = keys.iter().find(|k| k.kid == kid)
|
||
|
|
{
|
||
|
|
return Ok(k.clone());
|
||
|
|
}
|
||
|
|
let keys = self.fetch_keys().await?;
|
||
|
|
let found = keys.iter().find(|k| k.kid == kid).cloned();
|
||
|
|
*self.cache.write().await = Some((Instant::now(), keys));
|
||
|
|
found.ok_or_else(|| ApiError::InvalidCredentials("the Google token is signed with an unknown key".into()))
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn verify(&self, id_token: &str) -> Result<GoogleClaims, ApiError> {
|
||
|
|
if !self.enabled() {
|
||
|
|
return Err(ApiError::Forbidden("Google login is not configured".into()));
|
||
|
|
}
|
||
|
|
let invalid =
|
||
|
|
|e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid Google token: {e}"));
|
||
|
|
let header = decode_header(id_token).map_err(invalid)?;
|
||
|
|
if header.alg != Algorithm::RS256 {
|
||
|
|
return Err(ApiError::InvalidCredentials("invalid Google token: unexpected algorithm".into()));
|
||
|
|
}
|
||
|
|
let kid = header.kid.ok_or_else(|| ApiError::InvalidCredentials("invalid Google token: no key id".into()))?;
|
||
|
|
let jwk = self.key(&kid).await?;
|
||
|
|
let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(invalid)?;
|
||
|
|
let mut validation = Validation::new(Algorithm::RS256);
|
||
|
|
validation.set_audience(&self.client_ids);
|
||
|
|
validation.set_issuer(&ISSUERS);
|
||
|
|
validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
|
||
|
|
Ok(decode::<GoogleClaims>(id_token, &key, &validation).map_err(invalid)?.claims)
|
||
|
|
}
|
||
|
|
}
|