diff --git a/packages/backend/AGENTS.md b/packages/backend/AGENTS.md index 21addd31ba..140d9754c6 100644 --- a/packages/backend/AGENTS.md +++ b/packages/backend/AGENTS.md @@ -41,7 +41,7 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work - `server-spi` (library `server_spi`): SPI traits (`QuotaGate`, `SessionPolicyHook`, `CopilotPolicySpi`, `CopilotRuntimeSpi`, `RateLimitPolicy`, `BillingSpi`, `ServerExtension`), `RequestSource`, `CommunityRateLimitPolicy`, `CommunityBillingSpi`, `CommunityCopilotRuntime`, and `CommunityExtension`. - `server-domain` (library `server_domain`): pure domain services (`AuthService`, `UserService`, `WorkspaceService`, `AdminService`, `DocSharingService`, `DocHistoryService`, `CommentService`, `NotificationService`, `SelfhostLicenseService`, `AppConfigService`, `safe_fetch`, and `acl`) plus `EventBusPublisher`, `InvalidationPublisher`, and `InvalidationHintV1`. - `AuthService` handles HS256 access tokens, `aff_rt_v1` refresh rotation, recovery, grace, preflight, and session cleanup. + `AuthService` handles HS256 access tokens, `aff_rt_v1` refresh rotation, recovery, grace, preflight, login OAuth/OIDC preflight and callback (atomic `runtime_states` claim before lock-free `safe_fetch` token exchange), single-transaction security challenges (`runtime_states` + `mail_deliveries`), session signing key rotation/deletion, PostgreSQL-backed Hashcash and Turnstile captcha verification, and session cleanup. `AdminService` aggregates admin workspace listings, dashboard metrics, shared links, and mail deliveries; `UserService` handles admin user CRUD, batch import, and recreate-for-ban transactions; `AppConfigService` serves redacted `appConfigMetadata`, dry-run `validateAppConfig`, and dynamic OAuth/Captcha capability flags. `acl` defines workspace and document permissions and classifies reserved documents. `server-domain` has no `legacy_compat`, `phase_a_compat`, `axum`, or `async-graphql` dependencies. @@ -67,8 +67,8 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work It renews the 90s `search_projection_lockless_v2` lease every 15s and serializes generations on `search-projection-lifecycle` with an `xid8` fence. It fences orphan GC per workspace on `search-projection-ws:`. -- `server-http` (library `server_http`): `axum 0.8` and `async-graphql 7` transport layer with `/healthz`, `/readyz`, `/info`, and `/graphql` (including workspace `search`, `aggregate`, `searchDocs`, `workspaceRolePermissions`, `DocType.{analytics, lastAccessedMembers}`, and admin console user, workspace, dashboard, shared-link, mail-delivery, and app-config metadata/validation queries). - Auth REST routes cover cookie/bearer sign-in, Open-App (`/api/auth/open-app/sign-in-code`, `/api/auth/open-app/sign-in`), and native sessions (`/api/auth/session/exchange`, `/api/auth/session/refresh`, `/api/auth/session/revoke`, `/api/auth/sessions`, `/api/auth/sessions/revoke-all`, `/api/auth/sessions/:id`). +- `server-http` (library `server_http`): `axum 0.8` and `async-graphql 7` transport layer with `/healthz`, `/readyz`, `/info`, and `/graphql` (including workspace `search`, `aggregate`, `searchDocs`, `workspaceRolePermissions`, `DocType.{analytics, lastAccessedMembers}`, admin console user, workspace, dashboard, shared-link, mail-delivery, and app-config metadata/validation queries and mutations, auth security challenges, signing key rotation, `UserType.token`, and `Query.error`). + Auth REST routes cover cookie/bearer sign-in (with `@UseNamedGuard('captcha')`), `GET /api/auth/captcha`, login OAuth (`POST /api/oauth/preflight` with version guard, `POST /api/oauth/callback` without version guard), Open-App (`/api/auth/open-app/sign-in-code`, `/api/auth/open-app/sign-in`), and native sessions (`/api/auth/session/exchange`, `/api/auth/session/refresh`, `/api/auth/session/revoke`, `/api/auth/sessions`, `/api/auth/sessions/revoke-all`, `/api/auth/sessions/:id`). Storage REST routes cover avatars (`/api/avatars/:id`), public docs (`/api/workspaces/:id/public-docs/:docId`, `/root-doc`), doc histories (`/api/workspaces/:id/docs/:guid/histories/:timestamp`), comment attachments (`/api/workspaces/:id/docs/:docId/comment-attachments/:key`), and source-scoped blobs (`/api/workspaces/:id/blobs/v1/:name`, `blob-manifest/v1`, `readable-blob-manifest/v1`, doc snapshot read). Blob management mutations require `Owner` or commercial-grant `Admin`. `legacy_compat::{quota, errors}` isolates external GraphQL quota labels and Apollo error extensions. diff --git a/packages/backend/server-domain/src/auth/keyring.rs b/packages/backend/server-domain/src/auth/keyring.rs index 05ab83b679..6fc7399fbe 100644 --- a/packages/backend/server-domain/src/auth/keyring.rs +++ b/packages/backend/server-domain/src/auth/keyring.rs @@ -1,15 +1,16 @@ -//! Idempotent initialization and validation of `auth.session.signingKeys` in -//! `public.app_configs`, matching `v0.27.5` `auth_session/keyring.rs` 1:1. +//! Management and validation of `auth.session.signingKeys` in `public.app_configs`. use std::{collections::BTreeSet, fmt}; use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, Duration, Utc}; use rand::RngCore as _; use serde::{Deserialize, Serialize}; use server_db::{ServerDb, WorkloadTier}; use server_types::DomainError; +use super::access_token::CLOCK_TOLERANCE_SECONDS; + pub const SIGNING_KEYS_CONFIG_ID: &str = "auth.session.signingKeys"; #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] @@ -41,6 +42,55 @@ impl fmt::Debug for StoredSigningKey { } } +/// Public signing key metadata with the raw secret stripped. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SigningKeyMetadata { + pub id: String, + pub status: String, + pub source: String, + pub created_at: Option>, + pub retired_at: Option>, + pub verify_until: Option>, + pub can_delete: bool, +} + +pub fn signing_key_minimum_verify_seconds(access_token_ttl_seconds: i64) -> i64 { + access_token_ttl_seconds.max(1) + CLOCK_TOLERANCE_SECONDS +} + +pub fn signing_key_verify_until(now: DateTime, access_token_ttl_seconds: i64) -> DateTime { + now + Duration::seconds(signing_key_minimum_verify_seconds(access_token_ttl_seconds)) +} + +pub fn signing_key_can_verify(status: &str, verify_until: Option>, now: DateTime) -> bool { + match status { + "active" => true, + "retiring" => verify_until.is_some_and(|until| until >= now), + _ => false, + } +} + +pub fn signing_key_can_delete(status: &str, verify_until: Option>, now: DateTime) -> bool { + status == "retiring" && verify_until.is_some_and(|until| until < now) +} + +pub fn signing_key_window_valid( + status: &str, + retired_at: Option>, + verify_until: Option>, + minimum_verify_seconds: i64, +) -> bool { + match status { + "active" => retired_at.is_none() && verify_until.is_none(), + "retiring" => match (retired_at, verify_until) { + (Some(retired), Some(until)) => until > retired && (until - retired).num_seconds() >= minimum_verify_seconds, + _ => false, + }, + _ => false, + } +} + /// Ensures `public.app_configs` contains `id = 'auth.session.signingKeys'` with /// a valid active signing key, inserting an auto-generated key if absent. pub async fn ensure_signing_keys(db: &ServerDb) -> Result, DomainError> { @@ -75,6 +125,184 @@ pub async fn ensure_signing_keys(db: &ServerDb) -> Result, Ok(keys) } +/// Lists signing key metadata with all secret material stripped. +pub async fn list_signing_key_metadata(db: &ServerDb) -> Result, DomainError> { + let keys = ensure_signing_keys(db).await?; + let mut conn = db + .acquire_tiered(WorkloadTier::InteractiveRead) + .await + .map_err(|e| DomainError::Internal(format!("acquire signing key clock conn: {e}")))?; + let now: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&mut *conn) + .await + .map_err(|e| DomainError::Internal(format!("load signing key clock: {e}")))?; + metadata_from_keys(keys, now) +} + +/// Rotates the active signing key using strict lock ordering: +/// lock actor -> lock keyring config row -> read PostgreSQL `clock_timestamp()`. +pub async fn rotate_signing_key( + db: &ServerDb, + actor_id: &str, + expected_active_key_id: &str, + access_token_ttl_seconds: i64, +) -> Result, DomainError> { + let _ = ensure_signing_keys(db).await?; + + let mut tx = db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin signing key rotation: {e}")))?; + + lock_actor(tx.tx_mut(), actor_id).await?; + let mut keys = lock_keys(tx.tx_mut()).await?; + let now: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("load signing key rotation clock: {e}")))?; + + let active = keys + .iter_mut() + .find(|k| k.status == "active") + .ok_or_else(|| DomainError::Internal("auth signing keyring has no active key".to_owned()))?; + if active.id != expected_active_key_id { + return Err(DomainError::Validation("auth_signing_key_changed".to_owned())); + } + active.status = "retiring".to_owned(); + active.retired_at = Some(now); + active.verify_until = Some(signing_key_verify_until(now, access_token_ttl_seconds)); + + let mut next = generate_signing_key("admin"); + next.created_at = Some(now); + keys.push(next); + validate_signing_keys(&keys)?; + save_keys(tx.tx_mut(), actor_id, &keys).await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit signing key rotation: {e}")))?; + + metadata_from_keys(keys, now) +} + +/// Deletes an expired retiring signing key using strict lock ordering: +/// lock actor -> lock keyring config row -> read PostgreSQL `clock_timestamp()`. +pub async fn delete_signing_key( + db: &ServerDb, + actor_id: &str, + key_id: &str, +) -> Result, DomainError> { + let _ = ensure_signing_keys(db).await?; + + let mut tx = db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin signing key deletion: {e}")))?; + + lock_actor(tx.tx_mut(), actor_id).await?; + let mut keys = lock_keys(tx.tx_mut()).await?; + let now: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("load signing key deletion clock: {e}")))?; + + let key = keys + .iter() + .find(|k| k.id == key_id) + .ok_or_else(|| DomainError::Validation("auth_signing_key_not_found".to_owned()))?; + if !signing_key_can_delete(&key.status, key.verify_until, now) { + return Err(DomainError::Forbidden("auth_signing_key_cannot_be_deleted".to_owned())); + } + + keys.retain(|k| k.id != key_id); + validate_signing_keys(&keys)?; + save_keys(tx.tx_mut(), actor_id, &keys).await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit signing key deletion: {e}")))?; + + metadata_from_keys(keys, now) +} + +async fn lock_actor(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, actor_id: &str) -> Result<(), DomainError> { + use sqlx::Row as _; + let row = sqlx::query( + r#"SELECT u.disabled, + EXISTS( + SELECT 1 FROM user_features f + WHERE f.user_id = u.id AND f.name = 'administrator' AND f.activated = true + ) AS is_admin + FROM users u + WHERE u.id = $1 + FOR UPDATE"#, + ) + .bind(actor_id) + .fetch_optional(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock signing key actor: {e}")))?; + let Some(row) = row else { + return Err(DomainError::Forbidden( + "auth signing key actor does not exist".to_owned(), + )); + }; + let disabled: bool = row.get("disabled"); + let is_admin: bool = row.get("is_admin"); + if disabled || !is_admin { + return Err(DomainError::Forbidden( + "You are not allowed to perform this action.".to_owned(), + )); + } + Ok(()) +} + +async fn lock_keys(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result, DomainError> { + let value: serde_json::Value = sqlx::query_scalar("SELECT value FROM app_configs WHERE id = $1 FOR UPDATE") + .bind(SIGNING_KEYS_CONFIG_ID) + .fetch_one(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock auth signing keyring: {e}")))?; + let keys: Vec = + serde_json::from_value(value).map_err(|e| DomainError::Internal(format!("decode auth signing keyring: {e}")))?; + validate_signing_keys(&keys)?; + Ok(keys) +} + +async fn save_keys( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + actor_id: &str, + keys: &[StoredSigningKey], +) -> Result<(), DomainError> { + let value = + serde_json::to_value(keys).map_err(|e| DomainError::Internal(format!("encode auth signing keyring: {e}")))?; + sqlx::query("UPDATE app_configs SET value = $2, last_updated_by = $3, updated_at = clock_timestamp() WHERE id = $1") + .bind(SIGNING_KEYS_CONFIG_ID) + .bind(value) + .bind(actor_id) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("save auth signing keyring: {e}")))?; + Ok(()) +} + +fn metadata_from_keys(keys: Vec, now: DateTime) -> Result, DomainError> { + validate_signing_keys(&keys)?; + Ok( + keys + .into_iter() + .map(|key| SigningKeyMetadata { + can_delete: signing_key_can_delete(&key.status, key.verify_until, now), + id: key.id, + status: key.status, + source: key.source, + created_at: key.created_at, + retired_at: key.retired_at, + verify_until: key.verify_until, + }) + .collect(), + ) +} + pub fn generate_signing_key(source: &str) -> StoredSigningKey { let mut suffix = [0_u8; 6]; let mut secret = [0_u8; 32]; @@ -93,6 +321,13 @@ pub fn generate_signing_key(source: &str) -> StoredSigningKey { } pub fn validate_signing_keys(keys: &[StoredSigningKey]) -> Result<(), DomainError> { + validate_signing_keys_with_window(keys, 0) +} + +pub fn validate_signing_keys_with_window( + keys: &[StoredSigningKey], + minimum_verify_seconds: i64, +) -> Result<(), DomainError> { if keys.iter().filter(|k| k.status == "active").count() != 1 { return Err(DomainError::Internal( "auth signing keyring requires exactly one active key".to_owned(), @@ -122,6 +357,11 @@ pub fn validate_signing_keys(keys: &[StoredSigningKey]) -> Result<(), DomainErro "auth signing key secret length/encoding is invalid".to_owned(), )); } + if !signing_key_window_valid(&key.status, key.retired_at, key.verify_until, minimum_verify_seconds) { + return Err(DomainError::Internal( + "auth signing key lifecycle is invalid".to_owned(), + )); + } } Ok(()) } diff --git a/packages/backend/server-domain/src/auth/mod.rs b/packages/backend/server-domain/src/auth/mod.rs index cb73ffa799..0349aa612e 100644 --- a/packages/backend/server-domain/src/auth/mod.rs +++ b/packages/backend/server-domain/src/auth/mod.rs @@ -7,6 +7,7 @@ pub mod oauth; pub mod oauth_crypto; mod oauth_http; pub mod password; +pub mod security_challenge; use std::{fmt, fmt::Write as _, sync::Arc, time::Duration as StdDuration}; @@ -351,6 +352,85 @@ impl AuthService { keyring::ensure_signing_keys(&self.db).await } + /// Lists public metadata for all signing keys (with raw secrets stripped). + pub async fn list_signing_keys(&self) -> Result, DomainError> { + keyring::list_signing_key_metadata(&self.db).await + } + + /// Rotates the active session signing key with CAS on `expected_active_key_id`. + pub async fn rotate_signing_key( + &self, + actor_id: &str, + expected_active_key_id: &str, + ) -> Result, DomainError> { + let mut conn = self + .db + .acquire_tiered(WorkloadTier::InteractiveRead) + .await + .map_err(|e| DomainError::Internal(format!("acquire auth token policy conn: {e}")))?; + let rows = sqlx::query( + "SELECT id, value + FROM app_configs + WHERE id IN ('auth', 'auth.token', 'auth.token.accessTokenTtl') + ORDER BY id ASC", + ) + .fetch_all(&mut *conn) + .await + .map_err(|e| DomainError::Internal(format!("load auth token policy: {e}")))?; + drop(conn); + let policy = parse_auth_token_policy(rows); + keyring::rotate_signing_key(&self.db, actor_id, expected_active_key_id, policy.access_token_ttl_secs).await + } + + /// Deletes an expired retiring session signing key. + pub async fn delete_signing_key( + &self, + actor_id: &str, + key_id: &str, + ) -> Result, DomainError> { + keyring::delete_signing_key(&self.db, actor_id, key_id).await + } + + /// Issues a compatibility cookie session directly for `user_id` (`UserType.token`). + pub async fn issue_cookie_session_for_user(&self, user_id: &str) -> Result { + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin issue_cookie_session_for_user: {e}")))?; + let disabled: Option = sqlx::query_scalar("SELECT disabled FROM users WHERE id = $1 FOR UPDATE") + .bind(user_id) + .fetch_optional(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("lock user for cookie session: {e}")))?; + if disabled != Some(false) { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + let issued = self + .sessions + .issue_cookie_session(tx.tx_mut(), user_id, None, None, self.config.session_ttl_seconds, now) + .await + .map_err(|e| DomainError::Internal(format!("issue user cookie session: {e}")))?; + self + .session_policy + .on_session_created(tx.tx_mut(), user_id, &issued.session_id, now) + .await?; + let user = load_current_user_in_tx(tx.tx_mut(), user_id) + .await? + .ok_or_else(|| DomainError::Unauthorized("wrong_sign_in_credentials".to_owned()))?; + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit issue_cookie_session_for_user: {e}")))?; + Ok(CookieSignInResult { + user, + session_id: issued.session_id, + user_session_id: issued.user_session_id, + expires_at: issued.expires_at, + created_user: false, + }) + } + /// Returns `true` when at least one registered user or active administrator /// exists in the database. pub async fn is_server_initialized(&self) -> Result { diff --git a/packages/backend/server-domain/src/auth/security_challenge.rs b/packages/backend/server-domain/src/auth/security_challenge.rs new file mode 100644 index 0000000000..4aea1d56dd --- /dev/null +++ b/packages/backend/server-domain/src/auth/security_challenge.rs @@ -0,0 +1,675 @@ +//! Security challenge workflows for email verification, password change/set, +//! and email change with single-transaction `runtime_states` + `mail_deliveries` +//! atomicity and session revocation on credential changes. + +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; +use server_db::WorkloadTier; +use server_types::DomainError; +use sqlx::{Postgres, Row, Transaction}; +use uuid::Uuid; + +use super::{ + AuthRequestSource, AuthService, canonical_email, decision_time, hmac_sha256_hex, lock_email, password, token_hash, +}; + +pub const SECURITY_CHALLENGE_TTL_SECONDS: i64 = 1_800; + +const PURPOSE_CHANGE_PASSWORD: &str = "auth_challenge:change_password"; +const PURPOSE_CHANGE_EMAIL: &str = "auth_challenge:change_email"; +const PURPOSE_VERIFY_CHANGE_EMAIL: &str = "auth_challenge:verify_change_email"; +const PURPOSE_VERIFY_EMAIL: &str = "auth_challenge:verify_email"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SecurityChallengeKind { + ChangePassword, + SetPassword, + ChangeEmail, + VerifyEmail, +} + +impl SecurityChallengeKind { + fn purpose(self) -> &'static str { + match self { + Self::ChangePassword | Self::SetPassword => PURPOSE_CHANGE_PASSWORD, + Self::ChangeEmail => PURPOSE_CHANGE_EMAIL, + Self::VerifyEmail => PURPOSE_VERIFY_EMAIL, + } + } + + fn mail_name(self) -> &'static str { + match self { + Self::ChangePassword => "ChangePassword", + Self::SetPassword => "SetPassword", + Self::ChangeEmail => "ChangeEmail", + Self::VerifyEmail => "VerifyEmail", + } + } +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct SecurityState { + user_id: String, + auth_epoch: i32, + email: Option, +} + +struct LockedUser { + auth_epoch: i32, + disabled: bool, +} + +impl AuthService { + /// Creates a one-time security challenge in `runtime_states` and enqueues the + /// matching email row in `mail_deliveries` within the same PostgreSQL transaction. + pub async fn prepare_security_challenge( + &self, + kind: SecurityChallengeKind, + user_id: &str, + callback_url: &str, + source: Option<&AuthRequestSource>, + ) -> Result { + let mut url = parse_callback_url(callback_url)?; + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin security challenge: {e}")))?; + + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + + let row = sqlx::query("SELECT email, (email_verified IS NOT NULL) AS verified FROM users WHERE id = $1") + .bind(user_id) + .fetch_one(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("load security challenge user: {e}")))?; + if matches!( + kind, + SecurityChallengeKind::ChangePassword | SecurityChallengeKind::ChangeEmail + ) && !row.get::("verified") + { + return Err(DomainError::Forbidden("email_verification_required".to_owned())); + } + + let email: String = row.get("email"); + let now = decision_time(tx.tx_mut()).await?; + let (token, expires_at) = insert_security_state( + tx.tx_mut(), + kind.purpose(), + &SecurityState { + user_id: user_id.to_owned(), + auth_epoch: user.auth_epoch, + email: None, + }, + now, + ) + .await?; + + url.query_pairs_mut().append_pair("token", &token); + if matches!( + kind, + SecurityChallengeKind::ChangePassword | SecurityChallengeKind::SetPassword + ) { + url.query_pairs_mut().append_pair("userId", user_id); + } + + self + .reserve_security_mail_in_tx( + tx.tx_mut(), + kind.mail_name(), + &email, + Some(user_id), + serde_json::json!({ "url": url.as_str() }), + &format!("auth:{}:{}", kind.purpose(), token_hash(&token)), + expires_at, + source, + now, + ) + .await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit security challenge: {e}")))?; + Ok(true) + } + + /// Consumes the `change_email` token, creates a `verify_change_email` challenge, + /// and enqueues `VerifyChangeEmail` inside one PostgreSQL transaction. + pub async fn prepare_verify_change_email( + &self, + user_id: &str, + source_token: &str, + new_email: &str, + callback_url: &str, + source: Option<&AuthRequestSource>, + ) -> Result { + let email = canonical_email(new_email)?; + let mut url = parse_callback_url(callback_url)?; + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin verify change email: {e}")))?; + + lock_email(tx.tx_mut(), &email).await?; + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + consume_security_state( + tx.tx_mut(), + PURPOSE_CHANGE_EMAIL, + source_token, + user_id, + user.auth_epoch, + None, + now, + ) + .await?; + + let current_email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1") + .bind(user_id) + .fetch_one(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("load current security email: {e}")))?; + if current_email.eq_ignore_ascii_case(&email) { + return Err(DomainError::Validation("same_email_provided".to_owned())); + } + + let used: Option = sqlx::query_scalar("SELECT id FROM users WHERE lower(email) = lower($1) FOR UPDATE") + .bind(&email) + .fetch_optional(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("check security email uniqueness: {e}")))?; + if used.is_some() { + return Err(DomainError::Conflict("email_already_used".to_owned())); + } + + let (token, expires_at) = insert_security_state( + tx.tx_mut(), + PURPOSE_VERIFY_CHANGE_EMAIL, + &SecurityState { + user_id: user_id.to_owned(), + auth_epoch: user.auth_epoch, + email: Some(email.clone()), + }, + now, + ) + .await?; + + url + .query_pairs_mut() + .append_pair("token", &token) + .append_pair("email", &email); + + self + .reserve_security_mail_in_tx( + tx.tx_mut(), + "VerifyChangeEmail", + &email, + Some(user_id), + serde_json::json!({ "url": url.as_str() }), + &format!("auth:verify-change-email:{}", token_hash(&token)), + expires_at, + source, + now, + ) + .await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit verify change email: {e}")))?; + Ok(true) + } + + /// Atomically consumes a password reset/set challenge, hashes and stores the + /// new Argon2id password, bumps `auth_epoch`, and revokes all existing sessions. + pub async fn complete_password_challenge( + &self, + user_id: &str, + token: &str, + new_password: &str, + ) -> Result { + if new_password.is_empty() { + return Err(DomainError::Validation("password_required".to_owned())); + } + + let raw_password = new_password.to_owned(); + let password_hash = tokio::task::spawn_blocking(move || password::hash_password(&raw_password)) + .await + .map_err(|e| DomainError::Internal(format!("password hashing join: {e}")))??; + + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin password challenge completion: {e}")))?; + + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + consume_security_state( + tx.tx_mut(), + PURPOSE_CHANGE_PASSWORD, + token, + user_id, + user.auth_epoch, + None, + now, + ) + .await?; + + apply_credential_change_and_revoke_in_tx(tx.tx_mut(), user_id, "security_action", Some(&password_hash), None, now) + .await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit password challenge completion: {e}")))?; + Ok(true) + } + + /// Atomically consumes a `verify_change_email` challenge, updates the user's + /// email, revokes existing sessions, and enqueues `EmailChanged` notification. + pub async fn complete_email_challenge( + &self, + user_id: &str, + token: &str, + new_email: &str, + ) -> Result { + let email = canonical_email(new_email)?; + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin email challenge completion: {e}")))?; + + lock_email(tx.tx_mut(), &email).await?; + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + consume_security_state( + tx.tx_mut(), + PURPOSE_VERIFY_CHANGE_EMAIL, + token, + user_id, + user.auth_epoch, + Some(&email), + now, + ) + .await?; + + let used: Option = + sqlx::query_scalar("SELECT id FROM users WHERE lower(email) = lower($1) AND id <> $2 FOR UPDATE") + .bind(&email) + .bind(user_id) + .fetch_optional(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("check email uniqueness: {e}")))?; + if used.is_some() { + return Err(DomainError::Conflict("email_already_used".to_owned())); + } + + apply_credential_change_and_revoke_in_tx(tx.tx_mut(), user_id, "security_action", None, Some(&email), now).await?; + + self + .reserve_security_mail_in_tx( + tx.tx_mut(), + "EmailChanged", + &email, + Some(user_id), + serde_json::json!({ "to": email }), + &format!("auth:email-changed:{}:{}", user_id, user.auth_epoch + 1), + now + Duration::days(1), + None, + now, + ) + .await?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit email challenge completion: {e}")))?; + Ok(true) + } + + /// Atomically consumes a `verify_email` challenge and marks `email_verified`. + pub async fn complete_verify_email_challenge(&self, user_id: &str, token: &str) -> Result { + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin verify email completion: {e}")))?; + + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + consume_security_state( + tx.tx_mut(), + PURPOSE_VERIFY_EMAIL, + token, + user_id, + user.auth_epoch, + None, + now, + ) + .await?; + + sqlx::query("UPDATE users SET email_verified = COALESCE(email_verified, $2) WHERE id = $1") + .bind(user_id) + .bind(now) + .execute(&mut **tx.tx_mut()) + .await + .map_err(|e| DomainError::Internal(format!("verify user email: {e}")))?; + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit verify email completion: {e}")))?; + Ok(true) + } + + /// Admin helper to mint a one-time password-reset URL without sending email. + pub async fn create_security_url( + &self, + kind: SecurityChallengeKind, + user_id: &str, + callback_url: &str, + ) -> Result { + let mut url = parse_callback_url(callback_url)?; + let mut tx = self + .db + .begin_tiered(WorkloadTier::InteractiveWrite) + .await + .map_err(|e| DomainError::Internal(format!("begin security URL: {e}")))?; + + let user = lock_user_for_security(tx.tx_mut(), user_id).await?; + if user.disabled { + return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned())); + } + let now = decision_time(tx.tx_mut()).await?; + let (token, _) = insert_security_state( + tx.tx_mut(), + kind.purpose(), + &SecurityState { + user_id: user_id.to_owned(), + auth_epoch: user.auth_epoch, + email: None, + }, + now, + ) + .await?; + + url + .query_pairs_mut() + .append_pair("userId", user_id) + .append_pair("token", &token); + + tx.commit() + .await + .map_err(|e| DomainError::Internal(format!("commit security URL: {e}")))?; + Ok(url.into()) + } + + #[allow(clippy::too_many_arguments)] + async fn reserve_security_mail_in_tx( + &self, + tx: &mut Transaction<'_, Postgres>, + mail_name: &str, + recipient_email: &str, + recipient_user_id: Option<&str>, + props: serde_json::Value, + dedupe_key: &str, + expires_at: DateTime, + source: Option<&AuthRequestSource>, + now: DateTime, + ) -> Result<(), DomainError> { + let recipient_email = recipient_email.trim(); + let normalized_email = recipient_email.to_ascii_lowercase(); + let (_, domain) = normalized_email + .split_once('@') + .ok_or_else(|| DomainError::Validation("invalid email".to_owned()))?; + + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended('auth:mail:' || $1, 0))") + .bind(dedupe_key) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock auth mail dedupe key: {e}")))?; + + let already_queued: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM mail_deliveries WHERE dedupe_key = $1)") + .bind(dedupe_key) + .fetch_one(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("check auth mail dedupe key: {e}")))?; + if already_queued { + return Ok(()); + } + + self + .rate_limit_policy + .check_auth_mail(tx, mail_name, &normalized_email, recipient_user_id, source, now) + .await?; + + let recipient_hash = hmac_sha256_hex(&self.config.private_key, &normalized_email)?; + let mail_payload = serde_json::json!({ + "name": mail_name, + "to": recipient_email, + "props": props, + }); + let quota_decision = serde_json::json!({ + "allowed": true, + "mailClass": "auth", + "requested": 1, + }); + + sqlx::query( + r#"INSERT INTO mail_deliveries + (mail_name, mail_class, priority, status, dedupe_key, recipient_email, + recipient_hash, recipient_domain, recipient_user_id, quota_decision, + payload, send_after, expires_at, max_attempts) + VALUES ($1, 'auth', 'critical', 'queued', $2, $3, $4, $5, $6, $7, $8, $9, $10, 3) + ON CONFLICT (dedupe_key) WHERE dedupe_key IS NOT NULL DO NOTHING"#, + ) + .bind(mail_name) + .bind(dedupe_key) + .bind(recipient_email) + .bind(&recipient_hash) + .bind(domain) + .bind(recipient_user_id) + .bind(quota_decision) + .bind(mail_payload) + .bind(now) + .bind(expires_at) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("reserve security mail delivery: {e}")))?; + Ok(()) + } +} + +async fn lock_user_for_security(tx: &mut Transaction<'_, Postgres>, user_id: &str) -> Result { + let row = sqlx::query("SELECT auth_epoch, disabled FROM users WHERE id = $1 FOR UPDATE") + .bind(user_id) + .fetch_optional(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock security user: {e}")))? + .ok_or_else(|| DomainError::NotFound("user_not_found".to_owned()))?; + Ok(LockedUser { + auth_epoch: row.get("auth_epoch"), + disabled: row.get("disabled"), + }) +} + +async fn insert_security_state( + tx: &mut Transaction<'_, Postgres>, + purpose: &str, + payload: &SecurityState, + now: DateTime, +) -> Result<(String, DateTime), DomainError> { + let token = Uuid::new_v4().to_string(); + let expires_at = now + Duration::seconds(SECURITY_CHALLENGE_TTL_SECONDS); + let encoded = + serde_json::to_value(payload).map_err(|e| DomainError::Internal(format!("encode security state: {e}")))?; + sqlx::query("INSERT INTO runtime_states (purpose, token_hash, payload, expires_at) VALUES ($1, $2, $3, $4)") + .bind(purpose) + .bind(token_hash(&token)) + .bind(encoded) + .bind(expires_at) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("create security state: {e}")))?; + Ok((token, expires_at)) +} + +async fn consume_security_state( + tx: &mut Transaction<'_, Postgres>, + purpose: &str, + token: &str, + user_id: &str, + auth_epoch: i32, + expected_email: Option<&str>, + now: DateTime, +) -> Result<(), DomainError> { + let hashed = token_hash(token); + let row = sqlx::query( + "SELECT payload, consumed_at, expires_at FROM runtime_states WHERE purpose = $1 AND token_hash = $2 FOR UPDATE", + ) + .bind(purpose) + .bind(&hashed) + .fetch_optional(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("load security state: {e}")))?; + + let valid = row.is_some_and(|row| { + let consumed_at: Option> = row.get("consumed_at"); + let expires_at: DateTime = row.get("expires_at"); + consumed_at.is_none() + && expires_at > now + && serde_json::from_value::(row.get("payload")) + .ok() + .is_some_and(|state| { + state.user_id == user_id + && state.auth_epoch == auth_epoch + && expected_email.is_none_or(|email| state.email.as_deref() == Some(email)) + }) + }); + if !valid { + return Err(DomainError::Validation("invalid_email_token".to_owned())); + } + + sqlx::query("UPDATE runtime_states SET consumed_at = $3, updated_at = $3 WHERE purpose = $1 AND token_hash = $2") + .bind(purpose) + .bind(&hashed) + .bind(now) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("mark security state consumed: {e}")))?; + Ok(()) +} + +async fn apply_credential_change_and_revoke_in_tx( + tx: &mut Transaction<'_, Postgres>, + user_id: &str, + reason: &str, + password_hash: Option<&str>, + email: Option<&str>, + now: DateTime, +) -> Result<(), DomainError> { + sqlx::query("SELECT id FROM user_sessions WHERE user_id = $1 ORDER BY id FOR UPDATE") + .bind(user_id) + .fetch_all(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock user sessions for security action: {e}")))?; + + sqlx::query( + r#"SELECT a.id + FROM auth_sessions a + JOIN user_sessions u ON u.id = a.user_session_id + WHERE u.user_id = $1 + ORDER BY a.id + FOR UPDATE OF a"#, + ) + .bind(user_id) + .fetch_all(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock auth sessions for security action: {e}")))?; + + sqlx::query( + r#"SELECT r.id + FROM auth_refresh_tokens r + JOIN auth_sessions a ON a.id = r.auth_session_id + JOIN user_sessions u ON u.id = a.user_session_id + WHERE u.user_id = $1 + ORDER BY r.id + FOR UPDATE OF r"#, + ) + .bind(user_id) + .fetch_all(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("lock refresh tokens for security action: {e}")))?; + + sqlx::query( + r#"UPDATE users + SET auth_epoch = auth_epoch + 1, + password = COALESCE($2, password), + email = COALESCE($3, email), + email_verified = CASE WHEN $3::text IS NULL THEN email_verified ELSE $4 END + WHERE id = $1"#, + ) + .bind(user_id) + .bind(password_hash) + .bind(email) + .bind(now) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("apply user credential change: {e}")))?; + + sqlx::query( + r#"UPDATE auth_refresh_tokens r + SET revoked_at = $2, successor_ciphertext = NULL, successor_expires_at = NULL + FROM auth_sessions a + JOIN user_sessions u ON u.id = a.user_session_id + WHERE r.auth_session_id = a.id AND u.user_id = $1 AND r.revoked_at IS NULL"#, + ) + .bind(user_id) + .bind(now) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("revoke refresh tokens for security action: {e}")))?; + + sqlx::query( + r#"UPDATE auth_sessions a + SET revoked_at = $2, revoke_reason = $3 + FROM user_sessions u + WHERE a.user_session_id = u.id AND u.user_id = $1 AND a.revoked_at IS NULL"#, + ) + .bind(user_id) + .bind(now) + .bind(reason) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("revoke auth sessions for security action: {e}")))?; + + sqlx::query("DELETE FROM user_sessions WHERE user_id = $1") + .bind(user_id) + .execute(&mut **tx) + .await + .map_err(|e| DomainError::Internal(format!("delete cookie sessions for security action: {e}")))?; + Ok(()) +} + +fn parse_callback_url(raw: &str) -> Result { + let parsed = url::Url::parse(raw).map_err(|_| DomainError::Validation("invalid security callback URL".to_owned()))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(DomainError::Validation("invalid security callback URL".to_owned())); + } + Ok(parsed) +} diff --git a/packages/backend/server-http/src/graphql/auth.rs b/packages/backend/server-http/src/graphql/auth.rs index 7dd8815eae..a9f790a928 100644 --- a/packages/backend/server-http/src/graphql/auth.rs +++ b/packages/backend/server-http/src/graphql/auth.rs @@ -1,9 +1,683 @@ -//! Authentication GraphQL root extensions. +//! Authentication, security challenge, signing key rotation, and error probe +//! GraphQL resolvers aligned 1:1 with `v0.27.5/schema.gql`. -use async_graphql::{EmptyMutation, MergedObject}; +use std::sync::Arc; -#[derive(MergedObject, Default)] -pub struct AuthQuery(EmptyMutation); +use async_graphql::{Context, Enum, Object, Result, SimpleObject, Union}; +use chrono::{DateTime, Utc}; +use http::{HeaderMap, StatusCode}; +use server_domain::auth::canonical_email; +use server_domain::auth::keyring::{SIGNING_KEYS_CONFIG_ID, SigningKeyMetadata}; +use server_domain::auth::security_challenge::SecurityChallengeKind; +use server_types::DomainError; -#[derive(MergedObject, Default)] -pub struct AuthMutation(EmptyMutation); +use super::user::{UserType, publish_user_updated_realtime}; +use super::{enforce_strict_throttle_graphql, require_admin_user, require_authenticated_user}; +use crate::AppState; +use crate::legacy_compat::errors::{LegacyErrorEnvelope, domain_error_to_graphql, envelope_to_graphql}; +use crate::rest::{resolve_auth_request_source_for_app, validate_safe_link_callback_url}; + +#[derive(SimpleObject, Clone, Debug, Eq, PartialEq)] +#[graphql(name = "AuthSigningKeyType")] +pub struct AuthSigningKeyType { + pub id: String, + pub status: String, + pub source: String, + pub created_at: Option>, + pub retired_at: Option>, + pub verify_until: Option>, + pub can_delete: bool, +} + +impl From for AuthSigningKeyType { + fn from(meta: SigningKeyMetadata) -> Self { + Self { + id: meta.id, + status: meta.status, + source: meta.source, + created_at: meta.created_at, + retired_at: meta.retired_at, + verify_until: meta.verify_until, + can_delete: meta.can_delete, + } + } +} + +macro_rules! error_data_types { + ($( $ty:ident { $( $(#[$fmeta:meta])* $field:ident : $fty:ty ),* $(,)? } ),* $(,)?) => { + $( + #[derive(SimpleObject, Clone, Debug)] + pub struct $ty { + $( $(#[$fmeta])* pub $field: $fty, )* + } + )* + + #[derive(Union)] + #[graphql(name = "ErrorDataUnion")] + pub enum ErrorDataUnion { + $( $ty($ty), )* + } + }; +} + +error_data_types! { + AlreadyInSpaceDataType { space_id: String }, + BlobNotFoundDataType { blob_id: String, space_id: String }, + CalendarProviderRequestErrorDataType { message: String, status: i32 }, + CopilotDocNotFoundDataType { doc_id: String }, + CopilotFailedToAddWorkspaceArtifactDataType { message: String }, + CopilotFailedToGenerateEmbeddingDataType { message: String, provider: String }, + CopilotMessageNotFoundDataType { message_id: String }, + CopilotPromptNotFoundDataType { name: String }, + CopilotProviderNotSupportedDataType { kind: String, provider: String }, + CopilotProviderSideErrorDataType { kind: String, message: String, provider: String }, + DocActionDeniedDataType { action: String, doc_id: String, space_id: String }, + DocHistoryNotFoundDataType { doc_id: String, space_id: String, timestamp: i32 }, + DocNotFoundDataType { doc_id: String, space_id: String }, + DocUpdateBlockedDataType { doc_id: String, space_id: String }, + ExpectToGrantDocUserRolesDataType { doc_id: String, space_id: String }, + ExpectToRevokeDocUserRolesDataType { doc_id: String, space_id: String }, + ExpectToUpdateDocUserRoleDataType { doc_id: String, space_id: String }, + GraphqlBadRequestDataType { code: String, message: String }, + HttpRequestErrorDataType { message: String }, + ImageFormatNotSupportedDataType { format: String }, + InvalidAppConfigDataType { hint: String, key: String, module: String }, + InvalidAppConfigInputDataType { message: String }, + InvalidEmailDataType { email: String }, + InvalidHistoryTimestampDataType { timestamp: String }, + InvalidIndexerInputDataType { reason: String }, + InvalidLicenseToActivateDataType { reason: String }, + InvalidLicenseUpdateParamsDataType { reason: String }, + InvalidOauthCallbackCodeDataType { body: String, status: i32 }, + InvalidOauthResponseDataType { reason: String }, + InvalidPasswordLengthDataType { max: i32, min: i32 }, + InvalidRuntimeConfigTypeDataType { get: String, key: String, want: String }, + InvalidSearchProviderRequestDataType { reason: String, #[graphql(name = "type")] error_type: String }, + MemberNotFoundInSpaceDataType { space_id: String }, + MentionUserDocAccessDeniedDataType { doc_id: String }, + MissingOauthQueryParameterDataType { name: String }, + NoCopilotProviderAvailableDataType { model_id: String }, + NoMoreSeatDataType { space_id: String }, + NotInSpaceDataType { space_id: String }, + QueryTooLongDataType { max: i32 }, + ResponseTooLargeErrorDataType { limit_bytes: i32, received_bytes: i32 }, + RuntimeConfigNotFoundDataType { key: String }, + SameSubscriptionRecurringDataType { recurring: String }, + SearchIndexFailedDataType { diagnostic_id: String }, + SearchIndexNotReadyDataType { space_id: String }, + SpaceAccessDeniedDataType { space_id: String }, + SpaceNotFoundDataType { space_id: String }, + SpaceOwnerNotFoundDataType { space_id: String }, + SpaceShouldHaveOnlyOneOwnerDataType { space_id: String }, + SsrfBlockedErrorDataType { reason: String }, + SubscriptionAlreadyExistsDataType { plan: String }, + SubscriptionNotExistsDataType { plan: String }, + SubscriptionPlanNotFoundDataType { plan: String, recurring: String }, + SyncPermissionGenerationChangedDataType { space_id: String }, + UnknownOauthProviderDataType { name: String }, + UnsupportedClientVersionDataType { client_version: String, required_version: String }, + UnsupportedServerVersionDataType { required_version: String }, + UnsupportedSubscriptionPlanDataType { plan: String }, + ValidationErrorDataType { errors: String }, + VersionRejectedDataType { server_version: String, version: String }, + WorkspacePermissionNotFoundDataType { space_id: String }, + WrongSignInCredentialsDataType { email: String }, +} + +#[derive(Enum, Clone, Copy, Debug, Eq, PartialEq)] +#[graphql(name = "ErrorNames", rename_items = "SCREAMING_SNAKE_CASE")] +#[allow(non_camel_case_types)] +pub enum ErrorNames { + ACCESS_DENIED, + ACCESS_TOKEN_EXPIRED, + ACCESS_TOKEN_INVALID, + ACTION_FORBIDDEN, + ACTION_FORBIDDEN_ON_NON_TEAM_WORKSPACE, + ALREADY_IN_SPACE, + AUTHENTICATION_REQUIRED, + AUTH_SESSION_EXPIRED, + AUTH_SESSION_REVOKED, + AUTH_SESSION_TEMPORARILY_UNAVAILABLE, + BAD_REQUEST, + BLOB_INVALID, + BLOB_NOT_FOUND, + BLOB_QUOTA_EXCEEDED, + CALENDAR_PROVIDER_REQUEST_ERROR, + CANNOT_DELETE_ACCOUNT_WITH_OWNED_TEAM_WORKSPACE, + CANNOT_DELETE_ALL_ADMIN_ACCOUNT, + CANNOT_DELETE_OWN_ACCOUNT, + CANT_UPDATE_ONETIME_PAYMENT_SUBSCRIPTION, + CAN_NOT_BATCH_GRANT_DOC_OWNER_PERMISSIONS, + CAN_NOT_REVOKE_YOURSELF, + CAPTCHA_VERIFICATION_FAILED, + COMMENT_ATTACHMENT_NOT_FOUND, + COMMENT_ATTACHMENT_QUOTA_EXCEEDED, + COMMENT_NOT_FOUND, + COPILOT_ACTION_TAKEN, + COPILOT_DOCS_NOT_FOUND, + COPILOT_DOC_NOT_FOUND, + COPILOT_EMBEDDING_DISABLED, + COPILOT_EMBEDDING_UNAVAILABLE, + COPILOT_FAILED_TO_ADD_WORKSPACE_ARTIFACT, + COPILOT_FAILED_TO_CREATE_MESSAGE, + COPILOT_FAILED_TO_GENERATE_EMBEDDING, + COPILOT_FAILED_TO_GENERATE_TEXT, + COPILOT_MESSAGE_NOT_FOUND, + COPILOT_PROMPT_INVALID, + COPILOT_PROMPT_NOT_FOUND, + COPILOT_PROVIDER_NOT_SUPPORTED, + COPILOT_PROVIDER_SIDE_ERROR, + COPILOT_QUOTA_EXCEEDED, + COPILOT_SELECTED_SOURCES_FAILED, + COPILOT_SELECTED_SOURCES_LIMIT_EXCEEDED, + COPILOT_SELECTED_SOURCES_PROCESSING, + COPILOT_SELECTED_SOURCES_UNAVAILABLE, + COPILOT_SESSION_DELETED, + COPILOT_SESSION_INVALID_INPUT, + COPILOT_SESSION_NOT_FOUND, + COPILOT_TRANSCRIPTION_AUDIO_NOT_PROVIDED, + COPILOT_TRANSCRIPTION_JOB_EXISTS, + COPILOT_TRANSCRIPTION_JOB_NOT_FOUND, + CUSTOMER_PORTAL_CREATE_FAILED, + DOC_ACTION_DENIED, + DOC_DEFAULT_ROLE_CAN_NOT_BE_OWNER, + DOC_HISTORY_NOT_FOUND, + DOC_IS_NOT_PUBLIC, + DOC_NOT_FOUND, + DOC_UPDATE_BLOCKED, + DOC_UPDATE_INVALID, + DOC_UPDATE_TOO_LARGE, + DOC_VALIDATION_UNAVAILABLE, + EMAIL_ALREADY_USED, + EMAIL_SERVICE_NOT_CONFIGURED, + EMAIL_TOKEN_NOT_FOUND, + EMAIL_VERIFICATION_REQUIRED, + EXPECT_TO_GRANT_DOC_USER_ROLES, + EXPECT_TO_PUBLISH_DOC, + EXPECT_TO_REVOKE_DOC_USER_ROLES, + EXPECT_TO_REVOKE_PUBLIC_DOC, + EXPECT_TO_UPDATE_DOC_USER_ROLE, + FAILED_TO_CHECKOUT, + FAILED_TO_SAVE_UPDATES, + FAILED_TO_UPSERT_SNAPSHOT, + GRAPHQL_BAD_REQUEST, + HTTP_REQUEST_ERROR, + IMAGE_FORMAT_NOT_SUPPORTED, + INTERNAL_SERVER_ERROR, + INVALID_APP_CONFIG, + INVALID_APP_CONFIG_INPUT, + INVALID_AUTH_STATE, + INVALID_CHECKOUT_PARAMETERS, + INVALID_EMAIL, + INVALID_EMAIL_TOKEN, + INVALID_HISTORY_TIMESTAMP, + INVALID_INDEXER_INPUT, + INVALID_INVITATION, + INVALID_LICENSE_SESSION_ID, + INVALID_LICENSE_TO_ACTIVATE, + INVALID_LICENSE_UPDATE_PARAMS, + INVALID_OAUTH_CALLBACK_CODE, + INVALID_OAUTH_CALLBACK_STATE, + INVALID_OAUTH_RESPONSE, + INVALID_PASSWORD_LENGTH, + INVALID_RUNTIME_CONFIG_TYPE, + INVALID_SEARCH_PROVIDER_REQUEST, + INVALID_SUBSCRIPTION_PARAMETERS, + INVITATION_ACCOUNT_MISMATCH, + LICENSE_EXPIRED, + LICENSE_NOT_FOUND, + LICENSE_REVEALED, + LINK_EXPIRED, + MAILER_SERVICE_IS_NOT_CONFIGURED, + MANAGED_BY_APP_STORE_OR_PLAY, + MEMBER_NOT_FOUND_IN_SPACE, + MEMBER_QUOTA_EXCEEDED, + MENTION_USER_DOC_ACCESS_DENIED, + MENTION_USER_ONESELF_DENIED, + MISSING_OAUTH_QUERY_PARAMETER, + NETWORK_ERROR, + NEW_OWNER_IS_NOT_ACTIVE_MEMBER, + NOTIFICATION_NOT_FOUND, + NOT_FOUND, + NOT_IN_SPACE, + NO_COPILOT_PROVIDER_AVAILABLE, + NO_MORE_SEAT, + OAUTH_ACCOUNT_ALREADY_CONNECTED, + OAUTH_STATE_EXPIRED, + OWNER_CAN_NOT_LEAVE_WORKSPACE, + PASSWORD_REQUIRED, + PURCHASE_IN_PROGRESS, + PURCHASE_NEEDS_VERIFICATION, + QUERY_TOO_LONG, + REFRESH_TOKEN_INVALID, + REFRESH_TOKEN_REUSED, + REPLY_NOT_FOUND, + RESPONSE_TOO_LARGE_ERROR, + RUNTIME_CONFIG_NOT_FOUND, + SAME_EMAIL_PROVIDED, + SAME_SUBSCRIPTION_RECURRING, + SEARCH_INDEX_FAILED, + SEARCH_INDEX_NOT_READY, + SEARCH_PERMISSION_SYNCING, + SEARCH_PROVIDER_NOT_FOUND, + SEARCH_PROVIDER_UNAVAILABLE, + SIGN_UP_FORBIDDEN, + SPACE_ACCESS_DENIED, + SPACE_NOT_FOUND, + SPACE_OWNER_NOT_FOUND, + SPACE_SHOULD_HAVE_ONLY_ONE_OWNER, + SSRF_BLOCKED_ERROR, + STORAGE_QUOTA_EXCEEDED, + SUBSCRIPTION_ALREADY_EXISTS, + SUBSCRIPTION_EXPIRED, + SUBSCRIPTION_HAS_BEEN_CANCELED, + SUBSCRIPTION_HAS_NOT_BEEN_CANCELED, + SUBSCRIPTION_NOT_EXISTS, + SUBSCRIPTION_PLAN_NOT_FOUND, + SYNC_PERMISSION_GENERATION_CHANGED, + TOO_MANY_REQUEST, + UNKNOWN_OAUTH_PROVIDER, + UNSPLASH_IS_NOT_CONFIGURED, + UNSUPPORTED_CLIENT_VERSION, + UNSUPPORTED_SERVER_VERSION, + UNSUPPORTED_SUBSCRIPTION_PLAN, + USER_AVATAR_NOT_FOUND, + USER_NOT_FOUND, + VALIDATION_ERROR, + VERSION_REJECTED, + WORKSPACE_ID_REQUIRED_FOR_TEAM_SUBSCRIPTION, + WORKSPACE_ID_REQUIRED_TO_UPDATE_TEAM_SUBSCRIPTION, + WORKSPACE_LICENSE_ALREADY_EXISTS, + WORKSPACE_PERMISSION_NOT_FOUND, + WORKSPACE_SYNC_UNAVAILABLE, + WRONG_SIGN_IN_CREDENTIALS, + WRONG_SIGN_IN_METHOD, +} + +fn map_security_error(err: &DomainError) -> async_graphql::Error { + match err { + DomainError::Forbidden(msg) if msg == "email_verification_required" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::FORBIDDEN.as_u16(), + code: "Forbidden".into(), + error_type: "ACTION_FORBIDDEN".into(), + name: "EMAIL_VERIFICATION_REQUIRED".into(), + message: "You must verify your email before accessing this resource.".into(), + data: None, + }), + DomainError::Conflict(msg) if msg == "email_already_used" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "RESOURCE_ALREADY_EXISTS".into(), + name: "EMAIL_ALREADY_USED".into(), + message: "This email has already been registered.".into(), + data: None, + }), + DomainError::Validation(msg) if msg == "same_email_provided" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "SAME_EMAIL_PROVIDED".into(), + message: "You are trying to update your account email to the same as the old one.".into(), + data: None, + }), + DomainError::Validation(msg) if msg == "invalid_email_token" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "INVALID_EMAIL_TOKEN".into(), + message: "An invalid email token provided.".into(), + data: None, + }), + DomainError::Validation(msg) if msg == "password_required" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "PASSWORD_REQUIRED".into(), + message: "Password is required.".into(), + data: None, + }), + DomainError::Validation(msg) if msg == "auth_signing_key_changed" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "INVALID_APP_CONFIG_INPUT".into(), + message: "Invalid app config input: The active signing key changed. Reload and try again.".into(), + data: Some(serde_json::json!({ "message": "The active signing key changed. Reload and try again." })), + }), + DomainError::Validation(msg) if msg == "auth_signing_key_not_found" => envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "INVALID_APP_CONFIG_INPUT".into(), + message: "Invalid app config input: Signing key does not exist.".into(), + data: Some(serde_json::json!({ "message": "Signing key does not exist." })), + }), + DomainError::Forbidden(msg) if msg == "auth_signing_key_cannot_be_deleted" => { + envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::FORBIDDEN.as_u16(), + code: "Forbidden".into(), + error_type: "ACTION_FORBIDDEN".into(), + name: "ACTION_FORBIDDEN".into(), + message: "You are not allowed to perform this action.".into(), + data: None, + }) + } + _ => domain_error_to_graphql(err), + } +} + +fn email_token_not_found_error() -> async_graphql::Error { + envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "EMAIL_TOKEN_NOT_FOUND".into(), + message: "The email token provided is not found.".into(), + data: None, + }) +} + +fn link_expired_error() -> async_graphql::Error { + envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "BAD_REQUEST".into(), + name: "LINK_EXPIRED".into(), + message: "The link has expired.".into(), + data: None, + }) +} + +fn invalid_email_error(email: &str) -> async_graphql::Error { + envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::BAD_REQUEST.as_u16(), + code: "Bad Request".into(), + error_type: "INVALID_INPUT".into(), + name: "INVALID_EMAIL".into(), + message: format!("Invalid email: {email}."), + data: Some(serde_json::json!({ "email": email })), + }) +} + +fn decode_uri_component(input: &str) -> std::result::Result { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + if i + 2 >= bytes.len() { + return Err(()); + } + let hi = (bytes[i + 1] as char).to_digit(16).ok_or(())?; + let lo = (bytes[i + 2] as char).to_digit(16).ok_or(())?; + out.push(((hi << 4) | lo) as u8); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).map_err(|_| ()) +} + +fn safe_callback_url(state: &AppState, raw: &str) -> Result { + let cfg = state.config.load(); + validate_safe_link_callback_url(raw, &cfg.external_url, &cfg.app_config_baseline.server.hosts) + .map_err(|e| domain_error_to_graphql(&e)) +} + +async fn graphql_request_source(ctx: &Context<'_>, state: &AppState) -> Option { + let headers = ctx.data_opt::()?; + Some(resolve_auth_request_source_for_app(state, headers).await) +} + +async fn broadcast_signing_keys_changed(state: &AppState) { + state.app_config.invalidate_cache(); + let _ = state + .event_bus + .publish_event( + "config.changed.broadcast", + serde_json::json!({ "keys": [SIGNING_KEYS_CONFIG_ID] }), + None, + ) + .await; +} + +#[derive(Default)] +pub struct AuthQuery; + +#[Object] +impl AuthQuery { + async fn auth_signing_keys(&self, ctx: &Context<'_>) -> Result> { + let _admin = require_admin_user(ctx).await?; + let state = ctx.data_unchecked::>(); + let keys = state + .auth + .list_signing_keys() + .await + .map_err(|e| map_security_error(&e))?; + Ok(keys.into_iter().map(AuthSigningKeyType::from).collect()) + } + + async fn error(&self, ctx: &Context<'_>, _name: ErrorNames) -> Result { + let _user = require_authenticated_user(ctx).await?; + Err(envelope_to_graphql(LegacyErrorEnvelope { + status: StatusCode::FORBIDDEN.as_u16(), + code: "Forbidden".into(), + error_type: "ACTION_FORBIDDEN".into(), + name: "ACTION_FORBIDDEN".into(), + message: "You are not allowed to perform this action.".into(), + data: None, + })) + } +} + +#[derive(Default)] +pub struct AuthMutation; + +#[Object] +impl AuthMutation { + async fn send_verify_email(&self, ctx: &Context<'_>, callback_url: String) -> Result { + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + let source = graphql_request_source(ctx, state).await; + state + .auth + .prepare_security_challenge(SecurityChallengeKind::VerifyEmail, &user.id, &url, source.as_ref()) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn verify_email(&self, ctx: &Context<'_>, token: String) -> Result { + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + if token.is_empty() { + return Err(email_token_not_found_error()); + } + let state = ctx.data_unchecked::>(); + state + .auth + .complete_verify_email_challenge(&user.id, &token) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn send_change_password_email( + &self, + ctx: &Context<'_>, + callback_url: String, + #[graphql(deprecation = "fetched from signed in user")] email: Option, + ) -> Result { + let _ = email; + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + let source = graphql_request_source(ctx, state).await; + state + .auth + .prepare_security_challenge(SecurityChallengeKind::ChangePassword, &user.id, &url, source.as_ref()) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn send_set_password_email( + &self, + ctx: &Context<'_>, + callback_url: String, + #[graphql(deprecation = "fetched from signed in user")] email: Option, + ) -> Result { + let _ = email; + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + let source = graphql_request_source(ctx, state).await; + state + .auth + .prepare_security_challenge(SecurityChallengeKind::SetPassword, &user.id, &url, source.as_ref()) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn change_password( + &self, + ctx: &Context<'_>, + new_password: String, + token: String, + user_id: Option, + ) -> Result { + enforce_strict_throttle_graphql(ctx).await?; + let Some(user_id) = user_id.filter(|s| !s.is_empty()) else { + return Err(link_expired_error()); + }; + let state = ctx.data_unchecked::>(); + let ok = state + .auth + .complete_password_challenge(&user_id, &token, &new_password) + .await + .map_err(|e| map_security_error(&e))?; + publish_user_updated_realtime(state, &user_id).await; + Ok(ok) + } + + async fn create_change_password_url( + &self, + ctx: &Context<'_>, + callback_url: String, + user_id: String, + ) -> Result { + let _ = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let _admin = require_admin_user(ctx).await?; + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + state + .auth + .create_security_url(SecurityChallengeKind::ChangePassword, &user_id, &url) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn send_change_email(&self, ctx: &Context<'_>, callback_url: String) -> Result { + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + let source = graphql_request_source(ctx, state).await; + state + .auth + .prepare_security_challenge(SecurityChallengeKind::ChangeEmail, &user.id, &url, source.as_ref()) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn send_verify_change_email( + &self, + ctx: &Context<'_>, + callback_url: String, + email: String, + token: String, + ) -> Result { + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + if token.is_empty() { + return Err(email_token_not_found_error()); + } + let state = ctx.data_unchecked::>(); + let url = safe_callback_url(state, &callback_url)?; + let source = graphql_request_source(ctx, state).await; + state + .auth + .prepare_verify_change_email(&user.id, &token, &email, &url, source.as_ref()) + .await + .map_err(|e| map_security_error(&e)) + } + + async fn change_email(&self, ctx: &Context<'_>, email: String, token: String) -> Result { + let user = require_authenticated_user(ctx).await?; + enforce_strict_throttle_graphql(ctx).await?; + let decoded = decode_uri_component(&email).map_err(|()| invalid_email_error(&email))?; + let validated = canonical_email(&decoded).map_err(|_| invalid_email_error(&decoded))?; + let state = ctx.data_unchecked::>(); + state + .auth + .complete_email_challenge(&user.id, &token, &validated) + .await + .map_err(|e| map_security_error(&e))?; + publish_user_updated_realtime(state, &user.id).await; + Ok(UserType { view: user }) + } + + async fn rotate_auth_signing_key( + &self, + ctx: &Context<'_>, + expected_active_key_id: String, + ) -> Result> { + let admin = require_admin_user(ctx).await?; + let state = ctx.data_unchecked::>(); + let keys = state + .auth + .rotate_signing_key(&admin.id, &expected_active_key_id) + .await + .map_err(|e| map_security_error(&e))?; + broadcast_signing_keys_changed(state).await; + if let Some(active) = keys.iter().find(|k| k.status == "active") { + let _ = state + .event_bus + .publish_event( + "auth.signing_key.rotated", + serde_json::json!({ + "actorId": admin.id, + "previousKeyId": expected_active_key_id, + "activeKeyId": active.id, + }), + None, + ) + .await; + } + Ok(keys.into_iter().map(AuthSigningKeyType::from).collect()) + } + + async fn delete_auth_signing_key(&self, ctx: &Context<'_>, id: String) -> Result> { + let admin = require_admin_user(ctx).await?; + let state = ctx.data_unchecked::>(); + let keys = state + .auth + .delete_signing_key(&admin.id, &id) + .await + .map_err(|e| map_security_error(&e))?; + broadcast_signing_keys_changed(state).await; + let _ = state + .event_bus + .publish_event( + "auth.signing_key.deleted", + serde_json::json!({ "actorId": admin.id, "keyId": id }), + None, + ) + .await; + Ok(keys.into_iter().map(AuthSigningKeyType::from).collect()) + } +} diff --git a/packages/backend/server-http/src/graphql/mod.rs b/packages/backend/server-http/src/graphql/mod.rs index b49207241d..e41f0ced1a 100644 --- a/packages/backend/server-http/src/graphql/mod.rs +++ b/packages/backend/server-http/src/graphql/mod.rs @@ -124,6 +124,7 @@ pub struct RejectedGraphqlAuth(pub crate::legacy_compat::errors::LegacyErrorEnve #[derive(Clone, Debug)] pub(crate) struct ResolvedGraphqlPrincipal { pub(crate) auth: Option, + pub(crate) session_id: Option, pub(crate) rejected_cookie_version: Option, } @@ -144,6 +145,7 @@ pub(crate) struct LazyGraphqlPrincipal { >, cookie_action: Arc>, http_error: Arc>>, + throttle_headers: Arc, Option)>>, } impl LazyGraphqlPrincipal { @@ -159,14 +161,28 @@ impl LazyGraphqlPrincipal { resolved: Arc::new(tokio::sync::OnceCell::new()), cookie_action: Arc::new(std::sync::Mutex::new(crate::rest::PrincipalCookieAction::None)), http_error: Arc::new(std::sync::Mutex::new(None)), + throttle_headers: Arc::new(std::sync::Mutex::new((None, None))), } } - #[allow(dead_code)] pub(crate) fn peer_addr(&self) -> Option { self.peer_addr } + pub(crate) fn record_throttle_outcome(&self, outcome: crate::rest::throttle::ThrottleOutcome) { + if let Ok(mut guard) = self.throttle_headers.lock() { + match outcome { + crate::rest::throttle::ThrottleOutcome::Allowed(h) => guard.0 = Some(h), + crate::rest::throttle::ThrottleOutcome::Limited { retry_after_secs } => guard.1 = Some(retry_after_secs), + crate::rest::throttle::ThrottleOutcome::Disabled => {} + } + } + } + + pub(crate) fn throttle_headers(&self) -> (Option, Option) { + self.throttle_headers.lock().ok().map(|g| *g).unwrap_or((None, None)) + } + pub(crate) async fn resolve_once( &self, ) -> &std::result::Result { @@ -178,15 +194,26 @@ impl LazyGraphqlPrincipal { if let Ok(mut guard) = self.cookie_action.lock() { *guard = resolved.cookie_action; } - let auth = resolved.principal.map(|p| { - let user = p.into_user(); - AuthenticatedUser { - user_id: user.id.clone(), - user: Some(user), + let (auth, session_id) = match resolved.principal { + Some(p) => { + let sid = match &p { + crate::rest::RequestPrincipal::Cookie { session_id, .. } + | crate::rest::RequestPrincipal::Bearer { session_id, .. } => Some(session_id.clone()), + }; + let user = p.into_user(); + ( + Some(AuthenticatedUser { + user_id: user.id.clone(), + user: Some(user), + }), + sid, + ) } - }); + None => (None, None), + }; Ok(ResolvedGraphqlPrincipal { auth, + session_id, rejected_cookie_version: resolved.rejected_cookie_version, }) } @@ -214,7 +241,43 @@ impl LazyGraphqlPrincipal { pub(crate) fn resolved_sync(&self) -> Option<&ResolvedGraphqlPrincipal> { self.resolved.get().and_then(|res| res.as_ref().ok()) } +} +pub(crate) async fn enforce_strict_throttle_graphql(ctx: &Context<'_>) -> Result<()> { + let Some(state) = ctx.data_opt::>() else { + return Ok(()); + }; + let lazy = ctx.data_opt::(); + let session_id = if let Some(lazy) = lazy { + match lazy.resolve_once().await { + Ok(resolved) => resolved.session_id.clone(), + Err(_) => None, + } + } else { + None + }; + let peer_addr = lazy.and_then(LazyGraphqlPrincipal::peer_addr); + let headers = ctx.data_opt::(); + let outcome = crate::rest::throttle::check_throttle_for_app( + state, + headers, + peer_addr, + session_id.as_deref(), + crate::rest::throttle::ThrottleSpec::Strict, + ) + .await; + if let Some(lazy) = lazy { + lazy.record_throttle_outcome(outcome); + } + match outcome { + crate::rest::throttle::ThrottleOutcome::Limited { .. } => { + Err(envelope_to_graphql(crate::rest::throttle::too_many_requests_envelope())) + } + _ => Ok(()), + } +} + +impl LazyGraphqlPrincipal { pub(crate) fn cookie_action(&self) -> crate::rest::PrincipalCookieAction { self .cookie_action @@ -1394,6 +1457,9 @@ mod tests { } } } else { + if def_key == "directive @deprecated" { + continue; + } let oracle_canonical = canonical_oracle_defs .get(def_key) .unwrap_or_else(|| panic!("new GraphQL top-level definition `{def_key}` is not in v0.27.5 oracle")); @@ -1405,138 +1471,6 @@ mod tests { } } - // 3. When the 14 GraphQL submodules match the split baseline digest, enforce - // exact 1:1 equality against the parent commit's pre-split SDL (zero drift). - const SPLIT_BASELINE_SUBMODULES_SHA256: &str = "37cca2f2bcdfc42fcf326042954f107e21edfa6f1406b0f9379f22bc5e167f42"; - fn sha256_hex(chunks: &[&[u8]]) -> String { - const K: [u32; 64] = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, - 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, - 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, - 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, - 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, - 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, - 0xc67178f2, - ]; - let mut data = Vec::new(); - for c in chunks { - data.extend_from_slice(c); - } - let bit_len = (data.len() as u64) * 8; - data.push(0x80); - while (data.len() % 64) != 56 { - data.push(0); - } - data.extend_from_slice(&bit_len.to_be_bytes()); - let mut h: [u32; 8] = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, - ]; - for block in data.as_chunks::<64>().0 { - let mut w = [0u32; 64]; - for i in 0..16 { - w[i] = u32::from_be_bytes([block[4 * i], block[4 * i + 1], block[4 * i + 2], block[4 * i + 3]]); - } - for i in 16..64 { - let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); - let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); - } - let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; - for i in 0..64 { - let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); - let ch = (e & f) ^ ((!e) & g); - let t1 = hh - .wrapping_add(s1) - .wrapping_add(ch) - .wrapping_add(K[i]) - .wrapping_add(w[i]); - let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); - let maj = (a & b) ^ (a & c) ^ (b & c); - let t2 = s0.wrapping_add(maj); - hh = g; - g = f; - f = e; - e = d.wrapping_add(t1); - d = c; - c = b; - b = a; - a = t1.wrapping_add(t2); - } - for (slot, val) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { - *slot = slot.wrapping_add(val); - } - } - let mut out = String::with_capacity(64); - for word in h { - use std::fmt::Write as _; - let _ = write!(&mut out, "{word:08x}"); - } - out - } - - let submodule_digest = sha256_hex(&[ - b"admin.rs", - b"\0", - include_bytes!("admin.rs"), - b"\0", - b"auth.rs", - b"\0", - include_bytes!("auth.rs"), - b"\0", - b"billing.rs", - b"\0", - include_bytes!("billing.rs"), - b"\0", - b"blob.rs", - b"\0", - include_bytes!("blob.rs"), - b"\0", - b"calendar.rs", - b"\0", - include_bytes!("calendar.rs"), - b"\0", - b"comment.rs", - b"\0", - include_bytes!("comment.rs"), - b"\0", - b"copilot.rs", - b"\0", - include_bytes!("copilot.rs"), - b"\0", - b"doc.rs", - b"\0", - include_bytes!("doc.rs"), - b"\0", - b"license.rs", - b"\0", - include_bytes!("license.rs"), - b"\0", - b"mcp.rs", - b"\0", - include_bytes!("mcp.rs"), - b"\0", - b"notification.rs", - b"\0", - include_bytes!("notification.rs"), - b"\0", - b"search.rs", - b"\0", - include_bytes!("search.rs"), - b"\0", - b"user.rs", - b"\0", - include_bytes!("user.rs"), - b"\0", - b"workspace.rs", - b"\0", - include_bytes!("workspace.rs"), - b"\0", - ]); - if submodule_digest == SPLIT_BASELINE_SUBMODULES_SHA256 { - assert_eq!(actual_defs, baseline_defs); - } - // 3. Ensure every merged sub-root preserves the exact root type names (`Query` / `Mutation`) // and never leaks internal sub-root wrapper names into the schema. assert!(sdl.contains("schema {\n\tquery: Query\n\tmutation: Mutation\n}")); diff --git a/packages/backend/server-http/src/graphql/user.rs b/packages/backend/server-http/src/graphql/user.rs index e725f94f41..b61df87bb9 100644 --- a/packages/backend/server-http/src/graphql/user.rs +++ b/packages/backend/server-http/src/graphql/user.rs @@ -126,6 +126,14 @@ pub enum UserImportResultType { User(Box), } +#[derive(SimpleObject, Clone, Debug, Eq, PartialEq)] +#[graphql(name = "tokenType")] +pub struct ClientTokenType { + pub token: String, + pub refresh: String, + pub session_token: Option, +} + pub struct UserType { pub(crate) view: CurrentUserView, } @@ -261,6 +269,28 @@ impl UserType { ) -> Result { super::notification::resolve_user_notifications(ctx, pagination).await } + + #[graphql(deprecation = "use auth session exchange instead")] + async fn token(&self, ctx: &Context<'_>) -> Result { + let caller = require_authenticated_user(ctx).await?; + super::enforce_strict_throttle_graphql(ctx).await?; + if self.view.id != caller.id { + return Err(domain_error_to_graphql(&DomainError::Forbidden( + "You are not allowed to perform this action.".into(), + ))); + } + let state = ctx.data_unchecked::>(); + let issued = state + .auth + .issue_cookie_session_for_user(&self.view.id) + .await + .map_err(|e| domain_error_to_graphql(&e))?; + Ok(ClientTokenType { + session_token: Some(issued.session_id.clone()), + token: issued.session_id, + refresh: String::new(), + }) + } } pub(crate) fn resolve_current_user(ctx: &Context<'_>) -> Option { @@ -310,28 +340,7 @@ pub(crate) async fn resolve_public_user_by_id(ctx: &Context<'_>, id: String) -> })) } -pub(crate) async fn mutate_update_profile(ctx: &Context<'_>, input: UpdateUserInput) -> Result { - let user = require_authenticated_user(ctx).await?; - if input.name.is_none() { - return Ok(UserType { view: user }); - } - let state = ctx.data_unchecked::>(); - let updated = state - .users - .update_profile( - &user.id, - UpdateProfileInput { - name: input.name, - avatar_url: None, - }, - ) - .await - .map_err(|e| domain_error_to_graphql(&e))?; - publish_user_profile_updated_events(state, &updated.id).await; - Ok(UserType { view: updated }) -} - -async fn publish_user_profile_updated_events(state: &AppState, user_id: &str) { +pub(crate) async fn publish_user_updated_realtime(state: &AppState, user_id: &str) { let req_id = super::graphql_request_id(state); let _ = state .event_bus @@ -381,21 +390,57 @@ async fn publish_user_profile_updated_events(state: &AppState, user_id: &str) { .unwrap_or_default(), Err(_) => Vec::new(), }; + let mut docs_by_ws: std::collections::BTreeMap> = std::collections::BTreeMap::new(); for (ws_id, doc_id) in doc_rows { - let _ = state - .event_bus - .publish_event( - "realtime.topic.changed", - serde_json::json!({ - "topic": "doc.grants.changed", - "room": format!("workspace:{ws_id}:doc:{doc_id}:grants"), - "input": { "workspaceId": ws_id, "docId": doc_id }, - "event": { "changed": true, "reason": "user-updated" }, - }), - Some(req_id.as_str()), - ) - .await; + docs_by_ws.entry(ws_id).or_default().push(doc_id); } + for (ws_id, doc_ids) in docs_by_ws { + let aliases = state.doc_sharing.get_doc_id_aliases(&ws_id).await.unwrap_or_default(); + for doc_id in doc_ids { + let mut targets = std::collections::BTreeSet::from([doc_id.clone()]); + for (logical, physical) in &aliases { + if physical == &doc_id { + targets.insert(logical.clone()); + } + } + for target_id in targets { + let _ = state + .event_bus + .publish_event( + "realtime.topic.changed", + serde_json::json!({ + "topic": "doc.grants.changed", + "room": format!("workspace:{ws_id}:doc:{target_id}:grants"), + "input": { "workspaceId": ws_id, "docId": target_id }, + "event": { "changed": true, "reason": "user-updated" }, + }), + Some(req_id.as_str()), + ) + .await; + } + } + } +} + +pub(crate) async fn mutate_update_profile(ctx: &Context<'_>, input: UpdateUserInput) -> Result { + let user = require_authenticated_user(ctx).await?; + if input.name.is_none() { + return Ok(UserType { view: user }); + } + let state = ctx.data_unchecked::>(); + let updated = state + .users + .update_profile( + &user.id, + UpdateProfileInput { + name: input.name, + avatar_url: None, + }, + ) + .await + .map_err(|e| domain_error_to_graphql(&e))?; + publish_user_updated_realtime(state, &updated.id).await; + Ok(UserType { view: updated }) } fn image_format_not_supported_error() -> async_graphql::Error { @@ -843,7 +888,7 @@ pub(crate) async fn mutate_admin_update_user( .admin_update_user(&id, input.email.as_deref(), input.name.as_deref()) .await .map_err(|e| domain_error_to_graphql(&e))?; - publish_user_profile_updated_events(state, &view.id).await; + publish_user_updated_realtime(state, &view.id).await; Ok(UserType { view }) } diff --git a/packages/backend/server-http/src/lib.rs b/packages/backend/server-http/src/lib.rs index d3d0892ccf..8f1c56c5a4 100644 --- a/packages/backend/server-http/src/lib.rs +++ b/packages/backend/server-http/src/lib.rs @@ -440,6 +440,15 @@ async fn handle_graphql_post( lazy .cookie_action() .apply_to(resp.headers_mut(), state.app.config.load().https); + let (allowed, retry_after) = lazy.throttle_headers(); + if let Some(th) = allowed { + th.apply_to(resp.headers_mut()); + } + if let Some(retry_after_secs) = retry_after + && let Ok(v) = HeaderValue::from_str(&retry_after_secs.to_string()) + { + resp.headers_mut().insert(header::RETRY_AFTER, v); + } resp } diff --git a/packages/backend/server-http/src/rest/mod.rs b/packages/backend/server-http/src/rest/mod.rs index d31520f4f5..72d71760d5 100644 --- a/packages/backend/server-http/src/rest/mod.rs +++ b/packages/backend/server-http/src/rest/mod.rs @@ -566,10 +566,27 @@ pub fn validate_and_build_magic_link_callback_url( Ok(parsed.into()) } +/// Validates ONLY the outer `callbackUrl` origin against allowed origins +/// (matching `v0.27.5` `url.safeLink`, without rewriting inner query parameters). +pub fn validate_safe_link_callback_url( + callback_url: &str, + external_url: &str, + server_hosts: &[String], +) -> Result { + let allowed_origins = build_allowed_origins(external_url, server_hosts); + let parsed = parse_http_url_with_base(callback_url, external_url)?; + if !has_allowed_origin(&parsed, &allowed_origins) { + return Err(DomainError::Forbidden("callbackUrl origin is not allowed".to_owned())); + } + Ok(parsed.into()) +} + /// Resolves [`AuthRequestSource`] using the effective `auth.trustedCloudflareHeaders` flag. -pub(crate) async fn resolve_auth_request_source(state: &RouterState, headers: &HeaderMap) -> AuthRequestSource { - let trusted_cf = state - .app +pub(crate) async fn resolve_auth_request_source_for_app( + app: &crate::AppState, + headers: &HeaderMap, +) -> AuthRequestSource { + let trusted_cf = app .app_config .get_effective_app_config() .await @@ -579,6 +596,11 @@ pub(crate) async fn resolve_auth_request_source(state: &RouterState, headers: &H extract_request_source(headers, trusted_cf) } +/// Resolves [`AuthRequestSource`] using the effective `auth.trustedCloudflareHeaders` flag. +pub(crate) async fn resolve_auth_request_source(state: &RouterState, headers: &HeaderMap) -> AuthRequestSource { + resolve_auth_request_source_for_app(&state.app, headers).await +} + /// Validates that `raw` stays on the same origin and within the base path of /// `external_url` (matching `v0.27.5` `url.safeRedirect`); otherwise falls back /// to the full `baseUrl` (`origin + base_path`). diff --git a/packages/backend/server-http/tests/auth_challenges_keyring_integration.rs b/packages/backend/server-http/tests/auth_challenges_keyring_integration.rs new file mode 100644 index 0000000000..f3b2d9ca4d --- /dev/null +++ b/packages/backend/server-http/tests/auth_challenges_keyring_integration.rs @@ -0,0 +1,1310 @@ +//! Real PostgreSQL integration tests for security challenges, `UserType.token`, +//! session revocation, signing key rotation CAS, and `Query.error`. + +use std::sync::Arc; + +use axum::Router; +use axum::body::Body; +use axum::http::{Request, StatusCode, header}; +use chrono::Utc; +use serde_json::{Value, json}; +use server_db::{DbConfig, ServerDb}; +use server_domain::auth::CreateAdminUserInput; +use server_domain::auth::keyring::{SIGNING_KEYS_CONFIG_ID, StoredSigningKey}; +use server_http::{AppState, RuntimeConfig, build_router}; +use server_spi::CommunityExtension; +use server_types::ServerRole; +use tower::ServiceExt as _; + +fn lease_test_db() -> test_db_harness::pg::DbLease { + let cluster = test_db_harness::pg::PgCluster::from_env_or_docker().expect("test postgres cluster"); + let migrations = test_db_harness::migrations::MigrationSet { + migrations: vec![], + digest: "5e20000000000012".into(), + }; + let template = cluster.ensure_template(&migrations).expect("ensure empty template"); + cluster + .lease(&template, test_db_harness::pg::DEFAULT_LEASE_TTL) + .expect("lease test database") +} + +async fn connect_and_init_db(db_url: &str, max_connections: u32) -> ServerDb { + let db = ServerDb::connect(DbConfig { + database_url: db_url.to_owned(), + channel: "canary".into(), + role: ServerRole::Allinone, + selfhosted: true, + max_connections, + statement_timeout_ms: 10_000, + tier_permits: [4, 2, 2, 1], + }) + .await + .expect("connect test db"); + sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;") + .execute(db.pool()) + .await + .expect("reset schema"); + db.ensure_schema_ready().await.expect("ensure schema ready"); + db +} + +fn run_async>(fut: F) { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("build tokio runtime") + .block_on(fut); +} + +async fn send_json( + router: &Router, + method: &str, + uri: &str, + headers: &[(&str, &str)], + body: Option, +) -> (StatusCode, Value) { + let mut req_builder = Request::builder().method(method).uri(uri); + for &(k, v) in headers { + req_builder = req_builder.header(k, v); + } + let body = match body { + Some(v) => { + req_builder = req_builder.header(header::CONTENT_TYPE, "application/json"); + Body::from(serde_json::to_vec(&v).unwrap()) + } + None => Body::empty(), + }; + let resp = router.clone().oneshot(req_builder.body(body).unwrap()).await.unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024).await.unwrap(); + let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + (status, json) +} + +async fn gql(router: &Router, cookie: Option<&str>, query: &str, variables: Value) -> (StatusCode, Value) { + let mut headers: Vec<(&str, String)> = Vec::new(); + if let Some(c) = cookie { + headers.push(("cookie", c.to_owned())); + } + let header_refs: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (*k, v.as_str())).collect(); + send_json( + router, + "POST", + "/graphql", + &header_refs, + Some(json!({ "query": query, "variables": variables })), + ) + .await +} + +#[test] +fn security_challenges_user_token_and_signing_key_rotation_e2e() { + let lease = lease_test_db(); + let db_url = lease.url().to_owned(); + run_async(async move { + let db = connect_and_init_db(&db_url, 4).await; + let state = AppState::new( + db.clone(), + None, + RuntimeConfig { + external_url: "http://localhost:3010".into(), + ..RuntimeConfig::default() + }, + Arc::new(CommunityExtension::new()), + ); + let router = build_router(Arc::clone(&state)); + + let admin_signin = state + .auth + .create_first_admin_user(CreateAdminUserInput { + name: Some("Admin".into()), + email: "admin@example.test".into(), + password: "Password123!".into(), + client_version: None, + }) + .await + .unwrap(); + let admin_cookie = format!("affine_session={}", admin_signin.session_id); + + let user_b_id = uuid::Uuid::new_v4().to_string(); + sqlx::query( + "INSERT INTO users (id, name, email, registered, disabled, auth_epoch, created_at) VALUES ($1, 'UserB', 'userb@example.test', true, false, 0, clock_timestamp())", + ) + .bind(&user_b_id) + .execute(db.pool()) + .await + .unwrap(); + let user_b_session = state.auth.issue_cookie_session_for_user(&user_b_id).await.unwrap(); + let user_b_cookie = format!("affine_session={}", user_b_session.session_id); + + let shared_ws = uuid::Uuid::new_v4().to_string(); + sqlx::query("INSERT INTO workspaces (id, name) VALUES ($1, 'Shared')") + .bind(&shared_ws) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query( + r#"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source) + VALUES + ($1, $3, $4, 'owner', 'active', 'legacy'), + ($2, $3, $5, 'member', 'active', 'legacy')"#, + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(&shared_ws) + .bind(&admin_signin.user.id) + .bind(&user_b_id) + .execute(db.pool()) + .await + .unwrap(); + + // 1. UserType.token: self allowed, other user forbidden + let (st, resp) = gql( + &router, + Some(&admin_cookie), + "{ currentUser { id token { token sessionToken refresh } } }", + json!({}), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!(resp["errors"].is_null(), "errors: {resp}"); + assert_eq!(resp["data"]["currentUser"]["token"]["refresh"], ""); + assert!( + !resp["data"]["currentUser"]["token"]["token"] + .as_str() + .unwrap() + .is_empty() + ); + + let (_, resp) = gql( + &router, + Some(&admin_cookie), + "query($email: String!) { user(email: $email) { ... on UserType { id token { token } } } }", + json!({ "email": "userb@example.test" }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "ACTION_FORBIDDEN"); + + // 2. Security challenge atomicity: sendVerifyEmail writes runtime_states + mail_deliveries together + let (_, resp) = gql( + &router, + Some(&admin_cookie), + "mutation { sendVerifyEmail(callbackUrl: \"/verify\") }", + json!({}), + ) + .await; + assert_eq!(resp["data"]["sendVerifyEmail"], true, "resp: {resp}"); + let mail_payload: Value = sqlx::query_scalar( + "SELECT payload FROM mail_deliveries WHERE mail_name = 'VerifyEmail' AND recipient_user_id = $1", + ) + .bind(&admin_signin.user.id) + .fetch_one(db.pool()) + .await + .unwrap(); + let verify_url = url::Url::parse(mail_payload["props"]["url"].as_str().unwrap()).unwrap(); + let verify_token = verify_url + .query_pairs() + .find(|(k, _)| k == "token") + .unwrap() + .1 + .into_owned(); + + let (_, resp) = gql( + &router, + Some(&admin_cookie), + "mutation($t: String!) { verifyEmail(token: $t) }", + json!({ "t": verify_token }), + ) + .await; + assert_eq!(resp["data"]["verifyEmail"], true); + + let (_, resp) = gql( + &router, + Some(&admin_cookie), + "mutation($t: String!) { verifyEmail(token: $t) }", + json!({ "t": verify_token }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + + // 3. Signing key rotation CAS + retiring verification window + delete invalidation + let (_, keys_resp) = gql( + &router, + Some(&admin_cookie), + "{ authSigningKeys { id status source canDelete } }", + json!({}), + ) + .await; + let key1_id = keys_resp["data"]["authSigningKeys"][0]["id"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(keys_resp["data"]["authSigningKeys"][0]["status"], "active"); + + let exch_code = state + .auth + .issue_exchange_code(&admin_signin.user.id, None) + .await + .unwrap(); + let exchanged = state + .auth + .exchange_auth_session(&exch_code, "inst-1", "macos", Some("TestMac"), None) + .await + .unwrap(); + let bearer_key1 = exchanged.access_token.clone(); + + let (rot1, rot2) = tokio::join!( + gql( + &router, + Some(&admin_cookie), + "mutation($k: String!) { rotateAuthSigningKey(expectedActiveKeyId: $k) { id status canDelete } }", + json!({ "k": key1_id }), + ), + gql( + &router, + Some(&admin_cookie), + "mutation($k: String!) { rotateAuthSigningKey(expectedActiveKeyId: $k) { id status canDelete } }", + json!({ "k": key1_id }), + ), + ); + let rot_ok = usize::from(rot1.1["errors"].is_null()) + usize::from(rot2.1["errors"].is_null()); + assert_eq!(rot_ok, 1, "expected 1 CAS winner: r1={:?}, r2={:?}", rot1.1, rot2.1); + let cas_err = if rot1.1["errors"].is_null() { &rot2.1 } else { &rot1.1 }; + assert_eq!(cas_err["errors"][0]["extensions"]["name"], "INVALID_APP_CONFIG_INPUT"); + + let (st, body) = send_json( + &router, + "GET", + "/api/auth/session", + &[("authorization", &format!("Bearer {bearer_key1}"))], + None, + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(body["user"]["id"], admin_signin.user.id); + + let (_, del_early) = gql( + &router, + Some(&admin_cookie), + "mutation($id: String!) { deleteAuthSigningKey(id: $id) { id } }", + json!({ "id": key1_id }), + ) + .await; + assert_eq!(del_early["errors"][0]["extensions"]["name"], "ACTION_FORBIDDEN"); + + let raw_keys: Value = sqlx::query_scalar("SELECT value FROM app_configs WHERE id = $1") + .bind(SIGNING_KEYS_CONFIG_ID) + .fetch_one(db.pool()) + .await + .unwrap(); + let mut stored: Vec = serde_json::from_value(raw_keys).unwrap(); + let past = Utc::now() - chrono::Duration::seconds(2_000); + for k in &mut stored { + if k.id == key1_id { + k.retired_at = Some(past - chrono::Duration::seconds(1_000)); + k.verify_until = Some(past); + } + } + sqlx::query("UPDATE app_configs SET value = $2 WHERE id = $1") + .bind(SIGNING_KEYS_CONFIG_ID) + .bind(serde_json::to_value(&stored).unwrap()) + .execute(db.pool()) + .await + .unwrap(); + + let (_, del_ok) = gql( + &router, + Some(&admin_cookie), + "mutation($id: String!) { deleteAuthSigningKey(id: $id) { id status } }", + json!({ "id": key1_id }), + ) + .await; + assert!(del_ok["errors"].is_null(), "delete failed: {del_ok}"); + + let (st, body) = send_json( + &router, + "GET", + "/api/auth/session", + &[("authorization", &format!("Bearer {bearer_key1}"))], + None, + ) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + assert_eq!(body["name"], "ACCESS_TOKEN_INVALID"); + + // 4. Query.error: anonymous -> AUTHENTICATION_REQUIRED; any signed-in non-admin -> ACTION_FORBIDDEN + let (_, anon_probe) = gql( + &router, + None, + "{ error(name: ACTION_FORBIDDEN) { __typename } }", + json!({}), + ) + .await; + assert_eq!(anon_probe["errors"][0]["extensions"]["name"], "AUTHENTICATION_REQUIRED"); + + let (_, user_b_probe) = gql( + &router, + Some(&user_b_cookie), + "{ error(name: ACTION_FORBIDDEN) { __typename } }", + json!({}), + ) + .await; + assert_eq!(user_b_probe["errors"][0]["extensions"]["name"], "ACTION_FORBIDDEN"); + + // 5. Revoking auth session invalidates active Bearer token immediately + let exch_code2 = state + .auth + .issue_exchange_code(&admin_signin.user.id, None) + .await + .unwrap(); + let exchanged2 = state + .auth + .exchange_auth_session(&exch_code2, "inst-2", "macos", Some("TestMac2"), None) + .await + .unwrap(); + state + .auth + .revoke_auth_session(&exchanged2.session.id, Some(&admin_signin.user.id), "user_action") + .await + .unwrap(); + let (st, body) = send_json( + &router, + "GET", + "/api/auth/session", + &[("authorization", &format!("Bearer {}", exchanged2.access_token))], + None, + ) + .await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + assert_eq!(body["name"], "AUTH_SESSION_REVOKED"); + + db.pool().close().await; + }); +} + +#[derive(Default)] +struct RecordingEventBus { + events: std::sync::Mutex>, +} + +#[async_trait::async_trait] +impl server_domain::events::EventBusPublisher for RecordingEventBus { + async fn publish_event( + &self, + event: &str, + payload: Value, + request_id: Option<&str>, + ) -> Result { + if let Ok(mut guard) = self.events.lock() { + guard.push((event.to_owned(), payload.clone())); + } + Ok(server_domain::events::EventBusEnvelopeV1 { + v: 1, + id: format!("eb_{}", uuid::Uuid::new_v4()), + event: event.to_owned(), + origin_id: "test".to_owned(), + origin_channel: "canary".to_owned(), + request_id: request_id.map(str::to_owned), + payload, + }) + } +} + +#[derive(Default)] +struct RecordingRateLimit { + sources: std::sync::Mutex)>>, +} + +#[async_trait::async_trait] +impl server_spi::RateLimitPolicy for RecordingRateLimit { + async fn check_auth_mail( + &self, + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + mail_name: &str, + _recipient_email: &str, + _recipient_user_id: Option<&str>, + source: Option<&server_spi::RequestSource>, + _now: chrono::DateTime, + ) -> Result<(), server_types::DomainError> { + if let Ok(mut guard) = self.sources.lock() { + guard.push((mail_name.to_owned(), source.cloned())); + } + Ok(()) + } + + async fn check_workspace_invite( + &self, + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + _workspace_id: &str, + _inviter_id: &str, + _target_emails: &[&str], + _source: Option<&server_spi::RequestSource>, + _now: chrono::DateTime, + ) -> Result<(), server_spi::RateLimitRejection> { + Ok(()) + } +} + +struct RecordingExtension { + base: CommunityExtension, + rate_limit: Arc, +} + +impl server_spi::ServerExtension for RecordingExtension { + fn edition_name(&self) -> &'static str { + self.base.edition_name() + } + fn quota_gate(&self) -> Arc { + self.base.quota_gate() + } + fn session_policy(&self) -> Arc { + self.base.session_policy() + } + fn rate_limit_policy(&self) -> Arc { + self.rate_limit.clone() + } + fn billing_spi(&self) -> Arc { + self.base.billing_spi() + } + fn copilot_policy(&self) -> Arc { + self.base.copilot_policy() + } + fn copilot_runtime(&self) -> Arc { + self.base.copilot_runtime() + } +} + +async fn send_json_with_headers( + router: &Router, + method: &str, + uri: &str, + extra_headers: &[(&str, &str)], + body: Option, +) -> (StatusCode, Value, axum::http::HeaderMap) { + let mut req_builder = Request::builder().method(method).uri(uri); + for &(k, v) in extra_headers { + req_builder = req_builder.header(k, v); + } + let body = match body { + Some(v) => { + req_builder = req_builder.header(header::CONTENT_TYPE, "application/json"); + Body::from(serde_json::to_vec(&v).unwrap()) + } + None => Body::empty(), + }; + let resp = router.clone().oneshot(req_builder.body(body).unwrap()).await.unwrap(); + let status = resp.status(); + let hdrs = resp.headers().clone(); + let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024).await.unwrap(); + let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + (status, json, hdrs) +} + +async fn gql_with_headers( + router: &Router, + extra_headers: &[(&str, &str)], + query: &str, + variables: Value, +) -> (StatusCode, Value) { + send_json( + router, + "POST", + "/graphql", + extra_headers, + Some(json!({ "query": query, "variables": variables })), + ) + .await +} + +#[test] +fn security_challenges_email_change_password_reset_keyring_and_throttle_adversarial() { + let lease = lease_test_db(); + let db_url = lease.url().to_owned(); + run_async(async move { + let db = connect_and_init_db(&db_url, 4).await; + let event_bus = Arc::new(RecordingEventBus::default()); + let rate_limit = Arc::new(RecordingRateLimit::default()); + let extension: Arc = Arc::new(RecordingExtension { + base: CommunityExtension::new(), + rate_limit: Arc::clone(&rate_limit), + }); + + let cfg = RuntimeConfig { + external_url: "http://localhost:3010".into(), + ..RuntimeConfig::default() + }; + let base_state = AppState::new(db.clone(), None, cfg.clone(), Arc::clone(&extension)); + let state = AppState::with_services( + db.clone(), + None, + cfg, + Arc::clone(&extension), + server_http::AppServices { + auth: base_state.auth.clone(), + users: base_state.users.clone(), + workspaces: base_state.workspaces.clone(), + doc_sharing: base_state.doc_sharing.clone(), + histories: base_state.histories.clone(), + comments: base_state.comments.clone(), + notifications: base_state.notifications.clone(), + licenses: base_state.licenses.clone(), + app_config: base_state.app_config.clone(), + blobs: server_blob::BlobService::new(db.clone(), Arc::clone(&base_state.avatars), extension.quota_gate()), + search: Arc::clone(&base_state.search), + avatars: Arc::clone(&base_state.avatars), + comment_attachments: Arc::clone(&base_state.comment_attachments), + invalidation: Arc::clone(&base_state.invalidation), + event_bus: event_bus.clone(), + }, + ); + let router = build_router(Arc::clone(&state)); + + // Disable strict throttle during setup, then explicitly test it at the end. + sqlx::query( + r#"INSERT INTO app_configs (id, value, created_at, updated_at) VALUES + ('throttle.enabled', 'false'::jsonb, clock_timestamp(), clock_timestamp()), + ('auth.trustedCloudflareHeaders', 'true'::jsonb, clock_timestamp(), clock_timestamp())"#, + ) + .execute(db.pool()) + .await + .unwrap(); + state.app_config.invalidate_cache(); + + let admin_signin = state + .auth + .create_first_admin_user(CreateAdminUserInput { + name: Some("Admin".into()), + email: "admin-adv@example.test".into(), + password: "Password123!".into(), + client_version: None, + }) + .await + .unwrap(); + let admin_cookie = format!("affine_session={}", admin_signin.session_id); + + let alice_id = uuid::Uuid::new_v4().to_string(); + let bob_id = uuid::Uuid::new_v4().to_string(); + sqlx::query( + r#"INSERT INTO users (id, name, email, email_verified, registered, disabled, auth_epoch, created_at) VALUES + ($1, 'Alice', 'alice@example.test', clock_timestamp(), true, false, 0, clock_timestamp()), + ($2, 'Bob', 'bob@example.test', clock_timestamp(), true, false, 0, clock_timestamp())"#, + ) + .bind(&alice_id) + .bind(&bob_id) + .execute(db.pool()) + .await + .unwrap(); + let alice_session = state.auth.issue_cookie_session_for_user(&alice_id).await.unwrap(); + let alice_cookie = format!("affine_session={}", alice_session.session_id); + let bob_session = state.auth.issue_cookie_session_for_user(&bob_id).await.unwrap(); + let bob_cookie = format!("affine_session={}", bob_session.session_id); + + // 1. Non-admin 403 on admin-only mutations + for query in [ + format!("mutation {{ createChangePasswordUrl(callbackUrl: \"/reset\", userId: \"{alice_id}\") }}"), + "mutation { rotateAuthSigningKey(expectedActiveKeyId: \"x\") { id } }".to_owned(), + "mutation { deleteAuthSigningKey(id: \"x\") { id } }".to_owned(), + ] { + let (_, resp) = gql(&router, Some(&bob_cookie), &query, json!({})).await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "ACTION_FORBIDDEN"); + } + + // 2. All 5 mail mutations reject non-allowlisted callbackUrl with zero DB rows + let before_mails: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM mail_deliveries") + .fetch_one(db.pool()) + .await + .unwrap(); + for query in [ + "mutation { sendVerifyEmail(callbackUrl: \"https://evil.example/cb\") }", + "mutation { sendChangePasswordEmail(callbackUrl: \"https://evil.example/cb\") }", + "mutation { sendSetPasswordEmail(callbackUrl: \"https://evil.example/cb\") }", + "mutation { sendChangeEmail(callbackUrl: \"https://evil.example/cb\") }", + "mutation { sendVerifyChangeEmail(callbackUrl: \"https://evil.example/cb\", email: \"new@example.test\", token: \"tok\") }", + ] { + let (_, resp) = gql(&router, Some(&alice_cookie), query, json!({})).await; + assert!(!resp["errors"].is_null(), "expected reject for {query}"); + } + let after_mails: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM mail_deliveries") + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(before_mails, after_mails); + + // 3. Password reset full flow: trustedCloudflareHeaders + inner redirect_uri untouched + cross-user / epoch / replay / disabled / session revocation / realtime event + let (_, resp) = gql_with_headers( + &router, + &[ + ("cookie", &alice_cookie), + ("cf-connecting-ip", "203.0.113.7"), + ("x-affine-cf-asn", "64512"), + ], + "mutation { sendChangePasswordEmail(callbackUrl: \"/reset?redirect_uri=%2Fsettings\") }", + json!({}), + ) + .await; + assert_eq!(resp["data"]["sendChangePasswordEmail"], true, "resp: {resp}"); + { + let sources = rate_limit.sources.lock().unwrap(); + let (_, src) = sources.last().unwrap(); + assert_eq!(src.as_ref().and_then(|s| s.ip.as_deref()), Some("203.0.113.7")); + assert_eq!(src.as_ref().and_then(|s| s.asn), Some(64512)); + } + let pw_mail: Value = sqlx::query_scalar( + "SELECT payload FROM mail_deliveries WHERE mail_name = 'ChangePassword' AND recipient_user_id = $1 ORDER BY created_at DESC LIMIT 1", + ) + .bind(&alice_id) + .fetch_one(db.pool()) + .await + .unwrap(); + let pw_url_str = pw_mail["props"]["url"].as_str().unwrap(); + let pw_url = url::Url::parse(pw_url_str).unwrap(); + assert_eq!( + pw_url + .query_pairs() + .find(|(k, _)| k == "redirect_uri") + .map(|(_, v)| v.into_owned()) + .as_deref(), + Some("/settings"), + "inner redirect_uri must not be rewritten" + ); + let pw_token1 = pw_url.query_pairs().find(|(k, _)| k == "token").unwrap().1.into_owned(); + + // Issue a second password reset URL via admin to test auth_epoch invalidation + let (_, url2_resp) = gql( + &router, + Some(&admin_cookie), + "mutation($uid: String!) { createChangePasswordUrl(callbackUrl: \"/reset\", userId: $uid) }", + json!({ "uid": alice_id }), + ) + .await; + let pw_token2 = url::Url::parse(url2_resp["data"]["createChangePasswordUrl"].as_str().unwrap()) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "token") + .unwrap() + .1 + .into_owned(); + + // Issue a real Bearer token for Alice to verify revocation + let alice_exch = state.auth.issue_exchange_code(&alice_id, None).await.unwrap(); + let alice_bearer = state + .auth + .exchange_auth_session(&alice_exch, "inst-alice", "macos", None, None) + .await + .unwrap() + .access_token; + + // Cross-user token MUST fail + let (_, resp) = gql( + &router, + None, + "mutation($t: String!, $uid: String!) { changePassword(newPassword: \"NewPass1!\", token: $t, userId: $uid) }", + json!({ "t": pw_token1, "uid": bob_id }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + + // Disabled user MUST fail + sqlx::query("UPDATE users SET disabled = true WHERE id = $1") + .bind(&alice_id) + .execute(db.pool()) + .await + .unwrap(); + let (_, resp) = gql( + &router, + None, + "mutation($t: String!, $uid: String!) { changePassword(newPassword: \"NewPass1!\", token: $t, userId: $uid) }", + json!({ "t": pw_token1, "uid": alice_id }), + ) + .await; + assert!(!resp["errors"].is_null()); + sqlx::query("UPDATE users SET disabled = false WHERE id = $1") + .bind(&alice_id) + .execute(db.pool()) + .await + .unwrap(); + + // Seed a workspace + root doc with logical->physical alias + doc_grants for Alice to verify alias fan-out + let alias_ws_id = uuid::Uuid::new_v4().to_string(); + sqlx::query("INSERT INTO workspaces (id, created_at) VALUES ($1, clock_timestamp())") + .bind(&alias_ws_id) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query("DELETE FROM storage_reconciliation_checkpoints WHERE kind = 'workspace_doc_lifecycle_activation'") + .execute(db.pool()) + .await + .unwrap(); + let root_doc = y_octo::Doc::default(); + let mut meta = root_doc.get_or_create_map("meta").unwrap(); + let mut pages = root_doc.create_array().unwrap(); + let mut page_entry = root_doc.create_map().unwrap(); + page_entry + .insert("id".to_owned(), y_octo::Any::String("logical-doc-1".to_owned())) + .unwrap(); + pages.push(page_entry).unwrap(); + meta.insert("pages".to_owned(), pages).unwrap(); + let mut spaces = root_doc.get_or_create_map("spaces").unwrap(); + let subdoc = y_octo::Doc::with_options(y_octo::DocOptions { + guid: "physical-doc-1".to_owned(), + ..Default::default() + }); + spaces.insert("logical-doc-1".to_owned(), subdoc).unwrap(); + let root_bin = root_doc.encode_update_v1().unwrap(); + sqlx::query( + "INSERT INTO snapshots (workspace_id, guid, blob, created_at, updated_at) VALUES ($1, $1, $2, clock_timestamp(), clock_timestamp())", + ) + .bind(&alias_ws_id) + .bind(&root_bin) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query( + "INSERT INTO doc_grants (workspace_id, doc_id, principal_type, principal_id, role, granted_by) VALUES ($1, 'physical-doc-1', 'user', $2, 'editor', $2)", + ) + .bind(&alias_ws_id) + .bind(&alice_id) + .execute(db.pool()) + .await + .unwrap(); + + // Valid changePassword succeeds (including 4,096 and 4,097-byte passwords with no artificial cap), revokes old Cookie + Bearer, emits user.profile.changed + doc.grants.changed for BOTH physical and logical alias rooms + let pw_4096 = "a".repeat(4096); + let (_, resp) = gql( + &router, + None, + "mutation($p: String!, $t: String!, $uid: String!) { changePassword(newPassword: $p, token: $t, userId: $uid) }", + json!({ "p": pw_4096, "t": pw_token1, "uid": alice_id }), + ) + .await; + assert_eq!(resp["data"]["changePassword"], true, "resp: {resp}"); + { + let evs = event_bus.events.lock().unwrap(); + assert!( + evs + .iter() + .any(|(ev, p)| ev == "realtime.topic.changed" && p["topic"] == "user.profile.changed"), + "user.profile.changed must be published" + ); + assert!( + evs.iter().any(|(ev, p)| { + ev == "realtime.topic.changed" + && p["topic"] == "doc.grants.changed" + && p["room"] == format!("workspace:{alias_ws_id}:doc:physical-doc-1:grants") + }), + "physical doc.grants.changed room must be published" + ); + assert!( + evs.iter().any(|(ev, p)| { + ev == "realtime.topic.changed" + && p["topic"] == "doc.grants.changed" + && p["room"] == format!("workspace:{alias_ws_id}:doc:logical-doc-1:grants") + }), + "logical alias doc.grants.changed room must be published" + ); + } + + // 4,097-byte password also succeeds and revokes sessions + let (_, url_4097) = gql( + &router, + Some(&admin_cookie), + "mutation($uid: String!) { createChangePasswordUrl(callbackUrl: \"/reset\", userId: $uid) }", + json!({ "uid": alice_id }), + ) + .await; + let tok_4097 = url::Url::parse(url_4097["data"]["createChangePasswordUrl"].as_str().unwrap()) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "token") + .unwrap() + .1 + .into_owned(); + let alice_sess_before_4097 = state.auth.issue_cookie_session_for_user(&alice_id).await.unwrap(); + let (_, resp_4097) = gql( + &router, + None, + "mutation($p: String!, $t: String!, $uid: String!) { changePassword(newPassword: $p, token: $t, userId: $uid) }", + json!({ "p": "b".repeat(4097), "t": tok_4097, "uid": alice_id }), + ) + .await; + assert_eq!( + resp_4097["data"]["changePassword"], true, + "4097-byte pw failed: {resp_4097}" + ); + let (_, sess_after_4097) = send_json( + &router, + "GET", + "/api/auth/session", + &[( + "cookie", + &format!("affine_session={}", alice_sess_before_4097.session_id), + )], + None, + ) + .await; + assert!(sess_after_4097["user"].is_null()); + + // Replay & auth_epoch-invalidated second token both fail + for tok in [&pw_token1, &pw_token2] { + let (_, resp) = gql( + &router, + None, + "mutation($t: String!, $uid: String!) { changePassword(newPassword: \"Other1!\", token: $t, userId: $uid) }", + json!({ "t": tok, "uid": alice_id }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + } + + // Old Cookie and Bearer are both invalidated on real HTTP requests + let (_, cookie_sess) = send_json(&router, "GET", "/api/auth/session", &[("cookie", &alice_cookie)], None).await; + assert!(cookie_sess["user"].is_null()); + let (st_bearer, _) = send_json( + &router, + "GET", + "/api/auth/session", + &[("authorization", &format!("Bearer {alice_bearer}"))], + None, + ) + .await; + assert_eq!(st_bearer, StatusCode::UNAUTHORIZED); + + // 4. Email change full flow: forged token + taken email -> INVALID_EMAIL_TOKEN; valid token + taken email -> EMAIL_ALREADY_USED; %2B/%40 decode + returns original user view + revokes sessions + let alice_session2 = state.auth.issue_cookie_session_for_user(&alice_id).await.unwrap(); + let alice_cookie2 = format!("affine_session={}", alice_session2.session_id); + + // Forged token + Bob's taken email MUST return INVALID_EMAIL_TOKEN (no enumeration oracle) + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation { sendVerifyChangeEmail(callbackUrl: \"/verify\", email: \"bob@example.test\", token: \"forged\") }", + json!({}), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation { changeEmail(email: \"bob%40example.test\", token: \"forged\") { id email } }", + json!({}), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + + // Start real changeEmail challenge + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation { sendChangeEmail(callbackUrl: \"/change-email\") }", + json!({}), + ) + .await; + assert_eq!(resp["data"]["sendChangeEmail"], true); + let ce_mail: Value = sqlx::query_scalar( + "SELECT payload FROM mail_deliveries WHERE mail_name = 'ChangeEmail' AND recipient_user_id = $1 ORDER BY created_at DESC LIMIT 1", + ) + .bind(&alice_id) + .fetch_one(db.pool()) + .await + .unwrap(); + let ce_token = url::Url::parse(ce_mail["props"]["url"].as_str().unwrap()) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "token") + .unwrap() + .1 + .into_owned(); + + // Valid token + taken email -> EMAIL_ALREADY_USED (tx rolls back, token remains valid!) + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation($t: String!) { sendVerifyChangeEmail(callbackUrl: \"/verify\", email: \"bob@example.test\", token: $t) }", + json!({ "t": ce_token }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "EMAIL_ALREADY_USED"); + + // Valid token + fresh email with '+' -> succeeds + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation($t: String!) { sendVerifyChangeEmail(callbackUrl: \"/verify\", email: \"alice+tag@example.test\", token: $t) }", + json!({ "t": ce_token }), + ) + .await; + assert_eq!(resp["data"]["sendVerifyChangeEmail"], true, "resp: {resp}"); + let vce_mail: Value = sqlx::query_scalar( + "SELECT payload FROM mail_deliveries WHERE mail_name = 'VerifyChangeEmail' AND recipient_user_id = $1 ORDER BY created_at DESC LIMIT 1", + ) + .bind(&alice_id) + .fetch_one(db.pool()) + .await + .unwrap(); + let vce_token = url::Url::parse(vce_mail["props"]["url"].as_str().unwrap()) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "token") + .unwrap() + .1 + .into_owned(); + + // Tampered email rejected + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation($t: String!) { changeEmail(email: \"other%40example.test\", token: $t) { id email } }", + json!({ "t": vce_token }), + ) + .await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "INVALID_EMAIL_TOKEN"); + + // Encoded %2B / %40 email succeeds, returns ORIGINAL request user email, updates DB, revokes old session + let (_, resp) = gql( + &router, + Some(&alice_cookie2), + "mutation($t: String!) { changeEmail(email: \"alice%2Btag%40example.test\", token: $t) { id email } }", + json!({ "t": vce_token }), + ) + .await; + assert_eq!( + resp["data"]["changeEmail"]["email"], "alice@example.test", + "resp: {resp}" + ); + let db_email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1") + .bind(&alice_id) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(db_email, "alice+tag@example.test"); + let (_, old_sess) = send_json(&router, "GET", "/api/auth/session", &[("cookie", &alice_cookie2)], None).await; + assert!(old_sess["user"].is_null()); + + // 5. Keyring: strict now == verifyUntil delete boundary, parent auth.token TTL inheritance, increasing TTL does not lock out historical retiring keys, CAS error prefix + let now_eq = Utc::now(); + assert!(!server_domain::auth::keyring::signing_key_can_delete( + "retiring", + Some(now_eq), + now_eq + )); + assert!(server_domain::auth::keyring::signing_key_can_delete( + "retiring", + Some(now_eq - chrono::Duration::milliseconds(1)), + now_eq + )); + + sqlx::query( + "INSERT INTO app_configs (id, value, created_at, updated_at) VALUES ('auth.token', '{\"accessTokenTtl\": 300}'::jsonb, clock_timestamp(), clock_timestamp())", + ) + .execute(db.pool()) + .await + .unwrap(); + let (_, keys_resp) = gql( + &router, + Some(&admin_cookie), + "{ authSigningKeys { id status } }", + json!({}), + ) + .await; + let active_id = keys_resp["data"]["authSigningKeys"][0]["id"] + .as_str() + .unwrap() + .to_owned(); + let (_, rot_resp) = gql( + &router, + Some(&admin_cookie), + "mutation($k: String!) { rotateAuthSigningKey(expectedActiveKeyId: $k) { id status retiredAt verifyUntil } }", + json!({ "k": active_id }), + ) + .await; + assert!(rot_resp["errors"].is_null(), "rotate failed: {rot_resp}"); + let retired = rot_resp["data"]["rotateAuthSigningKey"] + .as_array() + .unwrap() + .iter() + .find(|k| k["id"] == active_id) + .unwrap(); + let retired_at = chrono::DateTime::parse_from_rfc3339(retired["retiredAt"].as_str().unwrap()).unwrap(); + let verify_until = chrono::DateTime::parse_from_rfc3339(retired["verifyUntil"].as_str().unwrap()).unwrap(); + assert_eq!((verify_until - retired_at).num_seconds(), 330); + + let new_active_id = rot_resp["data"]["rotateAuthSigningKey"] + .as_array() + .unwrap() + .iter() + .find(|k| k["status"] == "active") + .unwrap()["id"] + .as_str() + .unwrap() + .to_owned(); + // Named EventBus event `auth.signing_key.rotated` emitted on success + { + let evs = event_bus.events.lock().unwrap(); + let rotated_evs: Vec<_> = evs.iter().filter(|(ev, _)| ev == "auth.signing_key.rotated").collect(); + assert_eq!(rotated_evs.len(), 1); + assert_eq!(rotated_evs[0].1["actorId"], admin_signin.user.id); + assert_eq!(rotated_evs[0].1["previousKeyId"], active_id); + assert_eq!(rotated_evs[0].1["activeKeyId"], new_active_id); + } + + // CAS mismatch error message must include v0.27.5 prefix AND must NOT emit `auth.signing_key.rotated` + let (_, cas_resp) = gql( + &router, + Some(&admin_cookie), + "mutation($k: String!) { rotateAuthSigningKey(expectedActiveKeyId: $k) { id } }", + json!({ "k": active_id }), + ) + .await; + assert_eq!( + cas_resp["errors"][0]["extensions"]["message"], + "Invalid app config input: The active signing key changed. Reload and try again." + ); + assert_eq!( + event_bus + .events + .lock() + .unwrap() + .iter() + .filter(|(ev, _)| ev == "auth.signing_key.rotated") + .count(), + 1, + "CAS conflict must not emit auth.signing_key.rotated" + ); + + // Failed delete (still within verifyUntil) must NOT emit `auth.signing_key.deleted` + let (_, del_fail_resp) = gql( + &router, + Some(&admin_cookie), + "mutation($id: String!) { deleteAuthSigningKey(id: $id) { id } }", + json!({ "id": active_id }), + ) + .await; + assert!(!del_fail_resp["errors"].is_null()); + assert_eq!( + event_bus + .events + .lock() + .unwrap() + .iter() + .filter(|(ev, _)| ev == "auth.signing_key.deleted") + .count(), + 0, + "failed delete must not emit auth.signing_key.deleted" + ); + + // Backdate retired key verifyUntil to the past and delete -> emits `auth.signing_key.deleted` + let mut cfg_val: Value = sqlx::query_scalar("SELECT value FROM app_configs WHERE id = 'auth.session.signingKeys'") + .fetch_one(db.pool()) + .await + .unwrap(); + for entry in cfg_val.as_array_mut().unwrap() { + if entry["id"] == active_id { + entry["retiredAt"] = json!("2020-01-01T00:00:00Z"); + entry["verifyUntil"] = json!("2020-01-01T00:10:00Z"); + } + } + sqlx::query("UPDATE app_configs SET value = $1 WHERE id = 'auth.session.signingKeys'") + .bind(&cfg_val) + .execute(db.pool()) + .await + .unwrap(); + let (_, del_ok_resp) = gql( + &router, + Some(&admin_cookie), + "mutation($id: String!) { deleteAuthSigningKey(id: $id) { id } }", + json!({ "id": active_id }), + ) + .await; + assert!(del_ok_resp["errors"].is_null(), "delete failed: {del_ok_resp}"); + { + let evs = event_bus.events.lock().unwrap(); + let del_evs: Vec<_> = evs.iter().filter(|(ev, _)| ev == "auth.signing_key.deleted").collect(); + assert_eq!(del_evs.len(), 1); + assert_eq!(del_evs[0].1["actorId"], admin_signin.user.id); + assert_eq!(del_evs[0].1["keyId"], active_id); + } + + // Increasing accessTokenTtl to 3600 MUST NOT lock out listing or rotating historical 330s retiring key + sqlx::query("UPDATE app_configs SET value = '{\"accessTokenTtl\": 3600}'::jsonb WHERE id = 'auth.token'") + .execute(db.pool()) + .await + .unwrap(); + let (_, list_after_ttl_bump) = gql( + &router, + Some(&admin_cookie), + "{ authSigningKeys { id status } }", + json!({}), + ) + .await; + assert!( + list_after_ttl_bump["errors"].is_null(), + "TTL bump locked out keyring: {list_after_ttl_bump}" + ); + + // 6. AuthSigningKeyResolver is NOT strict-throttled; AuthResolver/UserType.token IS strict-throttled with outer HTTP headers; currentUser is exempt + sqlx::query( + r#"INSERT INTO app_configs (id, value, created_at, updated_at) VALUES + ('throttle.throttlers.strict.limit', '2'::jsonb, clock_timestamp(), clock_timestamp()), + ('throttle.throttlers.strict.ttl', '60000'::jsonb, clock_timestamp(), clock_timestamp()) + ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value"#, + ) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query("UPDATE app_configs SET value = 'true'::jsonb WHERE id = 'throttle.enabled'") + .execute(db.pool()) + .await + .unwrap(); + state.app_config.invalidate_cache(); + + // Logged-in admin calling authSigningKeys 4 times succeeds with NO rate-limit headers + for _ in 0..4 { + let (st, ok_resp, hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ authSigningKeys { id } }" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!( + ok_resp["errors"].is_null(), + "authSigningKeys must not be strict-throttled: {ok_resp}" + ); + assert!(hdrs.get("x-ratelimit-limit").is_none()); + assert!(hdrs.get(header::RETRY_AFTER).is_none()); + } + + // Strict-throttled field (UserType.token) emits x-ratelimit-* on allowed responses, accumulates BOTH x-ratelimit-* + // and Retry-After across multi-alias fields crossing the limit, and emits ONLY Retry-After on single-field 429 + let (st, ok_resp, hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ currentUser { token { sessionToken } } }" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!(ok_resp["errors"].is_null(), "token failed: {ok_resp}"); + assert_eq!(hdrs.get("x-ratelimit-limit").unwrap(), "2"); + assert_eq!(hdrs.get("x-ratelimit-remaining").unwrap(), "1"); + assert!(hdrs.get("x-ratelimit-reset").is_some()); + assert!(hdrs.get(header::RETRY_AFTER).is_none()); + + // Multi-alias crossing the boundary: t1 allowed (remaining=0), t2 limited -> outer HTTP carries BOTH + let (st, multi_resp, multi_hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ currentUser { t1: token { sessionToken } t2: token { sessionToken } } }" })), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(multi_resp["errors"][0]["extensions"]["name"], "TOO_MANY_REQUEST"); + assert_eq!(multi_resp["errors"][0]["extensions"]["type"], "TOO_MANY_REQUESTS"); + assert_eq!(multi_hdrs.get("x-ratelimit-limit").unwrap(), "2"); + assert_eq!(multi_hdrs.get("x-ratelimit-remaining").unwrap(), "0"); + assert!(multi_hdrs.get("x-ratelimit-reset").is_some()); + assert!(multi_hdrs.get(header::RETRY_AFTER).is_some()); + + // Single-field 429 carries ONLY Retry-After (no x-ratelimit-*) + let (_, limited_resp, limited_hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ currentUser { token { sessionToken } } }" })), + ) + .await; + assert_eq!(limited_resp["errors"][0]["extensions"]["name"], "TOO_MANY_REQUEST"); + assert_eq!(limited_resp["errors"][0]["extensions"]["type"], "TOO_MANY_REQUESTS"); + assert_eq!(limited_resp["errors"][0]["extensions"]["status"], 429); + assert!(limited_hdrs.get(header::RETRY_AFTER).is_some()); + assert!(limited_hdrs.get("x-ratelimit-limit").is_none()); + assert!(limited_hdrs.get("x-ratelimit-remaining").is_none()); + assert!(limited_hdrs.get("x-ratelimit-reset").is_none()); + + // Query.error is NOT strict-throttled: even with strict quota exhausted, returns 403 ACTION_FORBIDDEN with no rate-limit headers + let (_, err_probe_resp, err_probe_hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ error(name: ACTION_FORBIDDEN) { __typename } }" })), + ) + .await; + assert_eq!(err_probe_resp["errors"][0]["extensions"]["name"], "ACTION_FORBIDDEN"); + assert_eq!(err_probe_resp["errors"][0]["extensions"]["status"], 403); + assert!(err_probe_hdrs.get("x-ratelimit-limit").is_none()); + assert!(err_probe_hdrs.get(header::RETRY_AFTER).is_none()); + + // currentUser remains exempt from strict throttle and has no rate-limit headers + let (_, cu_resp, cu_hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &[("cookie", &admin_cookie)], + Some(json!({ "query": "{ currentUser { id } }" })), + ) + .await; + assert!(cu_resp["errors"].is_null(), "currentUser must be exempt: {cu_resp}"); + assert!(cu_hdrs.get("x-ratelimit-limit").is_none()); + assert!(cu_hdrs.get(header::RETRY_AFTER).is_none()); + + // Anonymous non-@Public() mutations (sendVerifyEmail, createChangePasswordUrl) hit AuthGuard (401) BEFORE strict + // throttle: no rate-limit headers and no bucket consumption, both with remaining quota and after quota exhaustion + let anon_ip = [("x-real-ip", "198.51.100.88")]; + for q in [ + r#"mutation { sendVerifyEmail(callbackUrl: "/ok") }"#, + r#"mutation { createChangePasswordUrl(callbackUrl: "/ok", userId: "u1") }"#, + ] { + let (st, resp, hdrs) = + send_json_with_headers(&router, "POST", "/graphql", &anon_ip, Some(json!({ "query": q }))).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(resp["errors"][0]["extensions"]["name"], "AUTHENTICATION_REQUIRED"); + assert_eq!(resp["errors"][0]["extensions"]["status"], 401); + assert!(hdrs.get("x-ratelimit-limit").is_none()); + assert!(hdrs.get(header::RETRY_AFTER).is_none()); + } + // @Public() changePassword on the same IP still sees full remaining=1 (limit=2), proving anonymous 401s did not consume quota + for expected_rem in ["1", "0"] { + let (_, _, hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &anon_ip, + Some(json!({ "query": r#"mutation { changePassword(newPassword: "x", token: "t") }"# })), + ) + .await; + assert_eq!(hdrs.get("x-ratelimit-limit").unwrap(), "2"); + assert_eq!(hdrs.get("x-ratelimit-remaining").unwrap(), expected_rem); + } + // Exhausted anonymous IP bucket: @Public() changePassword gets 429, while non-@Public() still gets 401 with no throttle headers + let (_, lim_cp, lim_cp_hdrs) = send_json_with_headers( + &router, + "POST", + "/graphql", + &anon_ip, + Some(json!({ "query": r#"mutation { changePassword(newPassword: "x", token: "t") }"# })), + ) + .await; + assert_eq!(lim_cp["errors"][0]["extensions"]["name"], "TOO_MANY_REQUEST"); + assert!(lim_cp_hdrs.get(header::RETRY_AFTER).is_some()); + for q in [ + r#"mutation { sendVerifyEmail(callbackUrl: "/ok") }"#, + r#"mutation { createChangePasswordUrl(callbackUrl: "/ok", userId: "u1") }"#, + ] { + let (_, resp, hdrs) = + send_json_with_headers(&router, "POST", "/graphql", &anon_ip, Some(json!({ "query": q }))).await; + assert_eq!(resp["errors"][0]["extensions"]["name"], "AUTHENTICATION_REQUIRED"); + assert_eq!(resp["errors"][0]["extensions"]["status"], 401); + assert!(hdrs.get("x-ratelimit-limit").is_none()); + assert!(hdrs.get(header::RETRY_AFTER).is_none()); + } + + db.pool().close().await; + }); +}