140 lines
5.1 KiB
Rust
140 lines
5.1 KiB
Rust
//! Sign-in with Google and Apple: verification of their ID tokens.
|
|||
|
|
//!
|
||
|
|
//! The frontend obtains an ID token (Google Identity Services, or Sign in with
|
||
|
|
//! Apple JS) and posts it to `POST /v1/auth/google` / `/v1/auth/apple`. The
|
||
|
|
//! token is a JWT signed by the provider; it is verified here against the
|
||
|
|
//! provider's published keys (JWKS, cached), the configured client ids
|
||
|
|
//! (audience: Google client ids, Apple Services IDs) 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 GOOGLE_ISSUERS: &[&str] = &["accounts.google.com", "https://accounts.google.com"];
|
||
|
|
const APPLE_ISSUERS: &[&str] = &["https://appleid.apple.com"];
|
||
|
|
const JWKS_MAX_AGE: Duration = Duration::from_secs(3600);
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
pub struct IdClaims {
|
||
|
|
/// Stable account id at the provider.
|
||
|
|
pub sub: String,
|
||
|
|
pub email: Option<String>,
|
||
|
|
/// Apple sends it as a string ("true").
|
||
|
|
#[serde(default, deserialize_with = "flexible_bool")]
|
||
|
|
pub email_verified: bool,
|
||
|
|
/// Google only; Apple gives the name to the frontend, at the first sign-in.
|
||
|
|
pub name: Option<String>,
|
||
|
|
pub locale: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn flexible_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
|
||
|
|
Ok(match serde_json::Value::deserialize(d)? {
|
||
|
|
serde_json::Value::Bool(b) => b,
|
||
|
|
serde_json::Value::String(s) => s == "true",
|
||
|
|
_ => false,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Clone, Deserialize)]
|
||
|
|
struct Jwk {
|
||
|
|
kid: String,
|
||
|
|
n: String,
|
||
|
|
e: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(Debug, Deserialize)]
|
||
|
|
struct JwkSet {
|
||
|
|
keys: Vec<Jwk>,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct IdTokenVerifier {
|
||
|
|
/// "Google" or "Apple", for messages.
|
||
|
|
provider: &'static str,
|
||
|
|
issuers: &'static [&'static str],
|
||
|
|
client_ids: Vec<String>,
|
||
|
|
jwks_url: String,
|
||
|
|
http: reqwest::Client,
|
||
|
|
cache: RwLock<Option<(Instant, Vec<Jwk>)>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl IdTokenVerifier {
|
||
|
|
fn new(
|
||
|
|
provider: &'static str,
|
||
|
|
issuers: &'static [&'static str],
|
||
|
|
client_ids: Vec<String>,
|
||
|
|
jwks_url: String,
|
||
|
|
) -> Self {
|
||
|
|
let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("static configuration");
|
||
|
|
Self { provider, issuers, client_ids, jwks_url, http, cache: RwLock::new(None) }
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn google(client_ids: Vec<String>, jwks_url: String) -> Self {
|
||
|
|
Self::new("Google", GOOGLE_ISSUERS, client_ids, jwks_url)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn apple(client_ids: Vec<String>, jwks_url: String) -> Self {
|
||
|
|
Self::new("Apple", APPLE_ISSUERS, client_ids, jwks_url)
|
||
|
|
}
|
||
|
|
|
||
|
|
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 {} keys: {e}", self.provider)))?
|
||
|
|
.json()
|
||
|
|
.await
|
||
|
|
.map_err(|e| ApiError::Internal(format!("parsing {} keys: {e}", self.provider)))?;
|
||
|
|
Ok(set.keys)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The key with `kid`; the key set is refetched when it is stale or the
|
||
|
|
/// key is unknown (the providers rotate their 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(format!("the {} token is signed with an unknown key", self.provider))
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn verify(&self, id_token: &str) -> Result<IdClaims, ApiError> {
|
||
|
|
let provider = self.provider;
|
||
|
|
if !self.enabled() {
|
||
|
|
return Err(ApiError::Forbidden(format!("{provider} login is not configured")));
|
||
|
|
}
|
||
|
|
let invalid =
|
||
|
|
|e: jsonwebtoken::errors::Error| ApiError::InvalidCredentials(format!("invalid {provider} token: {e}"));
|
||
|
|
let header = decode_header(id_token).map_err(invalid)?;
|
||
|
|
if header.alg != Algorithm::RS256 {
|
||
|
|
return Err(ApiError::InvalidCredentials(format!("invalid {provider} token: unexpected algorithm")));
|
||
|
|
}
|
||
|
|
let kid =
|
||
|
|
header.kid.ok_or_else(|| ApiError::InvalidCredentials(format!("invalid {provider} token: no key id")))?;
|
||
|
|
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(self.issuers);
|
||
|
|
validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
|
||
|
|
Ok(decode::<IdClaims>(id_token, &key, &validation).map_err(invalid)?.claims)
|
||
|
|
}
|
||
|
|
}
|