feat(backend): align HTTP, Auth, GraphQL, and Sync contracts with v0.27.5

Align HTTP routing, Auth, GraphQL, Blob, Calendar, and Realtime Sync behavior with frozen Node v0.27.5 contracts.

- Startup and routing: Run schema readiness before reading crypto.privateKey on fresh databases. Support AFFINE_SERVER_SUB_PATH and server.path mounting. Bind Socket.IO dev loopback allowance to dev_mode. Match /admin/setup strictly in selfhost setup middleware.

- Auth and rate limits: Align REST auth POST status codes with v0.27.5. Enforce redis.ioredis.keyPrefix on sign-in rate limits with millisecond PTTL self-healing and oldest-key memory eviction. Validate security tokens before email uniqueness checks.

- GraphQL and CSRF: Emit the UserFriendlyError extensions envelope on GraphQL 400 responses. Check GET /graphql operationName before rejecting multi-operation documents. Require preflight or a trusted Origin or Referer header on cookie-authenticated multipart uploads.

- Calendar and config: Add zero-clone AppConfigService snapshot access and internal unredacted readers for crypto.privateKey and redis.ioredis.keyPrefix. Derive calendar webhook verification tokens live from the active private key.

- Realtime snapshots and tests: Align quota-state plan names, owner-billed storage aggregation, readonlyReasons, and workspace.members.get INNER JOIN and UTF-16 length checks. Add real PostgreSQL, Redis, and Socket.IO end-to-end tests.
This commit is contained in:
DarkSky committed 2026-11-27 15:54:46 +09:00
1 parent 9bb56146c4
commit 35e18f17dc
52 files changed
+5388 -407

No files matched your search

+214 -14
View File
@@ -641,15 +641,78 @@ impl ServerCli {
}
}
/// Socket.IO handshake authenticator backed by [`AuthService::resolve_cookie_principal`]
/// so revoked `auth_sessions` and disabled users are rejected identically on HTTP and WS.
/// Socket.IO handshake authenticator supporting both native Bearer JWT
/// (`handshake.auth = { tokenType: "jwt", token }`) and cookie sessions
/// (`affine_session`), plus `client.versionControl` enforcement.
struct AuthServiceSyncAuthenticator {
auth: AuthService,
app_config: AppConfigService,
channel: String,
}
#[async_trait::async_trait]
impl SyncSessionAuthenticator for AuthServiceSyncAuthenticator {
async fn authenticate(&self, headers: &http::HeaderMap) -> Result<SyncUser, server_sync::error::SyncError> {
let allow_canary = self.channel == "canary";
let (vc_enabled, vc_required) = self.app_config.get_client_version_control().await.map_err(|e| {
tracing::error!(error = %e, "socketio client.versionControl lookup failed");
server_sync::error::SyncError::Internal("An internal error occurred.".into())
})?;
let vc_cfg = server_http::rest::version_guard::ClientVersionControlConfig {
enabled: vc_enabled,
required_version: vc_required,
};
let bearer_jwt = headers
.get(http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|raw| {
let mut parts = raw.split_whitespace();
let scheme = parts.next()?;
let token = parts.next()?;
if parts.next().is_some() || !scheme.eq_ignore_ascii_case("bearer") {
return None;
}
server_domain::auth::access_token::is_likely_jwt(token).then_some(token)
});
if let Some(token) = bearer_jwt {
let principal = self
.auth
.resolve_bearer_principal(token)
.await
.map_err(|err| match err {
server_domain::auth::BearerResolutionError::Token(code) => {
server_sync::error::SyncError::AuthenticationRequired(format!("invalid bearer token ({})", code.as_code()))
}
server_domain::auth::BearerResolutionError::Domain(e) => {
tracing::error!(error = %e, "socketio bearer authentication failed");
server_sync::error::SyncError::Internal("An internal error occurred.".into())
}
})?;
if vc_cfg.enabled
&& let Err(ver_err) = server_http::rest::version_guard::verify_session_client_version_now(
headers,
principal.refresh_client_version.as_deref(),
principal.sign_in_client_version.as_deref(),
&vc_cfg,
allow_canary,
)
{
let (client_version, required_version) = ver_err.into_parts();
return Err(server_sync::error::SyncError::UnsupportedClientVersion {
client_version,
required_version,
});
}
return Ok(SyncUser {
id: principal.user.id,
email: principal.user.email,
name: principal.user.name,
session_id: principal.session_id,
});
}
let cookies = parse_cookies(headers);
let session_id = cookies
.iter()
@@ -673,6 +736,22 @@ impl SyncSessionAuthenticator for AuthServiceSyncAuthenticator {
})?
.ok_or_else(|| server_sync::error::SyncError::AuthenticationRequired("invalid or expired session".into()))?;
if vc_cfg.enabled
&& let Err(ver_err) = server_http::rest::version_guard::verify_session_client_version_now(
headers,
principal.refresh_client_version.as_deref(),
principal.sign_in_client_version.as_deref(),
&vc_cfg,
allow_canary,
)
{
let (client_version, required_version) = ver_err.into_parts();
return Err(server_sync::error::SyncError::UnsupportedClientVersion {
client_version,
required_version,
});
}
Ok(SyncUser {
id: principal.user.id,
email: principal.user.email,
@@ -725,21 +804,24 @@ async fn build_server_with_bound_port(
let bind_host = cli.effective_host();
let effective_port = bound_port.unwrap_or(cli.port);
let (file_cfg, file_json, file_copilot_storage) = load_home_config_file(cli.config_path.as_deref())?;
// Fail-fast on explicitly blank AFFINE_PRIVATE_KEY for HTTP-serving roles.
let private_key = match cli.private_key.as_deref() {
let private_key_from_env_or_file = match cli.private_key.as_deref() {
Some(raw) if raw.trim().is_empty() => {
if matches!(role, ServerRole::Allinone | ServerRole::Front | ServerRole::Graphql) {
return Err(ServerError::InvalidConfig(
"AFFINE_PRIVATE_KEY must not be empty or whitespace".into(),
));
}
String::new()
Some(String::new())
}
Some(raw) => raw.to_owned(),
None => generate_ephemeral_private_key(),
Some(raw) => Some(raw.to_owned()),
None => file_json
.pointer("/crypto/privateKey")
.and_then(|v| v.as_str())
.filter(|s| !s.trim().is_empty())
.map(str::to_owned),
};
let (file_cfg, file_json, file_copilot_storage) = load_home_config_file(cli.config_path.as_deref())?;
let server_name = file_cfg
.server
.as_ref()
@@ -798,6 +880,37 @@ async fn build_server_with_bound_port(
)));
}
};
let normalize_sub_path = |raw: &str| -> Option<String> {
let trimmed = raw.trim().trim_end_matches('/');
if trimmed.is_empty() || trimmed == "/" {
None
} else if trimmed.starts_with('/') {
Some(trimmed.to_owned())
} else {
Some(format!("/{trimmed}"))
}
};
let env_sub_path = std::env::var("AFFINE_SERVER_SUB_PATH")
.ok()
.and_then(|s| normalize_sub_path(&s));
let file_sub_path = file_json
.pointer("/server/path")
.and_then(serde_json::Value::as_str)
.and_then(normalize_sub_path);
let _ = external_path;
let external_path = env_sub_path.or(file_sub_path).unwrap_or_default();
let mut file_json = file_json;
if !external_path.is_empty() {
if !file_json.is_object() {
file_json = serde_json::json!({});
}
if let Some(root) = file_json.as_object_mut() {
let server_obj = root.entry("server".to_owned()).or_insert_with(|| serde_json::json!({}));
if let Some(s) = server_obj.as_object_mut() {
s.insert("path".to_owned(), serde_json::Value::String(external_path.clone()));
}
}
}
let db = ServerDb::connect(DbConfig {
database_url: cli.database_url.clone(),
@@ -809,6 +922,9 @@ async fn build_server_with_bound_port(
tier_permits: [16, 8, 4, 2],
})
.await?;
if !cli.skip_schema_check {
db.ensure_schema_ready().await?;
}
let effective_redis_url = cli.effective_redis_url_with_file(&file_json)?;
let (redis_client, redis_db_index, session_redis_url_str, session_redis_db_index, session_mutex, redis_runtime_cfg) =
@@ -954,7 +1070,12 @@ async fn build_server_with_bound_port(
static_dir: cli.static_dir.clone(),
multipart_part_size: server_blob::MULTIPART_PART_SIZE,
multipart_threshold: server_blob::MULTIPART_THRESHOLD,
telemetry_allowed_origins: Vec::new(),
telemetry_allowed_origins: app_config_baseline
.file_json
.pointer("/telemetry/allowedOrigin")
.and_then(|v| v.as_array())
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
.unwrap_or_default(),
worker_proxy_allow_private_origins: Vec::new(),
};
@@ -975,6 +1096,25 @@ async fn build_server_with_bound_port(
}
};
let db_private_key: Option<String> =
match sqlx::query_scalar::<_, serde_json::Value>("SELECT value FROM app_configs WHERE id = 'crypto.privateKey'")
.fetch_optional(db.pool())
.await
{
Ok(val) => val.and_then(|v| v.as_str().filter(|s| !s.trim().is_empty()).map(str::to_owned)),
Err(sqlx::Error::Database(ref db_err)) if cli.skip_schema_check && db_err.code().as_deref() == Some("42P01") => {
None
}
Err(e) => {
return Err(ServerError::InvalidConfig(format!(
"failed to load crypto.privateKey from app_configs: {e}"
)));
}
};
let private_key = db_private_key
.or(private_key_from_env_or_file)
.unwrap_or_else(generate_ephemeral_private_key);
let mut auth_cfg = AuthConfig {
server_name,
private_key,
@@ -1122,7 +1262,7 @@ async fn build_server_with_bound_port(
config,
Arc::clone(&ext),
AppServices {
auth: auth.clone(),
auth: auth.clone().with_app_config(app_config.clone()),
users,
workspaces,
doc_sharing,
@@ -1151,10 +1291,18 @@ async fn build_server_with_bound_port(
DeploymentMode::Selfhosted => "selfhosted".to_owned(),
DeploymentMode::Cloud => "cloud".to_owned(),
};
sync_cfg.external_url = state.config.load().external_url.clone();
sync_cfg.allowed_origins = allowed_origins;
let authenticator = Arc::new(AuthServiceSyncAuthenticator { auth });
sync_cfg.allow_dev_loopback = state.config.load().dev_mode;
let authenticator = Arc::new(AuthServiceSyncAuthenticator {
auth: state.auth.clone(),
app_config: state.app_config.clone(),
channel: channel.clone(),
});
let server = SyncServer::start_with_dependencies(db, authenticator, ext.quota_gate(), sync_cfg).await;
router = router.merge(server.router());
let sync_router =
mount_router_with_server_path(server.router(), &state.config.load().app_config_baseline.server.path);
router = router.merge(sync_router);
Some(server)
} else {
None
@@ -1172,6 +1320,21 @@ async fn build_server_with_bound_port(
})
}
/// Nests `router` under `server_path` when a non-root subpath prefix (e.g. `"/affine"`) is configured.
fn mount_router_with_server_path(router: Router, server_path: &str) -> Router {
let trimmed = server_path.trim().trim_end_matches('/');
if trimmed.is_empty() || trimmed == "/" {
router
} else {
let prefix = if trimmed.starts_with('/') {
trimmed.to_owned()
} else {
format!("/{trimmed}")
};
Router::new().nest(&prefix, router)
}
}
/// Deterministically drains ready `public.mail_deliveries` rows once using the
/// given [`SmtpMailer`], suitable for worker ticks and zero-sleep E2E tests.
pub async fn drain_mail_deliveries_once(db: &ServerDb, mailer: &SmtpMailer) -> Result<usize, ServerError> {
@@ -1233,7 +1396,6 @@ where
let built = build_server_with_bound_port(&cli, ext, shutdown.clone(), Some(local_addr.port())).await?;
if !cli.skip_schema_check {
built.state.db.ensure_schema_ready().await?;
built
.state
.init_blob_storage_from_app_config()
@@ -1758,9 +1920,14 @@ mod tests {
assert!(dev_mode);
let dev_matrix =
server_http::RouteMountMatrix::for_mode_and_role(DeploymentMode::Cloud, dev_mode, ServerRole::Allinone);
assert!(dev_matrix.worker_proxy);
assert!(!dev_matrix.worker_proxy);
assert!(!dev_matrix.selfhost_setup);
let selfhost_matrix =
server_http::RouteMountMatrix::for_mode_and_role(DeploymentMode::Selfhosted, false, ServerRole::Allinone);
assert!(selfhost_matrix.worker_proxy);
assert!(selfhost_matrix.selfhost_setup);
let (prod_channel, prod_dev_mode) = effective_runtime_flags(Some("dev"), Some("production"));
assert_eq!(prod_channel, "dev");
assert!(!prod_dev_mode);
@@ -1769,4 +1936,37 @@ mod tests {
assert!(!prod_matrix.worker_proxy);
assert!(!prod_matrix.selfhost_setup);
}
#[tokio::test]
async fn sync_router_mounts_under_server_path_prefix() {
use axum::routing::get;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let fake_sync = Router::new().route("/socket.io/", get(|| async { "ok" }));
let nested = mount_router_with_server_path(fake_sync, "/affine");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let _ = axum::serve(listener, nested).await;
});
let get_status = |path: &str| {
let req = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n");
async move {
let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
stream.write_all(req.as_bytes()).await.unwrap();
let mut buf = String::new();
stream.read_to_string(&mut buf).await.unwrap();
buf.lines().next().unwrap_or("").to_owned()
}
};
let prefixed_line = get_status("/affine/socket.io/?EIO=4&transport=polling").await;
assert!(prefixed_line.contains(" 200 "), "got: {prefixed_line}");
let root_line = get_status("/socket.io/?EIO=4&transport=polling").await;
assert!(root_line.contains(" 404 "), "got: {root_line}");
server.abort();
}
}
@@ -146,7 +146,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
br#"{"name":"Admin","email":"ap-admin@affine.test","password":"StrongPassword123"}"#,
)
.await;
assert_eq!(st_su, 201);
assert_eq!(st_su, 200);
let (st_si, si_head, _) = raw_http(
addr1,
"POST",
@@ -245,6 +245,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={boundary}")),
],
mp_body.as_bytes(),
@@ -348,6 +349,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={boundary}")),
],
&mp_p1,
@@ -400,6 +402,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={boundary}")),
],
&mp_p2,
@@ -463,6 +466,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={boundary}")),
],
&mp_p3,
@@ -726,6 +730,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
],
&mp1,
@@ -751,6 +756,7 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
],
&mp1,
@@ -815,7 +821,8 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
],
&mp1,
)
@@ -919,7 +926,8 @@ fn assetpack_v0275_interop_mixed_boot_and_metadata_exact_keys() {
"/graphql",
&[
("Cookie", &cookie),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
("apollo-require-preflight", "true"),
("Content-Type", &format!("multipart/form-data; boundary={b3}")),
],
&mp1,
)
@@ -216,7 +216,7 @@ fn community_copilot_schema_guards_role_isolation_and_quota_usage() {
&setup_body,
)
.await;
assert_eq!(st, 201);
assert_eq!(st, 200);
let cookie = extract_cookie_header(&head);
assert!(!cookie.is_empty());
@@ -566,7 +566,7 @@ fn blob_contract_authz_app_config_rollback_smtp_isolation_and_magic_link_e2e() {
setup_body.to_string().as_bytes(),
)
.await;
assert_eq!(status, 201);
assert_eq!(status, 200);
let owner_cookie = extract_cookie_header(&head);
let ws_req = serde_json::json!({ "query": "mutation { createWorkspace { id } }" });
@@ -588,7 +588,11 @@ fn blob_contract_authz_app_config_rollback_smtp_isolation_and_magic_link_e2e() {
running.addr,
"POST",
"/graphql",
&[("Content-Type", &ct), ("Cookie", &owner_cookie)],
&[
("Content-Type", &ct),
("Cookie", &owner_cookie),
("apollo-require-preflight", "true"),
],
&mp_body,
)
.await;
@@ -730,7 +734,11 @@ fn blob_contract_authz_app_config_rollback_smtp_isolation_and_magic_link_e2e() {
running.addr,
"POST",
"/graphql",
&[("Content-Type", &ct2), ("Cookie", &owner_cookie)],
&[
("Content-Type", &ct2),
("Cookie", &owner_cookie),
("apollo-require-preflight", "true"),
],
&mp_body2,
)
.await;
@@ -967,7 +975,7 @@ fn blob_contract_authz_app_config_rollback_smtp_isolation_and_magic_link_e2e() {
complete_req.to_string().as_bytes(),
)
.await;
assert_eq!(comp_status, 201);
assert_eq!(comp_status, 200);
let comp_json: Value = serde_json::from_slice(&comp_bytes).unwrap();
assert!(comp_json["id"].as_str().is_some_and(|s| !s.is_empty()));
let ml_cookie = extract_cookie_header(&comp_head);
@@ -2652,3 +2660,456 @@ fn dual_instance_metrics_broadcast_invalidates_cache_and_cli_port_priority() {
});
let _ = std::fs::remove_dir_all(&tmp_dir);
}
#[test]
fn empty_schema_boot_runs_migrations_before_private_key_lookup() {
let cluster = PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).expect("lease db");
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
rt.block_on(async {
// Drop the public schema completely to simulate a brand-new empty PostgreSQL database.
let reset_pool = sqlx::PgPool::connect(lease.url()).await.expect("connect reset pool");
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(&reset_pool)
.await
.expect("wipe schema");
reset_pool.close().await;
let cli = ServerCli {
port: 0,
host: IpAddr::V4(Ipv4Addr::LOCALHOST),
role: Some(RoleArg::Allinone),
deployment_mode: DeploymentModeArg::Selfhosted,
database_url: lease.url().to_owned(),
redis_key_prefix: "affine:e2e:empty".to_owned(),
server_version: "0.27.5".to_owned(),
external_url: Some("http://127.0.0.1:3010".to_owned()),
channel: Some("production".to_owned()),
skip_schema_check: false,
db_max_connections: 4,
db_statement_timeout_ms: 5_000,
..ServerCli::default()
};
let shutdown = CancellationToken::new();
let running = serve_with_extension(cli, Arc::new(CommunityExtension::new()), shutdown)
.await
.expect("empty schema boot must run ensure_schema_ready before reading crypto.privateKey");
let (status, info) = http_request(running.addr, "GET", "/info", None).await;
assert_eq!(status, 200);
assert_eq!(info["compatibility"], "0.27.5");
running.shutdown.cancel();
running
.join_handle
.await
.expect("join server task")
.expect("server exited cleanly");
running.state.db.pool().close().await;
});
}
#[test]
fn server_sub_path_and_dev_loopback_socketio_origin_matrix() {
let cluster = PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).expect("lease db");
let tmp_dir = std::env::temp_dir().join(format!("affine-subpath-cfg-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&tmp_dir).expect("mkdir tmp");
let cfg_file = tmp_dir.join("config.json");
std::fs::write(&cfg_file, r#"{"server":{"path":"/affine"}}"#).expect("write config");
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
rt.block_on(async {
// Boot with server.path="/affine" and channel="dev" (NODE_ENV unset -> dev_mode=false).
let cli = ServerCli {
port: 0,
host: IpAddr::V4(Ipv4Addr::LOCALHOST),
role: Some(RoleArg::Allinone),
deployment_mode: DeploymentModeArg::Selfhosted,
database_url: lease.url().to_owned(),
redis_key_prefix: "affine:e2e:subpath".to_owned(),
server_version: "0.27.5".to_owned(),
external_url: Some("https://example.com".to_owned()),
channel: Some("dev".to_owned()),
config_path: Some(cfg_file.clone()),
skip_schema_check: true,
db_max_connections: 4,
db_statement_timeout_ms: 5_000,
..ServerCli::default()
};
let shutdown = CancellationToken::new();
let running = serve_with_extension(cli, Arc::new(CommunityExtension::new()), shutdown)
.await
.expect("boot subpath server");
let (st_sub, info_sub) = http_request(running.addr, "GET", "/affine/info", None).await;
assert_eq!(st_sub, 200);
assert_eq!(info_sub["compatibility"], "0.27.5");
let (st_hz, _) = http_request(running.addr, "GET", "/healthz", None).await;
assert_eq!(st_hz, 200);
// With channel="dev" but NODE_ENV != "development", dev_mode is false so plain http://localhost:8080
// is NOT allowed as a Socket.IO CORS origin when external_url is https://example.com.
let (_, sio_head, _) = raw_http_request(
running.addr,
"GET",
"/affine/socket.io/?EIO=4&transport=polling",
&[("Origin", "http://localhost:8080")],
b"",
)
.await;
assert!(
!sio_head.to_ascii_lowercase().contains("access-control-allow-origin:"),
"channel=dev without NODE_ENV=development must not allow loopback Origin: {sio_head}"
);
running.shutdown.cancel();
running
.join_handle
.await
.expect("join server task")
.expect("server exited cleanly");
running.state.db.pool().close().await;
});
let _ = std::fs::remove_dir_all(&tmp_dir);
}
#[test]
fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let cluster = PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).expect("lease db");
let redis_guard = TestRedis::from_env_or_docker().expect("test redis");
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
rt.block_on(async {
let reset_pool = sqlx::PgPool::connect(lease.url()).await.expect("connect reset pool");
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(&reset_pool)
.await
.expect("reset schema");
reset_pool.close().await;
let cli = ServerCli {
port: 0,
host: IpAddr::V4(Ipv4Addr::LOCALHOST),
role: Some(RoleArg::Allinone),
deployment_mode: DeploymentModeArg::Selfhosted,
database_url: lease.url().to_owned(),
redis_url: Some(redis_guard.url().to_owned()),
redis_key_prefix: "affine:e2e:sio".to_owned(),
server_version: "0.27.5".to_owned(),
external_url: Some("http://127.0.0.1:3010".to_owned()),
channel: Some("production".to_owned()),
skip_schema_check: false,
db_max_connections: 4,
db_statement_timeout_ms: 5_000,
..ServerCli::default()
};
let shutdown = CancellationToken::new();
let running = serve_with_extension(cli, Arc::new(CommunityExtension::new()), shutdown)
.await
.expect("boot socketio e2e server");
let addr = running.addr;
// 1. Create admin user and sign in as native client to obtain a real Bearer JWT.
let (st_su, su_head, _) = raw_http_request(
addr,
"POST",
"/api/setup/create-admin-user",
&[("Content-Type", "application/json")],
br#"{"name":"SIO Owner","email":"sio-owner@example.com","password":"StrongPassword123!"}"#,
)
.await;
assert_eq!(st_su, 200);
let owner_cookie = extract_cookie_header(&su_head);
let (st_ws, _, ws_bytes) = raw_http_request(
addr,
"POST",
"/graphql",
&[("Content-Type", "application/json"), ("Cookie", &owner_cookie)],
br#"{"query":"mutation { createWorkspace { id } }"}"#,
)
.await;
assert_eq!(st_ws, 200);
let ws_json: Value = serde_json::from_slice(&ws_bytes).unwrap();
let ws_id = ws_json["data"]["createWorkspace"]["id"].as_str().unwrap().to_owned();
let (st_si, _, si_bytes) = raw_http_request(
addr,
"POST",
"/api/auth/sign-in",
&[
("Content-Type", "application/json"),
("x-affine-client-kind", "native"),
("x-affine-version", "0.27.5"),
],
br#"{"email":"sio-owner@example.com","password":"StrongPassword123!"}"#,
)
.await;
assert_eq!(st_si, 200);
let si_json: Value = serde_json::from_slice(&si_bytes).unwrap();
let exchange_code = si_json["exchangeCode"].as_str().expect("exchangeCode");
let (st_ex, _, ex_bytes) = raw_http_request(
addr,
"POST",
"/api/auth/session/exchange",
&[
("Content-Type", "application/json"),
("x-affine-client-kind", "native"),
("x-affine-version", "0.27.5"),
],
serde_json::json!({
"code": exchange_code,
"installationId": "550e8400-e29b-41d4-a716-446655440099",
"platform": "electron",
"deviceName": "SIO Test Client"
})
.to_string()
.as_bytes(),
)
.await;
assert_eq!(st_ex, 201);
let ex_json: Value = serde_json::from_slice(&ex_bytes).unwrap();
let access_token = ex_json["accessToken"].as_str().expect("accessToken").to_owned();
// Helper for Engine.IO v4 HTTP polling calls.
let sio_open = |headers: &'static [(&'static str, &'static str)]| async move {
let (st, _, bytes) = raw_http_request(addr, "GET", "/socket.io/?EIO=4&transport=polling", headers, b"").await;
let text = String::from_utf8_lossy(&bytes).into_owned();
(st, text)
};
// 2. Enable client.versionControl and verify outdated x-affine-version on Socket.IO handshake is rejected.
sqlx::query(
r#"INSERT INTO app_configs (id, value, last_updated_by, created_at, updated_at)
VALUES ('client.versionControl', '{"enabled":true,"requiredVersion":">=0.27.0"}'::jsonb, NULL, now(), now())
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = now()"#,
)
.execute(running.state.db.pool())
.await
.expect("enable client.versionControl");
running.state.app_config.invalidate_cache();
let (st_old, old_body) = sio_open(&[("x-affine-version", "0.0.1")]).await;
if st_old == 200 {
let open_json: Value = serde_json::from_str(&old_body[1..]).expect("open json");
let old_sid = open_json["sid"].as_str().unwrap();
let connect_pkt = format!("40{}", serde_json::json!({"tokenType":"jwt","token":access_token}));
let _ = raw_http_request(
addr,
"POST",
&format!("/socket.io/?EIO=4&transport=polling&sid={old_sid}"),
&[
("x-affine-version", "0.0.1"),
("Content-Type", "text/plain;charset=UTF-8"),
],
connect_pkt.as_bytes(),
)
.await;
let (_, _, poll_bytes) = raw_http_request(
addr,
"GET",
&format!("/socket.io/?EIO=4&transport=polling&sid={old_sid}"),
&[("x-affine-version", "0.0.1")],
b"",
)
.await;
let poll_txt = String::from_utf8_lossy(&poll_bytes);
assert!(
poll_txt.contains("44") || poll_txt.contains("CLIENT_VERSION_OUTDATED") || poll_txt.contains("OUTDATED"),
"expected outdated version rejection, got: {poll_txt}"
);
} else {
assert!(
st_old == 400 || st_old == 403 || st_old == 426,
"unexpected outdated version status {st_old}: {old_body}"
);
}
// 3. Valid Bearer JWT handshake succeeds.
let (st_open, open_body) = sio_open(&[("x-affine-version", "0.27.5")]).await;
assert_eq!(st_open, 200, "sio open failed: {open_body}");
let open_json: Value = serde_json::from_str(&open_body[1..]).expect("parse open json");
let sid = open_json["sid"].as_str().expect("sid").to_owned();
let connect_pkt = format!("40{}", serde_json::json!({"tokenType":"jwt","token":access_token}));
let (st_conn, _, _) = raw_http_request(
addr,
"POST",
&format!("/socket.io/?EIO=4&transport=polling&sid={sid}"),
&[
("x-affine-version", "0.27.5"),
("Content-Type", "text/plain;charset=UTF-8"),
],
connect_pkt.as_bytes(),
)
.await;
assert_eq!(st_conn, 200);
let (st_poll0, _, poll0_bytes) = raw_http_request(
addr,
"GET",
&format!("/socket.io/?EIO=4&transport=polling&sid={sid}"),
&[("x-affine-version", "0.27.5")],
b"",
)
.await;
assert_eq!(st_poll0, 200);
let poll0_txt = String::from_utf8_lossy(&poll0_bytes);
assert!(
poll0_txt.starts_with("40"),
"expected Socket.IO CONNECT ack (40...), got: {poll0_txt}"
);
let emit_ack = |pkt_id: u32, event: &'static str, payload: Value| {
let sid = sid.clone();
async move {
let pkt = format!("42{pkt_id}{}", serde_json::json!([event, payload]));
let (st_p, _, _) = raw_http_request(
addr,
"POST",
&format!("/socket.io/?EIO=4&transport=polling&sid={sid}"),
&[
("x-affine-version", "0.27.5"),
("Content-Type", "text/plain;charset=UTF-8"),
],
pkt.as_bytes(),
)
.await;
assert_eq!(st_p, 200);
let (st_g, _, bytes) = raw_http_request(
addr,
"GET",
&format!("/socket.io/?EIO=4&transport=polling&sid={sid}"),
&[("x-affine-version", "0.27.5")],
b"",
)
.await;
assert_eq!(st_g, 200);
let txt = String::from_utf8_lossy(&bytes).into_owned();
let prefix = format!("43{pkt_id}");
let ack_part = txt
.split('\x1e')
.find(|seg| seg.starts_with(&prefix))
.unwrap_or_else(|| panic!("missing ack {prefix} in `{txt}`"));
let arr: Value = serde_json::from_str(&ack_part[prefix.len()..]).expect("parse ack json");
arr[0].clone()
}
};
// 4. realtime:request contract coverage.
let prof = emit_ack(1, "realtime:request", serde_json::json!({ "op": "user.profile.get" })).await;
assert_eq!(prof["data"]["user"]["email"], "sio-owner@example.com", "got {prof}");
let uq = emit_ack(
2,
"realtime:request",
serde_json::json!({ "op": "user.quota-state.get" }),
)
.await;
let uq_state = &uq["data"]["state"];
assert!(
uq_state["plan"]
.as_str()
.is_some_and(|p| p.chars().all(|c| c.is_ascii_lowercase() || c == '_')),
"expected lowercase plan, got {uq}"
);
assert!(
uq_state.as_object().unwrap().contains_key("copilotActionLimit"),
"copilotActionLimit must be present: {uq}"
);
let wq = emit_ack(
3,
"realtime:request",
serde_json::json!({ "op": "workspace.quota-state.get", "input": { "workspaceId": ws_id } }),
)
.await;
assert!(wq["data"]["state"]["usesOwnerQuota"].is_boolean(), "got {wq}");
assert!(wq["data"]["state"]["readonlyReasons"].is_array(), "got {wq}");
let wm = emit_ack(
4,
"realtime:request",
serde_json::json!({ "op": "workspace.members.get", "input": { "workspaceId": ws_id, "skip": 0, "take": 20 } }),
)
.await;
assert_eq!(wm["data"]["memberCount"], 1, "got {wm}");
assert_eq!(wm["data"]["members"].as_array().unwrap().len(), 1);
let inv = emit_ack(
5,
"realtime:request",
serde_json::json!({ "op": "workspace.invite-link.get", "input": { "workspaceId": ws_id } }),
)
.await;
assert!(inv.get("error").is_none(), "invite-link.get failed: {inv}");
let tr = emit_ack(
6,
"realtime:request",
serde_json::json!({ "op": "copilot.transcript.task.get", "input": { "workspaceId": ws_id, "taskId": "t1" } }),
)
.await;
assert_eq!(tr["error"]["name"], "COPILOT_DISABLED", "got {tr}");
let emb = emit_ack(
7,
"realtime:request",
serde_json::json!({ "op": "workspace.embedding.progress.get", "input": { "workspaceId": ws_id } }),
)
.await;
assert_eq!(emb["error"]["name"], "COPILOT_DISABLED", "got {emb}");
// 5. realtime:subscribe for 4 topics (authorized succeeds, unauthorized workspace rejected).
for (idx, (topic, input)) in [
("user.profile.changed", serde_json::json!({})),
("user.quota-state.changed", serde_json::json!({})),
(
"workspace.quota-state.changed",
serde_json::json!({ "workspaceId": ws_id }),
),
("workspace.members.changed", serde_json::json!({ "workspaceId": ws_id })),
]
.into_iter()
.enumerate()
{
let ack = emit_ack(
10 + idx as u32,
"realtime:subscribe",
serde_json::json!({ "topic": topic, "input": input }),
)
.await;
assert!(ack.get("error").is_none(), "subscribe {topic} failed: {ack}");
}
let unauth_sub = emit_ack(
20,
"realtime:subscribe",
serde_json::json!({ "topic": "workspace.members.changed", "input": { "workspaceId": "ws_nonexistent_unauth" } }),
)
.await;
assert!(
unauth_sub.get("error").is_some(),
"unauthorized workspace.members.changed must be rejected: {unauth_sub}"
);
running.shutdown.cancel();
running
.join_handle
.await
.expect("join server task")
.expect("server exited cleanly");
running.state.db.pool().close().await;
});
}
@@ -196,7 +196,7 @@ fn file_configured_oauth_provider_precedence_and_fallback() {
&json!({ "email": "brand-new-file-cfg@example.test" }),
)
.await;
assert_eq!(st, 200);
assert_eq!(st, 201);
assert_eq!(preflight_file["methods"]["oauth"]["available"], false);
// Real OAuth callback with file-configured allowSignupForOauth=false returns 403 SIGN_UP_FORBIDDEN and creates 0 users
@@ -242,7 +242,7 @@ fn file_configured_oauth_provider_precedence_and_fallback() {
&json!({ "email": "brand-new-file-cfg@example.test" }),
)
.await;
assert_eq!(st, 200);
assert_eq!(st, 201);
assert_eq!(preflight_pg["methods"]["oauth"]["available"], true);
sqlx::query("DELETE FROM app_configs WHERE id = 'auth.allowSignupForOauth'")
.execute(running.state.db.pool())
@@ -254,7 +254,7 @@ fn file_configured_oauth_provider_precedence_and_fallback() {
&json!({ "email": "brand-new-file-cfg@example.test" }),
)
.await;
assert_eq!(st, 200);
assert_eq!(st, 201);
assert_eq!(preflight_back["methods"]["oauth"]["available"], false);
let (st, body) = http_post_json(
running.addr,
@@ -0,0 +1,75 @@
# Intentional Divergences from Node v0.27.5
This document lists intentional improvements in the native Rust backend. Each entry differs from buggy or unsafe Node `v0.27.5` behavior.
## UserType Self-Access Enforcement
- Area: `packages/backend/server-http/src/graphql/user.rs` (`UserType.settings`, `UserType.quota`, `UserType.quotaUsage`).
- Node `v0.27.5` behavior: Resolvers ignored `@Parent()` and returned the active session user settings and quota.
- Native behavior: Resolvers read `self.view.id` and require `caller.id == self.view.id`. Other callers get `403` (`ACCESS_DENIED`).
- Test: `http_auth_graphql_and_rest_parity` in `packages/backend/server-http/tests/http_auth_sync_parity.rs`.
## GraphQL Body Limit and CSRF Protection
- Area: `packages/backend/server-http/src/lib.rs` (`handle_graphql_post`, `handle_graphql_get`, `execute_graphql_request`).
- Node `v0.27.5` behavior: Express JSON parser stopped at 100 KiB. `csrfPrevention` allowed weak header checks.
- Native behavior: JSON request bodies allow up to 16 MiB. Parsed `query` strings enforce a 100 KiB limit and a 64-level depth limit.
- `POST /graphql` rejects missing, empty, or non-JSON `Content-Type` headers.
- Cookie multipart requests without a preflight header require a trusted `Origin` or `Referer` header and reject `cross-site` and untrusted `same-site` requests.
- `GET /graphql?query=...` requires a non-`Content-Type` preflight header and allows read-only queries only.
- Test: `http_auth_graphql_and_rest_parity` in `packages/backend/server-http/tests/http_auth_sync_parity.rs`.
## S3 404 Error Classification
- Area: `packages/backend/server-blob/src/s3.rs` (`get`, `get_limited`).
- Node `v0.27.5` behavior: S3 `HEAD` 404 fell back to a full object `GET` probe.
- Native behavior: `HEAD` does not fall back to `GET`. `GET` 404 reads at most 64 KiB and propagates stream errors.
- Only `NoSuchKey` and `NotFound` map to missing objects. `NoSuchBucket` surfaces as a storage request error.
- Test: `s3_404_classification_distinguishes_missing_key_bucket_and_truncated_body` in `packages/backend/server-blob/src/s3.rs`.
## Avatar Last-Modified Format
- Area: `packages/backend/server-http/src/rest/blobs.rs` (`handle_get_avatar`).
- Node `v0.27.5` behavior: Emitted ISO-8601 timestamps in `Last-Modified`.
- Native behavior: Emits RFC 9110 IMF-fixdate timestamps. Evaluates `If-Modified-Since` at second precision for `200` and `304` responses.
- Test: `http_auth_graphql_and_rest_parity` in `packages/backend/server-http/tests/http_auth_sync_parity.rs`.
## Password Change and Security Challenge Guards
- Area: `packages/backend/server-domain/src/auth/security_challenge.rs` (`complete_password_challenge`, `send_verify_change_email`).
- Node `v0.27.5` behavior: `changePassword` skipped password length checks and disabled-user checks.
- Native behavior: Enforces dynamic `auth.passwordRequirements` and the 1024-byte ceiling. Blocks disabled users.
- Test: `http_auth_graphql_and_rest_parity` in `packages/backend/server-http/tests/http_auth_sync_parity.rs`.
## Calendar Webhook Verification Token Derivation
- Area: `packages/backend/server-domain/src/calendar/mod.rs` (`webhook_token_from_config`).
- Node `v0.27.5` behavior: Generated a random UUID per process without `webhookVerificationToken`. Multi-process webhook verification failed.
- Native behavior: Derives a deterministic HMAC-SHA256 token from the configured private key when `webhookVerificationToken` has no value.
- Database updates to `crypto.privateKey` take effect live without restarting the server.
- Test: `calendar_private_key_raw_bytes_and_db_override_interop` in `packages/backend/server-domain/src/calendar/mod.rs`.
## Link Preview, Telemetry, and Storage Robustness
- Area: `packages/backend/server-http/src/rest/worker_proxy.rs`, `packages/backend/server-http/src/rest/telemetry.rs`, `packages/backend/server-worker/src/mutex.rs`.
- Native behavior: Caps link-preview bodies at 16 KiB, uses `HEAD` for `head: true`, and caps telemetry bodies at 2 MiB.
- Also bounds HTML entity decoding, isolates `/favicon.ico` probe failures, and handles expired Redis mutex release cleanly.
- Test: `worker_proxy_doc_renderer_and_telemetry_contracts` in `packages/backend/server-http/tests/storage_static_telemetry_pg.rs`.
## Cloud Unmounts Worker Proxy Routes
- Area: `packages/backend/server-http/src/lib.rs` (`RouteMountMatrix::for_mode_and_role`).
- Node `v0.27.5` behavior: Cloud development mode mounted `/api/worker/*` proxy routes.
- Native behavior: Cloud mode never mounts `/api/worker/*` routes and returns `404` regardless of `dev_mode`. Only Selfhosted HTTP roles mount them.
- Test: `route_mount_matrix_truth_table_covers_all_mode_and_role_combinations` in `packages/backend/server-http/src/lib.rs`.
@@ -384,7 +384,7 @@ fn sign_proxy(
fields: &[Value],
extra: &[(&str, &str)],
) -> Result<Option<(String, DateTime<Utc>)>, DomainError> {
let exp_dt = Utc::now() + chrono::Duration::seconds(600);
let exp_dt = Utc::now() + chrono::Duration::seconds(3600);
let exp = exp_dt.timestamp();
let Some(token) = storage.sign_upload_token(path, fields, exp) else {
return Ok(None);
+64 -2
View File
@@ -27,6 +27,39 @@ use crate::storage::{
};
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
fn is_s3_missing_object_404(body: &str) -> bool {
let trimmed = body.trim();
if trimmed.is_empty() {
return true;
}
if let Some(start) = trimmed.find("<Code>")
&& let Some(end) = trimmed[start + 6..].find("</Code>")
{
let code = trimmed[start + 6..start + 6 + end].trim();
return matches!(code, "NoSuchKey" | "NotFound");
}
true
}
async fn read_bounded_error_body(context: &str, mut response: reqwest::Response) -> Result<String, StorageError> {
let mut buf = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|err| request_error(context, err.without_url()))?
{
let remaining = MAX_ERROR_RESPONSE_BODY_BYTES.saturating_sub(buf.len());
if remaining == 0 {
break;
}
buf.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
if buf.len() >= MAX_ERROR_RESPONSE_BODY_BYTES {
break;
}
}
Ok(String::from_utf8_lossy(&buf).into_owned())
}
const DEFAULT_PRESIGN_EXPIRES: Duration = Duration::from_secs(60);
const MAX_ERROR_RESPONSE_BODY_BYTES: usize = 64 * 1024;
const DIRECT_UPLOAD_PRESIGN_EXPIRES: Duration = Duration::from_secs(600);
@@ -361,7 +394,14 @@ impl BlobStorageBackend for S3BlobStorage {
let context = format!("get {key}");
let response = self.send(&context, Method::GET, url, &[], None).await?;
if response.status() == StatusCode::NOT_FOUND {
return Ok(None);
let body = read_bounded_error_body(&context, response).await?;
if is_s3_missing_object_404(&body) {
return Ok(None);
}
return Err(StorageError::Request {
context,
message: "404 non-missing-object error".to_owned(),
});
}
let response = Self::ensure_success(&context, response).await?;
let metadata = metadata_from_headers(response.headers());
@@ -378,7 +418,14 @@ impl BlobStorageBackend for S3BlobStorage {
let context = format!("get {key}");
let response = self.send(&context, Method::GET, url, &[], None).await?;
if response.status() == StatusCode::NOT_FOUND {
return Ok(None);
let body = read_bounded_error_body(&context, response).await?;
if is_s3_missing_object_404(&body) {
return Ok(None);
}
return Err(StorageError::Request {
context,
message: "404 non-missing-object error".to_owned(),
});
}
let mut response = Self::ensure_success(&context, response).await?;
if response.content_length().is_some_and(|len| len > max_bytes as u64) {
@@ -712,4 +759,19 @@ mod tests {
assert!(!debug.contains(secret), "{debug}");
}
}
#[test]
fn s3_404_classification_distinguishes_missing_key_bucket_and_truncated_body() {
assert!(is_s3_missing_object_404(
"<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message></Error>"
));
assert!(is_s3_missing_object_404("<Error><Code>NotFound</Code></Error>"));
assert!(!is_s3_missing_object_404(
"<Error><Code>NoSuchBucket</Code><Message>The specified bucket does not exist</Message></Error>"
));
assert!(!is_s3_missing_object_404("<Error><Code>AccessDenied</Code></Error>"));
// Truncated body without closing </Code> tag must not be misclassified as NoSuchBucket.
assert!(is_s3_missing_object_404("<Error><Code>NoSuch"));
assert!(is_s3_missing_object_404(""));
}
}
@@ -337,6 +337,7 @@ const OIDC_DISCOVERY_CACHE_TTL: Duration = Duration::from_secs(60);
const OIDC_DISCOVERY_CACHE_MAX_ENTRIES: usize = 64;
type CachedAppConfig = Option<(Instant, Arc<Value>)>;
type CachedPrivateKey = Option<(u64, Instant, Option<String>)>;
type OidcDiscoveryCache = std::collections::HashMap<(String, bool), (Instant, bool)>;
#[derive(Clone)]
@@ -345,6 +346,8 @@ pub struct AppConfigService {
baseline: RuntimeAppConfigBaseline,
event_bus: Arc<dyn EventBusPublisher>,
cache: Arc<RwLock<CachedAppConfig>>,
private_key_cache: Arc<RwLock<CachedPrivateKey>>,
redis_key_prefix_cache: Arc<RwLock<Option<(u64, Instant, String)>>>,
generation: Arc<AtomicU64>,
oidc_discovery_cache: Arc<RwLock<OidcDiscoveryCache>>,
}
@@ -388,6 +391,8 @@ impl AppConfigService {
baseline,
event_bus,
cache: Arc::new(RwLock::new(None)),
private_key_cache: Arc::new(RwLock::new(None)),
redis_key_prefix_cache: Arc::new(RwLock::new(None)),
generation: Arc::new(AtomicU64::new(0)),
oidc_discovery_cache: Arc::new(RwLock::new(std::collections::HashMap::new())),
}
@@ -400,6 +405,12 @@ impl AppConfigService {
if let Ok(mut guard) = self.cache.write() {
*guard = None;
}
if let Ok(mut guard) = self.private_key_cache.write() {
*guard = None;
}
if let Ok(mut guard) = self.redis_key_prefix_cache.write() {
*guard = None;
}
}
fn store_snapshot_if_generation_matches(&self, gen_before: u64, snapshot: &Arc<Value>) -> bool {
@@ -452,6 +463,108 @@ impl AppConfigService {
Ok(snapshot)
}
/// Returns the cached redacted `appConfig` snapshot as an `Arc<Value>`
/// without deep-cloning the JSON tree on read-only hot paths.
pub async fn get_effective_app_config_arc(&self) -> Result<Arc<Value>, DomainError> {
self.get_cached_effective_app_config().await
}
/// Internal backend-only lookup for unredacted `crypto.privateKey`,
/// preserving exact raw bytes (never `.trim()`). Precedence: non-blank DB
/// `app_configs` row -> non-blank `config.json` `/crypto/privateKey` -> `None`.
/// Cached with `self.generation` and `APP_CONFIG_CACHE_TTL`; never exposed over HTTP/GraphQL.
pub async fn get_internal_private_key(&self) -> Result<Option<String>, DomainError> {
let gen_before = self.generation.load(Ordering::Acquire);
if let Ok(guard) = self.private_key_cache.read()
&& let Some((cached_gen, cached_at, ref key)) = *guard
&& cached_gen == gen_before
&& cached_at.elapsed() < APP_CONFIG_CACHE_TTL
{
return Ok(key.clone());
}
let db_val = self.get_raw_config_value("crypto.privateKey").await?;
let resolved = db_val
.as_ref()
.and_then(Value::as_str)
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
.or_else(|| {
self
.baseline
.file_json
.pointer("/crypto/privateKey")
.and_then(Value::as_str)
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
});
if let Ok(mut guard) = self.private_key_cache.write()
&& self.generation.load(Ordering::Acquire) == gen_before
{
*guard = Some((gen_before, Instant::now(), resolved.clone()));
}
Ok(resolved)
}
/// Internal-only reader for the effective `redis.ioredis.keyPrefix` (falling back
/// to `redis.keyPrefix`), bypassing `SECRET_CONFIG_KEYS` redaction on `redis.ioredis`.
/// Cached with `self.generation` and `APP_CONFIG_CACHE_TTL`.
pub async fn get_internal_redis_key_prefix(&self) -> Result<String, DomainError> {
let gen_before = self.generation.load(Ordering::Acquire);
if let Ok(guard) = self.redis_key_prefix_cache.read()
&& let Some((cached_gen, cached_at, ref prefix)) = *guard
&& cached_gen == gen_before
&& cached_at.elapsed() < APP_CONFIG_CACHE_TTL
{
return Ok(prefix.clone());
}
let mut conn = self
.db
.acquire_tiered(WorkloadTier::InteractiveRead)
.await
.map_err(|e| DomainError::Internal(format!("acquire db for redis keyPrefix: {e}")))?;
let rows: Vec<(String, Value)> =
sqlx::query_as("SELECT id, value FROM app_configs WHERE id IN ('redis.ioredis', 'redis.keyPrefix')")
.fetch_all(&mut *conn)
.await
.map_err(|e| DomainError::Internal(format!("query redis keyPrefix: {e}")))?;
let resolved = rows
.iter()
.find(|(k, _)| k == "redis.ioredis")
.and_then(|(_, v)| v.get("keyPrefix").and_then(Value::as_str))
.filter(|s| !s.is_empty())
.or_else(|| {
rows
.iter()
.find(|(k, _)| k == "redis.keyPrefix")
.and_then(|(_, v)| v.as_str())
.filter(|s| !s.is_empty())
})
.or_else(|| {
self
.baseline
.lookup_file_config_value("redis.ioredis")
.and_then(|v| v.get("keyPrefix").and_then(Value::as_str))
.filter(|s| !s.is_empty())
})
.or_else(|| {
self
.baseline
.lookup_file_config_value("redis.keyPrefix")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
})
.unwrap_or("")
.to_owned();
if let Ok(mut guard) = self.redis_key_prefix_cache.write()
&& self.generation.load(Ordering::Acquire) == gen_before
{
*guard = Some((gen_before, Instant::now(), resolved.clone()));
}
Ok(resolved)
}
/// Builds the exact `v0.27.5` `appConfig` JSON object by combining runtime
/// defaults/env baseline with `public.app_configs` overrides and redacting
/// all secret keys.
@@ -98,8 +98,12 @@ struct ParsedAccessTokenClaims {
}
/// Returns `true` when `token` has the 3-segment base64url JWT shape.
/// Rejects raw cookie `session_id` UUIDs passed as `Authorization: Bearer`.
/// Rejects raw cookie `session_id` UUIDs and `aff_mcp_v1.*` MCP tokens passed
/// as `Authorization: Bearer`.
pub fn is_likely_jwt(token: &str) -> bool {
if token.starts_with("aff_mcp_v1.") {
return false;
}
let mut parts = token.split('.');
let (Some(h), Some(p), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return false;
@@ -82,6 +82,21 @@ fn db_err<E: std::fmt::Display>(ctx: &str) -> impl FnOnce(E) -> DomainError + '_
move |e| DomainError::Internal(format!("{ctx}: {e}"))
}
pub async fn load_effective_captcha_config(db: &ServerDb) -> Result<EffectiveCaptchaConfig, DomainError> {
load_effective_captcha_config_with_file(db, None).await
}
pub async fn load_effective_captcha_config_with_file(
db: &ServerDb,
file_json: Option<&serde_json::Value>,
) -> Result<EffectiveCaptchaConfig, DomainError> {
let mut enabled = file_json
.and_then(|v| v.pointer("/captcha/enabled")?.as_bool())
.unwrap_or(false);
let mut config = file_json
.and_then(|v| v.pointer("/captcha/config"))
.and_then(|v| serde_json::from_value::<CaptchaPluginConfig>(v.clone()).ok())
.unwrap_or_default();
let mut conn = db
.acquire_tiered(WorkloadTier::InteractiveRead)
.await
@@ -92,13 +107,12 @@ pub async fn load_effective_captcha_config(db: &ServerDb) -> Result<EffectiveCap
.await
.map_err(db_err("load captcha config"))?;
drop(conn);
let (mut enabled, mut config) = (false, CaptchaPluginConfig::default());
for row in rows {
use sqlx::Row as _;
let id: String = row.get("id");
let value: serde_json::Value = row.get("value");
match id.as_str() {
"captcha.enabled" => enabled = value.as_bool().unwrap_or(false),
"captcha.enabled" => enabled = value.as_bool().unwrap_or(enabled),
"captcha.config" => {
if let Ok(parsed) = serde_json::from_value::<CaptchaPluginConfig>(value) {
config = parsed;
+257 -21
View File
@@ -293,6 +293,7 @@ pub struct AuthService {
session_policy: Arc<dyn SessionPolicyHook>,
rate_limit_policy: Arc<dyn RateLimitPolicy>,
domain_verifier: Arc<dyn EmailDomainVerifier>,
app_config: Option<crate::app_config::AppConfigService>,
config: AuthConfig,
}
@@ -309,10 +310,16 @@ impl AuthService {
session_policy,
rate_limit_policy: Arc::new(CommunityRateLimitPolicy),
domain_verifier: Arc::new(DnsEmailDomainVerifier),
app_config: None,
config,
}
}
pub fn with_app_config(mut self, app_config: crate::app_config::AppConfigService) -> Self {
self.app_config = Some(app_config);
self
}
pub fn with_rate_limit_policy(mut self, rate_limit_policy: Arc<dyn RateLimitPolicy>) -> Self {
self.rate_limit_policy = rate_limit_policy;
self
@@ -347,6 +354,10 @@ impl AuthService {
&self.config
}
pub async fn session_ttr_seconds(&self) -> i64 {
self.load_dynamic_auth_runtime().await.session_ttr_seconds
}
/// Idempotently initializes `auth.session.signingKeys` in `public.app_configs`.
pub async fn ensure_signing_keys(&self) -> Result<Vec<keyring::StoredSigningKey>, DomainError> {
keyring::ensure_signing_keys(&self.db).await
@@ -450,17 +461,143 @@ impl AuthService {
Ok(initialized)
}
pub(crate) async fn load_dynamic_auth_runtime(&self) -> DynamicAuthRuntime {
let mut rt = DynamicAuthRuntime {
allow_signup: self.config.allow_signup,
allow_signup_for_oauth: self.config.allow_signup_for_oauth,
require_email_domain_verification: self.config.require_email_domain_verification,
password_min_length: self.config.password_min_length,
password_max_length: self.config.password_max_length,
session_ttl_seconds: self.config.session_ttl_seconds,
session_ttr_seconds: self.config.session_ttr_seconds,
};
if let Some(ref cfg_svc) = self.app_config
&& let Ok(eff) = cfg_svc.get_effective_app_config_arc().await
{
if let Some(b) = eff.pointer("/auth/allowSignup").and_then(Value::as_bool) {
rt.allow_signup = b;
}
if let Some(b) = eff.pointer("/auth/allowSignupForOauth").and_then(Value::as_bool) {
rt.allow_signup_for_oauth = b;
}
if let Some(b) = eff
.pointer("/auth/requireEmailDomainVerification")
.and_then(Value::as_bool)
{
rt.require_email_domain_verification = b;
}
if let Some(min) = eff.pointer("/auth/passwordRequirements/min").and_then(Value::as_u64) {
rt.password_min_length = min as usize;
}
if let Some(max) = eff.pointer("/auth/passwordRequirements/max").and_then(Value::as_u64) {
rt.password_max_length = max as usize;
}
if let Some(ttl) = eff
.pointer("/auth/session/ttl")
.and_then(Value::as_i64)
.filter(|&v| v > 0)
{
rt.session_ttl_seconds = ttl;
}
if let Some(ttr) = eff
.pointer("/auth/session/ttr")
.and_then(Value::as_i64)
.filter(|&v| v >= 0)
{
rt.session_ttr_seconds = ttr;
}
return rt;
}
let Ok(mut conn) = self.db.acquire_tiered(WorkloadTier::InteractiveRead).await else {
return rt;
};
let rows = sqlx::query("SELECT id, value FROM app_configs WHERE id = ANY($1)")
.bind(
&[
"auth.allowSignup",
"auth.allowSignupForOauth",
"auth.requireEmailDomainVerification",
"auth.passwordRequirements",
"auth.passwordRequirements.min",
"auth.passwordRequirements.max",
"auth.session.ttl",
"auth.session.ttr",
"auth.session",
][..],
)
.fetch_all(&mut *conn)
.await;
if let Ok(rows) = rows {
for row in rows {
let id: String = row.get("id");
let val: Value = row.get("value");
match id.as_str() {
"auth.allowSignup" => {
if let Some(b) = val.as_bool() {
rt.allow_signup = b;
}
}
"auth.allowSignupForOauth" => {
if let Some(b) = val.as_bool() {
rt.allow_signup_for_oauth = b;
}
}
"auth.requireEmailDomainVerification" => {
if let Some(b) = val.as_bool() {
rt.require_email_domain_verification = b;
}
}
"auth.passwordRequirements" => {
if let Some(min) = val.get("min").and_then(Value::as_u64) {
rt.password_min_length = min as usize;
}
if let Some(max) = val.get("max").and_then(Value::as_u64) {
rt.password_max_length = max as usize;
}
}
"auth.passwordRequirements.min" => {
if let Some(min) = val.as_u64() {
rt.password_min_length = min as usize;
}
}
"auth.passwordRequirements.max" => {
if let Some(max) = val.as_u64() {
rt.password_max_length = max as usize;
}
}
"auth.session.ttl" => {
if let Some(ttl) = val.as_i64().filter(|&v| v > 0) {
rt.session_ttl_seconds = ttl;
}
}
"auth.session.ttr" => {
if let Some(ttr) = val.as_i64().filter(|&v| v >= 0) {
rt.session_ttr_seconds = ttr;
}
}
"auth.session" => {
if let Some(ttl) = val.get("ttl").and_then(Value::as_i64).filter(|&v| v > 0) {
rt.session_ttl_seconds = ttl;
}
if let Some(ttr) = val.get("ttr").and_then(Value::as_i64).filter(|&v| v >= 0) {
rt.session_ttr_seconds = ttr;
}
}
_ => {}
}
}
}
rt
}
/// Atomically creates the initial self-hosted administrator account, grants
/// the `administrator` user feature, issues a cookie session via
/// [`SessionRepository`], and invokes [`SessionPolicyHook::on_session_created`]
/// inside the same transaction (rolling back everything if the hook fails).
pub async fn create_first_admin_user(&self, input: CreateAdminUserInput) -> Result<CookieSignInResult, DomainError> {
let email = canonical_email(&input.email)?;
password::validate_password_requirements(
&input.password,
self.config.password_min_length,
self.config.password_max_length,
)?;
let rt = self.load_dynamic_auth_runtime().await;
password::validate_password_requirements(&input.password, rt.password_min_length, rt.password_max_length)?;
let password_hash = password::hash_password(&input.password)?;
let mut tx = self
@@ -558,10 +695,60 @@ impl AuthService {
})
}
/// Authenticates an existing user by email + Argon2id password for a native
/// client, issuing ONLY a one-time `exchangeCode` (`runtime_states`) without
/// writing `user_sessions` or `multiple_users_sessions`.
pub async fn sign_in_with_password_native(
&self,
email: &str,
password: &str,
client_version: Option<&str>,
) -> Result<(CurrentUserView, String), DomainError> {
let email = canonical_email(email)?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
.await
.map_err(|e| DomainError::Internal(format!("begin native password sign in: {e}")))?;
lock_email(tx.tx_mut(), &email).await?;
let rows =
sqlx::query("SELECT id, password, disabled FROM users WHERE lower(email) = lower($1) ORDER BY id FOR UPDATE")
.bind(&email)
.fetch_all(&mut **tx.tx_mut())
.await
.map_err(|e| DomainError::Internal(format!("load native password login user: {e}")))?;
if rows.len() != 1 || rows[0].get::<bool, _>("disabled") {
return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned()));
}
let password_hash: Option<String> = rows[0].get("password");
let Some(password_hash) = password_hash else {
return Err(DomainError::Unauthorized("wrong_sign_in_method".to_owned()));
};
if !password::verify_password(password, &password_hash)? {
return Err(DomainError::Unauthorized("wrong_sign_in_credentials".to_owned()));
}
let user_id: String = rows[0].get("id");
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 native password sign in: {e}")))?;
let exchange_code = self.issue_exchange_code(&user.id, client_version).await?;
Ok((user, exchange_code))
}
/// Authenticates an existing user by email + Argon2id password and issues a
/// cookie session, invoking [`SessionPolicyHook::on_session_created`] inside
/// the same transaction.
pub async fn sign_in_with_password(&self, input: PasswordSignInInput) -> Result<CookieSignInResult, DomainError> {
let rt = self.load_dynamic_auth_runtime().await;
let email = canonical_email(&input.email)?;
let mut tx = self
.db
@@ -599,7 +786,7 @@ impl AuthService {
&user_id,
input.existing_session_id.as_deref(),
input.client_version.as_deref(),
self.config.session_ttl_seconds,
rt.session_ttl_seconds,
now,
)
.await
@@ -640,6 +827,7 @@ impl AuthService {
if session_id.trim().is_empty() {
return Ok(None);
}
let rt = self.load_dynamic_auth_runtime().await;
let tier = if refresh {
WorkloadTier::InteractiveWrite
} else {
@@ -660,8 +848,8 @@ impl AuthService {
requested_user_id,
refresh_client_version,
refresh,
self.config.session_ttl_seconds,
self.config.session_ttr_seconds,
rt.session_ttl_seconds,
rt.session_ttr_seconds,
now,
)
.await
@@ -763,6 +951,7 @@ impl AuthService {
/// Prepares a 6-digit Magic-Link OTP stored in `public.runtime_states` and
/// atomically queues a `public.mail_deliveries` row matching `v0.27.5`.
pub async fn prepare_magic_link(&self, input: PrepareMagicLinkInput) -> Result<PreparedMagicLink, DomainError> {
let rt = self.load_dynamic_auth_runtime().await;
let email = canonical_email(&input.email)?;
let email_lower = email.to_ascii_lowercase();
let mut callback = url::Url::parse(&input.callback_url)
@@ -774,7 +963,7 @@ impl AuthService {
}
// Perform DNS email-domain verification outside the write transaction / row locks.
let domain_precheck_ok = if self.config.require_email_domain_verification {
let domain_precheck_ok = if rt.require_email_domain_verification {
let mut read_conn = self
.db
.acquire_tiered(WorkloadTier::InteractiveRead)
@@ -811,10 +1000,10 @@ impl AuthService {
.map_err(|e| DomainError::Internal(format!("lock magic link user: {e}")))?;
if users.is_empty() {
if !self.config.allow_signup {
if !rt.allow_signup {
return Err(DomainError::Forbidden("sign_up_forbidden".to_owned()));
}
if self.config.require_email_domain_verification && !domain_precheck_ok {
if rt.require_email_domain_verification && !domain_precheck_ok {
self.verify_signup_domain(&email).await?;
}
}
@@ -935,12 +1124,15 @@ impl AuthService {
})
}
/// Completes a Magic-Link OTP challenge from `public.runtime_states`,
/// creating or verifying the user, issuing a cookie session, and invoking
/// [`SessionPolicyHook::on_session_created`] atomically.
pub async fn complete_magic_link(&self, input: CompleteMagicLinkInput) -> Result<CookieSignInResult, DomainError> {
/// Shared Magic-Link OTP/nonce verification and user upsert transaction helper
/// used by both [`Self::complete_magic_link`] and [`Self::complete_magic_link_native`].
async fn verify_and_upsert_magic_link_user(
&self,
input: &CompleteMagicLinkInput,
rt: &DynamicAuthRuntime,
) -> Result<(server_db::TieredTx<'_>, String, DateTime<Utc>, bool), DomainError> {
let email = canonical_email(&input.email)?;
let domain_precheck_ok = if self.config.require_email_domain_verification {
let domain_precheck_ok = if rt.require_email_domain_verification {
let mut read_conn = self
.db
.acquire_tiered(WorkloadTier::InteractiveRead)
@@ -986,7 +1178,7 @@ impl AuthService {
}
};
drop(read_conn);
if !known_user && valid_signup_challenge {
if !known_user && valid_signup_challenge && rt.allow_signup {
self.verify_signup_domain(&email).await?;
true
} else {
@@ -1098,10 +1290,10 @@ impl AuthService {
if challenge_uid.is_some() || challenge_epoch.is_some() {
return Err(DomainError::Unauthorized("invalid_email_token".to_owned()));
}
if !self.config.allow_signup {
if !rt.allow_signup {
return Err(DomainError::Forbidden("sign_up_forbidden".to_owned()));
}
if self.config.require_email_domain_verification && !domain_precheck_ok {
if rt.require_email_domain_verification && !domain_precheck_ok {
self.verify_signup_domain(&email).await?;
}
let uid = Uuid::new_v4().to_string();
@@ -1121,6 +1313,37 @@ impl AuthService {
};
consume_magic_state(tx.tx_mut(), &email, now).await?;
Ok((tx, user_id, now, created_user))
}
/// Completes a Magic-Link OTP challenge for a native client, creating or
/// verifying the user and issuing ONLY an `exchangeCode` (`runtime_states`)
/// without writing `user_sessions` or `multiple_users_sessions`.
pub async fn complete_magic_link_native(
&self,
input: CompleteMagicLinkInput,
) -> Result<(CurrentUserView, String), DomainError> {
let rt = self.load_dynamic_auth_runtime().await;
let (mut tx, user_id, _now, _created_user) = self.verify_and_upsert_magic_link_user(&input, &rt).await?;
let user = load_current_user_in_tx(tx.tx_mut(), &user_id)
.await?
.ok_or_else(|| DomainError::Internal("magic link user missing after upsert".to_owned()))?;
tx.commit()
.await
.map_err(|e| DomainError::Internal(format!("commit complete_magic_link_native: {e}")))?;
let exchange_code = self
.issue_exchange_code(&user.id, input.client_version.as_deref())
.await?;
Ok((user, exchange_code))
}
/// Completes a Magic-Link OTP challenge from `public.runtime_states`,
/// creating or verifying the user, issuing a cookie session, and invoking
/// [`SessionPolicyHook::on_session_created`] atomically.
pub async fn complete_magic_link(&self, input: CompleteMagicLinkInput) -> Result<CookieSignInResult, DomainError> {
let rt = self.load_dynamic_auth_runtime().await;
let (mut tx, user_id, now, created_user) = self.verify_and_upsert_magic_link_user(&input, &rt).await?;
let issued = self
.sessions
@@ -1129,7 +1352,7 @@ impl AuthService {
&user_id,
input.existing_session_id.as_deref(),
input.client_version.as_deref(),
self.config.session_ttl_seconds,
rt.session_ttl_seconds,
now,
)
.await
@@ -2281,7 +2504,8 @@ impl AuthService {
.map_err(|e| DomainError::Internal(format!("acquire list_auth_sessions: {e}")))?;
let rows = sqlx::query(
r#"SELECT a.id, a.installation_id, a.platform, a.device_name, a.app_version,
a.created_at, a.last_seen_at, a.idle_expires_at, a.absolute_expires_at
a.created_at, a.last_seen_at, a.idle_expires_at, a.absolute_expires_at,
a.revoke_reason
FROM auth_sessions a
JOIN user_sessions u ON u.id = a.user_session_id
WHERE u.user_id = $1
@@ -2309,6 +2533,7 @@ impl AuthService {
last_seen_at: row.get("last_seen_at"),
idle_expires_at: row.get("idle_expires_at"),
absolute_expires_at: row.get("absolute_expires_at"),
revoke_reason: row.get("revoke_reason"),
})
.collect(),
)
@@ -2792,6 +3017,16 @@ pub struct AuthTokenPair {
pub is_new_device: Option<bool>,
}
pub(crate) struct DynamicAuthRuntime {
pub(crate) allow_signup: bool,
pub(crate) allow_signup_for_oauth: bool,
pub(crate) require_email_domain_verification: bool,
pub(crate) password_min_length: usize,
pub(crate) password_max_length: usize,
pub(crate) session_ttl_seconds: i64,
pub(crate) session_ttr_seconds: i64,
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthSessionSummary {
@@ -2808,6 +3043,7 @@ pub struct AuthSessionSummary {
pub idle_expires_at: DateTime<Utc>,
#[serde(serialize_with = "serialize_rfc3339_millis")]
pub absolute_expires_at: DateTime<Utc>,
pub revoke_reason: Option<String>,
}
/// Generates a `v0.27.5`-compatible 3-segment refresh token
@@ -153,7 +153,7 @@ impl AuthService {
&input.redirect_allowed_origins,
&input.redirect_trusted_domains,
)
.ok_or_else(|| val_err("invalid_oauth_preflight"))
.ok_or_else(|| DomainError::Forbidden("invalid_oauth_redirect_uri".to_owned()))
})
.transpose()?;
let oidc = if provider == "oidc" {
@@ -18,12 +18,17 @@ fn canonical_argon2() -> Argon2<'static> {
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
}
/// Validates password length bounds (default `8..=32` in `v0.27.5`).
pub const MAX_PASSWORD_BYTES: usize = 1024;
/// Validates password length bounds (default `8..=32` in `v0.27.5`, plus 1024B hard cap).
pub fn validate_password_requirements(password: &str, min_len: usize, max_len: usize) -> Result<(), DomainError> {
if password.is_empty() {
return Err(DomainError::Validation("password_required".to_owned()));
}
let len = password.chars().count();
if len < min_len || len > max_len {
if password.len() > MAX_PASSWORD_BYTES || len < min_len || len > max_len {
return Err(DomainError::Validation(format!(
"password length must be between {min_len} and {max_len} characters"
"invalid_password_length:{min_len}:{max_len}"
)));
}
Ok(())
@@ -161,6 +161,7 @@ impl AuthService {
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,
@@ -235,9 +236,8 @@ impl AuthService {
token: &str,
new_password: &str,
) -> Result<bool, DomainError> {
if new_password.is_empty() {
return Err(DomainError::Validation("password_required".to_owned()));
}
let runtime = self.load_dynamic_auth_runtime().await;
password::validate_password_requirements(new_password, runtime.password_min_length, runtime.password_max_length)?;
let raw_password = new_password.to_owned();
let password_hash = tokio::task::spawn_blocking(move || password::hash_password(&raw_password))
@@ -329,6 +329,8 @@ pub struct CalendarService {
external_url: String,
generated_webhook_token: Arc<Mutex<Option<String>>>,
config_override: Option<EffectiveCalendarConfigs>,
file_json: Option<Value>,
app_config: Option<crate::app_config::AppConfigService>,
}
impl CalendarService {
pub fn new(db: ServerDb, private_key: String, external_url: String) -> Self {
@@ -338,8 +340,20 @@ impl CalendarService {
external_url,
generated_webhook_token: Arc::new(Mutex::new(None)),
config_override: None,
file_json: None,
app_config: None,
}
}
/// Wires `AppConfigService` so DB `crypto.privateKey` overrides take effect dynamically.
pub fn with_app_config(mut self, app_config: crate::app_config::AppConfigService) -> Self {
self.app_config = Some(app_config);
self
}
/// Provides `config.json` baseline values (`calendar.google`, `calendar.caldav`, `crypto.privateKey`).
pub fn with_file_json(mut self, file_json: Option<Value>) -> Self {
self.file_json = file_json;
self
}
/// Shares a process-wide generated webhook verification token across requests.
pub fn with_shared_webhook_token(mut self, token: Arc<Mutex<Option<String>>>) -> Self {
self.generated_webhook_token = token;
@@ -351,8 +365,15 @@ impl CalendarService {
self.config_override = Some(configs);
self
}
pub(crate) fn private_key(&self) -> &str {
&self.private_key
/// Resolves the effective `crypto.privateKey` preserving exact raw bytes (no `.trim()`),
/// reading the internal unredacted cache so DB `app_configs` overrides take effect dynamically.
pub async fn effective_private_key(&self) -> String {
if let Some(ref cfg_svc) = self.app_config
&& let Ok(Some(raw)) = cfg_svc.get_internal_private_key().await
{
return raw;
}
self.private_key.clone()
}
pub(crate) async fn read_conn(&self, ctx: &'static str) -> Result<TieredConn, CalendarError> {
self
@@ -371,11 +392,12 @@ impl CalendarService {
pub(crate) async fn begin_tx(&self, tier: WorkloadTier, ctx: &'static str) -> Result<TieredTx<'_>, CalendarError> {
self.db.begin_tiered(tier).await.map_err(internal_err(ctx))
}
fn encrypt_patch(&self, patch: &TokenPatch) -> Result<Option<String>, CalendarError> {
async fn encrypt_patch_async(&self, patch: &TokenPatch) -> Result<Option<String>, CalendarError> {
match patch {
TokenPatch::Set(v) => Ok(Some(
encrypt_token(&self.private_key, v).map_err(CalendarError::Domain)?,
)),
TokenPatch::Set(v) => {
let key = self.effective_private_key().await;
Ok(Some(encrypt_token(&key, v).map_err(CalendarError::Domain)?))
}
TokenPatch::Keep | TokenPatch::Clear => Ok(None),
}
}
@@ -385,18 +407,35 @@ impl CalendarService {
pub fn callback_url_for(&self, external_url: &str) -> String {
format!("{}/api/calendar/oauth/callback", external_url.trim_end_matches('/'))
}
pub fn webhook_token_from_config(&self, google: &CalendarGoogleConfig) -> String {
pub async fn webhook_token_from_config(&self, google: &CalendarGoogleConfig) -> String {
if let Some(ref configured) = google.webhook_verification_token
&& !configured.is_empty()
{
return configured.clone();
}
let mut guard = self.generated_webhook_token.lock().expect("webhook token mutex");
guard.get_or_insert_with(|| Uuid::new_v4().to_string()).clone()
let key = self.effective_private_key().await;
if !key.is_empty() {
use hmac::{Hmac, Mac as _};
if let Ok(mut mac) = Hmac::<sha2::Sha256>::new_from_slice(key.as_bytes()) {
mac.update(b"affine:calendar:google-webhook-token");
return hex::encode(mac.finalize().into_bytes());
}
}
if let Ok(guard) = self.generated_webhook_token.lock()
&& let Some(ref cached) = *guard
&& !cached.is_empty()
{
return cached.clone();
}
let derived = Uuid::new_v4().to_string();
if let Ok(mut guard) = self.generated_webhook_token.lock() {
*guard = Some(derived.clone());
}
derived
}
/// Verifies an incoming `x-goog-channel-token` header in constant time.
pub fn verify_webhook_token(&self, google: &CalendarGoogleConfig, provided: &str) -> bool {
let expected = self.webhook_token_from_config(google);
pub async fn verify_webhook_token(&self, google: &CalendarGoogleConfig, provided: &str) -> bool {
let expected = self.webhook_token_from_config(google).await;
expected.is_empty()
|| (expected.len() == provided.len() && bool::from(expected.as_bytes().ct_eq(provided.as_bytes())))
}
@@ -416,12 +455,23 @@ impl CalendarService {
if let Some(ref ov) = self.config_override {
return Ok(ov.clone());
}
let mut google = self
.file_json
.as_ref()
.and_then(|v| v.pointer("/calendar/google"))
.and_then(|v| serde_json::from_value::<CalendarGoogleConfig>(v.clone()).ok())
.unwrap_or_default();
let mut caldav = self
.file_json
.as_ref()
.and_then(|v| v.pointer("/calendar/caldav"))
.and_then(|v| serde_json::from_value::<CalendarCaldavConfig>(v.clone()).ok())
.unwrap_or_default();
let mut conn = self.read_conn("acquire calendar config read").await?;
let rows = sqlx::query("SELECT id, value FROM app_configs WHERE id IN ('calendar.google', 'calendar.caldav')")
.fetch_all(&mut *conn)
.await
.map_err(internal_err("load calendar app_configs"))?;
let (mut google, mut caldav) = (CalendarGoogleConfig::default(), CalendarCaldavConfig::default());
for row in rows {
let (id, val): (String, Value) = (row.get("id"), row.get("value"));
if id == "calendar.google" {
@@ -784,7 +834,8 @@ impl CalendarService {
.collect();
if !channels.is_empty()
&& let Some(enc) = account.access_token_encrypted.as_deref()
&& let Ok(access_token) = decrypt_token(&self.private_key, enc)
&& let key = self.effective_private_key().await
&& let Ok(access_token) = decrypt_token(&key, enc)
&& let Ok(configs) = self.load_configs().await
&& configs.google.is_configured()
{
@@ -1068,8 +1119,8 @@ impl CalendarService {
&self,
params: UpsertCalendarAccountParams,
) -> Result<CalendarAccountRecord, CalendarError> {
let enc_access = self.encrypt_patch(&params.access_token)?;
let enc_refresh = self.encrypt_patch(&params.refresh_token)?;
let enc_access = self.encrypt_patch_async(&params.access_token).await?;
let enc_refresh = self.encrypt_patch_async(&params.refresh_token).await?;
let mut conn = self.write_conn("acquire upsert_account").await?;
let row = sqlx::query(
r#"INSERT INTO calendar_accounts (
@@ -1130,8 +1181,8 @@ impl CalendarService {
status: Option<String>,
last_error: Option<Option<String>>,
) -> Result<CalendarAccountRecord, CalendarError> {
let enc_access = self.encrypt_patch(&access_token)?;
let enc_refresh = self.encrypt_patch(&refresh_token)?;
let enc_access = self.encrypt_patch_async(&access_token).await?;
let enc_refresh = self.encrypt_patch_async(&refresh_token).await?;
let mut conn = self.write_conn("acquire update_account_tokens").await?;
let row = sqlx::query(
r#"UPDATE calendar_accounts
@@ -1316,3 +1367,122 @@ fn row_to_subscription(row: sqlx::postgres::PgRow) -> CalendarSubscriptionRecord
channel_expiration: row.get("channel_expiration"),
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Arc;
use server_db::DbConfig;
use server_types::ServerRole;
use test_db_harness::{
migrations::MigrationSet,
pg::{DEFAULT_LEASE_TTL, PgCluster},
};
use super::*;
use crate::app_config::{AppConfigService, RuntimeAppConfigBaseline};
use crate::events::NoopEventPublisher;
#[test]
fn calendar_private_key_raw_bytes_and_db_override_interop() {
let raw_key_with_newline = "calendar-test-key-line-1\ncalendar-test-key-line-2\n";
let trimmed_key = raw_key_with_newline.trim();
assert_ne!(raw_key_with_newline, trimmed_key);
// Exact raw bytes (including trailing newline) round-trip cleanly and never collide with trimmed bytes.
let ct = encrypt_token(raw_key_with_newline, "oauth-refresh-secret").expect("encrypt with raw key");
assert_eq!(
decrypt_token(raw_key_with_newline, &ct).expect("decrypt with identical raw key"),
"oauth-refresh-secret"
);
assert!(
decrypt_token(trimmed_key, &ct).is_err(),
"trimmed key must derive a different SHA-256 key than raw key bytes"
);
let cluster = PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).expect("lease db");
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
rt.block_on(async {
let db = ServerDb::connect(DbConfig {
database_url: lease.url().to_owned(),
channel: "production".into(),
role: ServerRole::Allinone,
selfhosted: true,
max_connections: 4,
statement_timeout_ms: 5_000,
tier_permits: [8, 4, 4, 2],
})
.await
.expect("connect 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");
let baseline = RuntimeAppConfigBaseline {
file_json: serde_json::json!({ "crypto": { "privateKey": raw_key_with_newline } }),
..RuntimeAppConfigBaseline::default()
};
let app_config = AppConfigService::new(db.clone(), baseline, Arc::new(NoopEventPublisher::default()));
let calendar = CalendarService::new(
db.clone(),
raw_key_with_newline.to_owned(),
"http://localhost:3010".to_owned(),
)
.with_app_config(app_config.clone());
let google_cfg = google::CalendarGoogleConfig::default();
// 1. Initial key comes from file baseline with exact raw bytes; webhook token derives from it.
assert_eq!(calendar.effective_private_key().await, raw_key_with_newline);
let k1_webhook = calendar.webhook_token_from_config(&google_cfg).await;
assert!(calendar.verify_webhook_token(&google_cfg, &k1_webhook).await);
// 2. DB override with leading/trailing whitespace takes effect live without leaking via public config.
let db_override_key = " K2-db-override ";
sqlx::query(
r#"INSERT INTO app_configs (id, value, last_updated_by, created_at, updated_at)
VALUES ('crypto.privateKey', to_jsonb($1::text), NULL, now(), now())
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = now()"#,
)
.bind(db_override_key)
.execute(db.pool())
.await
.expect("insert db privateKey");
app_config.invalidate_cache();
let public_cfg = app_config.get_effective_app_config().await.expect("public config");
assert_ne!(
public_cfg.pointer("/crypto/privateKey").and_then(|v| v.as_str()),
Some(db_override_key),
"public get_effective_app_config must keep crypto.privateKey redacted"
);
assert_eq!(calendar.effective_private_key().await, db_override_key);
let ct2 = encrypt_token(db_override_key, "cal-token").expect("encrypt k2");
assert_eq!(decrypt_token(db_override_key, &ct2).expect("decrypt k2"), "cal-token");
assert!(decrypt_token(db_override_key.trim(), &ct2).is_err());
let k2_webhook = calendar.webhook_token_from_config(&google_cfg).await;
assert_ne!(k1_webhook, k2_webhook);
assert!(calendar.verify_webhook_token(&google_cfg, &k2_webhook).await);
assert!(!calendar.verify_webhook_token(&google_cfg, &k1_webhook).await);
// 3. Deleting DB override falls back to K1 file key live.
sqlx::query("DELETE FROM app_configs WHERE id = 'crypto.privateKey'")
.execute(db.pool())
.await
.expect("delete db privateKey");
app_config.invalidate_cache();
assert_eq!(calendar.effective_private_key().await, raw_key_with_newline);
assert_eq!(calendar.webhook_token_from_config(&google_cfg).await, k1_webhook);
assert!(calendar.verify_webhook_token(&google_cfg, &k1_webhook).await);
});
}
}
@@ -336,12 +336,13 @@ pub(crate) async fn ensure_access_token(
google_cfg: &super::google::CalendarGoogleConfig,
claim: Option<(&str, DateTime<Utc>)>,
) -> Result<Option<String>, CalendarError> {
let private_key = service.effective_private_key().await;
let access_token = match account.access_token_encrypted.as_deref() {
Some(enc) => Some(decrypt_token(service.private_key(), enc).map_err(CalendarError::Domain)?),
Some(enc) => Some(decrypt_token(&private_key, enc).map_err(CalendarError::Domain)?),
None => None,
};
let refresh_token = match account.refresh_token_encrypted.as_deref() {
Some(enc) => Some(decrypt_token(service.private_key(), enc).map_err(CalendarError::Domain)?),
Some(enc) => Some(decrypt_token(&private_key, enc).map_err(CalendarError::Domain)?),
None => None,
};
if let Some(ref token) = access_token
@@ -444,9 +445,9 @@ async fn update_tokens_under_claim(
expires_at: Option<DateTime<Utc>>,
scope: Option<&str>,
) -> Result<bool, CalendarError> {
let enc_access = super::crypto::encrypt_token(service.private_key(), access_token).map_err(CalendarError::Domain)?;
let enc_refresh =
super::crypto::encrypt_token(service.private_key(), refresh_token).map_err(CalendarError::Domain)?;
let private_key = service.effective_private_key().await;
let enc_access = super::crypto::encrypt_token(&private_key, access_token).map_err(CalendarError::Domain)?;
let enc_refresh = super::crypto::encrypt_token(&private_key, refresh_token).map_err(CalendarError::Domain)?;
let mut tx = service
.begin_tx(WorkloadTier::InteractiveWrite, "begin update_tokens_under_claim")
.await?;
@@ -629,7 +630,7 @@ async fn ensure_google_webhook_channel(
}
}
let channel_id = Uuid::new_v4().to_string();
let token = service.webhook_token_from_config(google_cfg);
let token = service.webhook_token_from_config(google_cfg).await;
match provider
.watch_calendar(
access_token,
@@ -709,6 +709,7 @@ fn to_domain_ws_filter(f: &ListWorkspaceInput) -> AdminWorkspaceFilter {
}
pub(crate) async fn resolve_server_config(ctx: &Context<'_>) -> Result<ServerConfigType> {
super::enforce_default_throttle_if_anonymous_graphql(ctx).await?;
let state = ctx.data_unchecked::<Arc<AppState>>();
let cfg = state.config.load();
let initialized = state
@@ -229,9 +229,6 @@ impl LazyGraphqlPrincipal {
}
Err(crate::rest::PrincipalResolutionError::AccessToken(code)) => {
let (env, _) = crate::rest::PrincipalResolutionError::AccessToken(code).into_envelope();
if let Ok(mut guard) = self.http_error.lock() {
*guard = Some(crate::rest::PrincipalResolutionError::AccessToken(code).into_http_response());
}
Err(env)
}
Err(crate::rest::PrincipalResolutionError::Domain(err)) => {
@@ -511,8 +508,14 @@ pub struct CoreQuery;
#[Object]
impl CoreQuery {
async fn current_user(&self, ctx: &Context<'_>) -> Option<UserType> {
user::resolve_current_user(ctx)
async fn current_user(&self, ctx: &Context<'_>) -> Result<Option<UserType>> {
if let Some(lazy) = ctx.data_opt::<LazyGraphqlPrincipal>()
&& let Err(env) = lazy.resolve_once().await
{
return Err(envelope_to_graphql(env.clone()));
}
enforce_default_throttle_if_anonymous_graphql(ctx).await?;
Ok(user::resolve_current_user(ctx))
}
async fn user(&self, ctx: &Context<'_>, email: String) -> Result<Option<UserOrLimitedUser>> {
@@ -190,15 +190,21 @@ impl UserType {
async fn quota(&self, ctx: &Context<'_>) -> Result<UserQuotaType> {
let caller = require_authenticated_user(ctx).await?;
if self.view.id != caller.id {
return Err(domain_error_to_graphql(&DomainError::Forbidden("access_denied".into())));
}
let state = ctx.data_unchecked::<Arc<AppState>>();
let (grant, used_storage_quota) = compute_user_quota_and_storage(state, &caller.id).await?;
let (grant, used_storage_quota) = compute_user_quota_and_storage(state, &self.view.id).await?;
Ok(user_quota_from_grant(&grant, used_storage_quota))
}
async fn quota_usage(&self, ctx: &Context<'_>) -> Result<UserQuotaUsageType> {
let caller = require_authenticated_user(ctx).await?;
if self.view.id != caller.id {
return Err(domain_error_to_graphql(&DomainError::Forbidden("access_denied".into())));
}
let state = ctx.data_unchecked::<Arc<AppState>>();
let (_grant, used_storage_quota) = compute_user_quota_and_storage(state, &caller.id).await?;
let (_grant, used_storage_quota) = compute_user_quota_and_storage(state, &self.view.id).await?;
let safe_used = SafeInt::try_from_i64(used_storage_quota)
.map_err(|_| domain_error_to_graphql(&DomainError::Internal("storage quota overflow".into())))?;
Ok(UserQuotaUsageType {
@@ -212,10 +218,13 @@ impl UserType {
async fn settings(&self, ctx: &Context<'_>) -> Result<UserSettingsType> {
let caller = require_authenticated_user(ctx).await?;
if self.view.id != caller.id {
return Err(domain_error_to_graphql(&DomainError::Forbidden("access_denied".into())));
}
let state = ctx.data_unchecked::<Arc<AppState>>();
let s = state
.users
.get_settings(&caller.id)
.get_settings(&self.view.id)
.await
.map_err(|e| domain_error_to_graphql(&e))?;
Ok(UserSettingsType {
@@ -4,7 +4,7 @@
//! transport returns as HTTP 413 without a GraphQL envelope.
use std::collections::HashMap;
use std::io::{Seek, Write};
use std::io::Write;
use async_graphql::{ParseRequestError, Request, UploadValue};
use multer::{Constraints, Multipart, SizeLimit};
@@ -36,26 +36,41 @@ pub(crate) async fn receive_graphql_multipart(
let mut multipart = Multipart::with_constraints(body.into_data_stream(), boundary, constraints);
let mut request = None;
let mut map = None;
let mut map: Option<HashMap<String, Vec<String>>> = None;
let mut files = Vec::new();
while let Some(mut field) = multipart.next_field().await? {
let name = field.name().map(str::to_owned);
if let Some(filename) = field.file_name().map(str::to_owned) {
let is_operations = name.as_deref() == Some("operations");
let is_map = name.as_deref() == Some("map");
let has_filename = field.file_name().is_some();
let is_mapped_part = !is_operations
&& !is_map
&& map
.as_ref()
.is_some_and(|m| name.as_deref().is_some_and(|n| m.contains_key(n)));
if has_filename || is_mapped_part {
if request.is_none() || map.is_none() {
return Err(ParseRequestError::InvalidRequest(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Misordered multipart fields; files should follow 'map'.",
))));
}
if files.len() == MAX_GRAPHQL_MULTIPART_FILES {
return Err(ParseRequestError::PayloadTooLarge);
}
let filename = field.file_name().map(str::to_owned).unwrap_or_default();
let content_type = field.content_type().map(ToString::to_string);
let mut file = tempfile::tempfile()?;
let mut named_file = tempfile::NamedTempFile::new()?;
let mut written = 0usize;
while let Some(chunk) = field.chunk().await? {
written += chunk.len();
if written > MAX_GRAPHQL_MULTIPART_FILE_BYTES {
return Err(ParseRequestError::PayloadTooLarge);
}
file.write_all(&chunk)?;
named_file.as_file_mut().write_all(&chunk)?;
}
file.rewind()?;
files.push((name, filename, content_type, file));
named_file.as_file_mut().flush()?;
files.push((name, filename, content_type, named_file));
continue;
}
let mut bytes = Vec::new();
@@ -76,6 +91,12 @@ pub(crate) async fn receive_graphql_multipart(
Some(serde_json::from_value::<Request>(value).map_err(|e| ParseRequestError::InvalidRequest(Box::new(e)))?);
}
Some("map") => {
if request.is_none() {
return Err(ParseRequestError::InvalidRequest(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Misordered multipart fields; 'map' should follow 'operations'.",
))));
}
let parsed: HashMap<String, Vec<String>> =
serde_json::from_slice(&bytes).map_err(|e| ParseRequestError::InvalidFilesMap(Box::new(e)))?;
let total_paths: usize = parsed.values().map(Vec::len).sum();
@@ -90,17 +111,20 @@ pub(crate) async fn receive_graphql_multipart(
let mut request = request.ok_or(ParseRequestError::MissingOperatorsPart)?;
let mut map = map.ok_or(ParseRequestError::MissingMapPart)?;
for (name, filename, content_type, content) in files {
for (name, filename, content_type, named_file) in files {
let Some(paths) = name.and_then(|name| map.remove(&name)) else {
continue;
};
let upload = UploadValue {
filename,
content_type,
content,
};
for path in paths {
request.set_upload(&path, upload.try_clone()?);
let reopened = named_file.reopen()?;
request.set_upload(
&path,
UploadValue {
filename: filename.clone(),
content_type: content_type.clone(),
content: reopened,
},
);
}
}
if !map.is_empty() {
@@ -352,11 +352,45 @@ pub fn domain_error_to_envelope(err: &DomainError) -> LegacyErrorEnvelope {
}
}
DomainError::Validation(msg) => {
if msg == "password_required" {
return 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,
};
}
if let Some(rest) = msg.strip_prefix("invalid_password_length:") {
let (min, max) = rest
.split_once(':')
.map(|(a, b)| (a.parse::<usize>().unwrap_or(8), b.parse::<usize>().unwrap_or(32)))
.unwrap_or((8, 32));
return LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "INVALID_PASSWORD_LENGTH".into(),
message: format!("Password length must be between {min} and {max} characters."),
data: Some(serde_json::json!({ "min": min, "max": max })),
};
}
if msg == "invalid_email" || msg.eq_ignore_ascii_case("invalid email format") || msg.contains("invalid email") {
return LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "INVALID_EMAIL".into(),
message: "Invalid email format.".into(),
data: None,
};
}
if let Some(detail) = msg.strip_prefix("blob_invalid:") {
return LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "BAD_REQUEST".into(),
error_type: "INVALID_INPUT".into(),
name: "BLOB_INVALID".into(),
message: detail.to_owned(),
data: None,
+471 -47
View File
@@ -299,11 +299,14 @@ impl AppState {
) -> Arc<Self> {
let admin = server_domain::admin::AdminService::new(db.clone());
let calendar_webhook_token = Arc::new(std::sync::Mutex::new(None));
let auth = services.auth.with_app_config(services.app_config.clone());
let calendar = CalendarService::new(
db.clone(),
services.auth.config().private_key.clone(),
auth.config().private_key.clone(),
config.external_url.clone(),
)
.with_app_config(services.app_config.clone())
.with_file_json(Some(config.app_config_baseline.file_json.clone()))
.with_shared_webhook_token(Arc::clone(&calendar_webhook_token));
let calendar_oauth = CalendarOAuthStore::new(redis.clone(), config.session_redis_db_index).ok();
let mcp = McpCredentialService::new(db.clone(), Arc::clone(&services.event_bus))
@@ -320,7 +323,7 @@ impl AppState {
redis,
config: ArcSwap::from_pointee(config),
extension,
auth: services.auth,
auth,
users: services.users,
workspaces: services.workspaces,
admin,
@@ -649,6 +652,10 @@ pub struct ReadyResponse {
#[derive(Debug, Deserialize)]
struct GraphqlGetQuery {
sdl: Option<String>,
query: Option<String>,
#[serde(rename = "operationName")]
operation_name: Option<String>,
variables: Option<String>,
}
fn role_flavor_str(role: ServerRole) -> &'static str {
@@ -801,6 +808,33 @@ pub fn graphql_query_exceeds_depth(query: &str, max_depth: usize) -> bool {
/// Largest JSON `/graphql` request body.
const MAX_GRAPHQL_JSON_BODY_BYTES: usize = 16 * 1024 * 1024;
fn graphql_bad_request_response(status: StatusCode, apollo_code: &str, message: &str) -> Response {
let formatted = format!("GraphQL bad request, code: {apollo_code}, {message}");
let body = serde_json::json!({
"errors": [{
"message": message,
"extensions": {
"status": status.as_u16(),
"code": "Bad Request",
"type": "BAD_REQUEST",
"name": "GRAPHQL_BAD_REQUEST",
"message": formatted,
"data": {
"code": apollo_code,
"message": message,
},
}
}]
})
.to_string();
(
status,
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
body,
)
.into_response()
}
/// Reads a `/graphql` POST body. A multipart body goes through
/// [`graphql_multipart::receive_graphql_multipart`]. Any other body must fit
/// in `MAX_GRAPHQL_JSON_BODY_BYTES`.
@@ -814,15 +848,24 @@ async fn read_graphql_post(
let rejected = |err: async_graphql::ParseRequestError| {
Box::new(async_graphql_axum::rejection::GraphQLRejection(err).into_response())
};
if let Some(ct) = content_type.filter(|ct| {
ct.trim_start()
.get(..19)
.is_some_and(|p| p.eq_ignore_ascii_case("multipart/form-data"))
}) {
return graphql_multipart::receive_graphql_multipart(ct, body)
let media_type = content_type
.and_then(|ct| ct.split(';').next())
.map(str::trim)
.unwrap_or("");
if media_type.eq_ignore_ascii_case("multipart/form-data") {
return graphql_multipart::receive_graphql_multipart(content_type.unwrap_or(""), body)
.await
.map_err(rejected);
}
if !media_type.eq_ignore_ascii_case("application/json")
&& !media_type.eq_ignore_ascii_case("application/graphql-response+json")
{
return Err(Box::new(graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"BAD_REQUEST",
"Unsupported Content-Type for GraphQL request",
)));
}
let bytes = axum::body::to_bytes(body, MAX_GRAPHQL_JSON_BODY_BYTES)
.await
.map_err(|_| Box::new(StatusCode::PAYLOAD_TOO_LARGE.into_response()))?;
@@ -835,40 +878,87 @@ async fn read_graphql_post(
.map_err(rejected)
}
async fn handle_graphql_post(
State(state): State<RouterState>,
rest::throttle::PeerAddr(peer): rest::throttle::PeerAddr,
/// Largest GraphQL query document string (`100 KiB`) to prevent alias-amplification DoS.
const MAX_GRAPHQL_QUERY_BYTES: usize = 100 * 1024;
async fn execute_graphql_request(
state: &RouterState,
peer: Option<std::net::SocketAddr>,
headers: HeaderMap,
body: axum::body::Body,
inner: async_graphql::Request,
) -> Response {
let inner = match read_graphql_post(&headers, body).await {
Ok(inner) => inner,
Err(resp) => return *resp,
};
if graphql_query_exceeds_depth(&inner.query, MAX_GRAPHQL_BRACKET_DEPTH) {
return (
if inner.query.len() > MAX_GRAPHQL_QUERY_BYTES {
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
r#"{"errors":[{"message":"Query exceeds maximum nesting depth"}]}"#,
)
.into_response();
"GRAPHQL_VALIDATION_FAILED",
"Query exceeds maximum allowed size",
);
}
if graphql_query_exceeds_depth(&inner.query, MAX_GRAPHQL_BRACKET_DEPTH) {
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"GRAPHQL_VALIDATION_FAILED",
"Query exceeds maximum nesting depth",
);
}
let introspection_enabled = state
.app
.app_config
.get_effective_app_config_arc()
.await
.ok()
.and_then(|c| c.pointer("/graphql/introspection")?.as_bool())
.unwrap_or(true);
let is_parse_error = async_graphql::parser::parse_query(&inner.query).is_err();
let lazy = LazyGraphqlPrincipal::new(state.clone(), headers.clone(), peer);
let gql_req = inner.data(lazy.clone()).data(headers);
let gql_resp: GraphQLResponse = state.schema.execute(gql_req).await.into();
let mut gql_req = inner.data(lazy.clone()).data(headers);
if !introspection_enabled {
gql_req = gql_req.disable_introspection();
}
let mut raw_resp = state.schema.execute(gql_req).await;
if let Some(http_err) = lazy.take_http_error() {
return http_err;
}
let mut is_bad_request = false;
if !raw_resp.errors.is_empty()
&& matches!(raw_resp.data, async_graphql::Value::Null)
&& raw_resp
.errors
.iter()
.all(|e| e.path.is_empty() && e.extensions.as_ref().is_none_or(|ext| ext.get("name").is_none()))
{
is_bad_request = true;
let apollo_code = if is_parse_error {
"GRAPHQL_PARSE_FAILED"
} else {
"GRAPHQL_VALIDATION_FAILED"
};
for err in &mut raw_resp.errors {
let formatted = format!("GraphQL bad request, code: {apollo_code}, {}", err.message);
let data = async_graphql::Value::from_json(serde_json::json!({
"code": apollo_code,
"message": err.message,
}))
.unwrap_or(async_graphql::Value::Null);
let ext = err.extensions.get_or_insert_with(Default::default);
ext.set("status", async_graphql::Value::from(400));
ext.set("code", async_graphql::Value::from("Bad Request"));
ext.set("type", async_graphql::Value::from("BAD_REQUEST"));
ext.set("name", async_graphql::Value::from("GRAPHQL_BAD_REQUEST"));
ext.set("message", async_graphql::Value::from(formatted));
ext.set("data", data);
}
}
let gql_resp: GraphQLResponse = raw_resp.into();
let mut resp = gql_resp.into_response();
if is_bad_request {
*resp.status_mut() = StatusCode::BAD_REQUEST;
}
let h = resp.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
h.insert(
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_static("true"),
);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
lazy
.cookie_action()
@@ -885,7 +975,186 @@ async fn handle_graphql_post(
resp
}
async fn handle_graphql_get(State(state): State<RouterState>, Query(params): Query<GraphqlGetQuery>) -> Response {
async fn handle_graphql_post(
State(state): State<RouterState>,
rest::throttle::PeerAddr(peer): rest::throttle::PeerAddr,
headers: HeaderMap,
body: axum::body::Body,
) -> Response {
let is_multipart = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| {
ct.split(';')
.next()
.unwrap_or("")
.trim()
.eq_ignore_ascii_case("multipart/form-data")
});
if is_multipart {
let has_session_cookie =
rest::extract_cookie(&rest::parse_cookies(&headers), rest::SESSION_COOKIE_NAME).is_some_and(|s| !s.is_empty());
let has_preflight = [
"x-operation-name",
"x-apollo-operation-name",
"apollo-require-preflight",
]
.iter()
.any(|name| {
headers
.get(*name)
.and_then(|v| v.to_str().ok())
.is_some_and(|s| !s.trim().is_empty())
});
if has_session_cookie && !has_preflight {
let csrf_blocked = || {
graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"BAD_REQUEST",
"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF).",
)
};
let sec_fetch_site = headers
.get("sec-fetch-site")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty());
let origin = headers
.get(header::ORIGIN)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty());
let referer_origin = headers
.get(header::REFERER)
.and_then(|v| v.to_str().ok())
.and_then(|r| url::Url::parse(r.trim()).ok())
.map(|u| u.origin().ascii_serialization());
let allowed =
rest::worker_proxy::allowed_origins_for_state_async(&state, rest::worker_proxy::CorsOriginScope::Global).await;
let dev_mode = state.app.config.load().dev_mode;
let origin_ok = origin.is_some_and(|o| rest::worker_proxy::is_cors_origin_allowed(o, &allowed, dev_mode));
let referer_ok = referer_origin
.as_deref()
.is_some_and(|r| rest::worker_proxy::is_cors_origin_allowed(r, &allowed, dev_mode));
if let Some(sfs) = sec_fetch_site
&& (sfs.eq_ignore_ascii_case("cross-site")
|| (sfs.eq_ignore_ascii_case("same-site") && !(origin_ok || referer_ok)))
{
return csrf_blocked();
}
if origin.is_some() && !origin_ok {
return csrf_blocked();
}
if referer_origin.is_some() && !referer_ok {
return csrf_blocked();
}
if !(origin_ok || referer_ok) {
return csrf_blocked();
}
}
}
let inner = match read_graphql_post(&headers, body).await {
Ok(inner) => inner,
Err(resp) => return *resp,
};
execute_graphql_request(&state, peer, headers, inner).await
}
fn has_apollo_csrf_header(headers: &HeaderMap) -> bool {
[
"x-operation-name",
"x-apollo-operation-name",
"apollo-require-preflight",
"x-affine-version",
"x-requested-with",
]
.iter()
.any(|name| {
headers
.get(*name)
.and_then(|v| v.to_str().ok())
.is_some_and(|s| !s.trim().is_empty())
})
}
async fn handle_graphql_get(
State(state): State<RouterState>,
rest::throttle::PeerAddr(peer): rest::throttle::PeerAddr,
headers: HeaderMap,
Query(params): Query<GraphqlGetQuery>,
) -> Response {
if let Some(query) = params.query {
if !has_apollo_csrf_header(&headers) {
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"BAD_REQUEST",
"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF).",
);
}
if query.len() > MAX_GRAPHQL_QUERY_BYTES {
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"GRAPHQL_VALIDATION_FAILED",
"Query exceeds maximum allowed size",
);
}
if graphql_query_exceeds_depth(&query, MAX_GRAPHQL_BRACKET_DEPTH) {
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"GRAPHQL_VALIDATION_FAILED",
"Query exceeds maximum nesting depth",
);
}
if let Ok(doc) = async_graphql::parser::parse_query(&query) {
let target_op_name = params
.operation_name
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
let is_non_query = match &doc.operations {
async_graphql::parser::types::DocumentOperations::Single(op) => {
target_op_name.is_none() && !matches!(op.node.ty, async_graphql::parser::types::OperationType::Query)
}
async_graphql::parser::types::DocumentOperations::Multiple(ops) => {
if let Some(name) = target_op_name {
ops
.iter()
.find(|(op_name, _)| op_name.as_str() == name)
.is_some_and(|(_, op)| !matches!(op.node.ty, async_graphql::parser::types::OperationType::Query))
} else if ops.len() == 1 {
ops
.values()
.next()
.is_some_and(|op| !matches!(op.node.ty, async_graphql::parser::types::OperationType::Query))
} else {
false
}
}
};
if is_non_query {
return graphql_bad_request_response(
StatusCode::METHOD_NOT_ALLOWED,
"BAD_REQUEST",
"GET supports only query operation",
);
}
}
let mut req = async_graphql::Request::new(query);
if let Some(op_name) = params.operation_name {
req = req.operation_name(op_name);
}
if let Some(vars_str) = params.variables {
match serde_json::from_str::<serde_json::Value>(&vars_str) {
Ok(val) => {
req = req.variables(async_graphql::Variables::from_json(val));
}
Err(_) => {
return graphql_bad_request_response(StatusCode::BAD_REQUEST, "BAD_REQUEST", "Variables are invalid JSON.");
}
}
}
return execute_graphql_request(&state, peer, headers, req).await;
}
let cfg = state.app.config.load();
if !cfg.graphql_playground {
return StatusCode::METHOD_NOT_ALLOWED.into_response();
@@ -922,7 +1191,7 @@ pub struct RouteMountMatrix {
impl RouteMountMatrix {
/// Computes the exact mount flags for `(deployment_mode, dev_mode, role)`.
pub fn for_mode_and_role(deployment_mode: DeploymentMode, dev_mode: bool, role: ServerRole) -> Self {
pub fn for_mode_and_role(deployment_mode: DeploymentMode, _dev_mode: bool, role: ServerRole) -> Self {
let is_http_role = matches!(role, ServerRole::Front | ServerRole::Graphql | ServerRole::Allinone);
let is_selfhosted = deployment_mode == DeploymentMode::Selfhosted;
let is_api_role = matches!(role, ServerRole::Graphql | ServerRole::Allinone);
@@ -936,7 +1205,7 @@ impl RouteMountMatrix {
auth_and_avatar_api: is_http_role,
graphql_flavor_api: is_api_role,
selfhost_setup: is_selfhosted && is_http_role,
worker_proxy: (is_selfhosted || dev_mode) && is_http_role,
worker_proxy: is_selfhosted && is_http_role,
selfhost_static: is_selfhosted && is_http_role,
front_static: role == ServerRole::Front,
doc_renderer: is_http_role,
@@ -1066,11 +1335,155 @@ pub fn build_router(app: Arc<AppState>) -> Router {
router = router.merge(rest::static_files::static_router(false));
}
let cors_state = state.clone();
let base_path = cfg
.app_config_baseline
.server
.path
.trim()
.trim_end_matches('/')
.to_owned();
let mut router = router.with_state(state);
if let Some(ext_router) = extra {
router = router.merge(ext_router);
}
router.layer(TraceLayer::new_for_http())
if !base_path.is_empty() && base_path != "/" {
let prefix = if base_path.starts_with('/') {
base_path
} else {
format!("/{base_path}")
};
let health_root = Router::new()
.route("/healthz", get(handle_healthz))
.route("/readyz", get(handle_readyz))
.with_state(cors_state.clone());
router = Router::new().nest(&prefix, router).merge(health_root);
}
router
.layer(axum::middleware::from_fn_with_state(cors_state, global_cors_middleware))
.layer(TraceLayer::new_for_http())
}
fn append_vary_origin(headers: &mut HeaderMap) {
let has_origin = headers
.get_all(header::VARY)
.iter()
.filter_map(|v| v.to_str().ok())
.any(|v| v.split(',').any(|p| p.trim().eq_ignore_ascii_case("origin")));
if !has_origin {
headers.append(header::VARY, HeaderValue::from_static("Origin"));
}
}
async fn global_cors_middleware(
State(state): State<RouterState>,
req: axum::http::Request<axum::body::Body>,
next: axum::middleware::Next,
) -> Response {
let req_path = req.uri().path().to_owned();
let is_options = *req.method() == axum::http::Method::OPTIONS;
let origin = req
.headers()
.get(header::ORIGIN)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
let has_acrm = req.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD);
let cfg_snap = state.app.config.load();
let stripped_path = {
let prefix = cfg_snap.app_config_baseline.server.path.trim().trim_end_matches('/');
if !prefix.is_empty() && prefix != "/" {
let normalized = if prefix.starts_with('/') {
prefix.to_owned()
} else {
format!("/{prefix}")
};
req_path
.strip_prefix(&normalized)
.filter(|rest| rest.is_empty() || rest.starts_with('/'))
.unwrap_or(req_path.as_str())
} else {
req_path.as_str()
}
};
let scope = if stripped_path == "/api/telemetry" || stripped_path.starts_with("/api/telemetry/") {
rest::worker_proxy::CorsOriginScope::Telemetry
} else if stripped_path == "/api/worker" || stripped_path.starts_with("/api/worker/") {
rest::worker_proxy::CorsOriginScope::Worker
} else {
rest::worker_proxy::CorsOriginScope::Global
};
let dev_mode = cfg_snap.dev_mode;
let allowed = if origin.is_some() || is_options {
rest::worker_proxy::allowed_origins_for_state_async(&state, scope).await
} else {
Vec::new()
};
let origin_allowed = origin
.as_deref()
.is_some_and(|o| rest::worker_proxy::is_cors_origin_allowed(o, &allowed, dev_mode));
let is_route_managed_options = req_path.ends_with("/api/worker/image-proxy")
|| req_path.ends_with("/api/worker/link-preview")
|| req_path.ends_with("/api/telemetry/collect")
|| req_path.contains("/socket.io");
if is_options && !is_route_managed_options && (has_acrm || origin.is_some()) {
let mut resp = StatusCode::NO_CONTENT.into_response();
let h = resp.headers_mut();
h.insert(
header::VARY,
HeaderValue::from_static("Origin, Access-Control-Request-Method, Access-Control-Request-Headers"),
);
if origin_allowed
&& let Some(ref orig) = origin
&& let Ok(val) = HeaderValue::from_str(orig)
{
h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, val);
h.insert(
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_static("true"),
);
h.insert(
header::ACCESS_CONTROL_ALLOW_METHODS,
HeaderValue::from_static(rest::worker_proxy::CORS_ALLOWED_METHODS),
);
h.insert(
header::ACCESS_CONTROL_ALLOW_HEADERS,
HeaderValue::from_static(rest::worker_proxy::CORS_ALLOWED_HEADERS),
);
h.insert(header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("86400"));
}
return resp;
}
let mut resp = next.run(req).await;
let is_server_err = resp.status().is_server_error();
let h = resp.headers_mut();
if is_server_err && !h.contains_key("x-request-id") {
let req_id = uuid::Uuid::new_v4().to_string();
if let Ok(v) = HeaderValue::from_str(&req_id) {
h.insert(header::HeaderName::from_static("x-request-id"), v);
}
}
append_vary_origin(h);
if let Some(ref orig) = origin {
if origin_allowed && let Ok(val) = HeaderValue::from_str(orig) {
h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, val);
h.insert(
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_static("true"),
);
h.insert(
header::ACCESS_CONTROL_EXPOSE_HEADERS,
HeaderValue::from_static(rest::worker_proxy::CORS_EXPOSED_HEADERS),
);
} else {
h.remove(header::ACCESS_CONTROL_ALLOW_ORIGIN);
h.remove(header::ACCESS_CONTROL_ALLOW_CREDENTIALS);
}
}
resp
}
#[cfg(test)]
@@ -1157,10 +1570,20 @@ mod tests {
let resp = app
.clone()
.oneshot(Request::builder().uri("/info").body(Body::empty()).unwrap())
.oneshot(
Request::builder()
.uri("/info")
.header(header::ORIGIN, "assets://.")
.body(Body::empty())
.unwrap(),
)
.await
.expect("info response");
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN),
Some(&HeaderValue::from_static("assets://."))
);
assert_eq!(
resp.headers().get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS),
Some(&HeaderValue::from_static("true"))
@@ -1357,7 +1780,7 @@ mod tests {
"map field ordered before operations",
&multipart_type,
multipart(vec![map(1), operations(1), Part::File("0".into(), 1)]),
StatusCode::OK,
StatusCode::BAD_REQUEST,
),
];
for (name, content_type, body, expected) in cases {
@@ -1717,7 +2140,7 @@ mod tests {
true,
true,
),
// Cloud + dev_mode=true mounts worker_proxy on HTTP roles while keeping selfhost_setup/selfhost_static off.
// Cloud + dev_mode=true keeps worker_proxy, selfhost_setup, and selfhost_static unmounted.
(
DeploymentMode::Cloud,
true,
@@ -1727,7 +2150,7 @@ mod tests {
true,
false,
false,
true,
false,
false,
true,
true,
@@ -1743,7 +2166,7 @@ mod tests {
true,
true,
false,
true,
false,
false,
false,
true,
@@ -1775,7 +2198,7 @@ mod tests {
true,
true,
false,
true,
false,
false,
false,
true,
@@ -1888,7 +2311,7 @@ mod tests {
)
.await
.unwrap();
assert_eq!(first.status(), StatusCode::CREATED);
assert_eq!(first.status(), StatusCode::OK);
let second = selfhost_app
.oneshot(
@@ -1944,7 +2367,7 @@ mod tests {
)
.await
.unwrap();
assert_eq!(create_resp.status(), StatusCode::CREATED);
assert_eq!(create_resp.status(), StatusCode::OK);
let admin_cookie = create_resp
.headers()
.get_all(header::SET_COOKIE)
@@ -1954,11 +2377,12 @@ mod tests {
.collect::<Vec<_>>()
.join("; ");
// Enable client.versionControl in app_configs and invalidate the snapshot cache.
// Enable client.versionControl in app_configs (and raise sign-in rate limit for repeated test logins).
sqlx::query(
r#"INSERT INTO app_configs (id, value, last_updated_by, created_at, updated_at)
VALUES ('client.versionControl.enabled', 'true'::jsonb, NULL, now(), now()),
('client.versionControl.requiredVersion', '">=0.25.0"'::jsonb, NULL, now(), now())
('client.versionControl.requiredVersion', '">=0.25.0"'::jsonb, NULL, now(), now()),
('auth.signInRateLimit', '{"ttl":60000,"emailLimit":100,"ipLimit":100}'::jsonb, NULL, now(), now())
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = now()"#,
)
.execute(db.pool())
@@ -2416,10 +2840,10 @@ mod tests {
// Lazy GraphQL auth: validation-error, @skip(if: true), and pure __typename queries
// with a low-version Bearer must NOT revoke the auth_session in PostgreSQL.
let (gql_auth_session_id, gql_access_token) = issue_bearer().await;
for non_exec_query in [
r#"{"query":"{ nonExistentRootField }"}"#,
r#"{"query":"{ currentUser @skip(if: true) { id } }"}"#,
r#"{"query":"{ __typename }"}"#,
for (non_exec_query, expected_status) in [
(r#"{"query":"{ nonExistentRootField }"}"#, StatusCode::BAD_REQUEST),
(r#"{"query":"{ currentUser @skip(if: true) { id } }"}"#, StatusCode::OK),
(r#"{"query":"{ __typename }"}"#, StatusCode::OK),
] {
let resp = app
.clone()
@@ -2435,7 +2859,7 @@ mod tests {
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "query={non_exec_query}");
assert_eq!(resp.status(), expected_status, "query={non_exec_query}");
let revoked_count: i64 =
sqlx::query_scalar("SELECT COUNT(*) FROM auth_sessions WHERE id = $1 AND revoked_at IS NOT NULL")
.bind(&gql_auth_session_id)
+316 -55
View File
@@ -67,9 +67,14 @@ struct AuthUserSummary {
pub(crate) async fn handle_create_admin_user(
State(state): State<RouterState>,
PeerAddr(peer): PeerAddr,
headers: HeaderMap,
axum::Json(body): axum::Json<CreateAdminUserBody>,
) -> Response {
let throttle = match enforce_throttle_http(&state, &headers, peer, None, ThrottleSpec::Default).await {
Ok(h) => h,
Err(resp) => return *resp,
};
let result = state
.app
.auth
@@ -81,11 +86,11 @@ pub(crate) async fn handle_create_admin_user(
})
.await;
match result {
let mut resp = match result {
Ok(sign_in) => {
let cfg = state.app.config.load();
let mut resp = json_utf8_response(
StatusCode::CREATED,
StatusCode::OK,
AuthUserSummary {
email: sign_in.user.email.clone(),
id: sign_in.user.id.clone(),
@@ -97,7 +102,9 @@ pub(crate) async fn handle_create_admin_user(
resp
}
Err(err) => domain_error_to_http_response(&err),
}
};
apply_throttle(resp.headers_mut(), throttle);
resp
}
#[derive(Debug, Serialize)]
@@ -249,7 +256,7 @@ pub(crate) async fn handle_preflight(
let mut resp = match serde_json::from_slice::<PreflightBody>(&body_bytes) {
Ok(body) => match canonical_email(&body.email) {
Ok(email) => match state.app.auth.login_preflight(&email).await {
Ok(preflight) => json_utf8_response(StatusCode::OK, preflight, true),
Ok(preflight) => json_utf8_response(StatusCode::CREATED, preflight, true),
Err(err) => domain_error_to_http_response(&err),
},
Err(_) => invalid_email_response(),
@@ -295,6 +302,154 @@ pub struct SignInBody {
pub challenge: Option<String>,
}
async fn check_sign_in_rate_bucket(state: &RouterState, key: &str, limit: u64, ttl_ms: u64) -> Result<(), u64> {
if limit == 0 || ttl_ms == 0 {
return Ok(());
}
if let Some(client) = state.app.redis.as_ref() {
let mut conn = state.app.throttle_redis_conn.lock().await.clone();
if conn.is_none() {
conn = tokio::time::timeout(
std::time::Duration::from_secs(2),
client.get_multiplexed_async_connection(),
)
.await
.ok()
.and_then(Result::ok);
}
if let Some(mut c) = conn {
let script = redis::Script::new(
"local h = redis.call('INCR', KEYS[1]) \
if h == 1 or redis.call('PTTL', KEYS[1]) == -1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end \
local pttl = redis.call('PTTL', KEYS[1]) \
if pttl < 0 then pttl = tonumber(ARGV[1]) end \
return {h, pttl}",
);
let res: Option<(u64, i64)> = tokio::time::timeout(
std::time::Duration::from_secs(2),
script.key(key).arg(ttl_ms).invoke_async(&mut c),
)
.await
.ok()
.and_then(Result::ok);
if let Some((hits, rem_ms)) = res {
*state.app.throttle_redis_conn.lock().await = Some(c);
if hits > limit {
let retry_after_secs = (rem_ms.max(1) as u64).div_ceil(1000).max(1);
return Err(retry_after_secs);
}
return Ok(());
}
}
}
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
struct MemRateTable {
map: HashMap<String, (u64, Instant)>,
last_gc: Instant,
}
const MAX_MEM_RATE_KEYS: usize = 4096;
static MEM: OnceLock<Mutex<MemRateTable>> = OnceLock::new();
let now = Instant::now();
let window = Duration::from_millis(ttl_ms);
let Ok(mut table) = MEM
.get_or_init(|| {
Mutex::new(MemRateTable {
map: HashMap::new(),
last_gc: now,
})
})
.lock()
else {
return Ok(());
};
if table.map.len() >= MAX_MEM_RATE_KEYS && now.duration_since(table.last_gc) >= Duration::from_secs(1) {
table.map.retain(|_, (_, exp)| *exp > now);
table.last_gc = now;
}
if table.map.len() >= MAX_MEM_RATE_KEYS
&& !table.map.contains_key(key)
&& let Some(oldest_key) = table
.map
.iter()
.min_by_key(|(_, (_, exp))| *exp)
.map(|(k, _)| k.clone())
{
table.map.remove(&oldest_key);
}
let entry = table.map.entry(key.to_owned()).or_insert((0, now + window));
if entry.1 <= now {
*entry = (0, now + window);
}
entry.0 += 1;
if entry.0 > limit {
let rem_ms = entry.1.saturating_duration_since(now).as_millis() as u64;
let retry_after_secs = rem_ms.div_ceil(1000).max(1);
return Err(retry_after_secs);
}
Ok(())
}
async fn enforce_sign_in_rate_limit(
state: &RouterState,
headers: &HeaderMap,
peer: Option<std::net::SocketAddr>,
canonical_email_str: &str,
) -> Result<(), Box<Response>> {
let eff = state.app.app_config.get_effective_app_config_arc().await.ok();
let rl = eff.as_ref().and_then(|c| c.pointer("/auth/signInRateLimit"));
let ttl_ms = rl.and_then(|v| v.get("ttl")?.as_u64()).unwrap_or(60_000);
let email_limit = rl.and_then(|v| v.get("emailLimit")?.as_u64()).unwrap_or(5);
let ip_limit = rl.and_then(|v| v.get("ipLimit")?.as_u64()).unwrap_or(20);
let key_prefix = state
.app
.app_config
.get_internal_redis_key_prefix()
.await
.unwrap_or_default();
use sha2::{Digest as _, Sha256};
let email_hash = hex::encode(Sha256::digest(canonical_email_str.to_ascii_lowercase().as_bytes()));
let email_key = format!("{key_prefix}auth:sign-in-rate:email:{email_hash}");
let email_res = check_sign_in_rate_bucket(state, &email_key, email_limit, ttl_ms).await;
let ip = ["cf-connecting-ip", "x-forwarded-for", "x-real-ip"]
.into_iter()
.find_map(|name| {
let raw = headers.get(name)?.to_str().ok()?;
let s = if name == "x-forwarded-for" {
raw.split(',').next()?
} else {
raw
}
.trim();
(!s.is_empty()).then(|| s.to_owned())
})
.or_else(|| peer.map(|a| a.ip().to_string()));
let ip_res = if let Some(ip_str) = ip {
let ip_hash = hex::encode(Sha256::digest(ip_str.as_bytes()));
let ip_key = format!("{key_prefix}auth:sign-in-rate:ip:{ip_hash}");
check_sign_in_rate_bucket(state, &ip_key, ip_limit, ttl_ms).await
} else {
Ok(())
};
let retry_after = match (email_res, ip_res) {
(Err(a), Err(b)) => Some(a.max(b)),
(Err(a), Ok(())) | (Ok(()), Err(a)) => Some(a),
(Ok(()), Ok(())) => None,
};
if let Some(retry_after_secs) = retry_after {
let mut resp = envelope_to_http_response(super::throttle::too_many_requests_envelope());
if let Ok(v) = HeaderValue::from_str(&retry_after_secs.to_string()) {
resp.headers_mut().insert(header::RETRY_AFTER, v);
}
return Err(Box::new(resp));
}
Ok(())
}
pub(crate) async fn handle_sign_in(
State(state): State<RouterState>,
PeerAddr(peer): PeerAddr,
@@ -329,6 +484,9 @@ pub(crate) async fn handle_sign_in(
Ok(e) => e,
Err(_) => return apply_old_cookie(invalid_email_response()),
};
if let Err(resp) = enforce_sign_in_rate_limit(&state, &headers, peer, &email).await {
return apply_old_cookie(*resp);
}
if let Some(password) = body.password {
if password.is_empty() {
@@ -336,6 +494,53 @@ pub(crate) async fn handle_sign_in(
"Password must not be empty.".to_owned(),
)));
}
if password.len() > server_domain::auth::password::MAX_PASSWORD_BYTES {
return apply_old_cookie(domain_error_to_http_response(&DomainError::Validation(
"Password exceeds maximum allowed length.".to_owned(),
)));
}
let client_version = extract_non_empty_client_version(&headers);
if is_native_client_request(&headers) {
return match state
.app
.auth
.sign_in_with_password_native(&email, &password, client_version.as_deref())
.await
{
Ok((user, exchange_code)) => {
let mut val = serde_json::to_value(SessionUserDto::from(user)).unwrap_or_default();
if let Some(obj) = val.as_object_mut() {
obj.insert("exchangeCode".to_owned(), serde_json::Value::String(exchange_code));
}
let mut resp = json_utf8_response(StatusCode::OK, val, false);
append_clear_auth_cookies(resp.headers_mut(), https);
apply_throttle(resp.headers_mut(), throttle);
resp
}
Err(DomainError::Unauthorized(code)) if code == "wrong_sign_in_credentials" => {
apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "WRONG_SIGN_IN_CREDENTIALS".into(),
message: format!("Wrong user email or password: {email}"),
data: Some(serde_json::json!({ "email": email })),
}))
}
Err(DomainError::Unauthorized(code)) if code == "wrong_sign_in_method" => {
apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "WRONG_SIGN_IN_METHOD".into(),
message: "Wrong sign in method.".into(),
data: None,
}))
}
Err(err) => apply_old_cookie(domain_error_to_http_response(&err)),
};
}
let cookies = parse_cookies(&headers);
let existing_session_id = extract_cookie(&cookies, SESSION_COOKIE_NAME).map(str::to_owned);
let result = state
@@ -345,32 +550,13 @@ pub(crate) async fn handle_sign_in(
email: email.clone(),
password,
existing_session_id,
client_version: extract_non_empty_client_version(&headers),
client_version,
})
.await;
return match result {
Ok(sign_in) => {
let cfg = state.app.config.load();
let client_version = extract_non_empty_client_version(&headers);
let body = if is_native_client_request(&headers) {
match state
.app
.auth
.issue_exchange_code(&sign_in.user.id, client_version.as_deref())
.await
{
Ok(exchange_code) => {
let mut val = serde_json::to_value(SessionUserDto::from(sign_in.user.clone())).unwrap_or_default();
if let Some(obj) = val.as_object_mut() {
obj.insert("exchangeCode".to_owned(), serde_json::Value::String(exchange_code));
}
val
}
Err(err) => return apply_old_cookie(domain_error_to_http_response(&err)),
}
} else {
serde_json::to_value(SessionUserDto::from(sign_in.user.clone())).unwrap_or_default()
};
let body = serde_json::to_value(SessionUserDto::from(sign_in.user.clone())).unwrap_or_default();
let mut resp = json_utf8_response(StatusCode::OK, body, false);
append_auth_cookies(resp.headers_mut(), &sign_in, cfg.https);
apply_throttle(resp.headers_mut(), throttle);
@@ -401,7 +587,12 @@ pub(crate) async fn handle_sign_in(
}
let cfg = state.app.config.load();
if cfg.app_config_baseline.smtp.host.trim().is_empty() {
let eff_cfg = state.app.app_config.get_effective_app_config().await.ok();
let smtp_host = eff_cfg
.as_ref()
.and_then(|c| c.pointer("/mailer/SMTP/host")?.as_str())
.unwrap_or(&cfg.app_config_baseline.smtp.host);
if smtp_host.trim().is_empty() {
return apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
code: "Internal Server Error".into(),
@@ -412,12 +603,16 @@ pub(crate) async fn handle_sign_in(
}));
}
let mut dynamic_hosts = cfg.app_config_baseline.server.hosts.clone();
if let Some(arr) = eff_cfg.as_ref().and_then(|c| c.pointer("/server/hosts")?.as_array()) {
for h in arr.iter().filter_map(serde_json::Value::as_str) {
if !h.is_empty() && !dynamic_hosts.iter().any(|x| x == h) {
dynamic_hosts.push(h.to_owned());
}
}
}
let raw_callback = body.callback_url.as_deref().unwrap_or("/magic-link");
let callback_url = match validate_and_build_magic_link_callback_url(
raw_callback,
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
) {
let callback_url = match validate_and_build_magic_link_callback_url(raw_callback, &cfg.external_url, &dynamic_hosts) {
Ok(url) => url,
Err(err) => return apply_old_cookie(domain_error_to_http_response(&err)),
};
@@ -428,7 +623,7 @@ pub(crate) async fn handle_sign_in(
.app
.auth
.prepare_magic_link(PrepareMagicLinkInput {
email,
email: email.clone(),
callback_url,
client_nonce: body.client_nonce,
source: Some(source),
@@ -437,6 +632,26 @@ pub(crate) async fn handle_sign_in(
let resp = match res {
Ok(prepared) => json_utf8_response(StatusCode::OK, serde_json::json!({ "email": prepared.email }), false),
Err(DomainError::Unauthorized(code)) if code == "wrong_sign_in_credentials" => {
envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "WRONG_SIGN_IN_CREDENTIALS".into(),
message: format!("Wrong user email or password: {email}"),
data: Some(serde_json::json!({ "email": email })),
})
}
Err(DomainError::Forbidden(code)) if code == "sign_up_forbidden" => {
envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "SIGN_UP_FORBIDDEN".into(),
message: "Sign up is forbidden.".into(),
data: None,
})
}
Err(err) => domain_error_to_http_response(&err),
};
apply_old_cookie(resp)
@@ -518,7 +733,7 @@ pub(crate) async fn handle_sign_out(
cookie_action.apply_to(resp.headers_mut(), https);
append_user_id_cookie(resp.headers_mut(), last_user_id);
} else {
append_clear_auth_cookies(resp.headers_mut());
append_clear_auth_cookies(resp.headers_mut(), https);
}
finish(resp)
}
@@ -570,6 +785,55 @@ pub(crate) async fn handle_complete_magic_link(
Err(_) => return apply_old_cookie(invalid_email_response()),
};
let client_version = extract_non_empty_client_version(&headers);
if is_native_client_request(&headers) {
let res = state
.app
.auth
.complete_magic_link_native(CompleteMagicLinkInput {
email,
otp: body.token,
client_nonce: body.client_nonce,
existing_session_id: None,
client_version,
})
.await;
return match res {
Ok((user, exchange_code)) => {
let mut resp = json_utf8_response(
StatusCode::OK,
serde_json::json!({ "id": user.id, "exchangeCode": exchange_code }),
false,
);
append_clear_auth_cookies(resp.headers_mut(), https);
apply_throttle(resp.headers_mut(), throttle);
resp
}
Err(DomainError::Unauthorized(code)) if code == "invalid_auth_state" => {
apply_old_cookie(invalid_auth_state_response())
}
Err(DomainError::Unauthorized(_)) => apply_old_cookie(envelope_to_http_response(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,
})),
Err(DomainError::Forbidden(code)) if code == "sign_up_forbidden" => {
apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "SIGN_UP_FORBIDDEN".into(),
message: "Sign up is forbidden.".into(),
data: None,
}))
}
Err(err) => apply_old_cookie(domain_error_to_http_response(&err)),
};
}
let cookies = parse_cookies(&headers);
let existing_session_id = extract_cookie(&cookies, SESSION_COOKIE_NAME).map(str::to_owned);
let res = state
@@ -580,28 +844,14 @@ pub(crate) async fn handle_complete_magic_link(
otp: body.token,
client_nonce: body.client_nonce,
existing_session_id,
client_version: extract_non_empty_client_version(&headers),
client_version,
})
.await;
match res {
Ok(sign_in) => {
let cfg = state.app.config.load();
let client_version = extract_non_empty_client_version(&headers);
let body = if is_native_client_request(&headers) {
match state
.app
.auth
.issue_exchange_code(&sign_in.user.id, client_version.as_deref())
.await
{
Ok(exchange_code) => serde_json::json!({ "id": sign_in.user.id, "exchangeCode": exchange_code }),
Err(err) => return apply_old_cookie(domain_error_to_http_response(&err)),
}
} else {
serde_json::json!({ "id": sign_in.user.id })
};
let mut resp = json_utf8_response(StatusCode::CREATED, body, false);
let mut resp = json_utf8_response(StatusCode::OK, serde_json::json!({ "id": sign_in.user.id }), false);
append_auth_cookies(resp.headers_mut(), &sign_in, cfg.https);
apply_throttle(resp.headers_mut(), throttle);
resp
@@ -624,6 +874,16 @@ pub(crate) async fn handle_complete_magic_link(
message: "An invalid email token provided.".into(),
data: None,
})),
Err(DomainError::Forbidden(code)) if code == "sign_up_forbidden" => {
apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "SIGN_UP_FORBIDDEN".into(),
message: "Sign up is forbidden.".into(),
data: None,
}))
}
Err(err) => apply_old_cookie(domain_error_to_http_response(&err)),
}
}
@@ -708,15 +968,15 @@ pub(crate) async fn handle_open_app_sign_in(
match state.app.auth.complete_open_app(&body.code, target).await {
Ok(server_domain::auth::OpenAppSignInResult::Native { user, exchange_code }) => {
let payload = serde_json::json!({ "id": user.id, "exchangeCode": exchange_code });
let mut resp = json_utf8_response(StatusCode::CREATED, payload, false);
append_clear_auth_cookies(resp.headers_mut());
let mut resp = json_utf8_response(StatusCode::OK, payload, false);
append_clear_auth_cookies(resp.headers_mut(), https);
apply_throttle(resp.headers_mut(), throttle);
resp
}
Ok(server_domain::auth::OpenAppSignInResult::Cookie(sign_in)) => {
let cfg = state.app.config.load();
let payload = serde_json::json!({ "id": sign_in.user.id });
let mut resp = json_utf8_response(StatusCode::CREATED, payload, false);
let mut resp = json_utf8_response(StatusCode::OK, payload, false);
append_auth_cookies(resp.headers_mut(), &sign_in, cfg.https);
apply_throttle(resp.headers_mut(), throttle);
resp
@@ -862,6 +1122,7 @@ pub(crate) async fn handle_exchange_session(
.await
{
Ok(pair) => auth_session_json_response(StatusCode::CREATED, pair),
Err(DomainError::Unauthorized(code)) if code == "invalid_auth_state" => invalid_auth_state_response(),
Err(err) => domain_error_to_http_response(&err),
};
apply_cookie(resp)
@@ -1046,7 +1307,7 @@ pub(crate) async fn handle_revoke_current_session(
let resp = match state
.app
.auth
.revoke_auth_session_by_refresh_token(refresh_token, "current_device_sign_out")
.revoke_auth_session_by_refresh_token(refresh_token, "refresh_token_revoke")
.await
{
Ok(_) => auth_session_json_response(StatusCode::CREATED, serde_json::json!({})),
@@ -1109,7 +1370,7 @@ pub(crate) async fn handle_revoke_all_sessions(
let mut resp = match state
.app
.auth
.revoke_all_user_sessions(&principal.user().id, "user_action")
.revoke_all_user_sessions(&principal.user().id, "security_action")
.await
{
Ok(()) => auth_session_json_response(StatusCode::CREATED, serde_json::json!({})),
@@ -1146,7 +1407,7 @@ pub(crate) async fn handle_revoke_auth_session_by_id(
let mut resp = match state
.app
.auth
.revoke_auth_session(&auth_session_id, Some(&principal.user().id), "user_action")
.revoke_auth_session(&auth_session_id, Some(&principal.user().id), "security_action")
.await
{
Ok(_) => auth_session_json_response(StatusCode::OK, serde_json::json!({})),
+132 -18
View File
@@ -67,22 +67,46 @@ pub(crate) async fn handle_get_avatar(
};
let (bytes, meta) = obj;
let mut resp = (StatusCode::OK, bytes).into_response();
let last_mod_dt = chrono::DateTime::from_timestamp_millis(meta.last_modified_ms);
let last_mod_str = last_mod_dt.map(super::format_http_date);
let not_modified = last_mod_dt.is_some_and(|dt| {
let mtime_secs = dt.timestamp();
headers
.get(header::IF_MODIFIED_SINCE)
.and_then(|v| v.to_str().ok())
.and_then(|raw| {
chrono::DateTime::parse_from_rfc2822(raw.trim())
.map(|d| d.with_timezone(&chrono::Utc))
.or_else(|_| {
chrono::NaiveDateTime::parse_from_str(raw.trim(), "%a, %d %b %Y %H:%M:%S GMT").map(|ndt| ndt.and_utc())
})
.ok()
})
.is_some_and(|ims| mtime_secs <= ims.timestamp())
});
let mut resp = if not_modified {
StatusCode::NOT_MODIFIED.into_response()
} else {
(StatusCode::OK, bytes).into_response()
};
let h = resp.headers_mut();
if !meta.content_type.is_empty()
&& let Ok(val) = HeaderValue::from_str(&meta.content_type)
{
h.insert(header::CONTENT_TYPE, val);
if !not_modified {
if !meta.content_type.is_empty()
&& let Ok(val) = HeaderValue::from_str(&meta.content_type)
{
h.insert(header::CONTENT_TYPE, val);
}
if let Ok(val) = HeaderValue::from_str(&meta.content_length.to_string()) {
h.insert(header::CONTENT_LENGTH, val);
}
}
if let Ok(val) = HeaderValue::from_str(&meta.content_length.to_string()) {
h.insert(header::CONTENT_LENGTH, val);
}
if let Some(dt) = chrono::DateTime::from_timestamp_millis(meta.last_modified_ms)
&& let Ok(val) = HeaderValue::from_str(&dt.to_rfc3339())
if let Some(lm) = last_mod_str
&& let Ok(val) = HeaderValue::from_str(&lm)
{
h.insert(header::LAST_MODIFIED, val);
}
apply_blob_security_headers(h, Some(&meta.content_type), Some(&id));
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=86400"));
resolved.cookie_action.apply_to(resp.headers_mut(), https);
resp
}
@@ -183,6 +207,14 @@ pub(crate) async fn handle_get_blob_v1(
message: "Blob not found.".into(),
data: None,
}),
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved.cookie_action.apply_to(resp.headers_mut(), https);
@@ -258,6 +290,14 @@ pub(crate) async fn handle_get_blob_manifest_v1(
true,
)
}
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved.cookie_action.apply_to(resp.headers_mut(), https);
@@ -267,7 +307,7 @@ pub(crate) async fn handle_get_blob_manifest_v1(
#[derive(Debug, Deserialize)]
pub struct ReadableManifestQuery {
pub cursor: Option<String>,
pub limit: Option<usize>,
pub limit: Option<String>,
}
/// Workspace readable blob manifest (`GET /api/workspaces/:id/readable-blob-manifest/v1`).
@@ -281,10 +321,19 @@ pub(crate) async fn handle_get_readable_blob_manifest_v1(
Ok(r) => r,
Err(err) => return err.into_http_response(),
};
let Some(principal) = resolved.principal else {
return domain_error_to_http_response(&DomainError::Unauthorized("Authentication required".into()));
};
let https = state.app.config.load().https;
let Some(principal) = resolved.principal else {
let mut resp = envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
});
resolved.cookie_action.apply_to(resp.headers_mut(), https);
return resp;
};
let user_id = principal.into_user().id;
if let Err(err) = state
.app
@@ -296,7 +345,12 @@ pub(crate) async fn handle_get_readable_blob_manifest_v1(
resolved.cookie_action.apply_to(resp.headers_mut(), https);
return resp;
}
let limit = query.limit.unwrap_or(25).clamp(1, 100);
let limit = query
.limit
.as_deref()
.and_then(|raw| raw.trim().parse::<usize>().ok())
.unwrap_or(25)
.clamp(1, 100);
let mut resp = match state
.app
.blobs
@@ -326,6 +380,14 @@ pub(crate) async fn handle_get_readable_blob_manifest_v1(
true,
)
}
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved.cookie_action.apply_to(resp.headers_mut(), https);
@@ -418,6 +480,14 @@ pub(crate) async fn handle_get_doc_snapshot(
message: "Doc not found.".into(),
data: Some(serde_json::json!({ "spaceId": workspace_id, "docId": doc_id })),
}),
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved
@@ -450,6 +520,14 @@ pub(crate) async fn handle_head_public_doc(
.insert("publish-mode", HeaderValue::from_static(publish_mode));
resp
}
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved
@@ -492,6 +570,14 @@ pub(crate) async fn handle_get_public_doc(
h.insert("publish-mode", HeaderValue::from_static(publish_mode));
resp
}
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved
@@ -526,6 +612,14 @@ pub(crate) async fn handle_get_public_root_doc(
);
resp
}
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
};
resolved
@@ -535,11 +629,23 @@ pub(crate) async fn handle_get_public_root_doc(
}
fn parse_history_timestamp(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(trimmed) {
return Some(dt.with_timezone(&chrono::Utc));
}
if let Ok(ms) = raw.parse::<i64>() {
return chrono::DateTime::from_timestamp_millis(ms);
if let Ok(dt) = chrono::DateTime::parse_from_rfc2822(trimmed) {
return Some(dt.with_timezone(&chrono::Utc));
}
if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(trimmed, "%a, %d %b %Y %H:%M:%S GMT") {
return Some(ndt.and_utc());
}
if let Ok(nd) = chrono::NaiveDate::parse_from_str(trimmed, "%Y-%m-%d")
&& let Some(ndt) = nd.and_hms_opt(0, 0, 0)
{
return Some(ndt.and_utc());
}
None
}
@@ -595,6 +701,14 @@ pub(crate) async fn handle_get_doc_history(
"timestamp": ts.timestamp_millis(),
})),
}),
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
}
} else {
@@ -320,7 +320,7 @@ async fn handle_google_webhook(State(state): State<RouterState>, headers: Header
.get("x-goog-channel-token")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if !svc.verify_webhook_token(&configs.google, token) {
if !svc.verify_webhook_token(&configs.google, token).await {
return with_cookies(StatusCode::UNAUTHORIZED.into_response(), &cookie_action, https);
}
match svc.handle_webhook(CalendarProviderName::Google, channel_id).await {
@@ -77,17 +77,36 @@ pub(crate) async fn enforce_named_captcha_guard(
headers: &HeaderMap,
pending_cookie_action: &PrincipalCookieAction,
) -> Result<(), Box<Response>> {
let (https, dev_mode, mut allowed_hosts) = {
let (https, dev_mode, mut allowed_hosts, file_json) = {
let cfg = state.app.config.load();
let mut hosts = cfg.app_config_baseline.server.hosts.clone();
hosts.push(cfg.app_config_baseline.server.host.clone());
(cfg.https, cfg.dev_mode, hosts)
(
cfg.https,
cfg.dev_mode,
hosts,
cfg.app_config_baseline.file_json.clone(),
)
};
if let Ok(eff) = state.app.app_config.get_effective_app_config().await
&& let Some(dyn_hosts) = eff.pointer("/server/hosts").and_then(serde_json::Value::as_array)
{
for h in dyn_hosts.iter().filter_map(serde_json::Value::as_str) {
if !h.is_empty() && !allowed_hosts.iter().any(|x| x == h) {
allowed_hosts.push(h.to_owned());
}
}
}
let fail = |mut resp: Response| -> Result<(), Box<Response>> {
pending_cookie_action.apply_to(resp.headers_mut(), https);
Err(Box::new(resp))
};
let effective = match load_effective_captcha_config(&state.app.db).await {
let effective = match server_domain::auth::captcha::load_effective_captcha_config_with_file(
&state.app.db,
Some(&file_json),
)
.await
{
Ok(v) => v,
Err(err) => return fail(domain_error_to_http_response(&err)),
};
@@ -283,7 +283,12 @@ async fn handle_render_workspace_path(
let avatar = row
.get::<Option<String>, _>("avatar_key")
.filter(|k| !k.is_empty())
.map(|k| format!("{}/api/avatars/{k}", cfg.external_url.trim_end_matches('/')));
.map(|k| {
format!(
"{}/api/workspaces/{ws_id}/blobs/v1/{k}?sourceType=currentDoc&docId={ws_id}",
cfg.external_url.trim_end_matches('/')
)
});
meta = Some((name, String::new(), avatar));
}
}
+72 -26
View File
@@ -99,12 +99,13 @@ pub(crate) fn format_http_date(dt: DateTime<Utc>) -> String {
dt.format("%a, %d %b %Y %H:%M:%S GMT").to_string()
}
pub(crate) fn append_clear_auth_cookies(headers: &mut HeaderMap) {
pub(crate) fn append_clear_auth_cookies(headers: &mut HeaderMap, https: bool) {
let expired = "Thu, 01 Jan 1970 00:00:00 GMT";
let secure_attr = if https { "; Secure" } else { "" };
let cookies = [
format!("{SESSION_COOKIE_NAME}=; Path=/; Expires={expired}"),
format!("{USER_ID_COOKIE_NAME}=; Path=/; Expires={expired}"),
format!("{CSRF_COOKIE_NAME}=; Path=/; Expires={expired}"),
format!("{SESSION_COOKIE_NAME}=; Path=/; Expires={expired}; HttpOnly; SameSite=Lax{secure_attr}"),
format!("{USER_ID_COOKIE_NAME}=; Path=/; Expires={expired}; SameSite=Lax{secure_attr}"),
format!("{CSRF_COOKIE_NAME}=; Path=/; Expires={expired}; SameSite=Lax{secure_attr}"),
];
for cookie in cookies {
if let Ok(val) = HeaderValue::from_str(&cookie) {
@@ -137,9 +138,11 @@ pub(crate) fn append_refresh_auth_cookies(
pub(crate) enum PrincipalCookieAction {
None,
Clear,
SetUserId(String),
Refresh {
session_id: String,
expires_at: DateTime<Utc>,
sync_user_id: Option<String>,
},
}
@@ -147,9 +150,25 @@ impl PrincipalCookieAction {
pub(crate) fn apply_to(&self, headers: &mut HeaderMap, https: bool) {
match self {
Self::None => {}
Self::Clear => append_clear_auth_cookies(headers),
Self::Refresh { session_id, expires_at } => {
Self::Clear => append_clear_auth_cookies(headers, https),
Self::SetUserId(uid) => {
let cookie = format!("{USER_ID_COOKIE_NAME}={uid}; Path=/; SameSite=Lax");
if let Ok(val) = HeaderValue::from_str(&cookie) {
headers.append(header::SET_COOKIE, val);
}
}
Self::Refresh {
session_id,
expires_at,
sync_user_id,
} => {
append_refresh_auth_cookies(headers, session_id, *expires_at, https);
if let Some(uid) = sync_user_id {
let cookie = format!("{USER_ID_COOKIE_NAME}={uid}; Path=/; SameSite=Lax");
if let Ok(val) = HeaderValue::from_str(&cookie) {
headers.append(header::SET_COOKIE, val);
}
}
}
}
}
@@ -173,17 +192,25 @@ pub enum PrincipalResolutionError {
impl PrincipalResolutionError {
pub fn into_envelope(self) -> (LegacyErrorEnvelope, bool) {
match self {
Self::AccessToken(code) => (
LegacyErrorEnvelope {
status: StatusCode::UNAUTHORIZED.as_u16(),
code: code.as_code().to_owned(),
error_type: "AUTHENTICATION_REQUIRED".into(),
name: code.as_name().to_owned(),
message: format!("Authentication failed ({}).", code.as_code()),
data: None,
},
false,
),
Self::AccessToken(code) => {
let message = match code {
AccessTokenErrorCode::AccessTokenExpired => "The access token has expired.",
AccessTokenErrorCode::AccessTokenInvalid => "The access token is invalid.",
AccessTokenErrorCode::AuthSessionRevoked => "The auth session has been revoked.",
AccessTokenErrorCode::AuthSessionExpired => "The auth session has expired.",
};
(
LegacyErrorEnvelope {
status: StatusCode::UNAUTHORIZED.as_u16(),
code: code.as_code().to_owned(),
error_type: "AUTHENTICATION_REQUIRED".into(),
name: code.as_name().to_owned(),
message: message.to_owned(),
data: None,
},
false,
)
}
Self::VersionGuard { error, clear_cookies } => (error.into_envelope(), clear_cookies),
Self::Domain(err) => (domain_error_to_envelope(&err), false),
}
@@ -193,7 +220,7 @@ impl PrincipalResolutionError {
let (env, clear_cookies) = self.into_envelope();
let mut resp = envelope_to_http_response(env);
if clear_cookies {
append_clear_auth_cookies(resp.headers_mut());
append_clear_auth_cookies(resp.headers_mut(), false);
}
resp
}
@@ -207,10 +234,6 @@ pub fn json_utf8_response(status: StatusCode, body: impl Serialize, no_store: bo
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
h.insert(
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_static("true"),
);
if no_store {
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
}
@@ -219,6 +242,20 @@ pub fn json_utf8_response(status: StatusCode, body: impl Serialize, no_store: bo
pub fn envelope_to_http_response(env: LegacyErrorEnvelope) -> Response {
let status = StatusCode::from_u16(env.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
if status.is_server_error() {
let request_id = Uuid::new_v4().to_string();
let mut val = serde_json::to_value(&env).unwrap_or_default();
if let Some(obj) = val.as_object_mut() {
obj.insert("requestId".to_owned(), serde_json::Value::String(request_id.clone()));
}
let mut resp = json_utf8_response(status, val, false);
if let Ok(v) = HeaderValue::from_str(&request_id) {
resp
.headers_mut()
.insert(header::HeaderName::from_static("x-request-id"), v);
}
return resp;
}
json_utf8_response(status, env, false)
}
@@ -367,7 +404,7 @@ pub(crate) async fn resolve_request_principal_with_policy(
else {
return Ok(ResolvedRequestPrincipal {
principal: None,
cookie_action: PrincipalCookieAction::None,
cookie_action: PrincipalCookieAction::Clear,
rejected_cookie_version: None,
});
};
@@ -401,7 +438,7 @@ pub(crate) async fn resolve_request_principal_with_policy(
});
}
let ttr_window = chrono::Duration::seconds(state.app.auth.config().session_ttr_seconds);
let ttr_window = chrono::Duration::seconds(state.app.auth.session_ttr_seconds().await);
let in_ttr_window = peek.expires_at.is_none_or(|exp| exp - Utc::now() <= ttr_window);
let p = if in_ttr_window {
let header_ver_for_refresh = extract_version_header(headers).filter(|s| !s.is_empty());
@@ -416,7 +453,7 @@ pub(crate) async fn resolve_request_principal_with_policy(
None => {
return Ok(ResolvedRequestPrincipal {
principal: None,
cookie_action: PrincipalCookieAction::None,
cookie_action: PrincipalCookieAction::Clear,
rejected_cookie_version: None,
});
}
@@ -425,12 +462,21 @@ pub(crate) async fn resolve_request_principal_with_policy(
peek
};
let sync_user_id = if user_id != Some(p.user.id.as_str()) {
Some(p.user.id.clone())
} else {
None
};
let cookie_action = match p.refreshed_expires_at {
Some(expires_at) => PrincipalCookieAction::Refresh {
session_id: p.session_id.clone(),
expires_at,
sync_user_id,
},
None => match sync_user_id {
Some(uid) => PrincipalCookieAction::SetUserId(uid),
None => PrincipalCookieAction::None,
},
None => PrincipalCookieAction::None,
};
Ok(ResolvedRequestPrincipal {
@@ -380,7 +380,7 @@ async fn handle_oauth_callback(
}
match &session {
OpenAppSignInResult::Cookie(cookie) => append_auth_cookies(r.headers_mut(), cookie, https),
OpenAppSignInResult::Native { .. } => append_clear_auth_cookies(r.headers_mut()),
OpenAppSignInResult::Native { .. } => append_clear_auth_cookies(r.headers_mut(), https),
}
r
} else {
@@ -397,7 +397,7 @@ async fn handle_oauth_callback(
let mut r = json_utf8_response(StatusCode::OK, dto, false);
match cookie_opt {
Some(cookie) => append_auth_cookies(r.headers_mut(), &cookie, https),
None => append_clear_auth_cookies(r.headers_mut()),
None => append_clear_auth_cookies(r.headers_mut(), https),
}
r
};
@@ -25,15 +25,15 @@ fn param<'a>(p: &'a HashMap<String, String>, f: &str) -> Result<&'a str, DomainE
p.get(f)
.map(String::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| DomainError::Validation(format!("Missing {f}.")))
.ok_or_else(|| DomainError::Validation(format!("blob_invalid:Missing {f}.")))
}
fn param_i64(p: &HashMap<String, String>, f: &str) -> Result<i64, DomainError> {
param(p, f)?
.parse()
.map_err(|_| DomainError::Validation(format!("Invalid {f}.")))
.map_err(|_| DomainError::Validation(format!("blob_invalid:Invalid {f}.")))
}
fn bad(m: &str) -> DomainError {
DomainError::Validation(m.into())
DomainError::Validation(format!("blob_invalid:{m}"))
}
async fn read_body_bounded(body: Body, expected_len: usize) -> Result<Vec<u8>, DomainError> {
let max_allowed = expected_len.min(MAX_PROXY_BODY_BYTES);
@@ -76,9 +76,34 @@ pub(crate) fn is_mobile_request(headers: &HeaderMap) -> bool {
async fn is_file_async(path: &Path) -> bool {
tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
}
fn percent_decode_path(raw: &str) -> Option<String> {
if !raw.contains('%') {
return Some(raw.to_owned());
}
let bytes = raw.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 None;
}
let hi = (bytes[i + 1] as char).to_digit(16)?;
let lo = (bytes[i + 2] as char).to_digit(16)?;
out.push(((hi << 4) | lo) as u8);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
fn safe_join(base: &Path, rel_path: &str) -> Option<PathBuf> {
let trimmed = rel_path.trim_start_matches('/');
if rel_path.contains(['\0', '\\']) || trimmed.is_empty() {
let decoded = percent_decode_path(rel_path)?;
let trimmed = decoded.trim_start_matches('/');
if decoded.contains(['\0', '\\']) || trimmed.is_empty() {
return None;
}
let mut out = base.to_path_buf();
@@ -125,17 +150,29 @@ async fn serve_file(
return None;
}
let mtime = meta.modified().ok().unwrap_or(UNIX_EPOCH);
let etag = format!(
"W/\"{}-{}\"",
meta.len(),
mtime.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
);
let mtime_secs = mtime.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() as i64;
let etag = format!("W/\"{}-{mtime_secs}\"", meta.len());
let last_mod = DateTime::<Utc>::from(mtime)
.format("%a, %d %b %Y %H:%M:%S GMT")
.to_string();
let hs = |n| h.get(n).and_then(|v| v.to_str().ok());
let not_mod = hs(header::IF_NONE_MATCH).is_some_and(|v| v.split(',').any(|t| t.trim() == etag || t.trim() == "*"))
|| hs(header::IF_MODIFIED_SINCE).is_some_and(|s| s.trim() == last_mod);
let not_mod = if let Some(inm) = hs(header::IF_NONE_MATCH) {
fn strip_weak(t: &str) -> &str {
let t = t.trim();
t.strip_prefix("W/").unwrap_or(t)
}
let strong_etag = strip_weak(&etag);
inm.split(',').any(|t| t.trim() == "*" || strip_weak(t) == strong_etag)
} else if let Some(ims) = hs(header::IF_MODIFIED_SINCE) {
let parsed = DateTime::parse_from_rfc2822(ims.trim())
.map(|dt| dt.with_timezone(&Utc))
.or_else(|_| {
chrono::NaiveDateTime::parse_from_str(ims.trim(), "%a, %d %b %Y %H:%M:%S GMT").map(|ndt| ndt.and_utc())
});
parsed.is_ok_and(|ims_dt| mtime_secs <= ims_dt.timestamp())
} else {
false
};
let mut resp = if not_mod {
StatusCode::NOT_MODIFIED.into_response()
} else if *m == Method::HEAD {
@@ -144,16 +181,21 @@ async fn serve_file(
(StatusCode::OK, tokio::fs::read(&path).await.ok()?).into_response()
};
let rh = resp.headers_mut();
for (name, val) in [
(header::CONTENT_TYPE, content_type_for_path(&path).to_owned()),
(header::ETAG, etag),
(header::LAST_MODIFIED, last_mod),
(header::CONTENT_LENGTH, meta.len().to_string()),
] {
for (name, val) in [(header::ETAG, etag), (header::LAST_MODIFIED, last_mod)] {
if let Ok(v) = HeaderValue::from_str(&val) {
rh.insert(name, v);
}
}
if !not_mod {
for (name, val) in [
(header::CONTENT_TYPE, content_type_for_path(&path).to_owned()),
(header::CONTENT_LENGTH, meta.len().to_string()),
] {
if let Ok(v) = HeaderValue::from_str(&val) {
rh.insert(name, v);
}
}
}
if ns {
rh.insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_CONTROL_NO_STORE));
}
@@ -182,6 +224,8 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
} else {
"index.html"
};
let is_selfhost_get = !is_front && cfg.deployment_mode == DeploymentMode::Selfhosted && method == Method::GET;
let is_setup_path = path == "/admin/setup";
let (m, h, https) = (&method, &headers, cfg.https);
if path == "/admin" || path.starts_with("/admin/") {
let admin_root = static_root.join("admin");
@@ -190,6 +234,14 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
{
return resp;
}
if is_selfhost_get && let Ok(initialized) = state.app.auth.is_server_initialized().await {
if !initialized && !is_setup_path {
return found_redirect(&state, "/admin/setup");
}
if initialized && is_setup_path {
return found_redirect(&state, "/admin");
}
}
return or_404(serve_file(&admin_root, html_entry, m, h, true, None, https).await);
}
if !is_front {
@@ -203,6 +255,12 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
return resp;
}
}
if is_selfhost_get
&& let Ok(initialized) = state.app.auth.is_server_initialized().await
&& !initialized
{
return found_redirect(&state, "/admin/setup");
}
let fb = if mobile && is_file_async(&mobile_root.join(html_entry)).await {
&mobile_root
} else {
@@ -18,7 +18,8 @@ use url::Url;
use crate::RouterState;
use crate::rest::worker_proxy::{
allowed_origins_for_state, append_cors_origin, apply_throttle_headers, bad_request_envelope, check_shared_throttle,
CorsOriginScope, allowed_origins_for_state_async, append_cors_origin, apply_throttle_headers, bad_request_envelope,
check_origin_or_referer, check_shared_throttle,
};
use crate::rest::{ResolvedRequestPrincipal, enforce_named_version_guard, resolve_request_principal_with_policy};
@@ -182,7 +183,7 @@ fn flatten_object(
}
pub fn sanitize_params(input: &Map<String, Value>, max_params: usize) -> Map<String, Value> {
let (mut flat, mut visited) = (Vec::new(), 0usize);
flatten_object(input, "", 0, &mut visited, max_params.min(25), &mut flat);
flatten_object(input, "", 0, &mut visited, 128, &mut flat);
let mut mapped: Vec<(String, Value)> = flat
.into_iter()
.filter_map(|(path, value)| {
@@ -351,11 +352,64 @@ fn clean_telemetry_event(
})
}
async fn forward_to_ga4_if_configured(state: &RouterState, events: &[CleanedTelemetryEvent]) {
let Ok(Some(cfg)) = state.app.app_config.get_raw_config_value("telemetry").await else {
return;
};
let ps = |p| cfg.pointer(p).and_then(Value::as_str).unwrap_or("").trim();
let (mid, secret) = (ps("/ga4/measurementId"), ps("/ga4/apiSecret"));
let dotted_mid = state
.app
.app_config
.get_raw_config_value("telemetry.ga4.measurementId")
.await
.ok()
.flatten()
.and_then(|v| v.as_str().map(str::to_owned));
let dotted_secret = state
.app
.app_config
.get_raw_config_value("telemetry.ga4.apiSecret")
.await
.ok()
.flatten()
.and_then(|v| v.as_str().map(str::to_owned));
let dotted_max = state
.app
.app_config
.get_raw_config_value("telemetry.batch.maxEvents")
.await
.ok()
.flatten()
.and_then(|v| v.as_u64());
let raw_telemetry = state
.app
.app_config
.get_raw_config_value("telemetry")
.await
.ok()
.flatten();
let mid = dotted_mid
.filter(|s| !s.trim().is_empty())
.or_else(|| {
raw_telemetry
.as_ref()
.and_then(|c| c.pointer("/ga4/measurementId")?.as_str())
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
})
.or_else(|| {
std::env::var("GA4_MEASUREMENT_ID")
.ok()
.filter(|s| !s.trim().is_empty())
})
.unwrap_or_default();
let secret = dotted_secret
.filter(|s| !s.trim().is_empty())
.or_else(|| {
raw_telemetry
.as_ref()
.and_then(|c| c.pointer("/ga4/apiSecret")?.as_str())
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
})
.or_else(|| std::env::var("GA4_API_SECRET").ok().filter(|s| !s.trim().is_empty()))
.unwrap_or_default();
let (mid, secret) = (mid.trim(), secret.trim());
let Ok(mut url) = Url::parse("https://www.google-analytics.com/mp/collect") else {
return;
};
@@ -366,9 +420,12 @@ async fn forward_to_ga4_if_configured(state: &RouterState, events: &[CleanedTele
.query_pairs_mut()
.append_pair("measurement_id", mid)
.append_pair("api_secret", secret);
let max_ev = cfg
.pointer("/batch/maxEvents")
.and_then(Value::as_u64)
let max_ev = dotted_max
.or_else(|| {
raw_telemetry
.as_ref()
.and_then(|c| c.pointer("/batch/maxEvents")?.as_u64())
})
.map_or(25, |n| usize::try_from(n).unwrap_or(25).clamp(1, 25));
let mut grouped: BTreeMap<_, Vec<&CleanedTelemetryEvent>> = BTreeMap::new();
for ev in events {
@@ -449,16 +506,16 @@ where
if let Err(r) = enforce_named_version_guard(st, hdrs, &resolved.cookie_action).await {
return *r;
}
let (allowed, https) = (allowed_origins_for_state(st, true), st.app.config.load().https);
let allowed = allowed_origins_for_state_async(st, CorsOriginScope::Telemetry).await;
let (https, dev_mode) = {
let cfg = st.app.config.load();
(cfg.https, cfg.dev_mode)
};
let (origin, referer) = (
hdrs.get(header::ORIGIN).and_then(|v| v.to_str().ok()),
hdrs.get(header::REFERER).and_then(|v| v.to_str().ok()),
);
let origin_ok = (origin.is_none() && referer.is_none())
|| origin.is_some_and(|o| allowed.iter().any(|a| a == o))
|| referer
.and_then(|r| Url::parse(r).ok())
.is_some_and(|u| allowed.iter().any(|a| a == &u.origin().ascii_serialization()));
let origin_ok = (origin.is_none() && referer.is_none()) || check_origin_or_referer(hdrs, &allowed, dev_mode);
let cookie_action = resolved.cookie_action.clone();
let mut resp = if !origin_ok {
let o = origin.unwrap_or("undefined");
@@ -504,9 +561,8 @@ async fn handle_collect(State(st): State<RouterState>, peer: PeerExt, hdrs: Head
.and_then(Value::as_f64)
.filter(|v| v.is_finite())
.map_or_else(|| Utc::now().timestamp_micros(), |v| (v * 1000.0) as i64);
dropped = events.len().saturating_sub(100);
let mut accepted_events = Vec::new();
for raw in events.iter().take(100) {
for raw in events {
let Some(c) = clean_telemetry_event(raw, uid.as_deref(), fallback) else {
dropped += 1;
continue;
@@ -83,6 +83,15 @@ pub enum VersionGuardError {
}
impl VersionGuardError {
pub fn into_parts(self) -> (String, String) {
match self {
Self::UnsupportedClientVersion {
client_version,
required_version,
} => (client_version, required_version),
}
}
/// Converts the error into the exact `v0.27.5` `UserFriendlyError` envelope.
pub fn into_envelope(self) -> LegacyErrorEnvelope {
match self {
@@ -117,6 +126,23 @@ impl VersionGuardError {
/// explicitly present empty header returns `Some("")`, matching `v0.27.5`
/// `getClientVersionFromRequest` so `"" ?? session.refreshClientVersion` does
/// not silently fall back to the session version.
pub fn verify_session_client_version_now(
headers: &HeaderMap,
refresh_client_version: Option<&str>,
sign_in_client_version: Option<&str>,
cfg: &ClientVersionControlConfig,
allow_canary: bool,
) -> Result<(), VersionGuardError> {
verify_session_client_version_at(
headers,
refresh_client_version,
sign_in_client_version,
cfg,
allow_canary,
Utc::now(),
)
}
pub fn extract_client_version(headers: &HeaderMap) -> Option<&str> {
headers
.get(CLIENT_VERSION_HEADER)
@@ -253,8 +253,9 @@ where
return *r;
}
};
let allowed = allowed_origins_for_state(state, false);
let mut resp = if require_origin && !check_origin_or_referer(headers, &allowed) {
let allowed = allowed_origins_for_state_async(state, CorsOriginScope::Worker).await;
let dev_mode = state.app.config.load().dev_mode;
let mut resp = if require_origin && !check_origin_or_referer(headers, &allowed, dev_mode) {
bad_request_envelope("Invalid header")
} else {
inner(allowed).await
@@ -296,7 +297,12 @@ pub(crate) fn router() -> Router<RouterState> {
};
Router::new()
.route("/api/worker/image-proxy", get(handle_image_proxy).options(img_opt))
.route("/api/worker/link-preview", post(handle_link_preview).options(lp_opt))
.route(
"/api/worker/link-preview",
post(handle_link_preview)
.options(lp_opt)
.layer(axum::extract::DefaultBodyLimit::max(MAX_LINK_PREVIEW_BODY_BYTES)),
)
}
fn err_env(status: u16, code: &str, ty: &str, name: &str, msg: impl Into<String>) -> Response {
let e = LegacyErrorEnvelope {
@@ -327,61 +333,179 @@ pub(crate) fn ssrf_error_to_bad_request_reason(err: &SafeFetchError) -> &'static
},
}
}
pub(crate) fn allowed_origins_for_state(state: &RouterState, include_telemetry: bool) -> Vec<String> {
pub(crate) const MOBILE_CLIENT_ORIGINS: &[&str] = &["https://localhost", "capacitor://localhost", "ionic://localhost"];
pub(crate) const DESKTOP_CLIENT_ORIGINS: &[&str] = &["assets://.", "assets://another-host", "file://"];
pub(crate) const CORS_ALLOWED_METHODS: &str = "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS";
pub(crate) const CORS_ALLOWED_HEADERS: &str = "accept, authorization, content-type, x-affine-version, x-affine-client-kind, x-operation-name, x-request-id, x-captcha-token, x-captcha-challenge, x-captcha-provider, x-affine-csrf-token, x-requested-with, range";
pub(crate) const CORS_EXPOSED_HEADERS: &str = "content-length, content-range, x-request-id";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CorsOriginScope {
Global,
Worker,
Telemetry,
}
fn is_dev_loopback_origin(origin: &str) -> bool {
let Ok(parsed) = Url::parse(origin) else {
return false;
};
if !matches!(parsed.scheme(), "http" | "https") {
return false;
}
let Some(host) = parsed.host_str() else {
return false;
};
let norm = host.trim_matches(['[', ']']).to_ascii_lowercase();
matches!(norm.as_str(), "localhost" | "127.0.0.1" | "::1")
}
pub(crate) fn normalize_cors_origin(origin: &str) -> Option<String> {
let trimmed = origin.trim();
if trimmed.is_empty() || trimmed == "null" {
return None;
}
if DESKTOP_CLIENT_ORIGINS.contains(&trimmed) || MOBILE_CLIENT_ORIGINS.contains(&trimmed) {
return Some(trimmed.to_owned());
}
let mut parsed = Url::parse(trimmed).ok()?;
if parsed.scheme() == "ws" {
let _ = parsed.set_scheme("http");
} else if parsed.scheme() == "wss" {
let _ = parsed.set_scheme("https");
}
match parsed.scheme() {
"http" | "https" => Some(parsed.origin().ascii_serialization()),
"assets" => {
let host = parsed.host_str().unwrap_or("");
Some(format!("assets://{host}"))
}
"file" => Some("file://".to_owned()),
_ => None,
}
}
pub(crate) fn is_cors_origin_allowed(origin: &str, allowed: &[String], dev_mode: bool) -> bool {
let trimmed = origin.trim();
if trimmed.is_empty() || trimmed == "null" {
return false;
}
if allowed.iter().any(|e| e == trimmed) {
return true;
}
if let Some(norm) = normalize_cors_origin(trimmed)
&& allowed.iter().any(|e| e == &norm)
{
return true;
}
dev_mode && is_dev_loopback_origin(trimmed)
}
fn push_normalized_origin(out: &mut Vec<String>, raw: &str, default_scheme: &str) {
let t = raw.trim().trim_end_matches('/');
if t.is_empty() {
return;
}
if DESKTOP_CLIENT_ORIGINS.contains(&t) || MOBILE_CLIENT_ORIGINS.contains(&t) {
if !out.iter().any(|x| x == t) {
out.push(t.to_owned());
}
return;
}
let cand = if t.contains("://") {
t.to_owned()
} else {
format!("{default_scheme}://{t}")
};
if let Ok(u) = Url::parse(&cand)
&& let Some(o) = match u.scheme() {
"http" | "https" => Some(u.origin().ascii_serialization()),
"assets" => Some(format!("assets://{}", u.host_str().unwrap_or(""))),
"file" => Some("file://".to_owned()),
_ => None,
}
&& !out.contains(&o)
{
out.push(o);
}
}
pub(crate) async fn allowed_origins_for_state_async(state: &RouterState, scope: CorsOriginScope) -> Vec<String> {
let cfg = state.app.config.load();
let mut out = Vec::new();
let scheme = Url::parse(&cfg.external_url).map_or("http".to_owned(), |u| u.scheme().to_owned());
let extra = if include_telemetry {
&cfg.telemetry_allowed_origins[..]
} else {
&[]
};
for raw in std::iter::once(cfg.external_url.as_str())
.chain(cfg.app_config_baseline.server.hosts.iter().map(String::as_str))
.chain(extra.iter().map(String::as_str))
{
let t = raw.trim().trim_end_matches('/');
let cand = if t.contains("://") {
t.to_owned()
} else {
format!("{scheme}://{t}")
};
if !t.is_empty()
&& let Ok(u) = Url::parse(&cand)
&& let Some(o) = match u.scheme() {
"http" | "https" => Some(u.origin().ascii_serialization()),
"assets" if include_telemetry => Some(u.as_str().to_owned()),
_ => None,
for &o in MOBILE_CLIENT_ORIGINS.iter().chain(DESKTOP_CLIENT_ORIGINS.iter()) {
out.push(o.to_owned());
}
push_normalized_origin(&mut out, &cfg.external_url, &scheme);
for h in &cfg.app_config_baseline.server.hosts {
push_normalized_origin(&mut out, h, &scheme);
}
if scope == CorsOriginScope::Telemetry {
for o in &cfg.telemetry_allowed_origins {
push_normalized_origin(&mut out, o, &scheme);
}
}
if let Ok(eff) = state.app.app_config.get_effective_app_config().await {
if let Some(hosts) = eff.pointer("/server/hosts").and_then(Value::as_array) {
for h in hosts.iter().filter_map(Value::as_str) {
push_normalized_origin(&mut out, h, &scheme);
}
&& !out.contains(&o)
}
if let Some(url_origins) = eff.pointer("/url/allowedOrigins").and_then(Value::as_array) {
for o in url_origins.iter().filter_map(Value::as_str) {
push_normalized_origin(&mut out, o, &scheme);
}
}
if scope == CorsOriginScope::Worker
&& let Some(worker_origins) = eff.pointer("/worker/allowedOrigin").and_then(Value::as_array)
{
out.push(o);
for o in worker_origins.iter().filter_map(Value::as_str) {
push_normalized_origin(&mut out, o, &scheme);
}
}
if scope == CorsOriginScope::Telemetry
&& let Some(tel_origins) = eff.pointer("/telemetry/allowedOrigin").and_then(Value::as_array)
{
for o in tel_origins.iter().filter_map(Value::as_str) {
push_normalized_origin(&mut out, o, &scheme);
}
}
}
out
}
pub(crate) fn append_cors_origin(target: &mut HeaderMap, origin: Option<&str>, allowed: &[String]) {
if let Some(o) = origin
&& allowed.iter().any(|e| e == o)
&& is_cors_origin_allowed(o, allowed, false)
&& let Ok(val) = HeaderValue::from_str(o)
{
target.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, val);
target.insert(header::VARY, HeaderValue::from_static("Origin"));
}
}
fn check_origin_or_referer(headers: &HeaderMap, allowed: &[String]) -> bool {
h_str(headers, header::ORIGIN).is_some_and(|o| allowed.iter().any(|e| e == o))
|| h_str(headers, header::REFERER)
.and_then(|r| Url::parse(r).ok())
.is_some_and(|u| {
let s = u.origin().ascii_serialization();
let o = if s == "null" {
format!("{}://{}", u.scheme(), u.host_str().unwrap_or(""))
} else {
s
};
allowed.iter().any(|e| e == &o)
})
pub(crate) fn check_origin_or_referer(headers: &HeaderMap, allowed: &[String], dev_mode: bool) -> bool {
let origin = h_str(headers, header::ORIGIN).map(str::trim);
if let Some(o) = origin
&& o != "null"
&& !o.is_empty()
&& is_cors_origin_allowed(o, allowed, dev_mode)
{
return true;
}
h_str(headers, header::REFERER).is_some_and(|r| {
let Ok(u) = Url::parse(r) else {
return false;
};
let candidate = match u.scheme() {
"http" | "https" => u.origin().ascii_serialization(),
"assets" => format!("assets://{}", u.host_str().unwrap_or("")),
"file" => "file://".to_owned(),
_ => return false,
};
is_cors_origin_allowed(&candidate, allowed, dev_mode)
})
}
fn fix_url_with_policy(raw: &str, allow_private: &[Origin]) -> Option<Url> {
let t = raw.trim();
@@ -550,6 +674,7 @@ async fn handle_image_proxy(
.and_then(|mut s| s.next_back())
.filter(|s| !s.is_empty());
apply_blob_security_headers(h, Some(&mime), fname);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=86400"));
if mime != "image/svg+xml"
&& let Some(val) = cd.as_deref().and_then(|c| HeaderValue::from_str(c).ok())
{
@@ -619,6 +744,72 @@ fn decode_html_bytes(bytes: &[u8], content_type: Option<&str>) -> String {
|e| e.decode(bytes).0.into_owned(),
)
}
const MAX_LINK_PREVIEW_BODY_BYTES: usize = 16 * 1024;
const MAX_PREVIEW_TEXT_BYTES: usize = 4096;
fn clamp_utf8_bytes(s: &str, max_bytes: usize) -> &str {
if s.len() <= max_bytes {
return s;
}
let mut end = max_bytes;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
fn decode_html_entities(input: &str) -> String {
let input = clamp_utf8_bytes(input, MAX_PREVIEW_TEXT_BYTES);
if !input.contains('&') {
return input.to_owned();
}
let mut out = String::with_capacity(input.len());
let bytes = input.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'&'
&& let Some(semi_rel) = bytes[i + 1..].iter().take(13).position(|&b| b == b';')
&& semi_rel > 0
&& semi_rel <= 12
{
let entity = &input[i + 1..i + 1 + semi_rel];
let decoded = match entity {
"amp" => Some('&'.to_string()),
"lt" => Some('<'.to_string()),
"gt" => Some('>'.to_string()),
"quot" => Some('"'.to_string()),
"apos" => Some('\''.to_string()),
"nbsp" => Some('\u{00A0}'.to_string()),
"ndash" => Some('\u{2013}'.to_string()),
"mdash" => Some('\u{2014}'.to_string()),
"hellip" => Some('\u{2026}'.to_string()),
"copy" => Some('\u{00A9}'.to_string()),
"reg" => Some('\u{00AE}'.to_string()),
"trade" => Some('\u{2122}'.to_string()),
s if s.starts_with("#x") || s.starts_with("#X") => u32::from_str_radix(&s[2..], 16)
.ok()
.and_then(char::from_u32)
.map(|c| c.to_string()),
s if s.starts_with('#') => s[1..]
.parse::<u32>()
.ok()
.and_then(char::from_u32)
.map(|c| c.to_string()),
_ => None,
};
if let Some(rep) = decoded {
out.push_str(&rep);
i += semi_rel + 2;
continue;
}
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn parse_html_preview(html: &str, final_url: &Url) -> (serde_json::Map<String, Value>, Vec<String>) {
let (mut title, mut site_name, mut desc, mut media_type) = (None, None, None, None);
let (mut images, mut videos, mut favicons) = (Vec::new(), Vec::new(), Vec::new());
@@ -627,8 +818,8 @@ fn parse_html_preview(html: &str, final_url: &Url) -> (serde_json::Map<String, V
&& let Some(gt) = lower[ts..].find('>')
&& let Some(te) = lower[ts + gt + 1..].find("</title>")
{
let t = html[ts + gt + 1..ts + gt + 1 + te].trim();
title = (!t.is_empty()).then(|| t.to_owned());
let t = decode_html_entities(html[ts + gt + 1..ts + gt + 1 + te].trim());
title = (!t.is_empty()).then_some(t);
}
let mut cursor = 0usize;
while let Some(rs) = html[cursor..].find('<') {
@@ -644,10 +835,11 @@ fn parse_html_preview(html: &str, final_url: &Url) -> (serde_json::Map<String, V
.to_ascii_lowercase();
match name.as_str() {
"meta" => {
if let (Some(p), Some(c)) = (
if let (Some(p), Some(raw_c)) = (
extract_attr(tag, "property").or_else(|| extract_attr(tag, "name")),
extract_attr(tag, "content"),
) {
let c = decode_html_entities(&raw_c);
match p.to_ascii_lowercase().as_str() {
"og:title" => title = Some(c),
"og:site_name" => site_name = Some(c),
@@ -662,12 +854,16 @@ fn parse_html_preview(html: &str, final_url: &Url) -> (serde_json::Map<String, V
}
"link" if extract_attr(tag, "rel").is_some_and(|r| r.to_ascii_lowercase().contains("icon")) => {
if let Some(href) = extract_attr(tag, "href") {
push_unique_url(&href, final_url, &mut favicons);
push_unique_url(&decode_html_entities(&href), final_url, &mut favicons);
}
}
"img" | "video" => {
if let Some(src) = extract_attr(tag, "src") {
push_unique_url(&src, final_url, if name == "img" { &mut images } else { &mut videos });
push_unique_url(
&decode_html_entities(&src),
final_url,
if name == "img" { &mut images } else { &mut videos },
);
}
}
_ => {}
@@ -696,6 +892,9 @@ async fn handle_link_preview(
hdrs: HeaderMap,
body: bytes::Bytes,
) -> Response {
if body.len() > MAX_LINK_PREVIEW_BODY_BYTES {
return StatusCode::PAYLOAD_TOO_LARGE.into_response();
}
let (st, hdrs) = (&st, &hdrs);
with_worker_throttle(
st,
@@ -2152,6 +2152,7 @@ fn user_by_email_scope_visibility_and_strict_throttle_parity() {
.method("POST")
.uri("/graphql")
.header(header::COOKIE, &alice_cookie)
.header("apollo-require-preflight", "true")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
@@ -769,13 +769,13 @@ fn security_challenges_email_change_password_reset_keyring_and_throttle_adversar
.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);
// Valid changePassword succeeds within dynamic auth.passwordRequirements, revokes old Cookie + Bearer, emits user.profile.changed + doc.grants.changed for BOTH physical and logical alias rooms
let pw_valid = "ValidPassword123456!";
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 }),
json!({ "p": pw_valid, "t": pw_token1, "uid": alice_id }),
)
.await;
assert_eq!(resp["data"]["changePassword"], true, "resp: {resp}");
@@ -805,7 +805,7 @@ fn security_challenges_email_change_password_reset_keyring_and_throttle_adversar
);
}
// 4,097-byte password also succeeds and revokes sessions
// Oversized 4,097-byte password is rejected with INVALID_PASSWORD_LENGTH; a valid second password succeeds and revokes sessions.
let (_, url_4097) = gql(
&router,
Some(&admin_cookie),
@@ -829,8 +829,19 @@ fn security_challenges_email_change_password_reset_keyring_and_throttle_adversar
)
.await;
assert_eq!(
resp_4097["data"]["changePassword"], true,
"4097-byte pw failed: {resp_4097}"
resp_4097["errors"][0]["extensions"]["name"], "INVALID_PASSWORD_LENGTH",
"4097-byte pw must be rejected: {resp_4097}"
);
let (_, resp_valid2) = gql(
&router,
None,
"mutation($p: String!, $t: String!, $uid: String!) { changePassword(newPassword: $p, token: $t, userId: $uid) }",
json!({ "p": "SecondValidPass123!", "t": tok_4097, "uid": alice_id }),
)
.await;
assert_eq!(
resp_valid2["data"]["changePassword"], true,
"second valid pw failed: {resp_valid2}"
);
let (_, sess_after_4097) = send_json(
&router,
@@ -850,7 +861,7 @@ fn security_challenges_email_change_password_reset_keyring_and_throttle_adversar
let (_, resp) = gql(
&router,
None,
"mutation($t: String!, $uid: String!) { changePassword(newPassword: \"Other1!\", token: $t, userId: $uid) }",
"mutation($t: String!, $uid: String!) { changePassword(newPassword: \"OtherPass123!\", token: $t, userId: $uid) }",
json!({ "t": tok, "uid": alice_id }),
)
.await;
@@ -896,7 +896,7 @@ fn oauth_apple_signup_matrix_state_ttl_role_and_strict_throttle_adversarial() {
Some(json!({ "email": "matrix-new@example.test" })),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(st, StatusCode::CREATED);
assert_eq!(body["registered"], false);
assert_eq!(body["methods"]["magicLink"]["available"], false);
assert_eq!(body["methods"]["oauth"]["available"], true);
@@ -960,7 +960,7 @@ fn oauth_apple_signup_matrix_state_ttl_role_and_strict_throttle_adversarial() {
Some(json!({ "email": "invited-placeholder@example.test" })),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(st, StatusCode::CREATED);
assert_eq!(body["registered"], false);
assert_eq!(body["methods"]["magicLink"]["available"], true);
@@ -977,7 +977,7 @@ fn oauth_apple_signup_matrix_state_ttl_role_and_strict_throttle_adversarial() {
Some(json!({ "email": "matrix-new@example.test" })),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(st, StatusCode::CREATED);
assert_eq!(body["registered"], false);
assert_eq!(body["methods"]["password"]["available"], false);
assert_eq!(body["methods"]["magicLink"]["available"], false);
@@ -1000,7 +1000,7 @@ fn oauth_apple_signup_matrix_state_ttl_role_and_strict_throttle_adversarial() {
Some(json!({ "email": "brand-new@example.test" })),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(st, StatusCode::CREATED);
assert_eq!(body["methods"]["magicLink"]["available"], true);
assert_eq!(body["methods"]["oauth"]["available"], false);
@@ -150,12 +150,10 @@ fn calendar_rest_webhook_and_oauth_callback_validation() {
.execute(state.db.pool())
.await
.expect("clear explicit webhook token");
let generated_token = {
let mut guard = state.calendar_webhook_token.lock().unwrap();
let tok = Uuid::new_v4().to_string();
*guard = Some(tok.clone());
tok
};
let generated_token = state
.calendar
.webhook_token_from_config(&server_domain::calendar::google::CalendarGoogleConfig::default())
.await;
let resp = router
.clone()
.oneshot(
@@ -133,7 +133,7 @@ fn doc_sharing_histories_comments_notifications_open_app_and_selfhost_license()
)
.await
.unwrap();
assert_eq!(setup_resp.status(), StatusCode::CREATED);
assert_eq!(setup_resp.status(), StatusCode::OK);
let owner_cookie = cookie_header_from_response(&setup_resp);
let owner_id = body_json(setup_resp).await["id"].as_str().unwrap().to_owned();
@@ -546,7 +546,7 @@ fn doc_sharing_histories_comments_notifications_open_app_and_selfhost_license()
)
.await
.unwrap();
assert_eq!(redeem_ok.status(), StatusCode::CREATED);
assert_eq!(redeem_ok.status(), StatusCode::OK);
assert_eq!(body_json(redeem_ok).await["id"], owner_id);
// Second redemption of the same code must fail with 400 INVALID_AUTH_STATE.
@@ -800,7 +800,7 @@ fn billing_spi_hooks_team_owner_delete_block_and_customer_portal() {
)
.await
.unwrap();
assert_eq!(setup.status(), StatusCode::CREATED);
assert_eq!(setup.status(), StatusCode::OK);
let owner_cookie = cookie_header_from_response(&setup);
let member_id = format!("usr_{}", uuid::Uuid::new_v4().simple());
@@ -824,7 +824,7 @@ fn billing_spi_hooks_team_owner_delete_block_and_customer_portal() {
)
.await
.unwrap();
assert_eq!(member_login.status(), StatusCode::CREATED);
assert_eq!(member_login.status(), StatusCode::OK);
let member_cookie = cookie_header_from_response(&member_login);
// Create workspace owned by owner, mark it as Team in mock QuotaGate.
@@ -934,7 +934,7 @@ async fn create_user_and_cookie(
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
assert_eq!(resp.status(), StatusCode::OK);
let cookie = cookie_header_from_response(&resp);
(user_id, cookie)
}
@@ -1400,7 +1400,7 @@ fn doc_acl_owner_protection_pagination_attachments_open_app_and_licenses() {
)
.await
.unwrap();
assert_eq!(native_resp.status(), StatusCode::CREATED);
assert_eq!(native_resp.status(), StatusCode::OK);
let set_cookies: Vec<String> = native_resp
.headers()
.get_all(header::SET_COOKIE)
File diff suppressed because it is too large. Load diff
@@ -121,7 +121,7 @@ fn bearer_jwt_auth_preflight_profile_avatar_and_session_cleanup() {
)
.await
.unwrap();
assert_eq!(create_resp.status(), StatusCode::CREATED);
assert_eq!(create_resp.status(), StatusCode::OK);
let set_cookies: Vec<String> = create_resp
.headers()
.get_all(header::SET_COOKIE)
@@ -154,7 +154,7 @@ fn bearer_jwt_auth_preflight_profile_avatar_and_session_cleanup() {
)
.await
.unwrap();
assert_eq!(preflight_resp.status(), StatusCode::OK);
assert_eq!(preflight_resp.status(), StatusCode::CREATED);
let preflight: serde_json::Value = serde_json::from_slice(
&axum::body::to_bytes(preflight_resp.into_body(), 64 * 1024)
.await
@@ -567,8 +567,8 @@ fn bearer_jwt_auth_preflight_profile_avatar_and_session_cleanup() {
"{ currentUser { id } }",
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(json["name"], "AUTH_SESSION_REVOKED");
assert_eq!(status, StatusCode::OK);
assert_eq!(json["errors"][0]["extensions"]["name"], "AUTH_SESSION_REVOKED");
// 5. updateProfile updates name and persists.
let (status, json) = post_graphql(
@@ -945,7 +945,7 @@ fn per_doc_acl_invite_link_accept_and_avatar_webp_transcode() {
}),
)
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(status, StatusCode::OK);
let alice_id: String = sqlx::query_scalar("SELECT id FROM users WHERE email = 'alice-acl@affine.test'")
.fetch_one(db.pool())
@@ -1558,7 +1558,7 @@ fn native_session_exchange_single_connection_pool_and_zod_validation() {
}),
)
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(status, StatusCode::OK);
// Sign in as native client to get exchangeCode.
let signin = app
@@ -180,7 +180,7 @@ fn create_blob_upload_graphql_then_set_blob_and_r2_proxy_zero_byte_preauth() {
)
.await
.expect("create admin");
assert_eq!(setup_resp.status(), StatusCode::CREATED);
assert_eq!(setup_resp.status(), StatusCode::OK);
let sign_in = app
.clone()
.oneshot(
@@ -245,6 +245,7 @@ fn create_blob_upload_graphql_then_set_blob_and_r2_proxy_zero_byte_preauth() {
.method("POST")
.uri("/graphql")
.header(header::COOKIE, &cookie)
.header("apollo-require-preflight", "true")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
@@ -883,6 +884,7 @@ fn create_blob_upload_graphql_then_set_blob_and_r2_proxy_zero_byte_preauth() {
.method("POST")
.uri("/graphql")
.header(header::COOKIE, &cookie)
.header("apollo-require-preflight", "true")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
@@ -1234,7 +1234,8 @@ fn worker_proxy_doc_renderer_and_telemetry_contracts() {
assert!(ws_html.contains("apple-touch-icon"));
assert!(ws_html.contains("emotion-insertion-point"));
assert!(
ws_html.contains("api&#x2f;avatars&#x2f;ws-av-key") || ws_html.contains("/api/avatars/ws-av-key"),
ws_html.contains("api&#x2f;workspaces&#x2f;ws-m4&#x2f;blobs&#x2f;v1&#x2f;ws-av-key")
|| ws_html.contains("/api/workspaces/ws-m4/blobs/v1/ws-av-key"),
"{ws_html}"
);
+47 -5
View File
@@ -400,7 +400,7 @@ fn check_origin_with_policy(
if allowed_origins.iter().any(|allowed| allowed == trimmed_slash) {
return Ok(Some(origin.to_owned()));
}
if (allow_dev_loopback || allowed_origins.is_empty()) && is_dev_loopback_origin(origin) {
if allow_dev_loopback && is_dev_loopback_origin(origin) {
return Ok(Some(origin.to_owned()));
}
Err(())
@@ -581,6 +581,28 @@ impl EngineIoState {
return;
};
let mut arg = arg;
if matches!(
event_name,
"realtime:request" | "realtime:subscribe" | "realtime:unsubscribe" | "space:join-batch"
) && let Some(obj) = arg.as_object_mut()
{
let has_ver = obj
.get("clientVersion")
.and_then(Value::as_str)
.is_some_and(|s| !s.trim().is_empty());
if !has_ver
&& let Some(hdr_ver) = session
.headers
.get("x-affine-version")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty())
{
obj.insert("clientVersion".to_owned(), Value::String(hdr_ver.to_owned()));
}
}
let response = self
.gateway
.handle_event(self, &session.socket_id, &user, event_name, arg)
@@ -671,7 +693,24 @@ impl EngineIoState {
if session.sio_connected.load(Ordering::Acquire) {
return true;
}
match self.authenticator.authenticate(&session.headers).await {
let mut effective_headers = session.headers.clone();
let auth_json = payload[1..].trim();
if auth_json.starts_with('{')
&& let Ok(auth_obj) = serde_json::from_str::<Value>(auth_json)
&& auth_obj
.get("tokenType")
.and_then(Value::as_str)
.is_some_and(|t| t.eq_ignore_ascii_case("jwt"))
&& let Some(tok) = auth_obj
.get("token")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
&& let Ok(hv) = header::HeaderValue::from_str(&format!("Bearer {tok}"))
{
effective_headers.insert(header::AUTHORIZATION, hv);
}
match self.authenticator.authenticate(&effective_headers).await {
Ok(user) => {
if session.sio_connected.swap(true, Ordering::AcqRel) {
return true;
@@ -814,7 +853,9 @@ async fn handle_options(State(state): State<Arc<EngineIoState>>, headers: Header
);
h.insert(
header::ACCESS_CONTROL_ALLOW_HEADERS,
header::HeaderValue::from_static("Content-Type, Authorization, Cookie"),
header::HeaderValue::from_static(
"accept, authorization, content-type, cookie, x-affine-version, x-affine-client-kind, x-operation-name, x-request-id, x-captcha-token, x-captcha-challenge, x-captcha-provider, x-affine-csrf-token, x-requested-with, range",
),
);
attach_cors_headers(resp, origin.as_deref())
}
@@ -1174,9 +1215,10 @@ mod tests {
assert!(check(&["http://affine.parity.test"], false, Some("ws://affine.parity.test")).is_ok());
assert!(check(&["https://app.affine.pro"], false, Some("ws://app.affine.pro")).is_err());
// 3. Empty allowed_origins NEVER reflects arbitrary external origins; only loopback + native.
// 3. Empty allowed_origins NEVER reflects arbitrary external origins or production loopback.
assert!(check(&[], false, Some("https://evil.example")).is_err());
assert!(check(&[], false, Some("http://127.0.0.1:3010")).is_ok());
assert!(check(&[], false, Some("http://127.0.0.1:3010")).is_err());
assert!(check(&[], true, Some("http://127.0.0.1:3010")).is_ok());
// 4. Production mode (allow_dev_loopback = false) with explicit allowed_origins rejects unconfigured loopback ports.
assert!(check(&["https://app.affine.pro"], false, Some("http://localhost:8080")).is_err());
@@ -10,6 +10,12 @@ pub enum SyncError {
#[error("bad request: {0}")]
BadRequest(String),
#[error("query is too long (max {max})")]
QueryTooLong { max: usize },
#[error("copilot is disabled")]
CopilotDisabled,
#[error("unsupported client version: {client_version} (required {required_version})")]
UnsupportedClientVersion {
client_version: String,
+101 -1
View File
@@ -99,7 +99,8 @@ pub struct SyncAwarenessEventPayload {
#[serde(rename_all = "camelCase")]
pub struct RealtimeTopicChangedPayload {
pub topic: String,
pub room: String,
#[serde(default)]
pub room: Option<String>,
#[serde(default)]
pub input: Value,
#[serde(default)]
@@ -108,6 +109,53 @@ pub struct RealtimeTopicChangedPayload {
pub payload: Value,
}
impl RealtimeTopicChangedPayload {
/// Returns the explicit `room` when present, or derives it from `topic` + `input`
/// so cross-generation Node `v0.27.5` events (which omit `room`) are never dropped.
pub fn resolved_room(&self) -> Option<String> {
if let Some(r) = self.room.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
return Some(r.to_owned());
}
let ws = self
.input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let doc = self
.input
.get("docId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let uid = self
.input
.get("userId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let task_id = self
.input
.get("taskId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
match self.topic.as_str() {
"workspace.access.changed" => ws.map(|w| format!("workspace:{w}:access")),
"workspace.config.changed" => ws.map(|w| format!("workspace:{w}:config")),
"workspace.members.changed" => ws.map(|w| format!("workspace:{w}:members")),
"workspace.invite-link.changed" => ws.map(|w| format!("workspace:{w}:invite-link")),
"workspace.quota-state.changed" => ws.map(|w| format!("workspace:{w}:quota-state")),
"workspace.embedding.progress.changed" => ws.map(|w| format!("workspace:{w}:embedding-progress")),
"doc.share-state.changed" => ws.zip(doc).map(|(w, d)| format!("workspace:{w}:doc:{d}:share-state")),
"doc.grants.changed" => ws.zip(doc).map(|(w, d)| format!("workspace:{w}:doc:{d}:grants")),
"comment.changed" => ws.zip(doc).map(|(w, d)| format!("workspace:{w}:doc:{d}:comment")),
"copilot.transcript.task.changed" => ws.zip(task_id).map(|(w, t)| format!("copilot:transcript:{w}:{t}")),
"notification.count.changed" => uid.map(|u| format!("user:{u}:notification")),
"user.settings.changed" => uid.map(|u| format!("user:{u}:settings")),
"user.profile.changed" => uid.map(|u| format!("user:{u}:profile")),
"user.quota-state.changed" => uid.map(|u| format!("user:{u}:quota-state")),
_ => None,
}
}
}
/// Incoming cluster events delivered to the local `SpaceSyncGateway`.
#[derive(Clone, Debug)]
pub enum ClusterSyncEvent {
@@ -515,3 +563,55 @@ async fn run_subscriber_loop(
}
}
}
#[cfg(test)]
mod realtime_topic_tests {
use super::*;
#[test]
fn realtime_topic_changed_deserializes_without_room_and_derives_room() {
let raw = serde_json::json!({
"topic": "doc.share-state.changed",
"input": { "workspaceId": "ws-1", "docId": "doc-2" },
"event": { "changed": true }
});
let payload: RealtimeTopicChangedPayload = serde_json::from_value(raw).expect("deserialize without room");
assert_eq!(payload.room, None);
assert_eq!(
payload.resolved_room().as_deref(),
Some("workspace:ws-1:doc:doc-2:share-state")
);
let raw_user = serde_json::json!({
"topic": "user.quota-state.changed",
"input": { "userId": "u-42" },
"event": {}
});
let payload_user: RealtimeTopicChangedPayload = serde_json::from_value(raw_user).expect("deserialize user topic");
assert_eq!(payload_user.resolved_room().as_deref(), Some("user:u-42:quota-state"));
let raw_transcript = serde_json::json!({
"topic": "copilot.transcript.task.changed",
"input": { "workspaceId": "ws-1", "taskId": "task-9" },
"event": {}
});
let payload_transcript: RealtimeTopicChangedPayload =
serde_json::from_value(raw_transcript).expect("deserialize transcript topic");
assert_eq!(
payload_transcript.resolved_room().as_deref(),
Some("copilot:transcript:ws-1:task-9")
);
let raw_embed = serde_json::json!({
"topic": "workspace.embedding.progress.changed",
"input": { "workspaceId": "ws-1" },
"event": {}
});
let payload_embed: RealtimeTopicChangedPayload =
serde_json::from_value(raw_embed).expect("deserialize embedding progress topic");
assert_eq!(
payload_embed.resolved_room().as_deref(),
Some("workspace:ws-1:embedding-progress")
);
}
}
+160 -7
View File
@@ -325,11 +325,14 @@ impl SpaceSyncGateway {
}
}
Ok(ClusterSyncEvent::RealtimeTopicChanged(payload)) => {
let Some(room) = payload.resolved_room() else {
continue;
};
let recipients_with_users: Vec<(String, Option<String>)> = {
let rooms = gateway.rooms.read().await;
rooms
.room_sockets
.get(&payload.room)
.get(&room)
.map(|s| {
s.iter()
.map(|sid| (sid.clone(), rooms.socket_users.get(sid).cloned()))
@@ -337,7 +340,7 @@ impl SpaceSyncGateway {
})
.unwrap_or_default()
};
let doc_room_check = parse_doc_realtime_room(&payload.room);
let doc_room_check = parse_doc_realtime_room(&room);
let event_val = if payload.event.is_null() {
payload.payload
} else {
@@ -364,8 +367,8 @@ impl SpaceSyncGateway {
let mut rooms = gateway.rooms.write().await;
rooms
.realtime_subscriptions
.retain(|_, (other_sid, other_room)| !(other_sid == &sid && other_room == &payload.room));
rooms.leave_room(&sid, &payload.room);
.retain(|_, (other_sid, other_room)| !(other_sid == &sid && other_room == &room));
rooms.leave_room(&sid, &room);
continue;
}
}
@@ -1364,6 +1367,99 @@ impl SpaceSyncGateway {
.await?;
Ok(json!({ "data": changes }))
}
"workspace.members.get" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let skip = input.get("skip").and_then(Value::as_i64).unwrap_or(0).max(0);
let take = input.get("take").and_then(Value::as_i64).unwrap_or(8).clamp(1, 100);
let query = input.get("query").and_then(Value::as_str);
let members = self
.storage
.get_workspace_members_snapshot(workspace_id, &user.id, skip, take, query)
.await?;
Ok(json!({ "data": members }))
}
"workspace.invite-link.get" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let invite_link = self
.storage
.get_workspace_invite_link_snapshot(workspace_id, &user.id)
.await?;
Ok(json!({ "data": { "inviteLink": invite_link } }))
}
"user.profile.get" => {
let profile = self.storage.get_user_profile_snapshot(&user.id).await?;
Ok(json!({ "data": { "user": profile } }))
}
"user.quota-state.get" => {
let state = self.storage.get_user_quota_state_snapshot(&user.id).await?;
Ok(json!({ "data": { "state": state } }))
}
"workspace.quota-state.get" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let state = self
.storage
.get_workspace_quota_state_snapshot(workspace_id, &user.id)
.await?;
Ok(json!({ "data": { "state": state } }))
}
"workspace.embedding.progress.get" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let progress = self
.storage
.copilot_realtime_get_embedding_progress(&user.id, workspace_id)
.await?;
Ok(json!({ "data": progress }))
}
"copilot.transcript.task.get" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let blob_id = input.get("blobId").and_then(Value::as_str).filter(|s| !s.is_empty());
let task_id = input.get("taskId").and_then(Value::as_str).filter(|s| !s.is_empty());
if blob_id.is_none() && task_id.is_none() {
return Err(SyncError::BadRequest("Missing blobId or taskId".into()));
}
let task = self
.storage
.copilot_realtime_get_transcript_task(&user.id, workspace_id, blob_id, task_id)
.await?;
Ok(json!({ "data": { "task": task } }))
}
"copilot.transcript.task.retry" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let task_id = input
.get("taskId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing taskId".into()))?;
let task = self
.storage
.copilot_realtime_retry_transcript_task(&user.id, workspace_id, task_id)
.await?;
Ok(json!({ "data": { "task": task } }))
}
other => Err(SyncError::BadRequest(format!("Unsupported realtime op: {other}"))),
}
}
@@ -1432,9 +1528,60 @@ impl SpaceSyncGateway {
.await?;
format!("workspace:{workspace_id}:doc:{doc_id}:{scope}")
}
"workspace.invite-link.changed" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
self
.storage
.assert_workspace_invite_manage(workspace_id, &user.id)
.await?;
format!("workspace:{workspace_id}:invite-link")
}
"workspace.quota-state.changed" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
self.storage.assert_workspace_readable(workspace_id, &user.id).await?;
format!("workspace:{workspace_id}:quota-state")
}
"workspace.embedding.progress.changed" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
self
.storage
.copilot_realtime_authorize_embedding_progress(&user.id, workspace_id)
.await?;
format!("workspace:{workspace_id}:embedding-progress")
}
"copilot.transcript.task.changed" => {
let workspace_id = input
.get("workspaceId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing workspaceId".into()))?;
let task_id = input
.get("taskId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| SyncError::BadRequest("Missing taskId".into()))?;
self
.storage
.copilot_realtime_authorize_transcript_task(&user.id, workspace_id, task_id)
.await?;
format!("copilot:transcript:{workspace_id}:{task_id}")
}
"notification.count.changed" => format!("user:{}:notification", user.id),
"user.settings.changed" => format!("user:{}:settings", user.id),
"user.profile.changed" => format!("user:{}:profile", user.id),
"user.quota-state.changed" => format!("user:{}:quota-state", user.id),
other => return Err(SyncError::BadRequest(format!("Unsupported realtime topic: {other}"))),
};
@@ -1829,11 +1976,17 @@ fn is_supported_realtime_client_version(ver: &str) -> bool {
if maj > 0 || min >= 26 {
return true;
}
// Allow canary date versions (e.g. `0.0.0-canary.20260101` or `0.0.0-20260101`).
// Allow non-expired canary date versions (within 30 days of current UTC date).
if let Some(pre) = pre {
let digits: String = pre.chars().filter(|c| c.is_ascii_digit()).collect();
if digits.len() >= 8 && pre.to_ascii_lowercase().contains("canary") {
return true;
if digits.len() >= 8
&& pre.to_ascii_lowercase().contains("canary")
&& let Ok(date) = chrono::NaiveDate::parse_from_str(&digits[..8], "%Y%m%d")
{
let today = chrono::Utc::now().date_naive();
if (today - date).num_days() <= 30 {
return true;
}
}
}
false
@@ -48,6 +48,24 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
data: None,
request_id,
},
SyncError::QueryTooLong { max } => WebsocketErrorBody {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "QUERY_TOO_LONG".into(),
error_type: "BAD_REQUEST".into(),
name: "QUERY_TOO_LONG".into(),
message: format!("Query is too long, max length is {max}."),
data: Some(json!({ "max": max })),
request_id,
},
SyncError::CopilotDisabled => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "COPILOT_DISABLED".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "COPILOT_DISABLED".into(),
message: "Copilot is disabled.".into(),
data: None,
request_id,
},
SyncError::UnsupportedClientVersion {
client_version,
required_version,
+34 -2
View File
@@ -27,13 +27,15 @@ use crate::{
storage::SyncStorage,
};
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct SyncConfig {
pub redis_url: Option<String>,
pub session_redis_url: Option<String>,
pub origin_channel: String,
pub origin_id: Option<String>,
pub deployment_prefix: String,
/// Public server base URL used to construct workspace invite links.
pub external_url: String,
/// Allowed browser `Origin` values (scheme + host + optional port) for
/// `/socket.io/` CORS / WebSocket handshake validation.
pub allowed_origins: Vec<String>,
@@ -41,6 +43,25 @@ pub struct SyncConfig {
/// permitted in addition to `allowed_origins` and the 6 native client
/// origins (enabled in dev/test channels, disabled in production/stable).
pub allow_dev_loopback: bool,
/// Optional commercial Copilot realtime handler (`copilot.transcript.task.*`
/// and `workspace.embedding.progress.*`). When `None`, those ops return `COPILOT_DISABLED`.
pub copilot_realtime: Option<Arc<dyn crate::storage::CopilotRealtimeHandler>>,
}
impl std::fmt::Debug for SyncConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SyncConfig")
.field("redis_url", &self.redis_url)
.field("session_redis_url", &self.session_redis_url)
.field("origin_channel", &self.origin_channel)
.field("origin_id", &self.origin_id)
.field("deployment_prefix", &self.deployment_prefix)
.field("external_url", &self.external_url)
.field("allowed_origins", &self.allowed_origins)
.field("allow_dev_loopback", &self.allow_dev_loopback)
.field("copilot_realtime", &self.copilot_realtime.is_some())
.finish()
}
}
impl SyncConfig {
@@ -58,8 +79,10 @@ impl SyncConfig {
origin_channel: format!("v2:{channel}"),
origin_id: None,
deployment_prefix: "selfhosted".to_owned(),
external_url: String::new(),
allowed_origins: Vec::new(),
allow_dev_loopback,
copilot_realtime: None,
}
}
}
@@ -108,7 +131,7 @@ impl SyncServer {
quota_gate: Arc<dyn QuotaGate>,
config: SyncConfig,
) -> Self {
let storage = match config.session_redis_url.as_deref() {
let mut storage = match config.session_redis_url.as_deref() {
Some(url) => {
match SyncStorage::with_quota_gate(db.clone(), Arc::clone(&quota_gate)).with_session_redis_url(url) {
Ok(s) => s,
@@ -120,6 +143,15 @@ impl SyncServer {
}
None => SyncStorage::with_quota_gate(db, quota_gate),
};
if let Some(url) = config.redis_url.as_deref() {
storage = storage.with_cache_redis_url(url);
}
if !config.external_url.is_empty() {
storage = storage.with_external_url(config.external_url);
}
if let Some(handler) = config.copilot_realtime {
storage = storage.with_copilot_realtime(handler);
}
let eventbus = match config.origin_id {
Some(origin_id) => {
RedisSyncBridge::start_with_origin_id(config.redis_url.as_deref(), config.origin_channel, origin_id).await
+317 -21
View File
@@ -28,6 +28,8 @@ use crate::{
},
};
#[path = "storage/realtime_snapshots.rs"]
mod realtime_snapshots;
#[path = "legacy_compat/root_lifecycle_migration.rs"]
mod root_lifecycle_migration;
#[path = "legacy_compat/userspace_redis_bridge.rs"]
@@ -318,11 +320,43 @@ impl DocRealtimeTopic {
}
}
/// Extension hook for commercial Copilot realtime operations
/// (`copilot.transcript.task.*` and `workspace.embedding.progress.*`).
/// When unconfigured (community edition), these operations return
/// [`SyncError::CopilotDisabled`].
#[async_trait::async_trait]
pub trait CopilotRealtimeHandler: Send + Sync {
async fn get_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
blob_id: Option<&str>,
task_id: Option<&str>,
) -> Result<serde_json::Value, SyncError>;
async fn retry_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<serde_json::Value, SyncError>;
async fn authorize_transcript_task(&self, user_id: &str, workspace_id: &str, task_id: &str) -> Result<(), SyncError>;
async fn get_embedding_progress(&self, user_id: &str, workspace_id: &str) -> Result<serde_json::Value, SyncError>;
async fn authorize_embedding_progress(&self, user_id: &str, workspace_id: &str) -> Result<(), SyncError>;
}
#[derive(Clone)]
pub struct SyncStorage {
db: ServerDb,
quota_gate: Arc<dyn QuotaGate>,
pub(super) db: ServerDb,
pub(super) quota_gate: Arc<dyn QuotaGate>,
session_redis: UserspaceRedisLockBackend,
pub(super) cache_redis: Option<redis::Client>,
pub(super) cache_redis_conn: Arc<tokio::sync::Mutex<Option<redis::aio::MultiplexedConnection>>>,
pub(super) external_url: String,
pub(super) copilot_realtime: Option<Arc<dyn CopilotRealtimeHandler>>,
userspace_lock_ttl_ms: u64,
doc_sharing: server_domain::doc_sharing::DocSharingService,
users: server_domain::users::UserService,
@@ -361,6 +395,10 @@ impl SyncStorage {
db,
quota_gate,
session_redis: UserspaceRedisLockBackend::Disabled,
cache_redis: None,
cache_redis_conn: Arc::new(tokio::sync::Mutex::new(None)),
external_url: String::new(),
copilot_realtime: None,
userspace_lock_ttl_ms: DEFAULT_LOCK_TTL_SECS * 1_000,
doc_sharing,
users,
@@ -370,6 +408,21 @@ impl SyncStorage {
}
}
pub fn with_cache_redis_url(mut self, redis_url: &str) -> Self {
self.cache_redis = redis::Client::open(redis_url).ok();
self
}
pub fn with_external_url(mut self, external_url: impl Into<String>) -> Self {
self.external_url = external_url.into();
self
}
pub fn with_copilot_realtime(mut self, handler: Arc<dyn CopilotRealtimeHandler>) -> Self {
self.copilot_realtime = Some(handler);
self
}
/// Configures the `SessionRedis` mutex for userspace document writes using
/// an empty key prefix (`""`), matching `v0.27.5` `Locker`'s literal
/// `MutexLock:userspace:<user_id>:<doc_id>` key even when `ioredis` has a
@@ -1116,6 +1169,39 @@ impl SyncStorage {
}
lock_domain_workspace(tx.tx_mut(), workspace_id).await?;
// Activation guard: Trash and Restore require an active global doc-lifecycle checkpoint;
// Delete remains allowed even before activation.
if !deleting {
let is_active: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints \
WHERE kind = 'workspace_doc_lifecycle_activation' AND scope = 'global' AND status = 'active')",
)
.fetch_one(&mut **tx.tx_mut())
.await?;
if !is_active {
return Err(SyncError::WorkspaceLifecycleNotActive);
}
}
// Alias / conflict check when deleting a physical doc alongside a logical doc ID.
if let Some(logical_id) = logical_doc_id {
let alias_exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM workspace_pages WHERE workspace_id = $1 AND page_id = $2 AND lifecycle_state IS DISTINCT FROM 'deleted') \
AND EXISTS(SELECT 1 FROM snapshots WHERE workspace_id = $1 AND guid = $2) \
AND EXISTS(SELECT 1 FROM snapshots WHERE workspace_id = $1 AND guid = $3)",
)
.bind(workspace_id)
.bind(logical_id)
.bind(doc_id)
.fetch_one(&mut **tx.tx_mut())
.await?;
if alias_exists {
return Err(SyncError::BadRequest(
"logical document ID conflicts with an existing active document".into(),
));
}
}
let grant = self
.quota_gate
.resolve_workspace_grant(tx.tx_mut(), workspace_id, now)
@@ -1216,25 +1302,68 @@ impl SyncStorage {
for id in &pending_ids {
if deleting {
delete_workspace_doc_rows(tx.tx_mut(), workspace_id, id).await?;
let _ = sqlx::query(
"DELETE FROM embedding_sources WHERE workspace_id = $1 AND source_kind = 'document' AND source_key = $2",
)
.bind(workspace_id)
.bind(id)
.execute(&mut **tx.tx_mut())
.await?;
} else if action == DocLifecycleAction::Trash {
let _ = sqlx::query(
"UPDATE embedding_sources \
SET deleted_at = clock_timestamp(), updated_at = clock_timestamp() \
WHERE workspace_id = $1 AND source_kind = 'document' AND source_key = $2 AND deleted_at IS NULL",
)
.bind(workspace_id)
.bind(id)
.execute(&mut **tx.tx_mut())
.await?;
}
let timestamp: DateTime<Utc> = sqlx::query_scalar(
r#"
INSERT INTO workspace_pages(workspace_id, page_id, lifecycle_state, lifecycle_changed_at)
VALUES ($1, $2, $3::"DocLifecycleState", date_trunc('milliseconds', clock_timestamp()))
ON CONFLICT (workspace_id, page_id) DO UPDATE SET
lifecycle_state = EXCLUDED.lifecycle_state,
lifecycle_changed_at = GREATEST(
EXCLUDED.lifecycle_changed_at,
workspace_pages.lifecycle_changed_at + interval '1 millisecond'
)
RETURNING lifecycle_changed_at
"#,
)
.bind(workspace_id)
.bind(id)
.bind(state)
.fetch_one(&mut **tx.tx_mut())
.await?;
let timestamp: DateTime<Utc> = if deleting {
sqlx::query_scalar(
r#"
INSERT INTO workspace_pages(workspace_id, page_id, lifecycle_state, lifecycle_changed_at)
VALUES ($1, $2, $3::"DocLifecycleState", date_trunc('milliseconds', clock_timestamp()))
ON CONFLICT (workspace_id, page_id) DO UPDATE SET
lifecycle_state = EXCLUDED.lifecycle_state,
lifecycle_changed_at = GREATEST(
EXCLUDED.lifecycle_changed_at,
workspace_pages.lifecycle_changed_at + interval '1 millisecond'
),
title = NULL,
summary = NULL,
mode = 0,
blocked = false,
published_at = NULL
RETURNING lifecycle_changed_at
"#,
)
.bind(workspace_id)
.bind(id)
.bind(state)
.fetch_one(&mut **tx.tx_mut())
.await?
} else {
sqlx::query_scalar(
r#"
INSERT INTO workspace_pages(workspace_id, page_id, lifecycle_state, lifecycle_changed_at)
VALUES ($1, $2, $3::"DocLifecycleState", date_trunc('milliseconds', clock_timestamp()))
ON CONFLICT (workspace_id, page_id) DO UPDATE SET
lifecycle_state = EXCLUDED.lifecycle_state,
lifecycle_changed_at = GREATEST(
EXCLUDED.lifecycle_changed_at,
workspace_pages.lifecycle_changed_at + interval '1 millisecond'
)
RETURNING lifecycle_changed_at
"#,
)
.bind(workspace_id)
.bind(id)
.bind(state)
.fetch_one(&mut **tx.tx_mut())
.await?
};
timestamps.push(timestamp);
}
@@ -1490,7 +1619,6 @@ impl SyncStorage {
}))
}
/// Resolves the `user.settings.get` realtime snapshot from `user_settings.payload` JSONB.
pub async fn get_user_settings_snapshot(&self, user_id: &str) -> Result<serde_json::Value, SyncError> {
let settings = self
.users
@@ -2095,6 +2223,15 @@ async fn delete_workspace_doc_rows(
.execute(&mut **tx)
.await?;
}
sqlx::query(
"UPDATE embedding_sources \
SET deleted_at = COALESCE(deleted_at, clock_timestamp()), updated_at = clock_timestamp() \
WHERE workspace_id = $1 AND source_kind = 'document' AND source_key = $2",
)
.bind(workspace_id)
.bind(doc_id)
.execute(&mut **tx)
.await?;
Ok(())
}
@@ -2454,4 +2591,163 @@ mod realtime_snapshot_tests {
db.pool().close().await;
});
}
#[test]
fn doc_lifecycle_activation_guard_trash_and_hard_delete_against_pg() {
let cluster = test_db_harness::pg::PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = test_db_harness::migrations::MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster
.lease(&template, test_db_harness::pg::DEFAULT_LEASE_TTL)
.expect("lease test database");
let db_url = lease.url().to_owned();
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("build tokio runtime");
rt.block_on(async move {
let db = ServerDb::connect(server_db::DbConfig {
database_url: db_url,
channel: "production".into(),
role: server_types::ServerRole::Allinone,
selfhosted: true,
max_connections: 4,
statement_timeout_ms: 5_000,
tier_permits: [8, 4, 4, 2],
})
.await
.expect("connect 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");
let user_id = uuid::Uuid::new_v4().to_string();
let ws_id = uuid::Uuid::new_v4().to_string();
let doc_trash_del = "doc-trash-delete";
let doc_pre_act_del = "doc-pre-activation-delete";
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, 'Owner', 'owner-lc@example.com')")
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query("INSERT INTO workspaces (id, name) VALUES ($1, 'Lifecycle WS')")
.bind(&ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_members (id, workspace_id, user_id, role, state) \
VALUES ($1, $2, $3, 'owner', 'active')",
)
.bind(uuid::Uuid::new_v4().to_string())
.bind(&ws_id)
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
let empty_bin = y_octo::Doc::default()
.encode_state_as_update_v1(&Default::default())
.unwrap();
for doc_id in [doc_trash_del, doc_pre_act_del] {
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, updated_at) VALUES ($1, $2, $3, clock_timestamp())",
)
.bind(&ws_id)
.bind(doc_id)
.bind(&empty_bin)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_pages (workspace_id, page_id, title, summary, mode, blocked, published_at) \
VALUES ($1, $2, 'My Title', 'My Summary', 1, true, clock_timestamp())",
)
.bind(&ws_id)
.bind(doc_id)
.execute(db.pool())
.await
.unwrap();
}
let storage = SyncStorage::new(db.clone());
// Before activation: Trash and Restore must fail with WorkspaceLifecycleNotActive,
// while Delete remains allowed and clears residual workspace_pages columns.
let err_trash = storage
.apply_doc_lifecycle(&ws_id, doc_trash_del, None, &user_id, DocLifecycleAction::Trash)
.await
.unwrap_err();
assert!(
matches!(err_trash, SyncError::WorkspaceLifecycleNotActive),
"expected WorkspaceLifecycleNotActive before activation, got {err_trash:?}"
);
let err_restore = storage
.apply_doc_lifecycle(&ws_id, doc_trash_del, None, &user_id, DocLifecycleAction::Restore)
.await
.unwrap_err();
assert!(
matches!(err_restore, SyncError::WorkspaceLifecycleNotActive),
"expected WorkspaceLifecycleNotActive on restore before activation, got {err_restore:?}"
);
storage
.apply_doc_lifecycle(&ws_id, doc_pre_act_del, None, &user_id, DocLifecycleAction::Delete)
.await
.expect("Delete must succeed even before lifecycle activation");
// Activate global workspace doc lifecycle checkpoint.
sqlx::query(
"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status) \
VALUES ('workspace_doc_lifecycle_activation', 'global', 'active') \
ON CONFLICT (kind, scope) DO UPDATE SET status = 'active'",
)
.execute(db.pool())
.await
.unwrap();
// After activation: Trash -> Delete runs end-to-end with zero SQL errors.
storage
.apply_doc_lifecycle(&ws_id, doc_trash_del, None, &user_id, DocLifecycleAction::Trash)
.await
.expect("Trash after activation");
storage
.apply_doc_lifecycle(&ws_id, doc_trash_del, None, &user_id, DocLifecycleAction::Delete)
.await
.expect("Delete after Trash");
let row = sqlx::query(
"SELECT lifecycle_state::text AS state, title, summary, mode, blocked, published_at \
FROM workspace_pages WHERE workspace_id = $1 AND page_id = $2",
)
.bind(&ws_id)
.bind(doc_trash_del)
.fetch_one(db.pool())
.await
.unwrap();
use sqlx::Row as _;
assert_eq!(row.get::<Option<String>, _>("state").as_deref(), Some("deleted"));
assert_eq!(row.get::<Option<String>, _>("title"), None);
assert_eq!(row.get::<Option<String>, _>("summary"), None);
assert_eq!(row.get::<i16, _>("mode"), 0);
assert!(!row.get::<bool, _>("blocked"));
assert_eq!(row.get::<Option<DateTime<Utc>>, _>("published_at"), None);
let snap_exists: bool =
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id = $1 AND guid = $2)")
.bind(&ws_id)
.bind(doc_trash_del)
.fetch_one(db.pool())
.await
.unwrap();
assert!(!snap_exists, "snapshots row must be deleted on hard delete");
db.pool().close().await;
});
}
}
@@ -0,0 +1,681 @@
//! Realtime snapshot queries and commercial Copilot realtime delegation for [`SyncStorage`].
use chrono::{DateTime, Duration, Utc};
use server_db::WorkloadTier;
use server_types::{BillingSubject, LicenseTier};
use sqlx::Row as _;
use super::SyncStorage;
use crate::{error::SyncError, permissions::WorkspaceRole};
fn external_plan_name(tier: LicenseTier) -> &'static str {
match tier {
LicenseTier::CloudFree => "free",
LicenseTier::CloudPro => "pro",
LicenseTier::CloudLifetimePro => "lifetime_pro",
LicenseTier::CloudAi => "ai",
LicenseTier::CloudTeam => "team",
LicenseTier::SelfhostDefault => "selfhost_free",
LicenseTier::SelfhostTeam => "selfhost_team",
LicenseTier::SelfhostEnterprise => "selfhost_enterprise",
}
}
fn escape_like_pattern(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'\\' | '%' | '_' => {
out.push('\\');
out.push(ch);
}
_ => out.push(ch),
}
}
out
}
impl SyncStorage {
/// Resolves the `user.profile.get` realtime snapshot (`CurrentUserProfileSnapshot`).
pub async fn get_user_profile_snapshot(&self, user_id: &str) -> Result<serde_json::Value, SyncError> {
let mut conn = self.db.acquire_tiered(WorkloadTier::InteractiveRead).await?;
let row = sqlx::query(
"SELECT id, name, email, avatar_url, email_verified, (password IS NOT NULL) AS has_password \
FROM users WHERE id = $1",
)
.bind(user_id)
.fetch_optional(&mut *conn)
.await?;
let Some(row) = row else {
return Err(SyncError::AuthenticationRequired("user not found".into()));
};
let raw_features: Vec<String> = sqlx::query_scalar(
"SELECT DISTINCT name FROM user_features \
WHERE user_id = $1 AND activated = true AND (expired_at IS NULL OR expired_at > clock_timestamp()) \
ORDER BY name ASC",
)
.bind(user_id)
.fetch_all(&mut *conn)
.await?;
let features: Vec<String> = raw_features
.into_iter()
.map(|f| match f.as_str() {
"administrator" => "Admin".to_owned(),
_ => f,
})
.collect();
let email_verified: Option<DateTime<Utc>> = row.get("email_verified");
Ok(serde_json::json!({
"id": row.get::<String, _>("id"),
"name": row.get::<String, _>("name"),
"email": row.get::<String, _>("email"),
"emailVerified": email_verified.is_some(),
"hasPassword": row.get::<bool, _>("has_password"),
"avatarUrl": row.get::<Option<String>, _>("avatar_url"),
"features": features,
}))
}
/// Authorizes `Workspace.Users.Manage` (workspace owner or commercial admin).
pub async fn assert_workspace_invite_manage(&self, workspace_id: &str, actor_user_id: &str) -> Result<(), SyncError> {
let mut tx = self.db.begin_tiered(WorkloadTier::InteractiveRead).await?;
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut **tx.tx_mut())
.await?;
let member_role_str: Option<String> = sqlx::query_scalar(
"SELECT role::text FROM workspace_members WHERE workspace_id = $1 AND user_id = $2 AND state = 'active'",
)
.bind(workspace_id)
.bind(actor_user_id)
.fetch_optional(&mut **tx.tx_mut())
.await?;
let grant = self
.quota_gate
.resolve_workspace_grant(tx.tx_mut(), workspace_id, now)
.await
.map_err(|e| SyncError::Internal(format!("resolve workspace grant for invite manage: {e}")))?;
let _ = tx.rollback().await;
let role = member_role_str.as_deref().and_then(WorkspaceRole::parse);
let allowed = matches!(role, Some(WorkspaceRole::Owner))
|| (grant.rights.commercial && matches!(role, Some(WorkspaceRole::Admin)));
if !allowed {
return Err(SyncError::AccessDenied(
"Workspace.Users.Manage permission required.".into(),
));
}
Ok(())
}
pub async fn get_workspace_members_snapshot(
&self,
workspace_id: &str,
actor_user_id: &str,
skip: i64,
take: i64,
query: Option<&str>,
) -> Result<serde_json::Value, SyncError> {
self
.assert_workspace_members_readable(workspace_id, actor_user_id)
.await?;
if let Some(q) = query
&& q.encode_utf16().count() > 255
{
return Err(SyncError::QueryTooLong { max: 255 });
}
let clamped_skip = skip.max(0);
let clamped_take = take.clamp(1, 100);
let mut conn = self.db.acquire_tiered(WorkloadTier::InteractiveRead).await?;
let kw = query
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| format!("%{}%", escape_like_pattern(&s.to_ascii_lowercase())));
let member_count: i64 = sqlx::query_scalar(
"SELECT (
(SELECT COUNT(*) FROM workspace_members WHERE workspace_id = $1 AND state = 'active')
+ (SELECT COUNT(*) FROM workspace_invitations WHERE workspace_id = $1)
)::bigint",
)
.bind(workspace_id)
.fetch_one(&mut *conn)
.await?;
let rows = sqlx::query(
r#"SELECT * FROM (
SELECT u.id AS user_id, u.name, u.email, u.avatar_url,
m.role::text AS role,
u.id AS invite_id,
'Accepted'::text AS status,
m.created_at AS sort_at
FROM workspace_members m
JOIN users u ON u.id = m.user_id
WHERE m.workspace_id = $1 AND m.state = 'active'
UNION ALL
SELECT u.id AS user_id,
u.name,
u.email,
u.avatar_url,
i.requested_role::text AS role,
u.id AS invite_id,
CASE i.status::text
WHEN 'waiting_review' THEN 'UnderReview'
WHEN 'waiting_seat' THEN 'NeedMoreSeat'
ELSE 'Pending'
END AS status,
i.created_at AS sort_at
FROM workspace_invitations i
INNER JOIN users u ON u.id = i.invitee_user_id
WHERE i.workspace_id = $1
) combined
WHERE ($2::text IS NULL OR lower(combined.name) LIKE $2 ESCAPE '\' OR lower(combined.email) LIKE $2 ESCAPE '\')
ORDER BY combined.sort_at ASC, combined.user_id ASC
OFFSET $3 LIMIT $4"#,
)
.bind(workspace_id)
.bind(kw.as_deref())
.bind(clamped_skip)
.bind(clamped_take)
.fetch_all(&mut *conn)
.await?;
let members: Vec<serde_json::Value> = rows
.into_iter()
.map(|r| {
let role_str: String = r.get("role");
let role_name = match role_str.as_str() {
"owner" => "Owner",
"admin" => "Admin",
"collaborator" | "member" => "Collaborator",
_ => "External",
};
serde_json::json!({
"id": r.get::<String, _>("user_id"),
"name": r.get::<String, _>("name"),
"email": r.get::<String, _>("email"),
"avatarUrl": r.get::<Option<String>, _>("avatar_url"),
"permission": role_name,
"role": role_name,
"inviteId": r.get::<String, _>("invite_id"),
"emailVerified": serde_json::Value::Null,
"status": r.get::<String, _>("status"),
})
})
.collect();
Ok(serde_json::json!({
"members": members,
"memberCount": member_count,
}))
}
pub async fn get_workspace_invite_link_snapshot(
&self,
workspace_id: &str,
actor_user_id: &str,
) -> Result<serde_json::Value, SyncError> {
self.assert_workspace_invite_manage(workspace_id, actor_user_id).await?;
let Some(client) = &self.cache_redis else {
return Ok(serde_json::Value::Null);
};
let mut conn = self.cache_redis_conn.lock().await.clone();
if conn.is_none() {
conn = tokio::time::timeout(
std::time::Duration::from_secs(2),
client.get_multiplexed_async_connection(),
)
.await
.ok()
.and_then(Result::ok);
}
let Some(mut conn) = conn else {
return Ok(serde_json::Value::Null);
};
let ws_key = format!("workspace:inviteLink:{workspace_id}");
let raw_res = tokio::time::timeout(
std::time::Duration::from_secs(2),
redis::cmd("GET").arg(&ws_key).query_async::<Option<String>>(&mut conn),
)
.await;
let Ok(Ok(raw_opt)) = raw_res else {
*self.cache_redis_conn.lock().await = None;
return Ok(serde_json::Value::Null);
};
*self.cache_redis_conn.lock().await = Some(conn.clone());
let Some(raw) = raw_opt else {
return Ok(serde_json::Value::Null);
};
let pttl: i64 = tokio::time::timeout(
std::time::Duration::from_secs(2),
redis::cmd("PTTL").arg(&ws_key).query_async::<i64>(&mut conn),
)
.await
.ok()
.and_then(Result::ok)
.unwrap_or(-1);
if pttl <= 0 {
return Ok(serde_json::Value::Null);
}
let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap_or_default();
let Some(invite_id) = parsed
.get("inviteId")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
else {
return Ok(serde_json::Value::Null);
};
let base = self.external_url.trim_end_matches('/');
let link = if base.is_empty() {
format!("/invite/{invite_id}")
} else {
format!("{base}/invite/{invite_id}")
};
let expire_time = (Utc::now() + Duration::milliseconds(pttl)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
Ok(serde_json::json!({
"link": link,
"expireTime": expire_time,
}))
}
async fn resolve_owner_billed_workspace_ids(
&self,
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
owner_user_id: &str,
now: DateTime<Utc>,
) -> Result<Vec<String>, SyncError> {
let candidate_ws_ids: Vec<String> = sqlx::query_scalar(
"SELECT workspace_id FROM workspace_members \
WHERE user_id = $1 AND role = 'owner' AND state = 'active' \
ORDER BY workspace_id",
)
.bind(owner_user_id)
.fetch_all(&mut **tx)
.await?;
let mut owner_billed = Vec::with_capacity(candidate_ws_ids.len());
for ws_id in candidate_ws_ids {
let ws_grant = self
.quota_gate
.resolve_workspace_grant(tx, &ws_id, now)
.await
.map_err(|e| SyncError::Internal(format!("resolve owner workspace grant {ws_id}: {e}")))?;
if ws_grant.billing_subject == BillingSubject::Owner {
owner_billed.push(ws_id);
}
}
Ok(owner_billed)
}
pub async fn get_user_quota_state_snapshot(&self, user_id: &str) -> Result<serde_json::Value, SyncError> {
let mut tx = self.db.begin_tiered(WorkloadTier::InteractiveRead).await?;
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut **tx.tx_mut())
.await?;
let grant = self
.quota_gate
.resolve_user_grant(tx.tx_mut(), user_id, now)
.await
.map_err(|e| SyncError::Internal(format!("resolve user quota grant: {e}")))?;
let personal_ws_ids = self
.resolve_owner_billed_workspace_ids(tx.tx_mut(), user_id, now)
.await?;
let used_storage: i64 = if personal_ws_ids.is_empty() {
0
} else {
sqlx::query_scalar(
"SELECT (
COALESCE((
SELECT SUM(b.size)::bigint FROM blobs b
WHERE b.workspace_id = ANY($1) AND b.deleted_at IS NULL
AND (b.status = 'completed' OR (b.status = 'pending' AND b.reservation_expires_at > $2))
), 0)
+ COALESCE((
SELECT SUM(ca.size)::bigint FROM comment_attachments ca
WHERE ca.workspace_id = ANY($1) AND ca.deleted_at IS NULL
AND (ca.status = 'completed' OR (ca.status = 'pending' AND ca.reservation_expires_at > $2))
), 0)
)::bigint",
)
.bind(&personal_ws_ids)
.bind(now)
.fetch_one(&mut **tx.tx_mut())
.await?
};
let _ = tx.rollback().await;
Ok(serde_json::json!({
"plan": external_plan_name(grant.tier),
"seatLimit": grant.limits.seat_limit,
"blobLimit": grant.limits.blob_limit_bytes,
"storageQuota": grant.limits.storage_quota_bytes,
"usedStorageQuota": used_storage,
"historyPeriodSeconds": grant.limits.history_period_seconds,
"copilotActionLimit": grant.limits.copilot_action_limit,
"unlimitedCopilot": grant.rights.unlimited_copilot,
}))
}
pub async fn get_workspace_quota_state_snapshot(
&self,
workspace_id: &str,
actor_user_id: &str,
) -> Result<serde_json::Value, SyncError> {
self.assert_workspace_readable(workspace_id, actor_user_id).await?;
let mut tx = self.db.begin_tiered(WorkloadTier::InteractiveRead).await?;
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut **tx.tx_mut())
.await?;
let grant = self
.quota_gate
.resolve_workspace_grant(tx.tx_mut(), workspace_id, now)
.await
.map_err(|e| SyncError::Internal(format!("resolve workspace quota grant: {e}")))?;
let owner_user_id: String = sqlx::query_scalar(
"SELECT user_id FROM workspace_members \
WHERE workspace_id = $1 AND role = 'owner' AND state = 'active' \
ORDER BY created_at ASC LIMIT 1",
)
.bind(workspace_id)
.fetch_optional(&mut **tx.tx_mut())
.await?
.unwrap_or_default();
let uses_owner_quota = grant.billing_subject == BillingSubject::Owner;
let storage_ws_ids: Vec<String> = if uses_owner_quota && !owner_user_id.is_empty() {
self
.resolve_owner_billed_workspace_ids(tx.tx_mut(), &owner_user_id, now)
.await?
} else {
vec![workspace_id.to_owned()]
};
let used_storage: i64 = if storage_ws_ids.is_empty() {
0
} else {
sqlx::query_scalar(
"SELECT (
COALESCE((
SELECT SUM(b.size)::bigint FROM blobs b
WHERE b.workspace_id = ANY($1) AND b.deleted_at IS NULL
AND (b.status = 'completed' OR (b.status = 'pending' AND b.reservation_expires_at > $2))
), 0)
+ COALESCE((
SELECT SUM(ca.size)::bigint FROM comment_attachments ca
WHERE ca.workspace_id = ANY($1) AND ca.deleted_at IS NULL
AND (ca.status = 'completed' OR (ca.status = 'pending' AND ca.reservation_expires_at > $2))
), 0)
)::bigint",
)
.bind(&storage_ws_ids)
.bind(now)
.fetch_one(&mut **tx.tx_mut())
.await?
};
let chargeable_statuses = ["pending", "waiting_review", "waiting_seat"];
let member_count: i64 = sqlx::query_scalar(
"SELECT (
(SELECT COUNT(*) FROM workspace_members WHERE workspace_id = $1 AND state = 'active')
+ (SELECT COUNT(*) FROM workspace_invitations WHERE workspace_id = $1 AND status::text = ANY($2))
)::bigint",
)
.bind(workspace_id)
.bind(chargeable_statuses.as_slice())
.fetch_one(&mut **tx.tx_mut())
.await?;
let _ = tx.rollback().await;
let overcapacity_member_count = (member_count - i64::from(grant.limits.seat_limit)).max(0);
let mut readonly_reasons: Vec<&'static str> = Vec::new();
if overcapacity_member_count > 0 {
readonly_reasons.push("member_overflow");
}
if grant.limits.storage_quota_bytes >= 0 && used_storage > grant.limits.storage_quota_bytes {
readonly_reasons.push("storage_overflow");
}
let readonly = !readonly_reasons.is_empty();
Ok(serde_json::json!({
"plan": external_plan_name(grant.tier),
"ownerUserId": owner_user_id,
"usesOwnerQuota": uses_owner_quota,
"seatLimit": grant.limits.seat_limit,
"memberCount": member_count,
"overcapacityMemberCount": overcapacity_member_count,
"blobLimit": grant.limits.blob_limit_bytes,
"storageQuota": grant.limits.storage_quota_bytes,
"usedStorageQuota": used_storage,
"historyPeriodSeconds": grant.limits.history_period_seconds,
"readonly": readonly,
"readonlyReasons": readonly_reasons,
"unlimitedCopilot": grant.rights.unlimited_copilot,
}))
}
pub async fn copilot_realtime_get_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
blob_id: Option<&str>,
task_id: Option<&str>,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler
.get_transcript_task(user_id, workspace_id, blob_id, task_id)
.await
}
pub async fn copilot_realtime_retry_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.retry_transcript_task(user_id, workspace_id, task_id).await
}
pub async fn copilot_realtime_authorize_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<(), SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.authorize_transcript_task(user_id, workspace_id, task_id).await
}
pub async fn copilot_realtime_get_embedding_progress(
&self,
user_id: &str,
workspace_id: &str,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.get_embedding_progress(user_id, workspace_id).await
}
pub async fn copilot_realtime_authorize_embedding_progress(
&self,
user_id: &str,
workspace_id: &str,
) -> Result<(), SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.authorize_embedding_progress(user_id, workspace_id).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn external_plan_name_and_like_escaping() {
assert_eq!(external_plan_name(LicenseTier::CloudFree), "free");
assert_eq!(external_plan_name(LicenseTier::CloudPro), "pro");
assert_eq!(external_plan_name(LicenseTier::CloudLifetimePro), "lifetime_pro");
assert_eq!(external_plan_name(LicenseTier::CloudAi), "ai");
assert_eq!(external_plan_name(LicenseTier::CloudTeam), "team");
assert_eq!(external_plan_name(LicenseTier::SelfhostDefault), "selfhost_free");
assert_eq!(external_plan_name(LicenseTier::SelfhostTeam), "selfhost_team");
assert_eq!(
external_plan_name(LicenseTier::SelfhostEnterprise),
"selfhost_enterprise"
);
assert_eq!(escape_like_pattern(r"a%b_c\d"), r"a\%b\_c\\d");
}
#[test]
fn realtime_snapshots_members_and_quota_state_pg() {
use std::path::Path;
use server_db::{DbConfig, ServerDb};
use server_spi::{CommunityExtension, ServerExtension as _};
use server_types::ServerRole;
use test_db_harness::{
migrations::MigrationSet,
pg::{DEFAULT_LEASE_TTL, PgCluster},
};
let cluster = PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster.lease(&template, DEFAULT_LEASE_TTL).expect("lease db");
let rt = tokio::runtime::Runtime::new().expect("tokio runtime");
rt.block_on(async {
let db = ServerDb::connect(DbConfig {
database_url: lease.url().to_owned(),
channel: "production".into(),
role: ServerRole::Allinone,
selfhosted: true,
max_connections: 4,
statement_timeout_ms: 5_000,
tier_permits: [8, 4, 4, 2],
})
.await
.expect("connect 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");
let ext = CommunityExtension::new();
let storage = SyncStorage::with_quota_gate(db.clone(), ext.quota_gate());
let owner_id = "usr_rt_owner";
let member_id = "usr_rt_member";
let invited_user_id = "usr_rt_invited";
let ws_id = "ws_rt_snap";
for (uid, name, email) in [
(owner_id, "Owner User", "owner-rt@example.com"),
(member_id, "Active Member", "member-rt@example.com"),
(invited_user_id, "Invited User", "invited-rt@example.com"),
] {
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, $2, $3)")
.bind(uid)
.bind(name)
.bind(email)
.execute(db.pool())
.await
.expect("insert user");
}
sqlx::query("INSERT INTO workspaces (id, name) VALUES ($1, 'RT WS')")
.bind(ws_id)
.execute(db.pool())
.await
.expect("insert workspace");
sqlx::query(
"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source) VALUES \
('wm_1', $1, $2, 'owner', 'active', 'legacy'), \
('wm_2', $1, $3, 'member', 'active', 'legacy')",
)
.bind(ws_id)
.bind(owner_id)
.bind(member_id)
.execute(db.pool())
.await
.expect("insert members");
// One linked-user invitation + one pure-email invitation (invitee_user_id IS NULL).
sqlx::query(
"INSERT INTO workspace_invitations \
(id, workspace_id, inviter_user_id, invitee_user_id, normalized_email, requested_role, status, kind, created_at, updated_at) VALUES \
('inv_linked', $1, $2, $3, 'invited-rt@example.com', 'member', 'pending', 'email', now(), now()), \
('inv_email_only', $1, $2, NULL, 'pure-email@example.com', 'member', 'pending', 'email', now(), now())",
)
.bind(ws_id)
.bind(owner_id)
.bind(invited_user_id)
.execute(db.pool())
.await
.expect("insert invitations");
let snap = storage
.get_workspace_members_snapshot(ws_id, owner_id, 0, 20, None)
.await
.expect("members snapshot");
assert_eq!(snap["memberCount"], 4, "memberCount counts active + all invitations");
let members = snap["members"].as_array().expect("members array");
assert_eq!(
members.len(),
3,
"unlinked pure-email invitation must be omitted from members"
);
let linked = members
.iter()
.find(|m| m["id"] == invited_user_id)
.expect("linked invited user present");
assert_eq!(linked["inviteId"], invited_user_id);
assert_eq!(linked["status"], "Pending");
// 100-CJK-char query (300 UTF-8 bytes, 100 UTF-16 code units) must succeed; 256-char query must fail.
let cjk_100 = "中".repeat(100);
assert!(
storage
.get_workspace_members_snapshot(ws_id, owner_id, 0, 20, Some(&cjk_100))
.await
.is_ok()
);
let too_long = "a".repeat(256);
assert!(matches!(
storage
.get_workspace_members_snapshot(ws_id, owner_id, 0, 20, Some(&too_long))
.await,
Err(SyncError::QueryTooLong { max: 255 })
));
// Quota snapshots emit lowercase snake_case plan, explicit copilotActionLimit key, and valid readonlyReasons.
let user_q = storage
.get_user_quota_state_snapshot(owner_id)
.await
.expect("user quota state");
assert!(
user_q["plan"]
.as_str()
.is_some_and(|p| p.chars().all(|c| c.is_ascii_lowercase() || c == '_')),
"plan must be lowercase snake_case, got {user_q}"
);
assert!(
user_q.as_object().unwrap().contains_key("copilotActionLimit"),
"copilotActionLimit key must always be present"
);
let ws_q = storage
.get_workspace_quota_state_snapshot(ws_id, owner_id)
.await
.expect("workspace quota state");
assert!(
ws_q["plan"]
.as_str()
.is_some_and(|p| p.chars().all(|c| c.is_ascii_lowercase() || c == '_')),
"workspace plan must be lowercase snake_case, got {ws_q}"
);
for reason in ws_q["readonlyReasons"].as_array().expect("readonlyReasons array") {
let r = reason.as_str().unwrap_or("");
assert!(
r == "member_overflow" || r == "storage_overflow",
"unexpected readonly reason: {r}"
);
}
});
}
}