Sign in with Apple
POST /v1/auth/apple verifies the ID token from Sign in with Apple JS against Apple's keys, the Services IDs in APPLE_CLIENT_IDS and Apple's issuer, then logs in like Google: the linked identity, else the user with the same verified address, else a new user (invitations and referrals as for Google). The Google verifier became a shared ID token verifier. Apple gives the name only at the first sign-in; the page sends it along (family name first). The login page shows Apple's white button under Google's when it is configured; the privacy pages say what Apple passes on, including the relay addresses. The deploy compose's MAIL_FROM default is noreply@ like production (the sender registered for Apple's e-mail relay). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -18,6 +18,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
| `FREE_PERSON_SLOTS` | `0` | ennyi személyt vehet fel csomag nélkül egy felhasználó |
|
||||
| `SIGNUP_MODE` | `invite` | `invite`: új fiók csak meghívóval jön létre (403 `not_invited`); `open`: bárki regisztrálhat |
|
||||
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
||||
| `APPLE_CLIENT_IDS` | – | Sign in with Apple: a Services ID(k) vesszővel elválasztva (pl. `hu.sorsfonalak.web`), az ID token `aud` mezője ezek egyike kell legyen; üresen az Apple-belépés ki van kapcsolva |
|
||||
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | az elemzések, előrejelzések és válaszok alapmodellje, és a tartalék, ha a választott modell hibára fut |
|
||||
|
||||
@@ -75,6 +75,12 @@ pub struct Config {
|
||||
pub google_client_ids: Vec<String>,
|
||||
/// `GOOGLE_JWKS_URL` (default Google's certificate endpoint).
|
||||
pub google_jwks_url: String,
|
||||
/// `APPLE_CLIENT_IDS`: comma-separated Services IDs (e.g.
|
||||
/// `hu.sorsfonalak.web`) accepted as the ID token audience; empty
|
||||
/// disables Sign in with Apple.
|
||||
pub apple_client_ids: Vec<String>,
|
||||
/// `APPLE_JWKS_URL` (default Apple's key endpoint).
|
||||
pub apple_jwks_url: String,
|
||||
/// `BOOTSTRAP_ADMIN_EMAILS`: these users get the admin role when they
|
||||
/// register or log in (to create the first administrator).
|
||||
pub bootstrap_admin_emails: Vec<String>,
|
||||
@@ -197,6 +203,8 @@ impl Config {
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
google_jwks_url: var("GOOGLE_JWKS_URL")
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
apple_client_ids: list("APPLE_CLIENT_IDS"),
|
||||
apple_jwks_url: var("APPLE_JWKS_URL").unwrap_or_else(|| "https://appleid.apple.com/auth/keys".into()),
|
||||
bootstrap_admin_emails: list("BOOTSTRAP_ADMIN_EMAILS").into_iter().map(|e| e.to_lowercase()).collect(),
|
||||
supported_locales,
|
||||
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
||||
@@ -240,6 +248,8 @@ impl Config {
|
||||
user_invites: true,
|
||||
referral_rewards: true,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
apple_client_ids: vec!["hu.sorsfonalak.test".into()],
|
||||
apple_jwks_url: google_jwks_url.clone(),
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
supported_locales: vec!["hu".into(), "en".into()],
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,9 @@ mod birth_changes;
|
||||
mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
mod google;
|
||||
mod invoices;
|
||||
mod models;
|
||||
mod oidc;
|
||||
mod packages;
|
||||
mod persons;
|
||||
mod routes;
|
||||
@@ -32,7 +32,7 @@ use sqlx::PgPool;
|
||||
|
||||
use crate::auth::LoginLimiter;
|
||||
use crate::config::Config;
|
||||
use crate::google::GoogleVerifier;
|
||||
use crate::oidc::IdTokenVerifier;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8081";
|
||||
|
||||
@@ -40,7 +40,8 @@ pub struct AppState {
|
||||
pub db: PgPool,
|
||||
pub config: Config,
|
||||
pub horoscope: HoroscopeClient,
|
||||
pub google: GoogleVerifier,
|
||||
pub google: IdTokenVerifier,
|
||||
pub apple: IdTokenVerifier,
|
||||
pub login_limiter: LoginLimiter,
|
||||
pub models: models::Catalog,
|
||||
pub stripe: stripe::Client,
|
||||
@@ -50,7 +51,8 @@ impl AppState {
|
||||
pub fn new(db: PgPool, config: Config) -> Self {
|
||||
Self {
|
||||
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
|
||||
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
||||
google: IdTokenVerifier::google(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
||||
apple: IdTokenVerifier::apple(config.apple_client_ids.clone(), config.apple_jwks_url.clone()),
|
||||
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
|
||||
models: models::Catalog::new(&config.openrouter_models_url),
|
||||
stripe: stripe::Client::default(),
|
||||
@@ -72,6 +74,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
db::migrate(&pool).await.context("running database migrations")?;
|
||||
tracing::info!(
|
||||
google_login = !config.google_client_ids.is_empty(),
|
||||
apple_login = !config.apple_client_ids.is_empty(),
|
||||
horoscope_api = %config.horoscope_api_url,
|
||||
"database ready"
|
||||
);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
@@ -307,20 +307,78 @@ pub async fn google(
|
||||
WithRejection(Json(req), _): Body<GoogleRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let claims = state.google.verify(&req.id_token).await?;
|
||||
let signup = Signup {
|
||||
name: claims.name.clone(),
|
||||
locale: claims.locale.clone(),
|
||||
invite_token: req.invite_token,
|
||||
referral: req.referral,
|
||||
};
|
||||
social_login(&state, headers, jar, "google", claims, signup).await
|
||||
}
|
||||
|
||||
// --- Apple ------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AppleRequest {
|
||||
/// ID token (JWT) from Sign in with Apple JS.
|
||||
id_token: String,
|
||||
/// The name Apple gives the page at the first sign-in only (it is not in
|
||||
/// the token): used when the account is created.
|
||||
name: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
}
|
||||
|
||||
/// Logs in with Apple, like [`google`]. The address may be an Apple relay
|
||||
/// (`…@privaterelay.appleid.com`), which forwards our e-mails.
|
||||
pub async fn apple(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
WithRejection(Json(req), _): Body<AppleRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let claims = state.apple.verify(&req.id_token).await?;
|
||||
let signup = Signup { name: req.name, locale: None, invite_token: req.invite_token, referral: req.referral };
|
||||
social_login(&state, headers, jar, "apple", claims, signup).await
|
||||
}
|
||||
|
||||
/// What a new account starts with.
|
||||
struct Signup {
|
||||
name: Option<String>,
|
||||
locale: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
}
|
||||
|
||||
/// Logs in with a verified provider identity: the linked user, else the user
|
||||
/// with the same (provider-verified) e-mail address, else a new user.
|
||||
async fn social_login(
|
||||
state: &AppState,
|
||||
headers: HeaderMap,
|
||||
jar: CookieJar,
|
||||
provider: &'static str,
|
||||
claims: crate::oidc::IdClaims,
|
||||
signup: Signup,
|
||||
) -> ApiResult<impl IntoResponse + use<>> {
|
||||
let email = match (claims.email.as_deref(), claims.email_verified) {
|
||||
(Some(e), true) => normalize_email(e)?,
|
||||
_ => return Err(ApiError::InvalidCredentials("the Google account has no verified e-mail address".into())),
|
||||
_ => {
|
||||
return Err(ApiError::InvalidCredentials(format!("the {provider} account has no verified e-mail address")));
|
||||
}
|
||||
};
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let linked: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = 'google' AND subject = $1")
|
||||
sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = $1 AND subject = $2")
|
||||
.bind(provider)
|
||||
.bind(&claims.sub)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let (user_id, created) = match linked {
|
||||
Some((id,)) => {
|
||||
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = 'google' AND subject = $1")
|
||||
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = $1 AND subject = $2")
|
||||
.bind(provider)
|
||||
.bind(&claims.sub)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
@@ -331,7 +389,7 @@ pub async fn google(
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
|
||||
let (id, created) = match existing {
|
||||
Some((id,)) => {
|
||||
// Google has verified the address, so it counts as verified here too.
|
||||
// The provider has verified the address, so it counts as verified here too.
|
||||
sqlx::query(
|
||||
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
|
||||
)
|
||||
@@ -341,9 +399,9 @@ pub async fn google(
|
||||
(id, false)
|
||||
}
|
||||
None => {
|
||||
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
|
||||
super::invitations::admit(state, &mut tx, &email, signup.invite_token.as_deref()).await?;
|
||||
let id = Uuid::now_v7();
|
||||
let locale = claims
|
||||
let locale = signup
|
||||
.locale
|
||||
.as_deref()
|
||||
.and_then(|l| l.split(['-', '_']).next())
|
||||
@@ -355,7 +413,7 @@ pub async fn google(
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(claims.name.clone()))
|
||||
.bind(clean_name(signup.name))
|
||||
.bind(locale)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
@@ -363,21 +421,27 @@ pub async fn google(
|
||||
&mut tx,
|
||||
id,
|
||||
&email,
|
||||
req.invite_token.as_deref(),
|
||||
signup.invite_token.as_deref(),
|
||||
state.config.free_person_slots,
|
||||
)
|
||||
.await?;
|
||||
super::shares::record_referral(&mut tx, state.config.referral_rewards, id, req.referral.as_deref())
|
||||
.await?;
|
||||
super::shares::record_referral(
|
||||
&mut tx,
|
||||
state.config.referral_rewards,
|
||||
id,
|
||||
signup.referral.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
(id, true)
|
||||
}
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO auth_identities (id, user_id, provider, subject, email, last_used_at) \
|
||||
VALUES ($1, $2, 'google', $3, $4, now())",
|
||||
VALUES ($1, $2, $3, $4, $5, now())",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(id)
|
||||
.bind(provider)
|
||||
.bind(&claims.sub)
|
||||
.bind(&email)
|
||||
.execute(&mut *tx)
|
||||
@@ -386,11 +450,11 @@ pub async fn google(
|
||||
}
|
||||
};
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
apply_bootstrap_admin(state, &mut tx, &mut user).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
|
||||
Ok(login_response(&state, jar, &user, session, created))
|
||||
Ok(login_response(state, jar, &user, session, created))
|
||||
}
|
||||
|
||||
// --- logout -------------------------------------------------------------------------------
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/auth/register", post(auth::register))
|
||||
.route("/v1/auth/login", post(auth::login))
|
||||
.route("/v1/auth/google", post(auth::google))
|
||||
.route("/v1/auth/apple", post(auth::apple))
|
||||
.route("/v1/auth/logout", post(auth::logout))
|
||||
.route("/v1/auth/logout-all", post(auth::logout_all))
|
||||
.route("/v1/auth/verify-email", post(auth::verify_email))
|
||||
@@ -164,6 +165,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
let c = &state.config;
|
||||
Json(json!({
|
||||
"google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() },
|
||||
"apple_login": { "enabled": state.apple.enabled(), "client_id": c.apple_client_ids.first() },
|
||||
"locales": c.supported_locales,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": payments::method(c) == Some("mock"),
|
||||
|
||||
@@ -195,6 +195,18 @@ fn google_token(sub: &str, email: &str, audience: &str) -> String {
|
||||
jsonwebtoken::encode(&header, &claims, &jsonwebtoken::EncodingKey::from_rsa_pem(GOOGLE_KEY_PEM).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn apple_token(sub: &str, email: &str, audience: &str) -> String {
|
||||
let now = time::OffsetDateTime::now_utc().unix_timestamp();
|
||||
// Apple sends email_verified as a string and no name.
|
||||
let claims = json!({
|
||||
"iss": "https://appleid.apple.com", "aud": audience, "sub": sub, "email": email,
|
||||
"email_verified": "true", "is_private_email": "true", "iat": now, "exp": now + 600
|
||||
});
|
||||
let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
|
||||
header.kid = Some("test-key".into());
|
||||
jsonwebtoken::encode(&header, &claims, &jsonwebtoken::EncodingKey::from_rsa_pem(GOOGLE_KEY_PEM).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
// --- test client -------------------------------------------------------------------------------
|
||||
|
||||
struct TestApp {
|
||||
@@ -851,7 +863,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 16] = [
|
||||
const PUBLIC_ROUTES: [&str; 17] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
@@ -860,6 +872,7 @@ const PUBLIC_ROUTES: [&str; 16] = [
|
||||
"/v1/auth/register",
|
||||
"/v1/auth/login",
|
||||
"/v1/auth/google",
|
||||
"/v1/auth/apple",
|
||||
"/v1/auth/verify-email",
|
||||
"/v1/auth/password-reset",
|
||||
"/v1/auth/password-reset/confirm",
|
||||
@@ -2673,3 +2686,59 @@ async fn tarot_readings_draw_on_the_server_and_use_tarot_units(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
|
||||
assert_eq!(count().await, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn apple_login_creates_links_and_rejects(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let r = app.get("/v1/config", None).await;
|
||||
assert_eq!(r.body["apple_login"], json!({"enabled": true, "client_id": "hu.sorsfonalak.test"}));
|
||||
let relay = "x7k2p9@privaterelay.appleid.com";
|
||||
// The name comes from the page (Apple gives it at the first sign-in only).
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/apple",
|
||||
None,
|
||||
json!({"id_token": apple_token("a-1", relay, "hu.sorsfonalak.test"), "name": "Kovács Anna"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((&r.body["created"], &r.body["user"]["display_name"]), (&json!(true), &json!("Kovács Anna")));
|
||||
assert_eq!(r.body["user"]["email"], relay);
|
||||
let r =
|
||||
app.post("/v1/auth/apple", None, json!({"id_token": apple_token("a-1", relay, "hu.sorsfonalak.test")})).await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
assert_eq!(r.body["user"]["display_name"], "Kovács Anna");
|
||||
|
||||
// the same address as a Google account: both log into one user
|
||||
let google = app
|
||||
.post("/v1/auth/google", None, json!({"id_token": google_token("g-9", "bela@example.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
let token = google.body["session"]["token"].as_str().unwrap().to_string();
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/apple",
|
||||
None,
|
||||
json!({"id_token": apple_token("a-2", "bela@example.com", "hu.sorsfonalak.test")}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
|
||||
assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["google", "apple"]));
|
||||
|
||||
// a Google token is no Apple token, nor one for another Services ID
|
||||
let r = app
|
||||
.post("/v1/auth/apple", None, json!({"id_token": google_token("g-1", "gabor@gmail.com", GOOGLE_CLIENT)}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let r = app.post("/v1/auth/apple", None, json!({"id_token": apple_token("a-3", relay, "other.service")})).await;
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn apple_login_can_be_off(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| c.apple_client_ids.clear()).await;
|
||||
assert_eq!(app.get("/v1/config", None).await.body["apple_login"]["enabled"], false);
|
||||
let r = app
|
||||
.post("/v1/auth/apple", None, json!({"id_token": apple_token("a-1", "a@b.hu", "hu.sorsfonalak.test")}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user