mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(server): add security challenges, signing key rotation, and UserType.token
Implement single-transaction security challenges (email verification, password change/set, email change with percent-decoding and realtime user-updated fan-out), admin session signing key rotation/deletion with strict verify_until boundary and parent token TTL policy, UserType.token, Query.error, and GraphQL strict throttling.
This commit is contained in:
1 parent
2f41f8977c
commit
c043f6c7ac
10 files changed
+3179
-190
No files matched your search
@@ -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:<workspace_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}`, 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.
|
||||
|
||||
@@ -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<DateTime<Utc>>,
|
||||
pub retired_at: Option<DateTime<Utc>>,
|
||||
pub verify_until: Option<DateTime<Utc>>,
|
||||
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<Utc>, access_token_ttl_seconds: i64) -> DateTime<Utc> {
|
||||
now + Duration::seconds(signing_key_minimum_verify_seconds(access_token_ttl_seconds))
|
||||
}
|
||||
|
||||
pub fn signing_key_can_verify(status: &str, verify_until: Option<DateTime<Utc>>, now: DateTime<Utc>) -> 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<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
|
||||
status == "retiring" && verify_until.is_some_and(|until| until < now)
|
||||
}
|
||||
|
||||
pub fn signing_key_window_valid(
|
||||
status: &str,
|
||||
retired_at: Option<DateTime<Utc>>,
|
||||
verify_until: Option<DateTime<Utc>>,
|
||||
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<Vec<StoredSigningKey>, DomainError> {
|
||||
@@ -75,6 +125,184 @@ pub async fn ensure_signing_keys(db: &ServerDb) -> Result<Vec<StoredSigningKey>,
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// Lists signing key metadata with all secret material stripped.
|
||||
pub async fn list_signing_key_metadata(db: &ServerDb) -> Result<Vec<SigningKeyMetadata>, 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<Utc> = 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<Vec<SigningKeyMetadata>, 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<Utc> = 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<Vec<SigningKeyMetadata>, 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<Utc> = 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<Vec<StoredSigningKey>, 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<StoredSigningKey> =
|
||||
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<StoredSigningKey>, now: DateTime<Utc>) -> Result<Vec<SigningKeyMetadata>, 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(())
|
||||
}
|
||||
|
||||
@@ -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<Vec<keyring::SigningKeyMetadata>, 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<Vec<keyring::SigningKeyMetadata>, 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<Vec<keyring::SigningKeyMetadata>, 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<CookieSignInResult, DomainError> {
|
||||
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<bool> = 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<bool, DomainError> {
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<bool, DomainError> {
|
||||
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::<bool, _>("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<bool, DomainError> {
|
||||
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<String> = 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<bool, DomainError> {
|
||||
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<bool, DomainError> {
|
||||
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<String> =
|
||||
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<bool, DomainError> {
|
||||
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<String, DomainError> {
|
||||
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<Utc>,
|
||||
source: Option<&AuthRequestSource>,
|
||||
now: DateTime<Utc>,
|
||||
) -> 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<LockedUser, DomainError> {
|
||||
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<Utc>,
|
||||
) -> Result<(String, DateTime<Utc>), 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<Utc>,
|
||||
) -> 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<DateTime<Utc>> = row.get("consumed_at");
|
||||
let expires_at: DateTime<Utc> = row.get("expires_at");
|
||||
consumed_at.is_none()
|
||||
&& expires_at > now
|
||||
&& serde_json::from_value::<SecurityState>(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<Utc>,
|
||||
) -> 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<url::Url, DomainError> {
|
||||
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)
|
||||
}
|
||||
@@ -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<DateTime<Utc>>,
|
||||
pub retired_at: Option<DateTime<Utc>>,
|
||||
pub verify_until: Option<DateTime<Utc>>,
|
||||
pub can_delete: bool,
|
||||
}
|
||||
|
||||
impl From<SigningKeyMetadata> 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<String, ()> {
|
||||
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<String> {
|
||||
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<server_domain::auth::AuthRequestSource> {
|
||||
let headers = ctx.data_opt::<HeaderMap>()?;
|
||||
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<Vec<AuthSigningKeyType>> {
|
||||
let _admin = require_admin_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<ErrorDataUnion> {
|
||||
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<bool> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
enforce_strict_throttle_graphql(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<bool> {
|
||||
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::<Arc<AppState>>();
|
||||
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<String>,
|
||||
) -> Result<bool> {
|
||||
let _ = email;
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
enforce_strict_throttle_graphql(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<String>,
|
||||
) -> Result<bool> {
|
||||
let _ = email;
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
enforce_strict_throttle_graphql(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<String>,
|
||||
) -> Result<bool> {
|
||||
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::<Arc<AppState>>();
|
||||
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<String> {
|
||||
let _ = require_authenticated_user(ctx).await?;
|
||||
enforce_strict_throttle_graphql(ctx).await?;
|
||||
let _admin = require_admin_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<bool> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
enforce_strict_throttle_graphql(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<bool> {
|
||||
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::<Arc<AppState>>();
|
||||
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<UserType> {
|
||||
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::<Arc<AppState>>();
|
||||
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<Vec<AuthSigningKeyType>> {
|
||||
let admin = require_admin_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<Vec<AuthSigningKeyType>> {
|
||||
let admin = require_admin_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,7 @@ pub struct RejectedGraphqlAuth(pub crate::legacy_compat::errors::LegacyErrorEnve
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ResolvedGraphqlPrincipal {
|
||||
pub(crate) auth: Option<AuthenticatedUser>,
|
||||
pub(crate) session_id: Option<String>,
|
||||
pub(crate) rejected_cookie_version: Option<VersionGuardError>,
|
||||
}
|
||||
|
||||
@@ -144,6 +145,7 @@ pub(crate) struct LazyGraphqlPrincipal {
|
||||
>,
|
||||
cookie_action: Arc<std::sync::Mutex<crate::rest::PrincipalCookieAction>>,
|
||||
http_error: Arc<std::sync::Mutex<Option<axum::response::Response>>>,
|
||||
throttle_headers: Arc<std::sync::Mutex<(Option<crate::rest::throttle::ThrottleHeaders>, Option<u64>)>>,
|
||||
}
|
||||
|
||||
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<std::net::SocketAddr> {
|
||||
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<crate::rest::throttle::ThrottleHeaders>, Option<u64>) {
|
||||
self.throttle_headers.lock().ok().map(|g| *g).unwrap_or((None, None))
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_once(
|
||||
&self,
|
||||
) -> &std::result::Result<ResolvedGraphqlPrincipal, crate::legacy_compat::errors::LegacyErrorEnvelope> {
|
||||
@@ -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::<Arc<AppState>>() else {
|
||||
return Ok(());
|
||||
};
|
||||
let lazy = ctx.data_opt::<LazyGraphqlPrincipal>();
|
||||
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::<axum::http::HeaderMap>();
|
||||
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}"));
|
||||
|
||||
@@ -126,6 +126,14 @@ pub enum UserImportResultType {
|
||||
User(Box<UserType>),
|
||||
}
|
||||
|
||||
#[derive(SimpleObject, Clone, Debug, Eq, PartialEq)]
|
||||
#[graphql(name = "tokenType")]
|
||||
pub struct ClientTokenType {
|
||||
pub token: String,
|
||||
pub refresh: String,
|
||||
pub session_token: Option<String>,
|
||||
}
|
||||
|
||||
pub struct UserType {
|
||||
pub(crate) view: CurrentUserView,
|
||||
}
|
||||
@@ -261,6 +269,28 @@ impl UserType {
|
||||
) -> Result<super::notification::PaginatedNotificationObjectType> {
|
||||
super::notification::resolve_user_notifications(ctx, pagination).await
|
||||
}
|
||||
|
||||
#[graphql(deprecation = "use auth session exchange instead")]
|
||||
async fn token(&self, ctx: &Context<'_>) -> Result<ClientTokenType> {
|
||||
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::<Arc<AppState>>();
|
||||
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<UserType> {
|
||||
@@ -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<UserType> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
if input.name.is_none() {
|
||||
return Ok(UserType { view: user });
|
||||
}
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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<String, Vec<String>> = 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<UserType> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
if input.name.is_none() {
|
||||
return Ok(UserType { view: user });
|
||||
}
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
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 })
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String, DomainError> {
|
||||
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`).
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user