fix(backend): close remaining v0.27.5 HTTP, auth, blob, and sync parity gaps

Align server-http, server-domain, server-sync, server-blob, server-spi, and
affine-server with Node v0.27.5 behavior across configuration precedence,
GraphQL and REST error envelopes, realtime sync, and storage adapters:

- Apply config.json precedence for captcha, GraphQL introspection, server.hosts,
  session/token TTLs, GA4 telemetry, and DB > File > Env private key loading.
- Enforce Apollo GraphQL introspection disabling, GET mutation 405 semantics,
  multipart CSRF origin checks for desktop/capacitor/ionic schemes, and 5xx
  requestId headers.
- Require authentication on readable-blob-manifest/v1, apply default throttling
  across avatar/blob/doc/history/comment-attachment routes, and align S3/R2
  status and ETag handling.
- Harden setup/auth endpoints (JSON 400 validation errors, pre-Argon2 setup
  guard, dynamic email domain verification, transactional change-email token
  validation, and Redis keyPrefix wiring for throttler, calendar OAuth, and
  mutexes).
- Align Socket.IO error codes/types, canary date-version parsing, doc-lifecycle
  alias/requireDeleted guards, quota invalidation fanout, subscription eviction,
  user profile feature filtering, and delegated Copilot SPI hooks.
This commit is contained in:
DarkSky committed 2026-11-27 21:59:49 +09:00
1 parent 6ba83ababb
commit 4be978f7ab
47 files changed
+2137 -595

No files matched your search

+202 -35
View File
@@ -708,6 +708,14 @@ impl SyncSessionAuthenticator for AuthServiceSyncAuthenticator {
allow_canary,
)
{
let _ = self
.auth
.revoke_auth_session(
&principal.auth_session_id,
Some(&principal.user.id),
"unsupported_client_version",
)
.await;
let (client_version, required_version) = ver_err.into_parts();
return Err(server_sync::error::SyncError::UnsupportedClientVersion {
client_version,
@@ -754,6 +762,7 @@ impl SyncSessionAuthenticator for AuthServiceSyncAuthenticator {
allow_canary,
)
{
let _ = self.auth.sign_out_cookie(&principal.session_id, None).await;
let (client_version, required_version) = ver_err.into_parts();
return Err(server_sync::error::SyncError::UnsupportedClientVersion {
client_version,
@@ -770,6 +779,131 @@ impl SyncSessionAuthenticator for AuthServiceSyncAuthenticator {
}
}
struct CopilotRealtimeSpiAdapter(Arc<dyn server_spi::CopilotRealtimeSpi>);
fn map_copilot_realtime_err(err: server_types::DomainError) -> server_sync::error::SyncError {
match err {
server_types::DomainError::Forbidden(msg) if msg == "Copilot is disabled." => {
server_sync::error::SyncError::CopilotDisabled
}
server_types::DomainError::Forbidden(msg) => server_sync::error::SyncError::AccessDenied(msg),
server_types::DomainError::Unauthorized(msg) => server_sync::error::SyncError::AuthenticationRequired(msg),
server_types::DomainError::Validation(msg)
| server_types::DomainError::Conflict(msg)
| server_types::DomainError::PreconditionFailed(msg) => server_sync::error::SyncError::BadRequest(msg),
server_types::DomainError::NotFound(msg) => server_sync::error::SyncError::BadRequest(msg),
server_types::DomainError::QuotaExceeded { message, .. } => server_sync::error::SyncError::QuotaExceeded(message),
server_types::DomainError::RateLimited(msg) => server_sync::error::SyncError::BadRequest(msg),
server_types::DomainError::Unavailable(msg) | server_types::DomainError::Internal(msg) => {
server_sync::error::SyncError::Internal(msg)
}
}
}
#[async_trait::async_trait]
impl server_sync::storage::CopilotRealtimeHandler for CopilotRealtimeSpiAdapter {
async fn get_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
blob_id: Option<&str>,
task_id: Option<&str>,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.get_transcript_task(user_id, workspace_id, blob_id, task_id)
.await
.map_err(map_copilot_realtime_err)
}
async fn retry_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.retry_transcript_task(user_id, workspace_id, task_id)
.await
.map_err(map_copilot_realtime_err)
}
async fn authorize_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<(), server_sync::error::SyncError> {
self
.0
.authorize_transcript_task(user_id, workspace_id, task_id)
.await
.map_err(map_copilot_realtime_err)
}
async fn get_embedding_progress(
&self,
user_id: &str,
workspace_id: &str,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.get_embedding_progress(user_id, workspace_id)
.await
.map_err(map_copilot_realtime_err)
}
async fn authorize_embedding_progress(
&self,
user_id: &str,
workspace_id: &str,
) -> Result<(), server_sync::error::SyncError> {
self
.0
.authorize_embedding_progress(user_id, workspace_id)
.await
.map_err(map_copilot_realtime_err)
}
async fn delegated_editor_upsert(
&self,
user_id: &str,
connection_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.delegated_editor_upsert(user_id, connection_id, input)
.await
.map_err(map_copilot_realtime_err)
}
async fn delegated_editor_release(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.delegated_editor_release(user_id, input)
.await
.map_err(map_copilot_realtime_err)
}
async fn delegated_tool_respond(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, server_sync::error::SyncError> {
self
.0
.delegated_tool_respond(user_id, input)
.await
.map_err(map_copilot_realtime_err)
}
}
/// Fully wired server components ready to bind and serve.
pub struct BuiltServer {
pub state: Arc<AppState>,
@@ -814,8 +948,9 @@ async fn build_server_with_bound_port(
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_from_env_or_file = match cli.private_key.as_deref() {
// Fail-fast on explicitly blank AFFINE_PRIVATE_KEY for HTTP-serving roles;
// otherwise resolve private key with File > Env priority (below DB override).
let env_private_key = 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(
@@ -825,12 +960,14 @@ async fn build_server_with_bound_port(
Some(String::new())
}
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),
None => None,
};
let file_private_key = file_json
.pointer("/crypto/privateKey")
.and_then(|v| v.as_str())
.filter(|s| !s.trim().is_empty())
.map(str::to_owned);
let private_key_from_env_or_file = file_private_key.or(env_private_key);
let server_name = file_cfg
.server
.as_ref()
@@ -936,6 +1073,13 @@ async fn build_server_with_bound_port(
}
let effective_redis_url = cli.effective_redis_url_with_file(&file_json)?;
let effective_redis_key_prefix = file_json
.pointer("/redis/ioredis/keyPrefix")
.or_else(|| file_json.pointer("/redis/keyPrefix"))
.and_then(serde_json::Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| cli.redis_key_prefix.clone());
let (redis_client, redis_db_index, session_redis_url_str, session_redis_db_index, session_mutex, redis_runtime_cfg) =
match effective_redis_url.as_deref() {
Some(url) => {
@@ -943,7 +1087,7 @@ async fn build_server_with_bound_port(
let base_db = parse_redis_db_index(url)?;
let (session_url, session_db) = session_redis_url(url)?;
let client = redis::Client::open(url)?;
let mutex = RedisMutex::new(&session_url, cli.redis_key_prefix.clone())?;
let mutex = RedisMutex::new(&session_url, effective_redis_key_prefix)?;
(
Some(client),
base_db,
@@ -1059,6 +1203,7 @@ async fn build_server_with_bound_port(
redis_configured: effective_redis_url.is_some(),
redis_url_env_set: env_redis_url_raw.is_some(),
redis_url_has_password,
redis_key_prefix: cli.redis_key_prefix.clone(),
};
let mut config = RuntimeConfig {
@@ -1106,30 +1251,12 @@ 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 env_or_file_private_key = private_key_from_env_or_file.clone();
let private_key = db_private_key
.or(private_key_from_env_or_file)
.unwrap_or_else(generate_ephemeral_private_key);
config.calendar_fallback_private_key = Some(env_or_file_private_key.unwrap_or_else(generate_ephemeral_private_key));
let fallback_private_key = private_key_from_env_or_file.unwrap_or_else(generate_ephemeral_private_key);
config.calendar_fallback_private_key = Some(fallback_private_key.clone());
let mut auth_cfg = AuthConfig {
server_name,
private_key: private_key.clone(),
private_key: fallback_private_key.clone(),
..AuthConfig::default()
};
if let Some(a) = file_cfg.auth.as_ref() {
@@ -1157,6 +1284,42 @@ async fn build_server_with_bound_port(
{
auth_cfg.password_max_length = v as usize;
}
auth_cfg.session_ttl_seconds = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/session/ttl"),
auth_cfg.session_ttl_seconds,
60,
365 * 86_400,
);
auth_cfg.session_ttr_seconds = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/session/ttr"),
auth_cfg.session_ttr_seconds,
0,
365 * 86_400,
);
auth_cfg.access_token_ttl_secs = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/token/accessTokenTtl"),
auth_cfg.access_token_ttl_secs,
server_domain::auth::MIN_ACCESS_TOKEN_TTL_SECS,
server_domain::auth::MAX_ACCESS_TOKEN_TTL_SECS,
);
auth_cfg.refresh_idle_ttl_secs = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/token/refreshIdleTtl"),
auth_cfg.refresh_idle_ttl_secs,
server_domain::auth::MIN_REFRESH_IDLE_TTL_SECS,
server_domain::auth::MAX_REFRESH_IDLE_TTL_SECS,
);
auth_cfg.refresh_absolute_ttl_secs = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/token/refreshAbsoluteTtl"),
auth_cfg.refresh_absolute_ttl_secs,
server_domain::auth::MIN_REFRESH_ABSOLUTE_TTL_SECS,
server_domain::auth::MAX_REFRESH_ABSOLUTE_TTL_SECS,
);
auth_cfg.refresh_grace_secs = server_domain::auth::parse_duration_secs_clamped(
a.pointer("/token/refreshGracePeriod"),
auth_cfg.refresh_grace_secs,
server_domain::auth::MIN_REFRESH_GRACE_SECS,
server_domain::auth::MAX_REFRESH_GRACE_SECS,
);
}
if let Some(providers) = file_cfg
.oauth
@@ -1193,7 +1356,7 @@ async fn build_server_with_bound_port(
let workspaces = WorkspaceService::new(db.clone(), ext.quota_gate(), Arc::clone(&invalidation))
.with_event_bus(Arc::clone(&event_bus))
.with_base_url(external_url.clone())
.with_private_key(private_key.clone())
.with_private_key(fallback_private_key.clone())
.with_rate_limit_policy(ext.rate_limit_policy())
.with_billing_spi(effective_billing)
.with_redis(redis_client.clone());
@@ -1225,7 +1388,7 @@ async fn build_server_with_bound_port(
)
.with_invalidation(Arc::clone(&invalidation))
.with_base_url(external_url.clone())
.with_private_key(private_key.clone());
.with_private_key(fallback_private_key.clone());
let notifications = NotificationService::new(
db.clone(),
ext.quota_gate(),
@@ -1233,7 +1396,7 @@ async fn build_server_with_bound_port(
Arc::clone(&event_bus),
)
.with_base_url(external_url.clone())
.with_private_key(private_key.clone());
.with_private_key(fallback_private_key.clone());
let blob_root = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(std::env::temp_dir)
@@ -1294,11 +1457,11 @@ async fn build_server_with_bound_port(
AppServices {
auth: auth.clone().with_app_config(app_config.clone()),
users,
workspaces,
workspaces: workspaces.with_app_config(app_config.clone()),
doc_sharing,
histories,
comments,
notifications,
comments: comments.with_app_config(app_config.clone()),
notifications: notifications.with_app_config(app_config.clone()),
licenses,
app_config,
blobs,
@@ -1324,6 +1487,10 @@ async fn build_server_with_bound_port(
sync_cfg.external_url = state.config.load().external_url.clone();
sync_cfg.allowed_origins = allowed_origins;
sync_cfg.allow_dev_loopback = state.config.load().dev_mode;
sync_cfg.copilot_realtime = ext
.copilot_realtime_spi()
.map(|spi| Arc::new(CopilotRealtimeSpiAdapter(spi)) as Arc<dyn server_sync::storage::CopilotRealtimeHandler>);
sync_cfg.available_user_features = ext.available_user_features();
let authenticator = Arc::new(AuthServiceSyncAuthenticator {
auth: state.auth.clone(),
app_config: state.app_config.clone(),
@@ -2967,7 +2967,45 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
);
}
// 3. Valid Bearer JWT handshake succeeds.
// 3. Outdated handshake revoked the previous JWT session; mint a fresh JWT and verify valid handshake succeeds.
let (st_si2, _, si2_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_si2, 200);
let si2_json: Value = serde_json::from_slice(&si2_bytes).unwrap();
let exchange_code2 = si2_json["exchangeCode"].as_str().expect("exchangeCode2");
let (st_ex2, _, ex2_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_code2,
"installationId": "550e8400-e29b-41d4-a716-446655440099",
"platform": "electron",
"deviceName": "SIO Test Client"
})
.to_string()
.as_bytes(),
)
.await;
assert_eq!(st_ex2, 201);
let ex2_json: Value = serde_json::from_slice(&ex2_bytes).unwrap();
let access_token = ex2_json["accessToken"].as_str().expect("accessToken2").to_owned();
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");
@@ -3037,14 +3075,19 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
}
};
// 4. realtime:request contract coverage.
let prof = emit_ack(1, "realtime:request", serde_json::json!({ "op": "user.profile.get" })).await;
// 4. realtime:request contract coverage (explicit clientVersion required).
let prof = emit_ack(
1,
"realtime:request",
serde_json::json!({ "op": "user.profile.get", "clientVersion": "0.27.5" }),
)
.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" }),
serde_json::json!({ "op": "user.quota-state.get", "clientVersion": "0.27.5" }),
)
.await;
let uq_state = &uq["data"]["state"];
@@ -3055,14 +3098,14 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
"expected lowercase plan, got {uq}"
);
assert!(
uq_state.as_object().unwrap().contains_key("copilotActionLimit"),
"copilotActionLimit must be present: {uq}"
uq_state["unlimitedCopilot"].is_boolean(),
"unlimitedCopilot must be boolean: {uq}"
);
let wq = emit_ack(
3,
"realtime:request",
serde_json::json!({ "op": "workspace.quota-state.get", "input": { "workspaceId": ws_id } }),
serde_json::json!({ "op": "workspace.quota-state.get", "input": { "workspaceId": ws_id }, "clientVersion": "0.27.5" }),
)
.await;
assert!(wq["data"]["state"]["usesOwnerQuota"].is_boolean(), "got {wq}");
@@ -3071,7 +3114,7 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let wm = emit_ack(
4,
"realtime:request",
serde_json::json!({ "op": "workspace.members.get", "input": { "workspaceId": ws_id, "skip": 0, "take": 20 } }),
serde_json::json!({ "op": "workspace.members.get", "input": { "workspaceId": ws_id, "skip": 0, "take": 20 }, "clientVersion": "0.27.5" }),
)
.await;
assert_eq!(wm["data"]["memberCount"], 1, "got {wm}");
@@ -3080,7 +3123,7 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let inv = emit_ack(
5,
"realtime:request",
serde_json::json!({ "op": "workspace.invite-link.get", "input": { "workspaceId": ws_id } }),
serde_json::json!({ "op": "workspace.invite-link.get", "input": { "workspaceId": ws_id }, "clientVersion": "0.27.5" }),
)
.await;
assert!(inv.get("error").is_none(), "invite-link.get failed: {inv}");
@@ -3088,18 +3131,18 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let tr = emit_ack(
6,
"realtime:request",
serde_json::json!({ "op": "copilot.transcript.task.get", "input": { "workspaceId": ws_id, "taskId": "t1" } }),
serde_json::json!({ "op": "copilot.transcript.task.get", "input": { "workspaceId": ws_id, "taskId": "t1" }, "clientVersion": "0.27.5" }),
)
.await;
assert_eq!(tr["error"]["name"], "COPILOT_DISABLED", "got {tr}");
assert_eq!(tr["error"]["name"], "ACTION_FORBIDDEN", "got {tr}");
let emb = emit_ack(
7,
"realtime:request",
serde_json::json!({ "op": "workspace.embedding.progress.get", "input": { "workspaceId": ws_id } }),
serde_json::json!({ "op": "workspace.embedding.progress.get", "input": { "workspaceId": ws_id }, "clientVersion": "0.27.5" }),
)
.await;
assert_eq!(emb["error"]["name"], "COPILOT_DISABLED", "got {emb}");
assert_eq!(emb["error"]["name"], "ACTION_FORBIDDEN", "got {emb}");
// 5. realtime:subscribe for 4 topics (authorized succeeds, unauthorized workspace rejected).
for (idx, (topic, input)) in [
@@ -3117,7 +3160,7 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let ack = emit_ack(
10 + idx as u32,
"realtime:subscribe",
serde_json::json!({ "topic": topic, "input": input }),
serde_json::json!({ "topic": topic, "input": input, "clientVersion": "0.27.5" }),
)
.await;
assert!(ack.get("error").is_none(), "subscribe {topic} failed: {ack}");
@@ -3126,7 +3169,7 @@ fn socketio_jwt_handshake_version_gate_and_realtime_contract_e2e() {
let unauth_sub = emit_ack(
20,
"realtime:subscribe",
serde_json::json!({ "topic": "workspace.members.changed", "input": { "workspaceId": "ws_nonexistent_unauth" } }),
serde_json::json!({ "topic": "workspace.members.changed", "input": { "workspaceId": "ws_nonexistent_unauth" }, "clientVersion": "0.27.5" }),
)
.await;
assert!(
@@ -50,7 +50,7 @@ This document lists intentional improvements in the native Rust backend. Each en
## Calendar Webhook Verification Token Derivation
- Area: `packages/backend/server-domain/src/calendar/mod.rs` (`webhook_token_from_config`).
- Area: `packages/backend/server-domain/src/calendar/mod.rs` (`try_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.
+32 -10
View File
@@ -30,7 +30,7 @@ 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;
return false;
}
if let Some(start) = trimmed.find("<Code>")
&& let Some(end) = trimmed[start + 6..].find("</Code>")
@@ -38,7 +38,17 @@ fn is_s3_missing_object_404(body: &str) -> bool {
let code = trimmed[start + 6..start + 6 + end].trim();
return matches!(code, "NoSuchKey" | "NotFound");
}
true
false
}
fn is_s3_no_such_bucket_404(body: &str) -> bool {
let trimmed = body.trim();
if let Some(start) = trimmed.find("<Code>")
&& let Some(end) = trimmed[start + 6..].find("</Code>")
{
return trimmed[start + 6..start + 6 + end].trim() == "NoSuchBucket";
}
false
}
async fn read_bounded_error_body(context: &str, mut response: reqwest::Response) -> Result<String, StorageError> {
@@ -265,10 +275,8 @@ fn parse_list_parts_xml(xml: &str) -> Vec<UploadedPart> {
.into_iter()
.filter_map(|b| {
let part_number = extract_xml_tag(&b, "PartNumber")?.parse::<i32>().ok()?;
Some(UploadedPart {
part_number,
etag: extract_xml_tag(&b, "ETag")?,
})
let etag = extract_xml_tag(&b, "ETag")?.trim().trim_matches('"').to_owned();
Some(UploadedPart { part_number, etag })
})
.collect()
}
@@ -526,6 +534,10 @@ impl BlobStorageBackend for S3BlobStorage {
let context = format!("delete {key}");
let response = self.send(&context, Method::DELETE, url, &[], None).await?;
if response.status() == StatusCode::NOT_FOUND {
let body = read_bounded_error_body(&context, response).await?;
if is_s3_no_such_bucket_404(&body) {
return Err(request_error(&context, format!("HTTP 404 Not Found: {body}")));
}
return Ok(());
}
Self::ensure_success(&context, response).await?;
@@ -621,7 +633,7 @@ impl BlobStorageBackend for S3BlobStorage {
.headers()
.get(ETAG)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.map(|s| s.trim().trim_matches('"').to_owned())
.ok_or_else(|| StorageError::Metadata("missing ETag in S3 upload part response".into()))
}
async fn list_multipart_parts(&self, key: &str, upload_id: &str) -> Result<Option<Vec<UploadedPart>>, StorageError> {
@@ -636,6 +648,10 @@ impl BlobStorageBackend for S3BlobStorage {
.send(&ctx, Method::GET, action.sign(DEFAULT_PRESIGN_EXPIRES), &[], None)
.await?;
if resp.status() == StatusCode::NOT_FOUND {
let body = read_bounded_error_body(&ctx, resp).await?;
if is_s3_no_such_bucket_404(&body) {
return Err(request_error(&ctx, format!("HTTP 404 Not Found: {body}")));
}
return Ok(None);
}
let xml = Self::ensure_success(&ctx, resp)
@@ -697,6 +713,10 @@ impl BlobStorageBackend for S3BlobStorage {
let ctx = format!("abort_multipart {key}");
let resp = self.send(&ctx, Method::DELETE, url, &[], None).await?;
if resp.status() == StatusCode::NOT_FOUND {
let body = read_bounded_error_body(&ctx, resp).await?;
if is_s3_no_such_bucket_404(&body) {
return Err(request_error(&ctx, format!("HTTP 404 Not Found: {body}")));
}
return Ok(false);
}
Self::ensure_success(&ctx, resp).await?;
@@ -816,9 +836,11 @@ mod tests {
"<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(""));
assert!(!is_s3_missing_object_404("<Error><Code>NoSuch"));
assert!(!is_s3_missing_object_404(""));
assert!(!is_s3_missing_object_404("<html><body>404 Not Found</body></html>"));
assert!(is_s3_no_such_bucket_404("<Error><Code>NoSuchBucket</Code></Error>"));
assert!(!is_s3_no_such_bucket_404("<Error><Code>NoSuchKey</Code></Error>"));
}
#[test]
@@ -266,6 +266,7 @@ pub struct RuntimeAppConfigBaseline {
pub redis_configured: bool,
pub redis_url_env_set: bool,
pub redis_url_has_password: bool,
pub redis_key_prefix: String,
}
impl RuntimeAppConfigBaseline {
@@ -506,7 +507,24 @@ impl AppConfigService {
}
Ok(resolved)
}
}
/// Resolves the effective private key from `AppConfigService` (`DB > File`),
/// falling back to `fallback` (`Env > startup ephemeral`) only when no DB/file
/// key is configured. Propagates transient DB errors to callers.
pub async fn resolve_effective_private_key(
app_config: Option<&AppConfigService>,
fallback: &str,
) -> Result<String, DomainError> {
if let Some(cfg) = app_config
&& let Some(key) = cfg.get_internal_private_key().await?
{
return Ok(key);
}
Ok(fallback.to_owned())
}
impl AppConfigService {
/// Internal-only reader for the effective `mailer` configuration, merging the
/// startup baseline with all `app_configs` rows matching `mailer` or
/// `mailer.%` without secret redaction. Never expose over HTTP or GraphQL.
@@ -534,8 +552,9 @@ impl AppConfigService {
}
/// Internal-only reader for the startup file baseline `redis.ioredis.keyPrefix`
/// (falling back to `redis.keyPrefix`), bypassing `SECRET_CONFIG_KEYS` redaction
/// on `redis.ioredis` and ignoring any legacy `app_configs` `redis.*` rows.
/// (falling back to `redis.keyPrefix`, then CLI `redis_key_prefix`), bypassing
/// `SECRET_CONFIG_KEYS` redaction on `redis.ioredis` and ignoring legacy
/// `app_configs` `redis.*` rows.
pub async fn get_internal_redis_key_prefix(&self) -> Result<String, DomainError> {
let resolved = self
.baseline
@@ -549,6 +568,7 @@ impl AppConfigService {
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
})
.or_else(|| (!self.baseline.redis_key_prefix.is_empty()).then_some(self.baseline.redis_key_prefix.as_str()))
.unwrap_or("")
.to_owned();
Ok(resolved)
@@ -2168,6 +2188,47 @@ mod tests {
assert!(enabled);
assert_eq!(required, ">=0.27.0");
// 5. resolve_effective_private_key reads DB override and falls back cleanly to Env after hot delete.
sqlx::query(
"INSERT INTO app_configs (id, value, created_at, updated_at) VALUES ('crypto.privateKey', '\"db-key-A\"'::jsonb, now(), now()) ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value",
)
.execute(db.pool())
.await
.expect("insert db private key");
svc.invalidate_cache();
assert_eq!(
resolve_effective_private_key(Some(&svc), "env-key-E").await.expect("db key"),
"db-key-A"
);
sqlx::query("DELETE FROM app_configs WHERE id = 'crypto.privateKey'")
.execute(db.pool())
.await
.expect("delete db private key");
svc.invalidate_cache();
assert_eq!(
resolve_effective_private_key(Some(&svc), "env-key-E")
.await
.expect("fallback env key"),
"env-key-E"
);
// 6. get_internal_redis_key_prefix falls back to CLI baseline when config.json omits redis.keyPrefix.
let cli_prefix_svc = AppConfigService::new(
db.clone(),
RuntimeAppConfigBaseline {
redis_key_prefix: "cli_pfx:".to_owned(),
..RuntimeAppConfigBaseline::default()
},
Arc::new(crate::events::NoopEventPublisher::default()),
);
assert_eq!(
cli_prefix_svc
.get_internal_redis_key_prefix()
.await
.expect("cli prefix"),
"cli_pfx:"
);
db.pool().close().await;
});
}
+85 -14
View File
@@ -184,6 +184,10 @@ pub struct AuthConfig {
pub password_max_length: usize,
pub session_ttl_seconds: i64,
pub session_ttr_seconds: i64,
pub access_token_ttl_secs: i64,
pub refresh_idle_ttl_secs: i64,
pub refresh_absolute_ttl_secs: i64,
pub refresh_grace_secs: i64,
pub oauth_providers: std::collections::HashMap<String, oauth::OAuthProviderConfig>,
}
@@ -219,6 +223,10 @@ impl Default for AuthConfig {
password_max_length: 32,
session_ttl_seconds: DEFAULT_COOKIE_SESSION_TTL_SECONDS,
session_ttr_seconds: DEFAULT_COOKIE_SESSION_TTR_SECONDS,
access_token_ttl_secs: DEFAULT_ACCESS_TOKEN_TTL_SECS,
refresh_idle_ttl_secs: DEFAULT_REFRESH_IDLE_TTL_SECS,
refresh_absolute_ttl_secs: DEFAULT_REFRESH_ABSOLUTE_TTL_SECS,
refresh_grace_secs: DEFAULT_REFRESH_GRACE_SECS,
oauth_providers: std::collections::HashMap::new(),
}
}
@@ -330,8 +338,18 @@ impl AuthService {
self
}
fn base_token_policy(&self) -> AuthTokenPolicy {
AuthTokenPolicy {
access_token_ttl_secs: self.config.access_token_ttl_secs,
refresh_idle_ttl_secs: self.config.refresh_idle_ttl_secs,
refresh_absolute_ttl_secs: self.config.refresh_absolute_ttl_secs,
refresh_grace_secs: self.config.refresh_grace_secs,
}
}
async fn verify_signup_domain(&self, email: &str) -> Result<(), DomainError> {
if !self.config.require_email_domain_verification {
let require_verification = self.load_dynamic_auth_runtime().await.require_email_domain_verification;
if !require_verification {
return Ok(());
}
let normalized = email.trim().to_ascii_lowercase();
@@ -389,7 +407,7 @@ impl AuthService {
.await
.map_err(|e| DomainError::Internal(format!("load auth token policy: {e}")))?;
drop(conn);
let policy = parse_auth_token_policy(rows);
let policy = parse_auth_token_policy(self.base_token_policy(), rows);
keyring::rotate_signing_key(&self.db, actor_id, expected_active_key_id, policy.access_token_ttl_secs).await
}
@@ -404,6 +422,7 @@ impl AuthService {
/// Issues a compatibility cookie session directly for `user_id` (`UserType.token`).
pub async fn issue_cookie_session_for_user(&self, user_id: &str) -> Result<CookieSignInResult, DomainError> {
let rt = self.load_dynamic_auth_runtime().await;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -420,7 +439,7 @@ impl AuthService {
let now = decision_time(tx.tx_mut()).await?;
let issued = self
.sessions
.issue_cookie_session(tx.tx_mut(), user_id, None, None, self.config.session_ttl_seconds, now)
.issue_cookie_session(tx.tx_mut(), user_id, None, None, rt.session_ttl_seconds, now)
.await
.map_err(|e| DomainError::Internal(format!("issue user cookie session: {e}")))?;
self
@@ -595,9 +614,24 @@ impl AuthService {
/// [`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> {
match self.create_first_admin_user_for_client(input, false).await? {
OpenAppSignInResult::Cookie(res) => Ok(res),
OpenAppSignInResult::Native { .. } => Err(DomainError::Internal("unexpected native setup result".to_owned())),
}
}
pub async fn create_first_admin_user_for_client(
&self,
input: CreateAdminUserInput,
is_native_client: bool,
) -> Result<OpenAppSignInResult, DomainError> {
let email = canonical_email(&input.email)?;
let rt = self.load_dynamic_auth_runtime().await;
password::validate_password_requirements(&input.password, rt.password_min_length, rt.password_max_length)?;
// Fail fast before Argon2id hashing if an admin or registered user already exists.
if self.is_server_initialized().await? {
return Err(DomainError::Forbidden("First user already created".to_owned()));
}
let password_hash = password::hash_password(&input.password)?;
let mut tx = self
@@ -659,6 +693,38 @@ impl AuthService {
.await
.map_err(|e| DomainError::Internal(format!("insert admin user feature: {e}")))?;
if is_native_client {
let exchange_code = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
let challenge_key = token_hash(&exchange_code);
let expires_at = now + Duration::seconds(AUTH_SESSION_EXCHANGE_TTL_SECONDS);
let payload = serde_json::json!({
"userId": user_id,
"authEpoch": 0,
"clientVersion": input.client_version,
});
sqlx::query(
r#"INSERT INTO runtime_states (purpose, token_hash, payload, created_at, updated_at, expires_at)
VALUES ($1, $2, $3, $4, $4, $5)"#,
)
.bind(AUTH_SESSION_EXCHANGE_PURPOSE)
.bind(&challenge_key)
.bind(&payload)
.bind(now)
.bind(expires_at)
.execute(&mut **tx.tx_mut())
.await
.map_err(|e| DomainError::Internal(format!("insert native admin exchange code: {e}")))?;
let user = load_current_user_in_tx(tx.tx_mut(), &user_id)
.await?
.ok_or_else(|| DomainError::Internal("newly created admin user missing".to_owned()))?;
tx.commit()
.await
.map_err(|e| DomainError::Internal(format!("commit create_first_admin_user native: {e}")))?;
return Ok(OpenAppSignInResult::Native { user, exchange_code });
}
let issued = self
.sessions
.issue_cookie_session(
@@ -666,7 +732,7 @@ impl AuthService {
&user_id,
None,
input.client_version.as_deref(),
self.config.session_ttl_seconds,
rt.session_ttl_seconds,
now,
)
.await
@@ -686,13 +752,13 @@ impl AuthService {
.await
.map_err(|e| DomainError::Internal(format!("commit create_first_admin_user: {e}")))?;
Ok(CookieSignInResult {
Ok(OpenAppSignInResult::Cookie(CookieSignInResult {
user,
session_id: issued.session_id,
user_session_id: issued.user_session_id,
expires_at: issued.expires_at,
created_user: true,
})
}))
}
/// Authenticates an existing user by email + Argon2id password for a native
@@ -985,6 +1051,8 @@ impl AuthService {
false
};
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.config.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1073,7 +1141,7 @@ impl AuthService {
.await?;
let recipient_domain = email_lower.split_once('@').map(|(_, d)| d).unwrap_or_default();
let recipient_hash = hmac_sha256_hex(&self.config.private_key, &email_lower)?;
let recipient_hash = hmac_sha256_hex(&private_key, &email_lower)?;
let mail_payload = serde_json::json!({
"name": mail_name,
"to": email,
@@ -1451,6 +1519,7 @@ impl AuthService {
.ok_or_else(|| DomainError::Unauthorized("invalid_auth_state".to_owned()))?
.to_owned();
let rt = self.load_dynamic_auth_runtime().await;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1528,7 +1597,7 @@ impl AuthService {
&user_id,
existing_session_id,
client_version,
self.config.session_ttl_seconds,
rt.session_ttl_seconds,
now,
)
.await
@@ -1832,7 +1901,7 @@ impl AuthService {
return Err(DomainError::Unauthorized("invalid_auth_state".to_owned()));
}
let token_policy = load_auth_token_policy_in_tx(tx.tx_mut()).await?;
let token_policy = load_auth_token_policy_in_tx(tx.tx_mut(), self.base_token_policy()).await?;
let now = decision_time(tx.tx_mut()).await?;
let absolute_expires_at = now + Duration::seconds(token_policy.refresh_absolute_ttl_secs);
let idle_expires_at = (now + Duration::seconds(token_policy.refresh_idle_ttl_secs)).min(absolute_expires_at);
@@ -2039,7 +2108,9 @@ impl AuthService {
// Independent per-token rolling refresh rate limit before locking session rows.
self.consume_refresh_rate_limit(&token_id).await?;
let encryption_key = SuccessorKey::derive(self.config.private_key.as_bytes())?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.config.private_key).await?;
let encryption_key = SuccessorKey::derive(private_key.as_bytes())?;
let attempt_hash = attempt_id.map(token_hash);
let keys = self.ensure_signing_keys().await?;
@@ -2057,7 +2128,7 @@ impl AuthService {
.await
.map_err(|e| DomainError::Internal(format!("begin refresh_auth_session: {e}")))?;
let token_policy = load_auth_token_policy_in_tx(tx.tx_mut()).await?;
let token_policy = load_auth_token_policy_in_tx(tx.tx_mut(), self.base_token_policy()).await?;
// Deadlock-free lock order: users -> user_sessions -> auth_sessions -> auth_refresh_tokens (ORDER BY id).
let disabled: bool = sqlx::query_scalar("SELECT disabled FROM users WHERE id = $1 FOR UPDATE")
@@ -2886,8 +2957,7 @@ pub enum BearerResolutionError {
Domain(DomainError),
}
fn parse_auth_token_policy(rows: Vec<sqlx::postgres::PgRow>) -> AuthTokenPolicy {
let mut policy = AuthTokenPolicy::default();
fn parse_auth_token_policy(mut policy: AuthTokenPolicy, rows: Vec<sqlx::postgres::PgRow>) -> AuthTokenPolicy {
let apply_token_obj = |policy: &mut AuthTokenPolicy, obj: &serde_json::Map<String, Value>| {
if let Some(v) = obj.get("accessTokenTtl") {
policy.access_token_ttl_secs = parse_duration_secs_clamped(
@@ -2977,6 +3047,7 @@ fn parse_auth_token_policy(rows: Vec<sqlx::postgres::PgRow>) -> AuthTokenPolicy
async fn load_auth_token_policy_in_tx(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
baseline: AuthTokenPolicy,
) -> Result<AuthTokenPolicy, DomainError> {
let rows = sqlx::query(
"SELECT id, value FROM app_configs
@@ -2986,7 +3057,7 @@ async fn load_auth_token_policy_in_tx(
.fetch_all(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load auth token policy: {e}")))?;
Ok(parse_auth_token_policy(rows))
Ok(parse_auth_token_policy(baseline, rows))
}
fn serialize_rfc3339_millis<S: serde::Serializer>(dt: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error> {
@@ -277,6 +277,7 @@ impl AuthService {
target: OpenAppIssueTarget<'_>,
) -> Result<OpenAppSignInResult, DomainError> {
let email = canonical_email(&account.email)?;
let session_ttl_seconds = self.load_dynamic_auth_runtime().await.session_ttl_seconds;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -382,7 +383,7 @@ impl AuthService {
&user_id,
existing_session_id,
client_version,
self.config.session_ttl_seconds,
session_ttl_seconds,
now,
)
.await
@@ -71,6 +71,8 @@ impl AuthService {
source: Option<&AuthRequestSource>,
) -> Result<bool, DomainError> {
let mut url = parse_callback_url(callback_url)?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.config.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -127,6 +129,7 @@ impl AuthService {
&format!("auth:{}:{}", kind.purpose(), token_hash(&token)),
expires_at,
source,
&private_key,
now,
)
.await?;
@@ -149,6 +152,8 @@ impl AuthService {
) -> Result<bool, DomainError> {
let email = canonical_email(new_email)?;
let mut url = parse_callback_url(callback_url)?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.config.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -162,6 +167,10 @@ impl AuthService {
}
let now = decision_time(tx.tx_mut()).await?;
// Validate and consume the challenge inside `tx` before checking email
// uniqueness so forged tokens always return `INVALID_EMAIL_TOKEN` without
// leaking whether an email is taken; on validation error `tx` rolls back
// and preserves the valid token.
consume_security_state(
tx.tx_mut(),
PURPOSE_CHANGE_EMAIL,
@@ -218,6 +227,7 @@ impl AuthService {
&format!("auth:verify-change-email:{}", token_hash(&token)),
expires_at,
source,
&private_key,
now,
)
.await?;
@@ -284,6 +294,8 @@ impl AuthService {
new_email: &str,
) -> Result<bool, DomainError> {
let email = canonical_email(new_email)?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.config.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -330,6 +342,7 @@ impl AuthService {
&format!("auth:email-changed:{}:{}", user_id, user.auth_epoch + 1),
now + Duration::days(1),
None,
&private_key,
now,
)
.await?;
@@ -430,6 +443,7 @@ impl AuthService {
dedupe_key: &str,
expires_at: DateTime<Utc>,
source: Option<&AuthRequestSource>,
private_key: &str,
now: DateTime<Utc>,
) -> Result<(), DomainError> {
let recipient_email = recipient_email.trim();
@@ -458,7 +472,7 @@ impl AuthService {
.check_auth_mail(tx, mail_name, &normalized_email, recipient_user_id, source, now)
.await?;
let recipient_hash = hmac_sha256_hex(&self.config.private_key, &normalized_email)?;
let recipient_hash = hmac_sha256_hex(private_key, &normalized_email)?;
let mail_payload = serde_json::json!({
"name": mail_name,
"to": recipient_email,
@@ -417,37 +417,44 @@ impl CalendarService {
pub fn callback_url_for(&self, external_url: &str) -> String {
format!("{}/api/calendar/oauth/callback", external_url.trim_end_matches('/'))
}
pub async fn webhook_token_from_config(&self, google: &CalendarGoogleConfig) -> String {
pub async fn try_webhook_token_from_config(&self, google: &CalendarGoogleConfig) -> Result<String, CalendarError> {
if let Some(ref configured) = google.webhook_verification_token
&& !configured.is_empty()
{
return configured.clone();
return Ok(configured.clone());
}
let key = self.effective_private_key().await;
let key = self.try_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());
return Ok(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();
return Ok(cached.clone());
}
let derived = Uuid::new_v4().to_string();
if let Ok(mut guard) = self.generated_webhook_token.lock() {
*guard = Some(derived.clone());
}
derived
Ok(derived)
}
/// Verifies an incoming `x-goog-channel-token` header in constant time.
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())))
/// Verifies an incoming `x-goog-channel-token` header in constant time,
/// propagating transient private-key lookup errors.
pub async fn try_verify_webhook_token(
&self,
google: &CalendarGoogleConfig,
provided: &str,
) -> Result<bool, CalendarError> {
let expected = self.try_webhook_token_from_config(google).await?;
Ok(
expected.is_empty()
|| (expected.len() == provided.len() && bool::from(expected.as_bytes().ct_eq(provided.as_bytes()))),
)
}
pub fn webhook_address_from_config(&self, google: &CalendarGoogleConfig, provider: &str) -> Option<String> {
let base = google.external_webhook_url.as_deref()?.trim();
@@ -1452,8 +1459,16 @@ mod tests {
// 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);
let k1_webhook = calendar
.try_webhook_token_from_config(&google_cfg)
.await
.expect("k1 webhook");
assert!(
calendar
.try_verify_webhook_token(&google_cfg, &k1_webhook)
.await
.expect("verify k1")
);
// 2. DB override with leading/trailing whitespace takes effect live without leaking via public config.
let db_override_key = " K2-db-override ";
@@ -1479,10 +1494,23 @@ mod tests {
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;
let k2_webhook = calendar
.try_webhook_token_from_config(&google_cfg)
.await
.expect("k2 webhook");
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);
assert!(
calendar
.try_verify_webhook_token(&google_cfg, &k2_webhook)
.await
.expect("verify k2")
);
assert!(
!calendar
.try_verify_webhook_token(&google_cfg, &k1_webhook)
.await
.expect("reject k1")
);
// 3. Deleting DB override falls back to K1 file key live.
sqlx::query("DELETE FROM app_configs WHERE id = 'crypto.privateKey'")
@@ -1491,8 +1519,19 @@ mod tests {
.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);
assert_eq!(
calendar
.try_webhook_token_from_config(&google_cfg)
.await
.expect("k1 webhook after delete"),
k1_webhook
);
assert!(
calendar
.try_verify_webhook_token(&google_cfg, &k1_webhook)
.await
.expect("verify k1 after delete")
);
// 4. Env key E with empty file config and pre-existing DB key D at startup:
// deleting DB D immediately falls back to E on the hot instance, matching a cold-started instance with E.
@@ -1526,8 +1565,14 @@ mod tests {
.with_app_config(empty_file_app_config);
assert_eq!(hot_calendar.effective_private_key().await, env_key_e);
assert_eq!(
hot_calendar.webhook_token_from_config(&google_cfg).await,
cold_calendar.webhook_token_from_config(&google_cfg).await
hot_calendar
.try_webhook_token_from_config(&google_cfg)
.await
.expect("hot webhook"),
cold_calendar
.try_webhook_token_from_config(&google_cfg)
.await
.expect("cold webhook")
);
let ct_e = encrypt_token(&hot_calendar.effective_private_key().await, "env-cal-secret").expect("encrypt E");
assert_eq!(
@@ -32,10 +32,19 @@ pub fn is_valid_oauth_state(state: &str) -> bool {
pub struct CalendarOAuthStore {
client: Option<redis::Client>,
conn: Arc<Mutex<Option<redis::aio::MultiplexedConnection>>>,
key_prefix: String,
}
impl CalendarOAuthStore {
/// Creates a store targeting `session_redis_db_index` on the given Redis client.
pub fn new(base_client: Option<redis::Client>, session_redis_db_index: u8) -> Result<Self, DomainError> {
Self::with_key_prefix(base_client, session_redis_db_index, String::new())
}
/// Creates a store targeting `session_redis_db_index` with an optional Redis key prefix.
pub fn with_key_prefix(
base_client: Option<redis::Client>,
session_redis_db_index: u8,
key_prefix: impl Into<String>,
) -> Result<Self, DomainError> {
let client = match base_client {
Some(base) => {
let mut info = base.get_connection_info().clone();
@@ -50,10 +59,11 @@ impl CalendarOAuthStore {
Ok(Self {
client,
conn: Arc::new(Mutex::new(None)),
key_prefix: key_prefix.into(),
})
}
fn redis_key(token: &str) -> String {
format!("{CALENDAR_OAUTH_STATE_PREFIX}:{token}")
fn redis_key(&self, token: &str) -> String {
format!("{}{CALENDAR_OAUTH_STATE_PREFIX}:{token}", self.key_prefix)
}
async fn connection(&self) -> Result<redis::aio::MultiplexedConnection, DomainError> {
if let Some(existing) = self.conn.lock().await.clone() {
@@ -80,7 +90,7 @@ impl CalendarOAuthStore {
let serialized = serde_json::to_string(&state)
.map_err(|err| DomainError::Internal(format!("serialize calendar oauth state: {err}")))?;
let mut conn = self.connection().await?;
let key = Self::redis_key(&token);
let key = self.redis_key(&token);
if let Err(err) = redis::cmd("SET")
.arg(&key)
.arg(&serialized)
@@ -97,7 +107,7 @@ impl CalendarOAuthStore {
/// Reads an OAuth state entry without deleting it.
pub async fn get_oauth_state(&self, token: &str) -> Result<Option<CalendarOAuthState>, DomainError> {
let mut conn = self.connection().await?;
let key = Self::redis_key(token);
let key = self.redis_key(token);
let raw: Option<String> = match redis::cmd("GET").arg(&key).query_async(&mut conn).await {
Ok(v) => v,
Err(err) => {
@@ -115,7 +125,7 @@ impl CalendarOAuthStore {
/// Deletes an OAuth state entry after successful callback redemption.
pub async fn delete_oauth_state(&self, token: &str) -> Result<(), DomainError> {
let mut conn = self.connection().await?;
let key = Self::redis_key(token);
let key = self.redis_key(token);
if let Err(err) = redis::cmd("DEL").arg(&key).query_async::<i64>(&mut conn).await {
self.reset_connection().await;
return Err(DomainError::Unavailable(format!("delete calendar oauth state: {err}")));
@@ -133,7 +143,7 @@ end
return value
"#;
let mut conn = self.connection().await?;
let key = Self::redis_key(token);
let key = self.redis_key(token);
let raw: Option<String> = match redis::Script::new(GET_AND_DEL_LUA)
.key(&key)
.invoke_async(&mut conn)
@@ -615,6 +615,7 @@ async fn ensure_google_webhook_channel(
if !is_claim_still_valid(service, &subscription.id, claimed_until).await? {
return Ok(());
}
let token = service.try_webhook_token_from_config(google_cfg).await?;
let provider = GoogleCalendarProvider::new(google_cfg.clone());
if let (Some(ch_id), Some(res_id)) = (
subscription.custom_channel_id.as_deref(),
@@ -630,7 +631,6 @@ async fn ensure_google_webhook_channel(
}
}
let channel_id = Uuid::new_v4().to_string();
let token = service.webhook_token_from_config(google_cfg).await;
match provider
.watch_calendar(
access_token,
+14 -3
View File
@@ -116,6 +116,7 @@ pub struct CommentService {
invalidation: Arc<dyn InvalidationPublisher>,
base_url: String,
private_key: String,
app_config: Option<crate::app_config::AppConfigService>,
}
impl CommentService {
@@ -133,6 +134,7 @@ impl CommentService {
invalidation: Arc::new(NoopEventPublisher::default()),
base_url: "http://localhost:3010".to_owned(),
private_key: String::new(),
app_config: None,
}
}
@@ -151,6 +153,11 @@ impl CommentService {
self
}
pub fn with_app_config(mut self, app_config: crate::app_config::AppConfigService) -> Self {
self.app_config = Some(app_config);
self
}
pub async fn create_comment(
&self,
actor_user_id: &str,
@@ -163,6 +170,8 @@ impl CommentService {
.doc_sharing
.resolve_storage_doc_id(workspace_id, raw_doc_id)
.await?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -222,7 +231,7 @@ impl CommentService {
None,
notification,
&self.base_url,
&self.private_key,
&private_key,
now,
)
.await?;
@@ -326,6 +335,8 @@ impl CommentService {
content: Value,
notification: CommentNotificationContext,
) -> Result<ReplyRecord, DomainError> {
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -384,7 +395,7 @@ impl CommentService {
Some(&reply_id),
notification,
&self.base_url,
&self.private_key,
&private_key,
now,
)
.await?;
@@ -676,7 +687,7 @@ impl CommentService {
)));
}
let limit = take.clamp(1, 10_000);
let limit = take.clamp(1, 10_001);
let comment_rows = if let Some(ts) = comment_updated_at {
sqlx::query(
r#"SELECT sid, id, workspace_id, doc_id, user_id, content, resolved, created_at, updated_at, deleted_at
@@ -1643,11 +1643,16 @@ impl DocSharingService {
.await
.map_err(|e| DomainError::Internal(format!("count doc_grants: {e}")))?;
let after_key: Option<(DateTime<Utc>, String)> = if let Some(raw_cursor) = after.filter(|s| !s.trim().is_empty()) {
enum DocGrantCursor {
Composite(DateTime<Utc>, String),
TimestampOnly(DateTime<Utc>),
}
let after_key: Option<DocGrantCursor> = if let Some(raw_cursor) = after.filter(|s| !s.trim().is_empty()) {
if let Some((ts_str, uid)) = raw_cursor.split_once('|') {
DateTime::parse_from_rfc3339(ts_str)
.ok()
.map(|dt| (dt.with_timezone(&Utc), uid.to_owned()))
.map(|dt| DocGrantCursor::Composite(dt.with_timezone(&Utc), uid.to_owned()))
} else {
// Legacy cursor encoding plain `user_id` or RFC3339 timestamp.
let by_user: Option<(DateTime<Utc>, String)> = sqlx::query_as(
@@ -1659,12 +1664,12 @@ impl DocSharingService {
.fetch_optional(&mut **tx.tx_mut())
.await
.map_err(|e| DomainError::Internal(format!("resolve doc_grants cursor: {e}")))?;
if by_user.is_some() {
by_user
if let Some((ts, uid)) = by_user {
Some(DocGrantCursor::Composite(ts, uid))
} else {
DateTime::parse_from_rfc3339(raw_cursor)
.ok()
.map(|dt| (dt.with_timezone(&Utc), String::new()))
.map(|dt| DocGrantCursor::TimestampOnly(dt.with_timezone(&Utc)))
}
}
} else {
@@ -1673,41 +1678,64 @@ impl DocSharingService {
let limit = first.clamp(1, 100);
let fetch_limit = limit + 1;
let rows = if let Some((after_ts, after_uid)) = after_key {
sqlx::query(
r#"SELECT g.role, g.created_at, u.id, u.name, u.email, u.avatar_url
FROM doc_grants g
JOIN users u ON u.id = g.principal_id
WHERE g.workspace_id = $1
AND g.doc_id = $2
AND g.principal_type = 'user'
AND (g.created_at > $3 OR (g.created_at = $3 AND g.principal_id > $4))
ORDER BY g.created_at ASC, g.principal_id ASC
OFFSET $5 LIMIT $6"#,
)
.bind(workspace_id)
.bind(&doc_id)
.bind(after_ts)
.bind(after_uid)
.bind(offset.max(0))
.bind(fetch_limit)
.fetch_all(&mut **tx.tx_mut())
.await
} else {
sqlx::query(
r#"SELECT g.role, g.created_at, u.id, u.name, u.email, u.avatar_url
FROM doc_grants g
JOIN users u ON u.id = g.principal_id
WHERE g.workspace_id = $1 AND g.doc_id = $2 AND g.principal_type = 'user'
ORDER BY g.created_at ASC, g.principal_id ASC
OFFSET $3 LIMIT $4"#,
)
.bind(workspace_id)
.bind(&doc_id)
.bind(offset.max(0))
.bind(fetch_limit)
.fetch_all(&mut **tx.tx_mut())
.await
let rows = match after_key {
Some(DocGrantCursor::Composite(after_ts, after_uid)) => {
sqlx::query(
r#"SELECT g.role, g.created_at, u.id, u.name, u.email, u.avatar_url
FROM doc_grants g
JOIN users u ON u.id = g.principal_id
WHERE g.workspace_id = $1
AND g.doc_id = $2
AND g.principal_type = 'user'
AND (g.created_at > $3 OR (g.created_at = $3 AND g.principal_id > $4))
ORDER BY g.created_at ASC, g.principal_id ASC
OFFSET $5 LIMIT $6"#,
)
.bind(workspace_id)
.bind(&doc_id)
.bind(after_ts)
.bind(after_uid)
.bind(offset.max(0))
.bind(fetch_limit)
.fetch_all(&mut **tx.tx_mut())
.await
}
Some(DocGrantCursor::TimestampOnly(after_ts)) => {
sqlx::query(
r#"SELECT g.role, g.created_at, u.id, u.name, u.email, u.avatar_url
FROM doc_grants g
JOIN users u ON u.id = g.principal_id
WHERE g.workspace_id = $1
AND g.doc_id = $2
AND g.principal_type = 'user'
AND g.created_at >= $3
ORDER BY g.created_at ASC, g.principal_id ASC
OFFSET $4 LIMIT $5"#,
)
.bind(workspace_id)
.bind(&doc_id)
.bind(after_ts)
.bind(offset.max(0).saturating_add(1))
.bind(fetch_limit)
.fetch_all(&mut **tx.tx_mut())
.await
}
None => {
sqlx::query(
r#"SELECT g.role, g.created_at, u.id, u.name, u.email, u.avatar_url
FROM doc_grants g
JOIN users u ON u.id = g.principal_id
WHERE g.workspace_id = $1 AND g.doc_id = $2 AND g.principal_type = 'user'
ORDER BY g.created_at ASC, g.principal_id ASC
OFFSET $3 LIMIT $4"#,
)
.bind(workspace_id)
.bind(&doc_id)
.bind(offset.max(0))
.bind(fetch_limit)
.fetch_all(&mut **tx.tx_mut())
.await
}
}
.map_err(|e| DomainError::Internal(format!("list doc_grants: {e}")))?;
let _ = tx.rollback().await;
@@ -42,6 +42,7 @@ pub struct NotificationService {
event_bus: Arc<dyn EventBusPublisher>,
base_url: String,
private_key: String,
app_config: Option<crate::app_config::AppConfigService>,
}
impl NotificationService {
@@ -58,6 +59,7 @@ impl NotificationService {
event_bus,
base_url: "http://localhost:3010".to_owned(),
private_key: String::new(),
app_config: None,
}
}
@@ -71,6 +73,11 @@ impl NotificationService {
self
}
pub fn with_app_config(mut self, app_config: crate::app_config::AppConfigService) -> Self {
self.app_config = Some(app_config);
self
}
pub async fn count_by_user(&self, user_id: &str) -> Result<i64, DomainError> {
let mut conn = self
.db
@@ -281,6 +288,8 @@ impl NotificationService {
return Err(DomainError::Validation("mention_user_oneself_denied".to_owned()));
}
let storage_doc_id = self.doc_sharing.resolve_storage_doc_id(workspace_id, &doc.id).await?;
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
@@ -365,7 +374,7 @@ impl NotificationService {
enqueue_notification_mail_in_tx(
tx.tx_mut(),
EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name: "Mention",
mail_class: "doc_mention",
recipient_user_id: target_user_id,
@@ -215,6 +215,7 @@ pub struct WorkspaceService {
redis: Option<redis::Client>,
base_url: String,
private_key: String,
app_config: Option<crate::app_config::AppConfigService>,
fallback_invite_links: Arc<tokio::sync::RwLock<std::collections::HashMap<String, WorkspaceInviteLink>>>,
}
@@ -230,6 +231,7 @@ impl WorkspaceService {
redis: None,
base_url: "http://localhost:3010".to_owned(),
private_key: String::new(),
app_config: None,
fallback_invite_links: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
}
}
@@ -244,6 +246,11 @@ impl WorkspaceService {
self
}
pub fn with_app_config(mut self, app_config: crate::app_config::AppConfigService) -> Self {
self.app_config = Some(app_config);
self
}
pub fn with_event_bus(mut self, event_bus: Arc<dyn crate::events::EventBusPublisher>) -> Self {
self.event_bus = event_bus;
self
@@ -781,6 +788,8 @@ impl WorkspaceService {
}
}
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1026,7 +1035,7 @@ impl WorkspaceService {
&invitation_id,
"Invitation",
&self.base_url,
&self.private_key,
&private_key,
)
.await?;
notified_invitees.push(uid.clone());
@@ -1083,6 +1092,8 @@ impl WorkspaceService {
invitee_user_id: &str,
invitation_id: &str,
) -> Result<WorkspaceMemberRecord, DomainError> {
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1250,7 +1261,7 @@ impl WorkspaceService {
invitation_id,
"InvitationAccepted",
&self.base_url,
&self.private_key,
&private_key,
)
.await?;
}
@@ -1306,6 +1317,8 @@ impl WorkspaceService {
));
}
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1395,7 +1408,7 @@ impl WorkspaceService {
crate::notifications::enqueue_notification_mail_in_tx(
tx.tx_mut(),
crate::notifications::EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name,
mail_class: "workspace_lifecycle",
recipient_user_id: target_user_id,
@@ -1505,6 +1518,8 @@ impl WorkspaceService {
return Err(DomainError::Forbidden("cannot_revoke_self".to_owned()));
}
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -1589,7 +1604,7 @@ impl WorkspaceService {
crate::notifications::enqueue_notification_mail_in_tx(
tx.tx_mut(),
crate::notifications::EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name: "MemberRemoved",
mail_class: "workspace_lifecycle",
recipient_user_id: target_user_id,
@@ -1617,7 +1632,7 @@ impl WorkspaceService {
&inv_id,
"InvitationReviewDeclined",
&self.base_url,
&self.private_key,
&private_key,
)
.await?;
declined_notify_user = Some(uid);
@@ -2077,6 +2092,8 @@ impl WorkspaceService {
/// Removes `actor_user_id` from `workspace_id`. Rejects Owners with
/// `workspace_owner_cannot_leave`.
pub async fn leave_workspace(&self, actor_user_id: &str, workspace_id: &str) -> Result<(), DomainError> {
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -2128,7 +2145,7 @@ impl WorkspaceService {
crate::notifications::enqueue_notification_mail_in_tx(
tx.tx_mut(),
crate::notifications::EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name: "MemberLeave",
mail_class: "workspace_lifecycle",
recipient_user_id: &owner_id,
@@ -2179,6 +2196,8 @@ impl WorkspaceService {
workspace_id: &str,
target_user_id: &str,
) -> Result<WorkspaceMemberRecord, DomainError> {
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -2278,7 +2297,7 @@ impl WorkspaceService {
crate::notifications::enqueue_notification_mail_in_tx(
tx.tx_mut(),
crate::notifications::EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name: "OwnershipTransferred",
mail_class: "workspace_lifecycle",
recipient_user_id: actor_user_id,
@@ -2294,7 +2313,7 @@ impl WorkspaceService {
crate::notifications::enqueue_notification_mail_in_tx(
tx.tx_mut(),
crate::notifications::EnqueueNotificationMail {
private_key: &self.private_key,
private_key: &private_key,
mail_name: "OwnershipReceived",
mail_class: "workspace_lifecycle",
recipient_user_id: target_user_id,
@@ -2359,6 +2378,8 @@ impl WorkspaceService {
workspace_id: &str,
target_user_id: &str,
) -> Result<(), DomainError> {
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -2454,7 +2475,7 @@ impl WorkspaceService {
&inv_id,
"InvitationReviewApproved",
&self.base_url,
&self.private_key,
&private_key,
)
.await?;
@@ -2726,6 +2747,8 @@ impl WorkspaceService {
return Err(DomainError::NotFound("invalid_invitation".to_owned()));
};
let private_key =
crate::app_config::resolve_effective_private_key(self.app_config.as_ref(), &self.private_key).await?;
let mut tx = self
.db
.begin_tiered(WorkloadTier::InteractiveWrite)
@@ -2904,7 +2927,7 @@ impl WorkspaceService {
&review_id,
"InvitationReviewRequest",
&self.base_url,
&self.private_key,
&private_key,
)
.await?;
}
@@ -7,7 +7,7 @@ use async_graphql::{Context, Enum, InputObject, Result, SimpleObject, Upload};
use chrono::{DateTime, Utc};
use server_blob::{PutBlobOutcome, UploadInitMethod, UploadedPart};
use server_domain::events::InvalidationHintV1;
use server_types::{DeploymentMode, DomainError};
use server_types::DomainError;
use super::{JsonObjectScalar, require_authenticated_user};
use crate::AppState;
@@ -85,43 +85,6 @@ async fn publish_quota_storage_invalidation(state: &AppState, workspace_id: &str
.publish_invalidation(&InvalidationHintV1::QuotaStorageUsage { subject })
.await;
}
let prefix = match state.config.load().deployment_mode {
DeploymentMode::Selfhosted => "selfhosted",
DeploymentMode::Cloud => "cloud",
};
let mut topics = vec![
(
"runtime-invalidation",
serde_json::json!({ "workspaceId": workspace_id }),
format!("workspace:{workspace_id}:quota-state"),
"workspace.quota-state.changed",
),
(
"quota-state-changed",
serde_json::json!({ "workspaceId": workspace_id }),
format!("workspace:{workspace_id}:access"),
"workspace.access.changed",
),
];
if let Some(ref owner) = owner_id {
topics.push((
"runtime-invalidation",
serde_json::json!({}),
format!("user:{owner}:quota-state"),
"user.quota-state.changed",
));
}
for (reason, input, room, topic) in topics {
let req = format!("{prefix}:event:{}", uuid::Uuid::new_v4());
let payload = serde_json::json!({
"event": { "changed": true, "reason": reason }, "input": input, "room": room, "topic": topic,
});
let _ = state
.event_bus
.publish_event("realtime.topic.changed", payload, Some(&req))
.await;
}
}
async fn require_member_state<'a>(ctx: &'a Context<'_>, workspace_id: &str) -> Result<&'a Arc<AppState>> {
@@ -400,12 +400,13 @@ impl CalendarMutation {
.and_then(|h| h.get(axum::http::header::HOST))
.and_then(|v| v.to_str().ok());
let cfg = state.config.load();
let server_hosts = crate::rest::effective_server_hosts(state).await;
let redirect_uri = match input.redirect_uri {
Some(raw) if !raw.is_empty() => Some(
crate::rest::validate_and_build_calendar_redirect_uri(
&raw,
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
&[],
@@ -426,7 +427,7 @@ impl CalendarMutation {
.map_err(|e| domain_error_to_graphql(&e))?;
let cb_origin = crate::rest::calendar_callback_origin(
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
);
@@ -221,7 +221,9 @@ impl LazyGraphqlPrincipal {
rejected_cookie_version: resolved.rejected_cookie_version,
})
}
Err(crate::rest::PrincipalResolutionError::VersionGuard { error, clear_cookies }) => {
Err(crate::rest::PrincipalResolutionError::VersionGuard {
error, clear_cookies, ..
}) => {
if clear_cookies && let Ok(mut guard) = self.cookie_action.lock() {
*guard = crate::rest::PrincipalCookieAction::Clear;
}
@@ -213,6 +213,10 @@ impl UserType {
}
async fn copilot(&self, ctx: &Context<'_>, workspace_id: Option<String>) -> Result<super::copilot::Copilot> {
let caller = require_authenticated_user(ctx).await?;
if self.view.id != caller.id {
return Err(domain_error_to_graphql(&DomainError::Forbidden("access_denied".into())));
}
super::copilot::resolve_user_copilot(ctx, workspace_id).await
}
@@ -239,6 +243,10 @@ impl UserType {
ctx: &Context<'_>,
pagination: super::doc::PaginationInput,
) -> Result<super::notification::PaginatedNotificationObjectType> {
let caller = require_authenticated_user(ctx).await?;
if self.view.id != caller.id {
return Err(domain_error_to_graphql(&DomainError::Forbidden("access_denied".into())));
}
super::notification::resolve_user_notifications(ctx, pagination).await
}
@@ -956,7 +964,7 @@ pub(crate) async fn resolve_admin_user_by_id(ctx: &Context<'_>, id: String) -> R
.get_user_by_id_admin(&id)
.await
.map_err(|e| domain_error_to_graphql(&e))?
.ok_or_else(|| async_graphql::Error::new("Cannot return null for non-nullable field Query.userById."))?;
.ok_or_else(|| domain_error_to_graphql(&DomainError::NotFound("user_not_found".into())))?;
Ok(UserType::session(view))
}
+136 -25
View File
@@ -319,7 +319,16 @@ impl AppState {
.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 redis_key_prefix = config
.app_config_baseline
.file_json
.pointer("/redis/ioredis/keyPrefix")
.or_else(|| config.app_config_baseline.file_json.pointer("/redis/keyPrefix"))
.and_then(serde_json::Value::as_str)
.unwrap_or("")
.to_owned();
let calendar_oauth =
CalendarOAuthStore::with_key_prefix(redis.clone(), config.session_redis_db_index, redis_key_prefix).ok();
let mcp = McpCredentialService::new(db.clone(), Arc::clone(&services.event_bus))
.with_quota_gate(extension.quota_gate())
.with_invalidation(Arc::clone(&services.invalidation));
@@ -763,6 +772,43 @@ const MAX_GRAPHQL_BRACKET_DEPTH: usize = 64;
/// Linear `O(n)` lexical pre-scan rejecting deeply nested unquoted `{`/`[`/`(`
/// before handing a query to `async-graphql`'s recursive-descent parser.
fn graphql_selection_set_uses_introspection(set: &async_graphql::parser::types::SelectionSet) -> bool {
for item in &set.items {
match &item.node {
async_graphql::parser::types::Selection::Field(field) => {
let name = field.node.name.node.as_str();
if name == "__schema" || name == "__type" {
return true;
}
if graphql_selection_set_uses_introspection(&field.node.selection_set.node) {
return true;
}
}
async_graphql::parser::types::Selection::InlineFragment(frag) => {
if graphql_selection_set_uses_introspection(&frag.node.selection_set.node) {
return true;
}
}
async_graphql::parser::types::Selection::FragmentSpread(_) => {}
}
}
false
}
fn graphql_doc_uses_introspection(doc: &async_graphql::parser::types::ExecutableDocument) -> bool {
for (_, op) in doc.operations.iter() {
if graphql_selection_set_uses_introspection(&op.node.selection_set.node) {
return true;
}
}
for frag in doc.fragments.values() {
if graphql_selection_set_uses_introspection(&frag.node.selection_set.node) {
return true;
}
}
false
}
pub fn graphql_query_exceeds_depth(query: &str, max_depth: usize) -> bool {
let (b, mut i, mut depth) = (query.as_bytes(), 0usize, 0usize);
while i < b.len() {
@@ -821,12 +867,17 @@ 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 code_str = if status == StatusCode::METHOD_NOT_ALLOWED {
"Method Not Allowed"
} else {
"Bad Request"
};
let body = serde_json::json!({
"errors": [{
"message": message,
"extensions": {
"status": status.as_u16(),
"code": "Bad Request",
"code": code_str,
"type": "BAD_REQUEST",
"name": "GRAPHQL_BAD_REQUEST",
"message": formatted,
@@ -838,12 +889,18 @@ fn graphql_bad_request_response(status: StatusCode, apollo_code: &str, message:
}]
})
.to_string();
(
let mut resp = (
status,
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
body,
)
.into_response()
.into_response();
if status == StatusCode::METHOD_NOT_ALLOWED {
resp
.headers_mut()
.insert(header::ALLOW, HeaderValue::from_static("POST"));
}
resp
}
/// Reads a `/graphql` POST body. A multipart body goes through
@@ -918,9 +975,24 @@ async fn execute_graphql_request(
.get_effective_app_config_arc()
.await
.ok()
.and_then(|c| c.pointer("/graphql/introspection")?.as_bool())
.and_then(|c| {
c.pointer("/graphql/apolloDriverConfig/introspection")
.or_else(|| c.pointer("/graphql/introspection"))
.and_then(serde_json::Value::as_bool)
})
.unwrap_or(true);
let is_parse_error = async_graphql::parser::parse_query(&inner.query).is_err();
let parsed_query = async_graphql::parser::parse_query(&inner.query);
let is_parse_error = parsed_query.is_err();
if !introspection_enabled
&& let Ok(ref doc) = parsed_query
&& graphql_doc_uses_introspection(doc)
{
return graphql_bad_request_response(
StatusCode::BAD_REQUEST,
"GRAPHQL_VALIDATION_FAILED",
"GraphQL introspection is not allowed by Apollo Server, but the query contained __schema or __type.",
);
}
let lazy = LazyGraphqlPrincipal::new(state.clone(), headers.clone(), peer);
let mut gql_req = inner.data(lazy.clone()).data(headers);
if !introspection_enabled {
@@ -960,12 +1032,39 @@ async fn execute_graphql_request(
ext.set("data", data);
}
}
let mut gql_server_err_req_id: Option<String> = None;
for err in &mut raw_resp.errors {
let is_5xx = err
.extensions
.as_ref()
.and_then(|ext| ext.get("status"))
.and_then(|v| match v {
async_graphql::Value::Number(n) => n.as_u64(),
_ => None,
})
.is_some_and(|s| s >= 500);
if is_5xx {
let rid = gql_server_err_req_id
.get_or_insert_with(|| uuid::Uuid::new_v4().to_string())
.clone();
let ext = err.extensions.get_or_insert_with(Default::default);
if ext.get("requestId").is_none() {
ext.set("requestId", async_graphql::Value::from(rid));
}
}
}
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();
if let Some(ref rid) = gql_server_err_req_id
&& !h.contains_key("x-request-id")
&& let Ok(v) = HeaderValue::from_str(rid)
{
h.insert(header::HeaderName::from_static("x-request-id"), v);
}
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
@@ -1005,18 +1104,7 @@ async fn handle_graphql_post(
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())
});
let has_preflight = has_apollo_csrf_header(&headers);
if has_session_cookie && !has_preflight {
let csrf_blocked = || {
graphql_bad_request_response(
@@ -1038,8 +1126,7 @@ async fn handle_graphql_post(
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());
.and_then(rest::worker_proxy::extract_origin_from_url);
let allowed =
rest::worker_proxy::allowed_origins_for_state_async(&state, rest::worker_proxy::CorsOriginScope::Global).await;
let cfg_snap = state.app.config.load();
@@ -1125,7 +1212,7 @@ async fn handle_graphql_get(
.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)
!matches!(op.node.ty, async_graphql::parser::types::OperationType::Query)
}
async_graphql::parser::types::DocumentOperations::Multiple(ops) => {
if let Some(name) = target_op_name {
@@ -1157,9 +1244,12 @@ async fn handle_graphql_get(
}
if let Some(vars_str) = params.variables {
match serde_json::from_str::<serde_json::Value>(&vars_str) {
Ok(val) => {
Ok(val @ (serde_json::Value::Object(_) | serde_json::Value::Null)) => {
req = req.variables(async_graphql::Variables::from_json(val));
}
Ok(_) => {
return graphql_bad_request_response(StatusCode::BAD_REQUEST, "BAD_REQUEST", "Variables must be an object.");
}
Err(_) => {
return graphql_bad_request_response(StatusCode::BAD_REQUEST, "BAD_REQUEST", "Variables are invalid JSON.");
}
@@ -1179,7 +1269,15 @@ async fn handle_graphql_get(
)
.into_response();
}
Html(GraphiQLSource::build().endpoint("/graphql").finish()).into_response()
let base_path = cfg.app_config_baseline.server.path.trim().trim_end_matches('/');
let endpoint = if base_path.is_empty() || base_path == "/" {
"/graphql".to_owned()
} else if base_path.starts_with('/') {
format!("{base_path}/graphql")
} else {
format!("/{base_path}/graphql")
};
Html(GraphiQLSource::build().endpoint(&endpoint).finish()).into_response()
}
/// Explicit `(DeploymentMode, ServerRole)` HTTP route mount matrix aligned
@@ -1285,10 +1383,17 @@ pub fn build_router(app: Arc<AppState>) -> Router {
post(rest::auth::handle_open_app_sign_in_code),
)
.route("/api/auth/open-app/sign-in", post(rest::auth::handle_open_app_sign_in))
.route("/api/avatars/{id}", get(rest::blobs::handle_get_avatar));
.merge(
Router::new()
.route("/api/avatars/{id}", get(rest::blobs::handle_get_avatar))
.layer(axum::middleware::from_fn_with_state(
state.clone(),
rest::blobs::blobs_default_throttle_middleware,
)),
);
}
if matrix.graphql_flavor_api {
router = router
let blobs_router = Router::new()
.route(
"/api/workspaces/{workspace_id}/blobs/v1/{name}",
get(rest::blobs::handle_get_blob_v1),
@@ -1325,6 +1430,12 @@ pub fn build_router(app: Arc<AppState>) -> Router {
"/api/workspaces/{workspace_id}/docs/{doc_id}/comment-attachments/{key}",
get(rest::blobs::handle_get_comment_attachment),
)
.layer(axum::middleware::from_fn_with_state(
state.clone(),
rest::blobs::blobs_default_throttle_middleware,
));
router = router
.merge(blobs_router)
.merge(rest::oauth::router())
.merge(rest::captcha::router())
.merge(rest::r2_proxy::router())
+211 -85
View File
@@ -54,8 +54,8 @@ fn append_user_id_cookie(headers: &mut HeaderMap, user_id: &str) {
#[derive(Debug, Deserialize)]
pub struct CreateAdminUserBody {
pub name: Option<String>,
pub email: String,
pub password: String,
pub email: Option<String>,
pub password: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -69,25 +69,80 @@ pub(crate) async fn handle_create_admin_user(
State(state): State<RouterState>,
PeerAddr(peer): PeerAddr,
headers: HeaderMap,
axum::Json(body): axum::Json<CreateAdminUserBody>,
body_bytes: axum::body::Bytes,
) -> Response {
let throttle = match enforce_throttle_http(&state, &headers, peer, None, ThrottleSpec::Default).await {
Ok(h) => h,
Err(resp) => return *resp,
};
let body: CreateAdminUserBody = match serde_json::from_slice(&body_bytes) {
Ok(b) => b,
Err(_) => {
let mut resp = envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "VALIDATION_ERROR".into(),
message: "Invalid create-admin-user payload.".into(),
data: None,
});
apply_throttle(resp.headers_mut(), throttle);
return resp;
}
};
let email = match body.email.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
Some(e) => e.to_owned(),
None => {
let mut resp = invalid_email_response();
apply_throttle(resp.headers_mut(), throttle);
return resp;
}
};
let password = match body.password.filter(|s| !s.is_empty()) {
Some(p) => p,
None => {
let mut resp = envelope_to_http_response(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,
});
apply_throttle(resp.headers_mut(), throttle);
return resp;
}
};
let client_version = extract_non_empty_client_version(&headers);
let is_native = is_native_client_request(&headers);
let result = state
.app
.auth
.create_first_admin_user(CreateAdminUserInput {
name: body.name,
email: body.email,
password: body.password,
client_version: extract_non_empty_client_version(&headers),
})
.create_first_admin_user_for_client(
CreateAdminUserInput {
name: body.name,
email,
password,
client_version,
},
is_native,
)
.await;
let mut resp = match result {
Ok(sign_in) => {
Ok(server_domain::auth::OpenAppSignInResult::Native { user, exchange_code }) => {
let cfg = state.app.config.load();
let val = serde_json::json!({
"email": user.email,
"id": user.id,
"name": user.name,
"exchangeCode": exchange_code,
});
let mut resp = json_utf8_response(StatusCode::OK, val, false);
append_clear_auth_cookies(resp.headers_mut(), cfg.https);
resp
}
Ok(server_domain::auth::OpenAppSignInResult::Cookie(sign_in)) => {
let cfg = state.app.config.load();
let mut resp = json_utf8_response(
StatusCode::OK,
@@ -302,9 +357,9 @@ 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> {
async fn check_sign_in_rate_bucket(state: &RouterState, key: &str, limit: u64, ttl_ms: u64) -> (bool, Result<(), u64>) {
if limit == 0 || ttl_ms == 0 {
return Ok(());
return (state.app.redis.is_some(), Ok(()));
}
if let Some(client) = state.app.redis.as_ref() {
let mut conn = state.app.throttle_redis_conn.lock().await.clone();
@@ -336,9 +391,9 @@ async fn check_sign_in_rate_bucket(state: &RouterState, key: &str, limit: u64, t
*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 (true, Err(retry_after_secs));
}
return Ok(());
return (true, Ok(()));
}
}
}
@@ -360,18 +415,21 @@ async fn check_sign_in_rate_bucket(state: &RouterState, key: &str, limit: u64, t
})
.lock()
else {
return Ok(());
return (false, Ok(()));
};
const MAX_MEM_RATE_KEYS: usize = 65_536;
let table = &mut *table;
check_mem_rate_table(
&mut table.map,
&mut table.last_gc,
now,
key,
limit,
ttl_ms,
MAX_MEM_RATE_KEYS,
(
false,
check_mem_rate_table(
&mut table.map,
&mut table.last_gc,
now,
key,
limit,
ttl_ms,
MAX_MEM_RATE_KEYS,
),
)
}
@@ -435,6 +493,17 @@ mod mem_rate_limit_tests {
}
}
fn should_increment_email_bucket_after_ip_limit(has_shared_redis: bool, ip_exceeded: bool) -> bool {
!ip_exceeded || has_shared_redis
}
fn combine_sign_in_retry_after(ip_retry_after: Option<u64>, email_retry_after: Option<u64>) -> Option<u64> {
match (ip_retry_after, email_retry_after) {
(Some(a), Some(b)) => Some(a.max(b)),
(a, b) => a.or(b),
}
}
async fn enforce_sign_in_rate_limit(
state: &RouterState,
headers: &HeaderMap,
@@ -467,21 +536,28 @@ async fn enforce_sign_in_rate_limit(
(!s.is_empty()).then(|| s.to_owned())
})
.or_else(|| peer.map(|a| a.ip().to_string()));
let mut ip_retry_after = None;
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}");
if let Err(retry_after_secs) = check_sign_in_rate_bucket(state, &ip_key, ip_limit, ttl_ms).await {
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);
let (ip_used_shared_redis, ip_res) = check_sign_in_rate_bucket(state, &ip_key, ip_limit, ttl_ms).await;
if let Err(retry_after_secs) = ip_res {
if !should_increment_email_bucket_after_ip_limit(ip_used_shared_redis, true) {
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));
}
return Err(Box::new(resp));
ip_retry_after = Some(retry_after_secs);
}
}
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}");
if let Err(retry_after_secs) = check_sign_in_rate_bucket(state, &email_key, email_limit, ttl_ms).await {
let (_, email_res) = check_sign_in_rate_bucket(state, &email_key, email_limit, ttl_ms).await;
let email_retry_after = email_res.err();
if let Some(retry_after_secs) = combine_sign_in_retry_after(ip_retry_after, email_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);
@@ -503,7 +579,8 @@ pub(crate) async fn handle_sign_in(
};
let role = state.app.config.load().role;
if role != server_types::ServerRole::Front
&& let Err(mut resp) = super::captcha::enforce_named_captcha_guard(&state, &headers, &resolved.cookie_action).await
&& let Err(mut resp) =
super::captcha::enforce_named_captcha_guard(&state, &headers, peer, &resolved.cookie_action).await
{
apply_throttle(resp.headers_mut(), throttle);
return *resp;
@@ -516,30 +593,47 @@ pub(crate) async fn handle_sign_in(
let body: SignInBody = match serde_json::from_slice(&body_bytes) {
Ok(b) => b,
Err(err) => {
return apply_old_cookie(domain_error_to_http_response(&DomainError::Validation(format!(
"Invalid sign-in payload: {err}"
))));
return apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "VALIDATION_ERROR".into(),
message: format!("Invalid sign-in payload: {err}"),
data: None,
}));
}
};
let email = match canonical_email(&body.email) {
Ok(e) => e,
Err(_) => return apply_old_cookie(invalid_email_response()),
};
if let Some(ref password) = body.password {
if password.is_empty() {
return apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "VALIDATION_ERROR".into(),
message: "Password must not be empty.".to_owned(),
data: None,
}));
}
if password.len() > server_domain::auth::password::MAX_PASSWORD_BYTES {
return apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "INVALID_INPUT".into(),
name: "VALIDATION_ERROR".into(),
message: "Password exceeds maximum allowed length.".to_owned(),
data: None,
}));
}
}
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() {
return apply_old_cookie(domain_error_to_http_response(&DomainError::Validation(
"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
@@ -644,14 +738,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 dynamic_hosts = if let Some(arr) = eff_cfg.as_ref().and_then(|c| c.pointer("/server/hosts")?.as_array()) {
arr
.iter()
.filter_map(serde_json::Value::as_str)
.filter(|h| !h.is_empty())
.map(str::to_owned)
.collect::<Vec<_>>()
} else {
cfg.app_config_baseline.server.hosts.clone()
};
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, &dynamic_hosts) {
Ok(url) => url,
@@ -683,6 +779,16 @@ pub(crate) async fn handle_sign_in(
data: Some(serde_json::json!({ "email": email })),
})
}
Err(DomainError::Unavailable(code)) if code == "email_domain_verification_unavailable" => {
envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::GATEWAY_TIMEOUT.as_u16(),
code: "Gateway Timeout".into(),
error_type: "NETWORK_ERROR".into(),
name: "NETWORK_ERROR".into(),
message: "Email domain verification unavailable.".into(),
data: None,
})
}
Err(DomainError::Forbidden(code)) if code == "sign_up_forbidden" => {
envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
@@ -853,21 +959,23 @@ pub(crate) async fn handle_complete_magic_link(
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" => {
Err(DomainError::Unavailable(code)) if code == "email_domain_verification_unavailable" => {
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(),
status: StatusCode::GATEWAY_TIMEOUT.as_u16(),
code: "Gateway Timeout".into(),
error_type: "NETWORK_ERROR".into(),
name: "NETWORK_ERROR".into(),
message: "Email domain verification unavailable.".into(),
data: None,
}))
}
Err(DomainError::Unauthorized(_)) | Err(DomainError::Forbidden(_)) => {
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,
}))
}
@@ -898,30 +1006,25 @@ pub(crate) async fn handle_complete_magic_link(
resp
}
Err(DomainError::Unauthorized(code)) if code == "invalid_auth_state" => {
apply_old_cookie(invalid_auth_state_response())
}
Err(DomainError::Unavailable(code)) if code == "email_domain_verification_unavailable" => {
apply_old_cookie(envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "Bad Request".into(),
error_type: "BAD_REQUEST".into(),
name: "INVALID_AUTH_STATE".into(),
message: "Invalid auth state.".into(),
status: StatusCode::GATEWAY_TIMEOUT.as_u16(),
code: "Gateway Timeout".into(),
error_type: "NETWORK_ERROR".into(),
name: "NETWORK_ERROR".into(),
message: "Email domain verification unavailable.".into(),
data: None,
}))
}
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" => {
Err(DomainError::Unauthorized(_)) | Err(DomainError::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(),
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,
}))
}
@@ -1448,7 +1551,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), "security_action")
.revoke_auth_session(&auth_session_id, Some(&principal.user().id), "user_action")
.await
{
Ok(_) => auth_session_json_response(StatusCode::OK, serde_json::json!({})),
@@ -1458,3 +1561,26 @@ pub(crate) async fn handle_revoke_auth_session_by_id(
apply_throttle(resp.headers_mut(), throttle);
resp
}
#[cfg(test)]
mod tests {
use super::{combine_sign_in_retry_after, should_increment_email_bucket_after_ip_limit};
#[test]
fn sign_in_rate_limit_increments_email_bucket_only_when_shared_redis_succeeded() {
assert!(should_increment_email_bucket_after_ip_limit(true, false));
assert!(should_increment_email_bucket_after_ip_limit(true, true));
assert!(should_increment_email_bucket_after_ip_limit(false, false));
// Unreachable Redis falling back to memory table passes ip_used_shared_redis = false.
assert!(!should_increment_email_bucket_after_ip_limit(false, true));
}
#[test]
fn sign_in_rate_limit_retry_after_takes_max_across_both_buckets() {
assert_eq!(combine_sign_in_retry_after(None, None), None);
assert_eq!(combine_sign_in_retry_after(Some(12), None), Some(12));
assert_eq!(combine_sign_in_retry_after(None, Some(45)), Some(45));
assert_eq!(combine_sign_in_retry_after(Some(12), Some(45)), Some(45));
assert_eq!(combine_sign_in_retry_after(Some(55), Some(20)), Some(55));
}
}
+48 -25
View File
@@ -6,6 +6,7 @@ use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use server_types::DomainError;
use super::throttle::{ThrottleOutcome, ThrottleSpec, check_throttle_for_app, too_many_requests_envelope};
use super::{
apply_blob_security_headers, domain_error_to_http_response, envelope_to_http_response, json_utf8_response,
resolve_request_principal_with_policy,
@@ -13,6 +14,35 @@ use super::{
use crate::RouterState;
use crate::legacy_compat::errors::LegacyErrorEnvelope;
pub(crate) async fn blobs_default_throttle_middleware(
State(state): State<RouterState>,
req: axum::http::Request<axum::body::Body>,
next: axum::middleware::Next,
) -> Response {
if super::has_valid_authenticated_principal(&state, req.headers()).await {
return next.run(req).await;
}
let peer = req
.extensions()
.get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
.map(|c| c.0);
match check_throttle_for_app(&state.app, Some(req.headers()), peer, None, ThrottleSpec::Default).await {
ThrottleOutcome::Disabled => next.run(req).await,
ThrottleOutcome::Allowed(th) => {
let mut resp = next.run(req).await;
th.apply_to(resp.headers_mut());
resp
}
ThrottleOutcome::Limited { retry_after_secs } => {
let mut resp = envelope_to_http_response(too_many_requests_envelope());
if let Ok(v) = HeaderValue::from_str(&retry_after_secs.to_string()) {
resp.headers_mut().insert(header::RETRY_AFTER, v);
}
resp
}
}
}
/// Serves locally stored user avatars (`GET /api/avatars/:id`) matching
/// `v0.27.5` `core/user/controller.ts`.
pub(crate) async fn handle_get_avatar(
@@ -135,7 +165,7 @@ fn validate_blob_source_query(query: &BlobSourceQuery) -> Result<(&str, &str, Op
error_type: "INVALID_INPUT".into(),
name: "INVALID_HISTORY_TIMESTAMP".into(),
message: "Invalid history timestamp.".into(),
data: None,
data: Some(serde_json::json!({ "timestamp": query.timestamp_ms })),
})));
}
Err(Box::new(envelope_to_http_response(LegacyErrorEnvelope {
@@ -210,9 +240,9 @@ pub(crate) async fn handle_get_blob_v1(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -293,9 +323,9 @@ pub(crate) async fn handle_get_blob_manifest_v1(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -323,14 +353,7 @@ pub(crate) async fn handle_get_readable_blob_manifest_v1(
};
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,
});
let mut resp = domain_error_to_http_response(&DomainError::Unauthorized("Authentication required".into()));
resolved.cookie_action.apply_to(resp.headers_mut(), https);
return resp;
};
@@ -383,9 +406,9 @@ pub(crate) async fn handle_get_readable_blob_manifest_v1(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -487,9 +510,9 @@ pub(crate) async fn handle_get_doc_snapshot(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -546,9 +569,9 @@ pub(crate) async fn handle_head_public_doc(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -600,9 +623,9 @@ pub(crate) async fn handle_get_public_doc(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -642,9 +665,9 @@ pub(crate) async fn handle_get_public_root_doc(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -731,9 +754,9 @@ pub(crate) async fn handle_get_doc_history(
Err(DomainError::Unauthorized(_)) => envelope_to_http_response(LegacyErrorEnvelope {
status: StatusCode::FORBIDDEN.as_u16(),
code: "Forbidden".into(),
error_type: "ACTION_FORBIDDEN".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: "Access denied.".into(),
message: "You do not have permission to access this resource.".into(),
data: None,
}),
Err(err) => domain_error_to_http_response(&err),
@@ -153,11 +153,12 @@ async fn handle_oauth_preflight(
}
let req_host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
let cfg = state.app.config.load();
let server_hosts = super::effective_server_hosts(&state.app).await;
let canonical_redirect = match body.redirect_uri.as_deref().filter(|s| !s.is_empty()) {
Some(raw) => match validate_and_build_calendar_redirect_uri(
raw,
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
&[],
@@ -185,7 +186,7 @@ async fn handle_oauth_preflight(
};
let cb_origin = calendar_callback_origin(
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
);
@@ -248,10 +249,11 @@ async fn handle_oauth_callback(
};
let svc = calendar_service_from_state(&state.app);
let cfg = state.app.config.load();
let server_hosts = super::effective_server_hosts(&state.app).await;
let req_host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
let cb_origin = calendar_callback_origin(
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
);
@@ -265,7 +267,7 @@ async fn handle_oauth_callback(
let canonical = match validate_and_build_calendar_redirect_uri(
redirect_uri,
&cfg.external_url,
&cfg.app_config_baseline.server.hosts,
&server_hosts,
cfg.app_config_baseline.server.port,
req_host,
&[("error", msg.as_str())],
@@ -320,8 +322,10 @@ 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).await {
return with_cookies(StatusCode::UNAUTHORIZED.into_response(), &cookie_action, https);
match svc.try_verify_webhook_token(&configs.google, token).await {
Ok(true) => {}
Ok(false) => return with_cookies(StatusCode::UNAUTHORIZED.into_response(), &cookie_action, https),
Err(err) => return with_cookies(cal_err_resp(&err), &cookie_action, https),
}
match svc.handle_webhook(CalendarProviderName::Google, channel_id).await {
Ok(()) => with_cookies(StatusCode::OK.into_response(), &cookie_action, https),
@@ -3,7 +3,7 @@
use super::throttle::{ThrottleSpec, enforce_throttle_http};
use super::{
PrincipalCookieAction, domain_error_to_http_response, envelope_to_http_response, json_utf8_response,
resolve_auth_request_source, resolve_request_principal_with_policy,
resolve_captcha_remote_ip, resolve_request_principal_with_policy,
};
use crate::RouterState;
use crate::legacy_compat::errors::LegacyErrorEnvelope;
@@ -14,7 +14,7 @@ use axum::response::Response;
use axum::routing::get;
use serde_json::json;
use server_domain::auth::captcha::{
CaptchaVerificationRequest, create_hashcash_challenge, load_effective_captcha_config, verify_captcha,
CaptchaVerificationRequest, create_hashcash_challenge, load_effective_captcha_config_with_file, verify_captcha,
};
use server_types::DomainError;
pub(crate) fn router() -> Router<RouterState> {
@@ -49,7 +49,8 @@ async fn handle_get_captcha(
Err(err) => domain_error_to_http_response(&err),
}
} else {
match load_effective_captcha_config(&state.app.db).await {
let file_json = state.app.config.load().app_config_baseline.file_json.clone();
match load_effective_captcha_config_with_file(&state.app.db, Some(&file_json)).await {
Ok(e) => json_utf8_response(
StatusCode::OK,
json!({ "provider": "turnstile", "siteKey": e.config.turnstile.site_key, "action": e.config.turnstile.action }),
@@ -75,27 +76,33 @@ fn captcha_failed_response(message: &str) -> Response {
pub(crate) async fn enforce_named_captcha_guard(
state: &RouterState,
headers: &HeaderMap,
peer: Option<std::net::SocketAddr>,
pending_cookie_action: &PrincipalCookieAction,
) -> Result<(), Box<Response>> {
let (https, dev_mode, mut allowed_hosts, file_json) = {
let (https, dev_mode, default_host, baseline_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.app_config_baseline.server.host.clone(),
cfg.app_config_baseline.server.hosts.clone(),
cfg.app_config_baseline.file_json.clone(),
)
};
if let Ok(eff) = state.app.app_config.get_effective_app_config().await
let mut allowed_hosts = 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());
}
}
dyn_hosts
.iter()
.filter_map(serde_json::Value::as_str)
.filter(|h| !h.is_empty())
.map(str::to_owned)
.collect::<Vec<_>>()
} else {
baseline_hosts
};
if !default_host.is_empty() && !allowed_hosts.iter().any(|x| x == &default_host) {
allowed_hosts.push(default_host);
}
let fail = |mut resp: Response| -> Result<(), Box<Response>> {
pending_cookie_action.apply_to(resp.headers_mut(), https);
@@ -127,7 +134,7 @@ pub(crate) async fn enforce_named_captcha_guard(
return fail(captcha_failed_response("Invalid Credential"));
}
allowed_hosts.retain(|h| !h.is_empty());
let ip = resolve_auth_request_source(state, headers).await.ip;
let ip = resolve_captcha_remote_ip(state, headers, peer).await;
match verify_captcha(
&state.app.db,
&effective.config,
@@ -182,9 +182,20 @@ async fn handle_render_workspace_path(
};
let wants_md = headers.get_all(header::ACCEPT).iter().any(|val| {
val.to_str().is_ok_and(|raw| {
raw
.split(',')
.any(|p| MARKDOWN_TYPES.contains(&p.split(';').next().unwrap_or("").trim().to_ascii_lowercase().as_str()))
raw.split(',').any(|p| {
let mut segs = p.split(';');
let media = segs.next().unwrap_or("").trim().to_ascii_lowercase();
if !MARKDOWN_TYPES.contains(&media.as_str()) {
return false;
}
let q_zero = segs.any(|param| {
param
.trim()
.split_once('=')
.is_some_and(|(k, v)| k.trim().eq_ignore_ascii_case("q") && v.trim().parse::<f32>().ok() == Some(0.0))
});
!q_zero
})
})
});
if let Some(doc_id) = resolved_doc_id.as_deref()
+71 -2
View File
@@ -185,6 +185,7 @@ pub enum PrincipalResolutionError {
VersionGuard {
error: VersionGuardError,
clear_cookies: bool,
https: bool,
},
Domain(DomainError),
}
@@ -211,16 +212,22 @@ impl PrincipalResolutionError {
false,
)
}
Self::VersionGuard { error, clear_cookies } => (error.into_envelope(), clear_cookies),
Self::VersionGuard {
error, clear_cookies, ..
} => (error.into_envelope(), clear_cookies),
Self::Domain(err) => (domain_error_to_envelope(&err), false),
}
}
pub fn into_http_response(self) -> Response {
let https = match &self {
Self::VersionGuard { https, .. } => *https,
_ => false,
};
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(), false);
append_clear_auth_cookies(resp.headers_mut(), https);
}
resp
}
@@ -300,6 +307,28 @@ pub fn extract_bearer_token(headers: &HeaderMap) -> Option<&str> {
if token.is_empty() { None } else { Some(token) }
}
/// Side-effect-free read-only check for whether the request carries a valid
/// Bearer JWT or active Cookie session (without running version-guard
/// revocation or TTR refresh, which belong to the route handler).
pub(crate) async fn has_valid_authenticated_principal(state: &RouterState, headers: &HeaderMap) -> bool {
if let Some(bearer) = extract_bearer_token(headers).filter(|token| is_likely_jwt(token)) {
return state.app.auth.resolve_bearer_principal(bearer).await.is_ok();
}
let cookies = parse_cookies(headers);
let Some(session_id) = extract_cookie(&cookies, SESSION_COOKIE_NAME) else {
return false;
};
let user_id = extract_cookie(&cookies, USER_ID_COOKIE_NAME);
matches!(
state
.app
.auth
.resolve_cookie_principal(session_id, user_id, None, false)
.await,
Ok(Some(_))
)
}
/// Resolves the authenticated principal from `Authorization: Bearer <jwt>` or
/// `affine_session` cookie, enforcing `client.versionControl` and cookie TTR
/// refresh matching `v0.27.5` `core/auth/guard.ts:85-220` 1:1.
@@ -369,6 +398,7 @@ pub(crate) async fn resolve_request_principal_with_policy(
return Err(PrincipalResolutionError::VersionGuard {
error: ver_err,
clear_cookies: false,
https: state.app.config.load().https,
});
}
@@ -435,6 +465,7 @@ pub(crate) async fn resolve_request_principal_with_policy(
return Err(PrincipalResolutionError::VersionGuard {
error: ver_err,
clear_cookies: true,
https: state.app.config.load().https,
});
}
@@ -800,6 +831,44 @@ pub(crate) async fn resolve_auth_request_source_for_app(
extract_request_source(headers, trusted_cf)
}
/// Returns effective `server.hosts` (DB override replacing baseline).
pub(crate) async fn effective_server_hosts(app: &crate::AppState) -> Vec<String> {
if let Ok(eff) = app.app_config.get_effective_app_config_arc().await
&& let Some(arr) = eff.pointer("/server/hosts").and_then(serde_json::Value::as_array)
{
return arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
}
app.config.load().app_config_baseline.server.hosts.clone()
}
/// Resolves client IP for Turnstile `remoteip`, falling back to `x-real-ip`,
/// `x-forwarded-for`, or socket `peer_addr` when Cloudflare headers are untrusted.
pub(crate) async fn resolve_captcha_remote_ip(
state: &RouterState,
headers: &HeaderMap,
peer: Option<std::net::SocketAddr>,
) -> Option<String> {
if let Some(ip) = resolve_auth_request_source(state, headers).await.ip {
return Some(ip);
}
headers
.get("x-real-ip")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.or_else(|| {
headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|raw| raw.split(',').next())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
})
.or_else(|| peer.map(|p| p.ip().to_string()))
}
/// Resolves [`AuthRequestSource`] using the effective `auth.trustedCloudflareHeaders` flag.
pub(crate) async fn resolve_auth_request_source(state: &RouterState, headers: &HeaderMap) -> AuthRequestSource {
resolve_auth_request_source_for_app(&state.app, headers).await
@@ -166,10 +166,8 @@ async fn handle_oauth_preflight(
Ok(v) => v,
Err(resp) => return *resp,
};
let (external_url, server_hosts) = {
let cfg = state.app.config.load();
(cfg.external_url.clone(), cfg.app_config_baseline.server.hosts.clone())
};
let external_url = state.app.config.load().external_url.clone();
let server_hosts = super::effective_server_hosts(&state.app).await;
let apply_headers = |mut resp: Response| -> Response {
resolved.cookie_action.apply_to(resp.headers_mut(), https);
apply_throttle(resp.headers_mut(), throttle);
@@ -40,7 +40,7 @@ async fn read_body_bounded(body: Body, expected_len: usize) -> Result<Vec<u8>, D
let mut stream = body.into_data_stream();
let mut out = Vec::with_capacity(max_allowed.min(64 * 1024));
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| DomainError::Validation(format!("Failed to read upload body: {e}")))?;
let chunk = chunk.map_err(|e| bad(&format!("Failed to read upload body: {e}")))?;
if out.len().saturating_add(chunk.len()) > max_allowed {
return Err(bad("Content length mismatch"));
}
@@ -28,8 +28,10 @@ fn found_redirect(state: &RouterState, target: &str) -> Response {
let base = cfg.app_config_baseline.server.path.trim().trim_end_matches('/');
let loc = if base.is_empty() || base == "/" {
target.to_owned()
} else {
} else if base.starts_with('/') {
format!("{base}{target}")
} else {
format!("/{base}{target}")
};
(StatusCode::FOUND, [(header::LOCATION, loc)]).into_response()
}
@@ -156,13 +158,16 @@ async fn serve_file(
.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 = if let Some(inm) = hs(header::IF_NONE_MATCH) {
let mut inm_headers = h.get_all(header::IF_NONE_MATCH).iter().peekable();
let not_mod = if inm_headers.peek().is_some() {
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)
inm_headers
.filter_map(|v| v.to_str().ok())
.any(|inm| 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))
@@ -224,7 +229,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_selfhost_get =
cfg.deployment_mode == DeploymentMode::Selfhosted && matches!(method, Method::GET | Method::HEAD);
let is_setup_path = path == "/admin/setup";
let (m, h, https) = (&method, &headers, cfg.https);
if path == "/admin" || path.starts_with("/admin/") {
@@ -313,6 +319,12 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
if let Some(resp) = serve_file(&shell_root, path, m, h, true, explicit, https).await {
return resp;
}
if is_selfhost_get
&& let Ok(initialized) = state.app.auth.is_server_initialized().await
&& !initialized
{
return found_redirect(&state, "/admin/setup");
}
let is_auth = MOBILE_AUTH_PATHS
.iter()
.any(|p| path == *p || path.strip_prefix(p).is_some_and(|r| r.starts_with('/')));
@@ -383,6 +383,7 @@ async fn forward_to_ga4_if_configured(state: &RouterState, events: &[CleanedTele
.await
.ok()
.flatten();
let file_json = state.app.config.load().app_config_baseline.file_json.clone();
let mid = dotted_mid
.filter(|s| !s.trim().is_empty())
.or_else(|| {
@@ -392,6 +393,13 @@ async fn forward_to_ga4_if_configured(state: &RouterState, events: &[CleanedTele
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
})
.or_else(|| {
file_json
.pointer("/telemetry/ga4/measurementId")
.and_then(Value::as_str)
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
})
.or_else(|| {
std::env::var("GA4_MEASUREMENT_ID")
.ok()
@@ -407,6 +415,13 @@ async fn forward_to_ga4_if_configured(state: &RouterState, events: &[CleanedTele
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
})
.or_else(|| {
file_json
.pointer("/telemetry/ga4/apiSecret")
.and_then(Value::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());
@@ -241,9 +241,21 @@ pub(crate) async fn check_throttle_for_app(
(key, limit.max(1), eff_ttl)
}
};
let redis_key_prefix = {
let cfg = app.config.load();
cfg
.app_config_baseline
.file_json
.pointer("/redis/ioredis/keyPrefix")
.or_else(|| cfg.app_config_baseline.file_json.pointer("/redis/keyPrefix"))
.and_then(serde_json::Value::as_str)
.unwrap_or("")
.to_owned()
};
let prefixed_key = format!("{redis_key_prefix}{key}");
let (hits, pttl_ms, block_ttl_ms) = app
.strict_throttler
.increment(app.redis.as_ref(), &key, ttl_ms, limit)
.increment(app.redis.as_ref(), &prefixed_key, ttl_ms, limit)
.await;
if block_ttl_ms > 0 || hits > limit {
let retry_after_secs = if block_ttl_ms > 0 { block_ttl_ms } else { ttl_ms }
@@ -57,7 +57,7 @@ pub(crate) async fn check_shared_throttle(
session_id: Option<&str>,
worker_handler: Option<&str>,
) -> Result<Option<ThrottleQuota>, Box<Response>> {
let cfg = state.app.app_config.get_effective_app_config().await.ok();
let cfg = state.app.app_config.get_effective_app_config_arc().await.ok();
if cfg.as_ref().and_then(|c| c.pointer("/throttle/enabled")) == Some(&Value::Bool(false)) {
return Ok(None);
}
@@ -401,7 +401,18 @@ pub(crate) fn is_cors_origin_allowed(origin: &str, allowed: &[String], dev_mode:
dev_mode && is_dev_loopback_origin(trimmed)
}
fn push_normalized_origin(out: &mut Vec<String>, raw: &str, default_scheme: &str) {
pub(crate) fn extract_origin_from_url(raw: &str) -> Option<String> {
let u = Url::parse(raw.trim()).ok()?;
match u.scheme() {
"http" | "https" => Some(u.origin().ascii_serialization()),
"assets" => Some(format!("assets://{}", u.host_str().unwrap_or(""))),
"capacitor" | "ionic" => Some(format!("{}://{}", u.scheme(), u.host_str().unwrap_or("localhost"))),
"file" => Some("file://".to_owned()),
_ => None,
}
}
fn push_normalized_origin(out: &mut Vec<String>, raw: &str, default_scheme: &str, default_port: Option<u16>) {
let t = raw.trim().trim_end_matches('/');
if t.is_empty() {
return;
@@ -412,63 +423,80 @@ fn push_normalized_origin(out: &mut Vec<String>, raw: &str, default_scheme: &str
}
return;
}
let cand = if t.contains("://") {
let has_scheme = t.contains("://");
let cand = if has_scheme {
t.to_owned()
} else if !t.starts_with('[') && t.matches(':').count() > 1 {
format!("{default_scheme}://[{t}]")
} 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,
if let Ok(mut u) = Url::parse(&cand) {
if let Some(o) = extract_origin_from_url(u.as_str())
&& !out.contains(&o)
{
out.push(o);
}
if !has_scheme
&& u.port().is_none()
&& matches!(u.scheme(), "http" | "https")
&& let Some(port) = default_port
&& u.set_port(Some(port)).is_ok()
&& let Some(o) = extract_origin_from_url(u.as_str())
&& !out.contains(&o)
{
out.push(o);
}
&& !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 parsed_ext = Url::parse(&cfg.external_url).ok();
let scheme = parsed_ext.as_ref().map_or("http".to_owned(), |u| u.scheme().to_owned());
let default_port = parsed_ext.as_ref().and_then(Url::port);
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);
push_normalized_origin(&mut out, &cfg.external_url, &scheme, None);
let eff = state.app.app_config.get_effective_app_config_arc().await.ok();
if let Some(hosts) = eff
.as_ref()
.and_then(|v| v.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, default_port);
}
} else {
for h in &cfg.app_config_baseline.server.hosts {
push_normalized_origin(&mut out, h, &scheme, default_port);
}
}
if scope == CorsOriginScope::Telemetry {
for o in &cfg.telemetry_allowed_origins {
push_normalized_origin(&mut out, o, &scheme);
push_normalized_origin(&mut out, o, &scheme, None);
}
}
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);
}
}
if let Some(eff) = eff {
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);
push_normalized_origin(&mut out, o, &scheme, None);
}
}
if scope == CorsOriginScope::Worker
&& let Some(worker_origins) = eff.pointer("/worker/allowedOrigin").and_then(Value::as_array)
{
for o in worker_origins.iter().filter_map(Value::as_str) {
push_normalized_origin(&mut out, o, &scheme);
push_normalized_origin(&mut out, o, &scheme, None);
}
}
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);
push_normalized_origin(&mut out, o, &scheme, None);
}
}
}
@@ -494,18 +522,9 @@ pub(crate) fn check_origin_or_referer(headers: &HeaderMap, allowed: &[String], d
{
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)
})
h_str(headers, header::REFERER)
.and_then(extract_origin_from_url)
.is_some_and(|candidate| is_cors_origin_allowed(&candidate, allowed, dev_mode))
}
fn fix_url_with_policy(raw: &str, allow_private: &[Origin]) -> Option<Url> {
let t = raw.trim();
@@ -242,7 +242,7 @@ fn admin_user_lifecycle_ban_recreate_import_and_features() {
assert_eq!(ban_resp["data"]["banUser"]["disabled"], true);
assert!(ban_resp["data"]["banUser"]["avatarUrl"].is_null());
// Old user ID no longer exists (non-null GraphQL error, not a business 404).
// Old user ID no longer exists (standard 404 USER_NOT_FOUND envelope).
let (_, old_lookup) = post_graphql(
&app,
Some(&admin_cookie),
@@ -251,7 +251,8 @@ fn admin_user_lifecycle_ban_recreate_import_and_features() {
)
.await;
assert!(!old_lookup["errors"].as_array().unwrap().is_empty());
assert!(old_lookup["errors"][0]["extensions"]["status"].is_null());
assert_eq!(old_lookup["errors"][0]["extensions"]["status"], 404);
assert_eq!(old_lookup["errors"][0]["extensions"]["name"], "USER_NOT_FOUND");
// Owned workspace and snapshot were deleted.
let ws_exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM workspaces WHERE id = $1)")
@@ -152,8 +152,9 @@ fn calendar_rest_webhook_and_oauth_callback_validation() {
.expect("clear explicit webhook token");
let generated_token = state
.calendar
.webhook_token_from_config(&server_domain::calendar::google::CalendarGoogleConfig::default())
.await;
.try_webhook_token_from_config(&server_domain::calendar::google::CalendarGoogleConfig::default())
.await
.expect("generated webhook token");
let resp = router
.clone()
.oneshot(
@@ -544,6 +545,17 @@ fn calendar_rest_webhook_and_oauth_callback_validation() {
multi_host_cfg.app_config_baseline.server.hosts = vec!["app2.affine.local".to_owned()];
multi_host_cfg.app_config_baseline.server.port = 3010;
state.config.store(Arc::new(multi_host_cfg));
state
.app_config
.update_app_config(
None,
&[server_domain::app_config::AppConfigUpdate {
key: "server.hosts".to_owned(),
value: Some(serde_json::json!(["app2.affine.local"])),
}],
)
.await
.expect("update server.hosts for multi-host test");
let resp = router
.clone()
.oneshot(
@@ -629,6 +641,17 @@ fn calendar_rest_webhook_and_oauth_callback_validation() {
root_cfg.external_url = "http://localhost:3010".to_owned();
root_cfg.app_config_baseline.server.hosts.clear();
state.config.store(Arc::new(root_cfg));
state
.app_config
.update_app_config(
None,
&[server_domain::app_config::AppConfigUpdate {
key: "server.hosts".to_owned(),
value: Some(serde_json::json!([])),
}],
)
.await
.expect("clear server.hosts for root deployment test");
for (body_json, expected_uri, expect_redirect) in [
(r#"{"provider":"google"}"#, None, false),
(r#"{"provider":"google","redirect_uri":""}"#, None, false),
@@ -839,6 +862,17 @@ fn calendar_oauth_success_callback_redirect_and_token_exchange() {
root_cfg.external_url = "http://localhost:3010".to_owned();
root_cfg.app_config_baseline.server.hosts.clear();
state.config.store(Arc::new(root_cfg));
state
.app_config
.update_app_config(
None,
&[server_domain::app_config::AppConfigUpdate {
key: "server.hosts".to_owned(),
value: Some(serde_json::json!([])),
}],
)
.await
.expect("clear server.hosts for root deployment callback test");
for (body_json, expected_uri, expect_302) in [
(r#"{"provider":"google"}"#, None, false),
(r#"{"provider":"google","redirect_uri":""}"#, None, false),
@@ -762,8 +762,8 @@ fn http_auth_graphql_and_rest_parity() {
.unwrap(),
)
.await;
assert_eq!(st, StatusCode::FORBIDDEN);
assert_eq!(anon_manifest["name"], "ACCESS_DENIED");
assert_eq!(st, StatusCode::UNAUTHORIZED);
assert_eq!(anon_manifest["name"], "AUTHENTICATION_REQUIRED");
// PUT /api/storage/upload missing params returns 400 BLOB_INVALID with type=INVALID_INPUT.
let (st, _, r2_err, _) = send(
@@ -1018,3 +1018,166 @@ fn sign_in_rate_limit_honors_ioredis_key_prefix_and_ms_pttl() {
);
});
}
#[test]
fn blobs_default_throttle_allows_authed_and_limits_forged_cookies_by_ip() {
let _lease = 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 cfg = RuntimeConfig {
deployment_mode: DeploymentMode::Selfhosted,
role: ServerRole::Allinone,
external_url: "http://127.0.0.1:3010".to_owned(),
..RuntimeConfig::default()
};
let app = AppState::new(db.clone(), None, cfg, Arc::new(CommunityExtension::new()));
let admin = app
.auth
.create_first_admin_user(server_domain::auth::CreateAdminUserInput {
name: Some("Admin".to_owned()),
email: "throttle-admin@example.com".to_owned(),
password: "Password123!".to_owned(),
client_version: None,
})
.await
.expect("create admin");
let valid_cookie = format!("affine_session={}; affine_user_id={}", admin.session_id, admin.user.id);
let router = build_router(Arc::clone(&app));
// (a) Authenticated session gets 0 429 responses across 130 requests.
for _ in 0..130 {
let (st, _, _, _) = send(
&router,
Request::builder()
.method(Method::GET)
.uri("/api/avatars/nonexistent-avatar-id")
.header(header::COOKIE, &valid_cookie)
.header("x-forwarded-for", "203.0.113.10")
.body(Body::empty())
.unwrap(),
)
.await;
assert_ne!(st, StatusCode::TOO_MANY_REQUESTS);
}
// (b) Unauthenticated client with 130 distinct forged affine_session cookies is bucketed by IP and gets 429 on 121..=130.
for i in 1..=130 {
let (st, _, _, _) = send(
&router,
Request::builder()
.method(Method::GET)
.uri("/api/avatars/nonexistent-avatar-id")
.header(header::COOKIE, format!("affine_session=rand-{i}"))
.header("x-forwarded-for", "203.0.113.11")
.body(Body::empty())
.unwrap(),
)
.await;
if i <= 120 {
assert_ne!(st, StatusCode::TOO_MANY_REQUESTS, "req {i} should not be limited");
} else {
assert_eq!(st, StatusCode::TOO_MANY_REQUESTS, "req {i} must be 429");
}
}
});
}
#[test]
fn magic_link_and_sign_in_map_sign_up_forbidden_distinctly() {
let _lease = 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 mut cfg = RuntimeConfig {
deployment_mode: DeploymentMode::Selfhosted,
role: ServerRole::Allinone,
external_url: "http://127.0.0.1:3010".to_owned(),
..RuntimeConfig::default()
};
cfg.app_config_baseline.smtp.host = "127.0.0.1".to_owned();
let app = AppState::new(db.clone(), None, cfg, Arc::new(CommunityExtension::new()));
let prepared = app
.auth
.prepare_magic_link(server_domain::auth::PrepareMagicLinkInput {
email: "new-user-forbidden@example.com".to_owned(),
callback_url: "http://127.0.0.1:3010/magic-link".to_owned(),
client_nonce: None,
source: None,
})
.await
.expect("prepare magic link while signup is enabled");
sqlx::query(
"INSERT INTO app_configs (id, value, created_at, updated_at) VALUES ('auth.allowSignup', 'false'::jsonb, now(), now())",
)
.execute(db.pool())
.await
.expect("disable allowSignup");
app.app_config.invalidate_cache();
let router = build_router(Arc::clone(&app));
let (st_send, _, _, body_send) = send(
&router,
Request::builder()
.method(Method::POST)
.uri("/api/auth/sign-in")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
json!({ "email": "new-user-forbidden@example.com", "callbackUrl": "/magic-link" }).to_string(),
))
.unwrap(),
)
.await;
assert_eq!(st_send, StatusCode::FORBIDDEN, "body={body_send}");
let json_send: Value = serde_json::from_str(&body_send).expect("json send");
assert_eq!(json_send["name"], "SIGN_UP_FORBIDDEN");
let (st_complete, _, _, body_complete) = send(
&router,
Request::builder()
.method(Method::POST)
.uri("/api/auth/magic-link")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
json!({ "email": "new-user-forbidden@example.com", "token": prepared.otp }).to_string(),
))
.unwrap(),
)
.await;
assert_eq!(st_complete, StatusCode::BAD_REQUEST, "body={body_complete}");
let json_complete: Value = serde_json::from_str(&body_complete).expect("json complete");
assert_eq!(json_complete["name"], "INVALID_EMAIL_TOKEN");
});
}
+54
View File
@@ -191,6 +191,54 @@ pub trait RateLimitPolicy: Send + Sync + 'static {
}
}
#[async_trait::async_trait]
pub trait CopilotRealtimeSpi: Send + Sync + 'static {
async fn get_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
blob_id: Option<&str>,
task_id: Option<&str>,
) -> Result<serde_json::Value, DomainError>;
async fn retry_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<serde_json::Value, DomainError>;
async fn authorize_transcript_task(
&self,
user_id: &str,
workspace_id: &str,
task_id: &str,
) -> Result<(), DomainError>;
async fn get_embedding_progress(&self, user_id: &str, workspace_id: &str) -> Result<serde_json::Value, DomainError>;
async fn authorize_embedding_progress(&self, user_id: &str, workspace_id: &str) -> Result<(), DomainError>;
async fn delegated_editor_upsert(
&self,
user_id: &str,
connection_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, DomainError>;
async fn delegated_editor_release(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, DomainError>;
async fn delegated_tool_respond(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, DomainError>;
}
pub trait ServerExtension: Send + Sync + 'static {
fn edition_name(&self) -> &'static str;
fn quota_gate(&self) -> Arc<dyn QuotaGate>;
@@ -208,6 +256,12 @@ pub trait ServerExtension: Send + Sync + 'static {
fn copilot_transcript_spi(&self) -> Arc<dyn CopilotTranscriptSpi> {
Arc::new(CommunityCopilotTranscriptSpi)
}
fn copilot_realtime_spi(&self) -> Option<Arc<dyn CopilotRealtimeSpi>> {
None
}
fn available_user_features(&self) -> &'static [&'static str] {
&["administrator"]
}
fn rate_limit_policy(&self) -> Arc<dyn RateLimitPolicy> {
Arc::new(CommunityRateLimitPolicy)
}
@@ -581,28 +581,6 @@ 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)
@@ -44,6 +44,12 @@ pub enum SyncError {
#[error("document not found: {doc_id} in {space_id}")]
DocNotFound { space_id: String, doc_id: String },
#[error("user not found")]
UserNotFound,
#[error("space owner not found: {space_id}")]
SpaceOwnerNotFound { space_id: String },
#[error("document update blocked: {doc_id} in {space_id}")]
DocUpdateBlocked { space_id: String, doc_id: String },
+59 -7
View File
@@ -136,6 +136,11 @@ impl RealtimeTopicChangedPayload {
.get("taskId")
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let client_id = self
.input
.get("clientId")
.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")),
@@ -147,6 +152,7 @@ impl RealtimeTopicChangedPayload {
"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}")),
"copilot.delegated.tool.requested" => uid.zip(client_id).map(|(u, c)| format!("user:{u}:copilot:{c}")),
"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")),
@@ -551,14 +557,60 @@ async fn run_subscriber_loop(
}
} else if channel == INVALIDATION_CHANNEL_V1
&& let Ok(val) = serde_json::from_str::<Value>(&raw)
&& val.get("kind").and_then(Value::as_str) == Some("workspaceInventoryChanged")
&& let Some(workspace_id) = val.get("workspaceId").and_then(Value::as_str)
&& let Some(kind) = val.get("kind").and_then(Value::as_str)
{
let doc_id = val.get("docId").and_then(Value::as_str).map(ToOwned::to_owned);
let _ = incoming_tx.send(ClusterSyncEvent::WorkspaceInventoryChanged {
workspace_id: workspace_id.to_owned(),
doc_id,
});
let emit_workspace_quota_and_access = |workspace_id: &str| {
let _ = incoming_tx.send(ClusterSyncEvent::WorkspaceInventoryChanged {
workspace_id: workspace_id.to_owned(),
doc_id: None,
});
let _ = incoming_tx.send(ClusterSyncEvent::RealtimeTopicChanged(RealtimeTopicChangedPayload {
topic: "workspace.quota-state.changed".to_owned(),
room: Some(format!("workspace:{workspace_id}:quota-state")),
input: json!({ "workspaceId": workspace_id }),
event: json!({ "changed": true, "reason": "runtime-invalidation" }),
payload: Value::Null,
}));
let _ = incoming_tx.send(ClusterSyncEvent::RealtimeTopicChanged(RealtimeTopicChangedPayload {
topic: "workspace.access.changed".to_owned(),
room: Some(format!("workspace:{workspace_id}:access")),
input: json!({ "workspaceId": workspace_id }),
event: json!({ "changed": true, "reason": "quota-state-changed" }),
payload: Value::Null,
}));
};
match kind {
"workspaceInventoryChanged" => {
if let Some(workspace_id) = val.get("workspaceId").and_then(Value::as_str) {
let doc_id = val.get("docId").and_then(Value::as_str).map(ToOwned::to_owned);
let _ = incoming_tx.send(ClusterSyncEvent::WorkspaceInventoryChanged {
workspace_id: workspace_id.to_owned(),
doc_id,
});
}
}
"quotaEntitlement" | "quotaStorageUsage" => {
if let Some(subject) = val.get("subject").and_then(Value::as_str) {
if let Some(user_id) = subject.strip_prefix("user:").filter(|s| !s.is_empty()) {
let _ = incoming_tx.send(ClusterSyncEvent::RealtimeTopicChanged(RealtimeTopicChangedPayload {
topic: "user.quota-state.changed".to_owned(),
room: Some(format!("user:{user_id}:quota-state")),
input: json!({}),
event: json!({ "changed": true, "reason": "runtime-invalidation" }),
payload: Value::Null,
}));
} else if let Some(workspace_id) = subject.strip_prefix("workspace:").filter(|s| !s.is_empty()) {
emit_workspace_quota_and_access(workspace_id);
}
}
}
"quotaOwnerMapping" | "quotaSeatUsage" => {
if let Some(workspace_id) = val.get("workspaceId").and_then(Value::as_str).filter(|s| !s.is_empty()) {
emit_workspace_quota_and_access(workspace_id);
}
}
_ => {}
}
}
}
}
+165 -81
View File
@@ -34,8 +34,8 @@ use crate::{
BroadcastDocInvalidationMessage, BroadcastDocUpdatesMessage, DeleteDocMessage, DocLifecycleAction,
DocLifecycleMessage, LeaveSpaceMessage, LoadDocMessage, LoadDocTimestampsMessage, LoadSpaceAwarenessesMessage,
LoadWorkspaceStateMessage, PushDocIntent, PushDocUpdateMessage, SpaceType, UpdateAwarenessMessage, active_doc_key,
canonical_doc_id, is_batch_ws_client_version, parse_join_space_batch_message, parse_leave_space_batch_message,
space_room,
canonical_doc_id, is_batch_ws_client_version_with_canary, parse_join_space_batch_message,
parse_leave_space_batch_message, space_room,
},
storage::{DocAction, SyncStorage},
};
@@ -248,10 +248,20 @@ pub struct SpaceSyncGateway {
presence_flush_lock: tokio::sync::Mutex<()>,
presence_notify: Notify,
deployment_prefix: String,
allow_canary: bool,
}
impl SpaceSyncGateway {
pub fn new(storage: SyncStorage, eventbus: Arc<RedisSyncBridge>, deployment_prefix: impl Into<String>) -> Arc<Self> {
Self::with_canary(storage, eventbus, deployment_prefix, false)
}
pub fn with_canary(
storage: SyncStorage,
eventbus: Arc<RedisSyncBridge>,
deployment_prefix: impl Into<String>,
allow_canary: bool,
) -> Arc<Self> {
Arc::new(Self {
storage,
eventbus,
@@ -259,6 +269,7 @@ impl SpaceSyncGateway {
presence_flush_lock: tokio::sync::Mutex::new(()),
presence_notify: Notify::new(),
deployment_prefix: deployment_prefix.into(),
allow_canary,
})
}
@@ -340,7 +351,9 @@ impl SpaceSyncGateway {
})
.unwrap_or_default()
};
let doc_room_check = parse_doc_realtime_room(&room);
let needs_auth_check = parse_doc_realtime_room(&room).is_some()
|| room.starts_with("workspace:")
|| room.starts_with("copilot:transcript:");
let event_val = if payload.event.is_null() {
payload.payload
} else {
@@ -354,13 +367,9 @@ impl SpaceSyncGateway {
"event": event_val,
});
for (sid, user_id_opt) in recipients_with_users {
if let Some((ws_id, doc_id, topic)) = doc_room_check {
if needs_auth_check {
let allowed = match user_id_opt.as_deref() {
Some(uid) => gateway
.storage
.assert_doc_realtime_topic_access(ws_id, doc_id, uid, topic)
.await
.is_ok(),
Some(uid) => gateway.is_realtime_room_authorized(&room, uid).await,
None => false,
};
if !allowed {
@@ -602,8 +611,8 @@ impl SpaceSyncGateway {
.await;
}
// Revalidate realtime room subscriptions (`workspace:<ws>:config`,
// `workspace:<ws>:access`, and doc-scoped `workspace:<ws>:doc:<doc>:<scope>`)
// Revalidate realtime room subscriptions (`workspace:<ws>:*`,
// `copilot:transcript:<ws>:<task>`, and doc-scoped `workspace:<ws>:doc:<doc>:<scope>`)
// and evict sockets that lost workspace or document-level permissions.
let rt_candidates: Vec<(String, String, String, String)> = {
let rooms = self.rooms.read().await;
@@ -613,10 +622,16 @@ impl SpaceSyncGateway {
.filter_map(|(sub_id, (sid, room))| {
let ws_id = if let Some((ws, _doc, _topic)) = parse_doc_realtime_room(room) {
ws
} else if let Some(rest) = room.strip_prefix("copilot:transcript:") {
let (ws, _task) = rest.split_once(':')?;
ws
} else {
let rest = room.strip_prefix("workspace:")?;
let (ws, kind) = rest.rsplit_once(':')?;
if !matches!(kind, "config" | "access" | "members") {
if !matches!(
kind,
"config" | "access" | "members" | "invite-link" | "quota-state" | "embedding-progress"
) {
return None;
}
ws
@@ -633,30 +648,7 @@ impl SpaceSyncGateway {
};
for (sub_id, sid, user_id, room) in rt_candidates {
let still_allowed = if let Some((ws_id, doc_id, topic)) = parse_doc_realtime_room(&room) {
self
.storage
.assert_doc_realtime_topic_access(ws_id, doc_id, &user_id, topic)
.await
.is_ok()
} else if let Some((ws_id, kind)) = room.strip_prefix("workspace:").and_then(|r| r.rsplit_once(':')) {
match kind {
"config" => self
.storage
.assert_space_accessible(SpaceType::Workspace, ws_id, &user_id)
.await
.is_ok(),
"access" => self.storage.assert_workspace_readable(ws_id, &user_id).await.is_ok(),
"members" => self
.storage
.assert_workspace_members_readable(ws_id, &user_id)
.await
.is_ok(),
_ => true,
}
} else {
true
};
let still_allowed = self.is_realtime_room_authorized(&room, &user_id).await;
if !still_allowed {
let mut rooms = self.rooms.write().await;
if rooms.realtime_subscriptions.remove(&sub_id).is_some() {
@@ -718,8 +710,24 @@ impl SpaceSyncGateway {
payload: Value,
) -> EventResponse {
let request_id = format!("{}:ws:{}", self.deployment_prefix, Uuid::new_v4());
if event == "space:join-batch" {
return match self.on_join_batch(socket_id, user, &payload).await {
if event == "space:join-batch" || event == "space:join" {
let join_payload = if event == "space:join" && payload.get("spaces").is_none() {
let mut obj = payload.as_object().cloned().unwrap_or_default();
let space_type = obj.get("spaceType").cloned().unwrap_or(Value::Null);
let space_id = obj.get("spaceId").cloned().unwrap_or(Value::Null);
let mut entry = serde_json::Map::new();
entry.insert("spaceType".into(), space_type);
entry.insert("spaceId".into(), space_id);
if let Some(doc_id) = obj.get("docId").cloned() {
entry.insert("docId".into(), doc_id);
}
obj.insert("spaces".into(), Value::Array(vec![Value::Object(entry)]));
obj.entry("protocolVersion".to_owned()).or_insert_with(|| json!(1));
Value::Object(obj)
} else {
payload
};
return match self.on_join_batch(socket_id, user, &join_payload).await {
Ok(resp) => resp,
Err(err) => {
let env = sync_error_to_ws_envelope(&err, Some(request_id));
@@ -747,7 +755,7 @@ impl SpaceSyncGateway {
"space:doc-lifecycle" => self.on_doc_lifecycle(socket_id, user, payload).await,
"space:load-awarenesses" => self.on_load_awarenesses(engine, socket_id, payload).await,
"space:update-awareness" => self.on_update_awareness(engine, socket_id, payload).await,
"realtime:request" => self.on_realtime_request(user, payload).await,
"realtime:request" => self.on_realtime_request(socket_id, user, payload).await,
"realtime:subscribe" => self.on_realtime_subscribe(socket_id, user, payload).await,
"realtime:unsubscribe" => self.on_realtime_unsubscribe(socket_id, payload).await,
other => Err(SyncError::BadRequest(format!("Unsupported event: {other}"))),
@@ -767,9 +775,52 @@ impl SpaceSyncGateway {
}
}
async fn is_realtime_room_authorized(&self, room: &str, user_id: &str) -> bool {
if let Some((ws_id, doc_id, topic)) = parse_doc_realtime_room(room) {
self
.storage
.assert_doc_realtime_topic_access(ws_id, doc_id, user_id, topic)
.await
.is_ok()
} else if let Some((ws_id, task_id)) = room.strip_prefix("copilot:transcript:").and_then(|r| r.split_once(':')) {
self
.storage
.copilot_realtime_authorize_transcript_task(user_id, ws_id, task_id)
.await
.is_ok()
} else if let Some((ws_id, kind)) = room.strip_prefix("workspace:").and_then(|r| r.rsplit_once(':')) {
match kind {
"config" => self
.storage
.assert_space_accessible(SpaceType::Workspace, ws_id, user_id)
.await
.is_ok(),
"access" | "quota-state" => self.storage.assert_workspace_readable(ws_id, user_id).await.is_ok(),
"members" => self
.storage
.assert_workspace_members_readable(ws_id, user_id)
.await
.is_ok(),
"invite-link" => self
.storage
.assert_workspace_invite_manage(ws_id, user_id)
.await
.is_ok(),
"embedding-progress" => self
.storage
.copilot_realtime_authorize_embedding_progress(user_id, ws_id)
.await
.is_ok(),
_ => true,
}
} else {
true
}
}
async fn on_join_batch(&self, socket_id: &str, user: &SyncUser, payload: &Value) -> Result<EventResponse, SyncError> {
let msg = parse_join_space_batch_message(payload)?;
if !is_batch_ws_client_version(&msg.client_version) {
if !is_batch_ws_client_version_with_canary(&msg.client_version, self.allow_canary) {
// Return `close_after_flush: true` so `EngineIoState` atomically enqueues
// the reject ACK and arms `close_after_flush` under one lock.
return Ok(EventResponse {
@@ -1209,23 +1260,34 @@ impl SpaceSyncGateway {
));
}
let (storage_doc_id, logical_doc_id) = match msg.physical_doc_id {
Some(phys) => {
let phys_canonical = canonical_doc_id(&phys, &msg.space_id)?;
let logical = (phys_canonical != doc_id).then_some(doc_id);
(phys_canonical, logical)
}
None => (doc_id, None),
let aliases = self.storage.get_doc_id_aliases(&msg.space_id).await?;
let resolved_doc_id = aliases.get(&doc_id).cloned().unwrap_or_else(|| doc_id.clone());
let phys_canonical = match msg.physical_doc_id.as_deref() {
Some(phys) => Some(canonical_doc_id(phys, &msg.space_id)?),
None => None,
};
let storage_doc_id = if action == DocLifecycleAction::Delete {
phys_canonical.unwrap_or_else(|| resolved_doc_id.clone())
} else {
resolved_doc_id.clone()
};
let logical_doc_id = (action == DocLifecycleAction::Delete && storage_doc_id != doc_id).then_some(doc_id.clone());
let has_storage_identity_conflict = action == DocLifecycleAction::Delete
&& storage_doc_id != doc_id
&& aliases.iter().any(|(l, s)| l != &doc_id && s == &doc_id);
let require_deleted = action == DocLifecycleAction::Delete
&& (has_storage_identity_conflict || (msg.physical_doc_id.is_some() && storage_doc_id != resolved_doc_id));
let result = self
.storage
.apply_doc_lifecycle(
.apply_doc_lifecycle_with_options(
&msg.space_id,
&storage_doc_id,
logical_doc_id.as_deref(),
&user.id,
action,
require_deleted,
has_storage_identity_conflict,
)
.await?;
@@ -1241,7 +1303,7 @@ impl SpaceSyncGateway {
Ok(json!({ "data": data }))
}
fn validate_realtime_client_version(payload: &Value) -> Result<(), SyncError> {
fn validate_realtime_client_version(&self, payload: &Value) -> Result<(), SyncError> {
const REQUIRED: &str = ">=0.26.0";
let raw = payload
.get("clientVersion")
@@ -1254,7 +1316,7 @@ impl SpaceSyncGateway {
required_version: REQUIRED.to_owned(),
});
};
if is_supported_realtime_client_version(ver) {
if is_supported_realtime_client_version(ver, self.allow_canary) {
Ok(())
} else {
Err(SyncError::UnsupportedClientVersion {
@@ -1264,8 +1326,8 @@ impl SpaceSyncGateway {
}
}
async fn on_realtime_request(&self, user: &SyncUser, payload: Value) -> Result<Value, SyncError> {
Self::validate_realtime_client_version(&payload)?;
async fn on_realtime_request(&self, socket_id: &str, user: &SyncUser, payload: Value) -> Result<Value, SyncError> {
self.validate_realtime_client_version(&payload)?;
let op = payload
.get("op")
.and_then(Value::as_str)
@@ -1373,8 +1435,13 @@ impl SpaceSyncGateway {
.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 raw_skip = input.get("skip").and_then(Value::as_i64).unwrap_or(0);
let raw_take = input.get("take").and_then(Value::as_i64).unwrap_or(8);
if raw_skip < 0 || raw_take < 0 {
return Err(SyncError::BadRequest("skip and take must be non-negative".into()));
}
let skip = raw_skip;
let take = raw_take.clamp(1, 100);
let query = input.get("query").and_then(Value::as_str);
let members = self
.storage
@@ -1460,12 +1527,33 @@ impl SpaceSyncGateway {
.await?;
Ok(json!({ "data": { "task": task } }))
}
"copilot.delegated.editor.upsert" => {
let out = self
.storage
.copilot_realtime_delegated_editor_upsert(&user.id, socket_id, input)
.await?;
Ok(json!({ "data": out }))
}
"copilot.delegated.editor.release" => {
let out = self
.storage
.copilot_realtime_delegated_editor_release(&user.id, input)
.await?;
Ok(json!({ "data": out }))
}
"copilot.delegated.tool.respond" => {
let out = self
.storage
.copilot_realtime_delegated_tool_respond(&user.id, input)
.await?;
Ok(json!({ "data": out }))
}
other => Err(SyncError::BadRequest(format!("Unsupported realtime op: {other}"))),
}
}
async fn on_realtime_subscribe(&self, socket_id: &str, user: &SyncUser, payload: Value) -> Result<Value, SyncError> {
Self::validate_realtime_client_version(&payload)?;
self.validate_realtime_client_version(&payload)?;
let topic = payload
.get("topic")
.and_then(Value::as_str)
@@ -1578,6 +1666,18 @@ impl SpaceSyncGateway {
.await?;
format!("copilot:transcript:{workspace_id}:{task_id}")
}
"copilot.delegated.tool.requested" => {
if !self.storage.has_copilot_realtime() {
return Err(SyncError::CopilotDisabled);
}
let client_id = input
.get("clientId")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty() && s.len() <= 128)
.ok_or_else(|| SyncError::BadRequest("Invalid clientId".into()))?;
format!("user:{}:copilot:{client_id}", user.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),
@@ -1609,7 +1709,7 @@ impl SpaceSyncGateway {
}
async fn on_realtime_unsubscribe(&self, socket_id: &str, payload: Value) -> Result<Value, SyncError> {
Self::validate_realtime_client_version(&payload)?;
self.validate_realtime_client_version(&payload)?;
let Some(subscription_id) = payload
.get("subscriptionId")
.and_then(Value::as_str)
@@ -1955,17 +2055,17 @@ fn realtime_input_key(input: &Value) -> String {
}
}
/// Validates realtime `clientVersion` (`>= 0.26.0-0` or valid canary date version).
fn is_supported_realtime_client_version(ver: &str) -> bool {
let trimmed = ver.trim().trim_start_matches('v');
/// Validates realtime `clientVersion` (`>= 0.26.0-0` or valid canary date version
/// when `allow_canary` is enabled).
fn is_supported_realtime_client_version(ver: &str, allow_canary: bool) -> bool {
if let Some(canary_ok) = crate::protocol::check_canary_date_version(ver, allow_canary) {
return canary_ok;
}
let trimmed = ver.trim().trim_start_matches(['v', 'V']);
if trimmed.is_empty() {
return false;
}
let (core, pre) = match trimmed.split_once('-') {
Some((c, p)) => (c, Some(p)),
None => (trimmed, None),
};
let core = core.split('+').next().unwrap_or(core);
let core = trimmed.split(['-', '+']).next().unwrap_or(trimmed);
let mut parts = core.split('.');
let (Some(maj_s), Some(min_s), Some(pat_s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return false;
@@ -1973,21 +2073,5 @@ fn is_supported_realtime_client_version(ver: &str) -> bool {
let (Ok(maj), Ok(min), Ok(_pat)) = (maj_s.parse::<u64>(), min_s.parse::<u64>(), pat_s.parse::<u64>()) else {
return false;
};
if maj > 0 || min >= 26 {
return true;
}
// 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")
&& 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
(maj == 0 && min >= 26) || (maj > 0 && maj < 2000)
}
@@ -59,9 +59,9 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
},
SyncError::CopilotDisabled => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "COPILOT_DISABLED".into(),
code: "ACTION_FORBIDDEN".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "COPILOT_DISABLED".into(),
name: "ACTION_FORBIDDEN".into(),
message: "Copilot is disabled.".into(),
data: None,
request_id,
@@ -84,16 +84,16 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
SyncError::SpaceAccessDenied { space_id } => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "SPACE_ACCESS_DENIED".into(),
error_type: "SPACE_ACCESS_DENIED".into(),
error_type: "NO_PERMISSION".into(),
name: "SPACE_ACCESS_DENIED".into(),
message: format!("Space {space_id} access denied"),
data: Some(json!({ "spaceId": space_id })),
request_id,
},
SyncError::NotInSpace { space_id } => WebsocketErrorBody {
status: StatusCode::BAD_REQUEST.as_u16(),
status: StatusCode::FORBIDDEN.as_u16(),
code: "NOT_IN_SPACE".into(),
error_type: "NOT_IN_SPACE".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "NOT_IN_SPACE".into(),
message: format!("Not in space {space_id}"),
data: Some(json!({ "spaceId": space_id })),
@@ -106,7 +106,7 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
} => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "DOC_ACTION_DENIED".into(),
error_type: "DOC_ACTION_DENIED".into(),
error_type: "NO_PERMISSION".into(),
name: "DOC_ACTION_DENIED".into(),
message: format!("Action {action} denied on doc {doc_id} in space {space_id}"),
data: Some(json!({
@@ -119,7 +119,7 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
SyncError::AccessDenied(msg) => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "ACCESS_DENIED".into(),
error_type: "ACCESS_DENIED".into(),
error_type: "NO_PERMISSION".into(),
name: "ACCESS_DENIED".into(),
message: msg.clone(),
data: None,
@@ -137,7 +137,7 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
SyncError::DocNotFound { space_id, doc_id } => WebsocketErrorBody {
status: StatusCode::NOT_FOUND.as_u16(),
code: "DOC_NOT_FOUND".into(),
error_type: "DOC_NOT_FOUND".into(),
error_type: "RESOURCE_NOT_FOUND".into(),
name: "DOC_NOT_FOUND".into(),
message: format!("Doc {doc_id} not found in space {space_id}"),
data: Some(json!({
@@ -146,10 +146,28 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
})),
request_id,
},
SyncError::UserNotFound => WebsocketErrorBody {
status: StatusCode::NOT_FOUND.as_u16(),
code: "USER_NOT_FOUND".into(),
error_type: "RESOURCE_NOT_FOUND".into(),
name: "USER_NOT_FOUND".into(),
message: "User not found.".into(),
data: None,
request_id,
},
SyncError::SpaceOwnerNotFound { space_id } => WebsocketErrorBody {
status: StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
code: "SPACE_OWNER_NOT_FOUND".into(),
error_type: "INTERNAL_SERVER_ERROR".into(),
name: "SPACE_OWNER_NOT_FOUND".into(),
message: format!("Space {space_id} owner not found"),
data: Some(json!({ "spaceId": space_id })),
request_id,
},
SyncError::DocUpdateBlocked { space_id, doc_id } => WebsocketErrorBody {
status: StatusCode::FORBIDDEN.as_u16(),
code: "DOC_UPDATE_BLOCKED".into(),
error_type: "DOC_UPDATE_BLOCKED".into(),
error_type: "ACTION_FORBIDDEN".into(),
name: "DOC_UPDATE_BLOCKED".into(),
message: format!("Doc {doc_id} in space {space_id} is blocked for updates"),
data: Some(json!({
@@ -161,43 +179,43 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
SyncError::DocUpdateInvalid(msg) => WebsocketErrorBody {
status: StatusCode::BAD_REQUEST.as_u16(),
code: "DOC_UPDATE_INVALID".into(),
error_type: "DOC_UPDATE_INVALID".into(),
error_type: "INVALID_INPUT".into(),
name: "DOC_UPDATE_INVALID".into(),
message: msg.clone(),
data: None,
request_id,
},
SyncError::DocUpdateTooLarge => WebsocketErrorBody {
status: StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
status: StatusCode::BAD_REQUEST.as_u16(),
code: "DOC_UPDATE_TOO_LARGE".into(),
error_type: "DOC_UPDATE_TOO_LARGE".into(),
error_type: "INVALID_INPUT".into(),
name: "DOC_UPDATE_TOO_LARGE".into(),
message: "Document update exceeds maximum allowed size".into(),
message: "The document update exceeds the size limit.".into(),
data: None,
request_id,
},
SyncError::SyncPermissionGenerationChanged { space_id } => WebsocketErrorBody {
status: StatusCode::CONFLICT.as_u16(),
status: StatusCode::SERVICE_UNAVAILABLE.as_u16(),
code: "SYNC_PERMISSION_GENERATION_CHANGED".into(),
error_type: "SYNC_PERMISSION_GENERATION_CHANGED".into(),
error_type: "SERVICE_UNAVAILABLE".into(),
name: "SYNC_PERMISSION_GENERATION_CHANGED".into(),
message: format!("Sync permission generation changed for space {space_id}"),
data: Some(json!({ "spaceId": space_id })),
request_id,
},
SyncError::WorkspaceLifecycleNotActive => WebsocketErrorBody {
status: StatusCode::PRECONDITION_FAILED.as_u16(),
code: "BAD_REQUEST".into(),
error_type: "BAD_REQUEST".into(),
name: "BAD_REQUEST".into(),
message: "workspace_lifecycle_not_active".into(),
status: StatusCode::SERVICE_UNAVAILABLE.as_u16(),
code: "WORKSPACE_SYNC_UNAVAILABLE".into(),
error_type: "SERVICE_UNAVAILABLE".into(),
name: "WORKSPACE_SYNC_UNAVAILABLE".into(),
message: "Workspace synchronization is temporarily unavailable.".into(),
data: None,
request_id,
},
SyncError::TooManyConcurrentWritings => WebsocketErrorBody {
status: StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
code: "INTERNAL_SERVER_ERROR".into(),
error_type: "INTERNAL_ERROR".into(),
error_type: "INTERNAL_SERVER_ERROR".into(),
name: "INTERNAL_SERVER_ERROR".into(),
message: "Internal Server Error".into(),
data: None,
+19 -3
View File
@@ -43,9 +43,15 @@ 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`.
/// Whether canary date-versioned clients (`YYYY.M.D-canary.N`) are accepted
/// (enabled only on the `canary` deployment channel).
pub allow_canary: bool,
/// Optional commercial Copilot realtime handler (`copilot.transcript.task.*`,
/// `workspace.embedding.progress.*`, and `copilot.delegated.*`).
/// When `None`, those ops return `ACTION_FORBIDDEN`.
pub copilot_realtime: Option<Arc<dyn crate::storage::CopilotRealtimeHandler>>,
/// Allowlisted user feature names exposed by `user.profile.get`.
pub available_user_features: &'static [&'static str],
}
impl std::fmt::Debug for SyncConfig {
@@ -59,6 +65,7 @@ impl std::fmt::Debug for SyncConfig {
.field("external_url", &self.external_url)
.field("allowed_origins", &self.allowed_origins)
.field("allow_dev_loopback", &self.allow_dev_loopback)
.field("allow_canary", &self.allow_canary)
.field("copilot_realtime", &self.copilot_realtime.is_some())
.finish()
}
@@ -73,6 +80,7 @@ impl SyncConfig {
channel.trim().to_ascii_lowercase().as_str(),
"dev" | "development" | "test" | "testing"
);
let allow_canary = channel.trim().eq_ignore_ascii_case("canary");
Self {
redis_url: None,
session_redis_url: None,
@@ -82,7 +90,9 @@ impl SyncConfig {
external_url: String::new(),
allowed_origins: Vec::new(),
allow_dev_loopback,
allow_canary,
copilot_realtime: None,
available_user_features: &["administrator"],
}
}
}
@@ -152,13 +162,19 @@ impl SyncServer {
if let Some(handler) = config.copilot_realtime {
storage = storage.with_copilot_realtime(handler);
}
storage = storage.with_available_user_features(config.available_user_features);
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
}
None => RedisSyncBridge::start(config.redis_url.as_deref(), config.origin_channel).await,
};
let gateway = SpaceSyncGateway::new(storage, Arc::clone(&eventbus), config.deployment_prefix);
let gateway = SpaceSyncGateway::with_canary(
storage,
Arc::clone(&eventbus),
config.deployment_prefix,
config.allow_canary,
);
let engine = EngineIoState::with_origin_policy(
authenticator,
Arc::clone(&gateway),
+117 -5
View File
@@ -227,18 +227,81 @@ pub fn classify_reserved_doc(workspace_id: &str, doc_id: &str, actor_user_id: &s
}
}
/// Checks `clientVersion >= 0.27.5-0` (semver major.minor.patch comparison).
pub fn is_batch_ws_client_version(client_version: &str) -> bool {
let core = client_version.trim().trim_start_matches('v');
/// Checks whether `client_version` matches the `YYYY.M.D-canary.N` date format.
/// When `allow_canary` is false (stable/beta/production channels), any canary
/// date build returns `Some(false)`. When `allow_canary` is true, returns
/// `Some(true)` if the UTC midnight date is within `[-2 days, +62 days]` of
/// `now_ms`, `Some(false)` if invalid or expired, and `None` for non-canary
/// semver strings.
pub fn check_canary_date_version_at(client_version: &str, allow_canary: bool, now_ms: i64) -> Option<bool> {
const DAY_MS: i64 = 86_400_000;
let trimmed = client_version.trim();
let stripped = trimmed
.strip_prefix('v')
.or_else(|| trimmed.strip_prefix('V'))
.unwrap_or(trimmed);
let no_build = stripped.split('+').next().unwrap_or(stripped);
let (date_part, pre_part) = no_build.split_once('-')?;
let lower_pre = pre_part.to_ascii_lowercase();
let build_num = lower_pre.strip_prefix("canary.")?;
if build_num.is_empty() || !build_num.chars().all(|c| c.is_ascii_digit()) {
return None;
}
let mut parts = date_part.split('.');
let (Some(y_s), Some(m_s), Some(d_s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return None;
};
if y_s.len() != 4 || m_s.is_empty() || m_s.len() > 2 || d_s.is_empty() || d_s.len() > 2 {
return None;
}
if !y_s.chars().all(|c| c.is_ascii_digit())
|| !m_s.chars().all(|c| c.is_ascii_digit())
|| !d_s.chars().all(|c| c.is_ascii_digit())
{
return None;
}
if !allow_canary {
return Some(false);
}
let (Ok(year), Ok(month), Ok(day)) = (y_s.parse::<i32>(), m_s.parse::<u32>(), d_s.parse::<u32>()) else {
return Some(false);
};
let Some(date) = chrono::NaiveDate::from_ymd_opt(year, month, day) else {
return Some(false);
};
let Some(dt) = date.and_hms_opt(0, 0, 0) else {
return Some(false);
};
let date_ms = dt.and_utc().timestamp_millis();
let age_ms = now_ms - date_ms;
Some((-2 * DAY_MS..=62 * DAY_MS).contains(&age_ms))
}
pub fn check_canary_date_version(client_version: &str, allow_canary: bool) -> Option<bool> {
check_canary_date_version_at(client_version, allow_canary, chrono::Utc::now().timestamp_millis())
}
/// Checks `clientVersion >= 0.27.5-0` or valid non-expired canary date version
/// when `allow_canary` is enabled.
pub fn is_batch_ws_client_version_with_canary(client_version: &str, allow_canary: bool) -> bool {
if let Some(canary_ok) = check_canary_date_version(client_version, allow_canary) {
return canary_ok;
}
let core = client_version.trim().trim_start_matches(['v', 'V']);
let core = core.split(['-', '+']).next().unwrap_or("");
let mut parts = core.split('.');
let (Some(maj), Some(min), Some(pat)) = (parts.next(), parts.next(), parts.next()) else {
let (Some(maj), Some(min), Some(pat), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return false;
};
let (Ok(maj), Ok(min), Ok(pat)) = (maj.parse::<u64>(), min.parse::<u64>(), pat.parse::<u64>()) else {
return false;
};
(maj, min, pat) >= (0, 27, 5)
maj < 2000 && (maj, min, pat) >= (0, 27, 5)
}
/// Checks `clientVersion >= 0.27.5-0` on stable channels (`allow_canary = false`).
pub fn is_batch_ws_client_version(client_version: &str) -> bool {
is_batch_ws_client_version_with_canary(client_version, false)
}
pub fn parse_join_space_batch_message(value: &Value) -> Result<JoinSpaceBatchMessage, SyncError> {
@@ -375,3 +438,52 @@ pub fn space_room(space_type: SpaceType, space_id: &str, room_type: &str) -> Str
pub fn active_doc_key(space_type: SpaceType, space_id: &str, doc_id: &str) -> String {
format!("{}:{space_id}:{doc_id}", space_type.as_str())
}
#[cfg(test)]
mod canary_version_tests {
use super::{check_canary_date_version_at, is_batch_ws_client_version_with_canary};
#[test]
fn canary_date_version_requires_canary_channel_and_millisecond_window() {
const DAY_MS: i64 = 86_400_000;
let base_ms = chrono::NaiveDate::from_ymd_opt(2026, 6, 1)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp_millis();
// Stable channel always rejects canary date builds.
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", false, base_ms),
Some(false)
);
assert!(!is_batch_ws_client_version_with_canary("2026.6.1-canary.1", false));
// Canary channel enforces [-2 days, +62 days] in milliseconds.
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", true, base_ms),
Some(true)
);
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", true, base_ms + 62 * DAY_MS),
Some(true)
);
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", true, base_ms + 62 * DAY_MS + 1),
Some(false)
);
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", true, base_ms - 2 * DAY_MS),
Some(true)
);
assert_eq!(
check_canary_date_version_at("2026.6.1-canary.1", true, base_ms - 2 * DAY_MS - 1),
Some(false)
);
// Non-canary semver returns None and falls back to semver check.
assert_eq!(check_canary_date_version_at("0.27.5", false, base_ms), None);
assert!(is_batch_ws_client_version_with_canary("0.27.5", false));
}
}
+100 -27
View File
@@ -346,6 +346,31 @@ pub trait CopilotRealtimeHandler: Send + Sync {
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>;
async fn delegated_editor_upsert(
&self,
_user_id: &str,
_connection_id: &str,
_input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
Err(SyncError::CopilotDisabled)
}
async fn delegated_editor_release(
&self,
_user_id: &str,
_input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
Err(SyncError::CopilotDisabled)
}
async fn delegated_tool_respond(
&self,
_user_id: &str,
_input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
Err(SyncError::CopilotDisabled)
}
}
#[derive(Clone)]
@@ -357,6 +382,7 @@ pub struct SyncStorage {
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>>,
pub(super) available_user_features: &'static [&'static str],
userspace_lock_ttl_ms: u64,
doc_sharing: server_domain::doc_sharing::DocSharingService,
users: server_domain::users::UserService,
@@ -399,6 +425,7 @@ impl SyncStorage {
cache_redis_conn: Arc::new(tokio::sync::Mutex::new(None)),
external_url: String::new(),
copilot_realtime: None,
available_user_features: &["administrator"],
userspace_lock_ttl_ms: DEFAULT_LOCK_TTL_SECS * 1_000,
doc_sharing,
users,
@@ -423,6 +450,23 @@ impl SyncStorage {
self
}
pub fn with_available_user_features(mut self, features: &'static [&'static str]) -> Self {
self.available_user_features = features;
self
}
pub fn has_copilot_realtime(&self) -> bool {
self.copilot_realtime.is_some()
}
pub async fn get_doc_id_aliases(&self, workspace_id: &str) -> Result<HashMap<String, String>, SyncError> {
self
.doc_sharing
.get_doc_id_aliases(workspace_id)
.await
.map_err(|e| map_domain_error(e, workspace_id, workspace_id))
}
/// 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
@@ -1134,6 +1178,30 @@ impl SyncStorage {
logical_doc_id: Option<&str>,
actor_user_id: &str,
action: DocLifecycleAction,
) -> Result<DocLifecycleResult, SyncError> {
self
.apply_doc_lifecycle_with_options(
workspace_id,
doc_id,
logical_doc_id,
actor_user_id,
action,
false,
false,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn apply_doc_lifecycle_with_options(
&self,
workspace_id: &str,
doc_id: &str,
logical_doc_id: Option<&str>,
actor_user_id: &str,
action: DocLifecycleAction,
require_deleted: bool,
has_storage_identity_conflict: bool,
) -> Result<DocLifecycleResult, SyncError> {
let deleting = action == DocLifecycleAction::Delete;
if logical_doc_id.is_some() && !deleting {
@@ -1183,25 +1251,6 @@ impl SyncStorage {
}
}
// 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)
@@ -1224,6 +1273,18 @@ impl SyncStorage {
.fetch_all(&mut **tx.tx_mut())
.await?;
if require_deleted && tombstones.len() != doc_ids.len() {
if has_storage_identity_conflict {
return Err(SyncError::BadRequest(
"Deleting this document would also delete another document.".into(),
));
}
return Err(SyncError::DocNotFound {
space_id: workspace_id.to_owned(),
doc_id: doc_id.to_owned(),
});
}
let tombstone_ids: HashSet<&str> = tombstones.iter().map(|(id, _)| id.as_str()).collect();
if deleting && !tombstones.is_empty() {
let member_role_str: Option<String> = sqlx::query_scalar(
@@ -1583,15 +1644,17 @@ impl SyncStorage {
use base64::Engine as _;
let decoded_after = after
.and_then(|c| base64::engine::general_purpose::STANDARD.decode(c).ok())
.and_then(|b| String::from_utf8(b).ok());
.and_then(|b| String::from_utf8(b).ok())
.map(|raw| serde_json::from_str::<String>(&raw).unwrap_or(raw));
let (total_count, items, has_next_page) = self
.doc_sharing
.paginate_granted_users(workspace_id, doc_id, user_id, first, offset, decoded_after.as_deref())
.await
.map_err(|e| map_domain_error(e, workspace_id, doc_id))?;
let end_cursor = items.last().map(|g| {
let raw = format!("{}|{}", g.created_at.to_rfc3339(), g.user_id);
base64::engine::general_purpose::STANDARD.encode(raw.as_bytes())
let iso = g.created_at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let json_iso = serde_json::to_string(&iso).unwrap_or_else(|_| format!("\"{iso}\""));
base64::engine::general_purpose::STANDARD.encode(json_iso.as_bytes())
});
let edges: Vec<serde_json::Value> = items
.into_iter()
@@ -1697,7 +1760,13 @@ impl SyncStorage {
.and_then(|s| DateTime::parse_from_rfc3339(s).ok())
.map(|dt| dt.with_timezone(&Utc));
let take = first.map(|n| n.saturating_add(1)).unwrap_or(1001);
let (take, explicit_limit) = match first {
Some(raw) => {
let limit = raw.clamp(0, 10_000);
(limit.saturating_add(1), Some(limit))
}
None => (10_000, None),
};
let mut changes = svc
.list_comment_changes(
user_id,
@@ -1709,10 +1778,14 @@ impl SyncStorage {
)
.await
.map_err(|e| map_domain_error(e, workspace_id, doc_id))?;
let has_next_page = first.is_some_and(|n| (changes.len() as i64) > n);
if let Some(n) = first {
changes.truncate(n.max(0) as usize);
}
let has_next_page = match explicit_limit {
Some(limit) => {
let more = (changes.len() as i64) > limit;
changes.truncate(limit as usize);
more
}
None => false,
};
if let Some(obj) = cursor.as_object_mut() {
for change in &changes {
let ts = change.item.get("updatedAt").and_then(|v| v.as_str()).map(str::to_owned);
@@ -16,8 +16,7 @@ fn external_plan_name(tier: LicenseTier) -> &'static str {
LicenseTier::CloudAi => "ai",
LicenseTier::CloudTeam => "team",
LicenseTier::SelfhostDefault => "selfhost_free",
LicenseTier::SelfhostTeam => "selfhost_team",
LicenseTier::SelfhostEnterprise => "selfhost_enterprise",
LicenseTier::SelfhostTeam | LicenseTier::SelfhostEnterprise => "selfhost_team",
}
}
@@ -47,7 +46,7 @@ impl SyncStorage {
.fetch_optional(&mut *conn)
.await?;
let Some(row) = row else {
return Err(SyncError::AuthenticationRequired("user not found".into()));
return Err(SyncError::UserNotFound);
};
let raw_features: Vec<String> = sqlx::query_scalar(
"SELECT DISTINCT name FROM user_features \
@@ -59,6 +58,7 @@ impl SyncStorage {
.await?;
let features: Vec<String> = raw_features
.into_iter()
.filter(|f| self.available_user_features.contains(&f.as_str()))
.map(|f| match f.as_str() {
"administrator" => "Admin".to_owned(),
_ => f,
@@ -394,7 +394,7 @@ impl SyncStorage {
.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(
let Some(owner_user_id): Option<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",
@@ -402,7 +402,12 @@ impl SyncStorage {
.bind(workspace_id)
.fetch_optional(&mut **tx.tx_mut())
.await?
.unwrap_or_default();
else {
let _ = tx.rollback().await;
return Err(SyncError::SpaceOwnerNotFound {
space_id: workspace_id.to_owned(),
});
};
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
@@ -445,7 +450,11 @@ impl SyncStorage {
.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 overcapacity_member_count = if grant.limits.seat_limit >= 0 {
(member_count - i64::from(grant.limits.seat_limit)).max(0)
} else {
0
};
let mut readonly_reasons: Vec<&'static str> = Vec::new();
if overcapacity_member_count > 0 {
readonly_reasons.push("member_overflow");
@@ -531,6 +540,40 @@ impl SyncStorage {
};
handler.authorize_embedding_progress(user_id, workspace_id).await
}
pub async fn copilot_realtime_delegated_editor_upsert(
&self,
user_id: &str,
connection_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.delegated_editor_upsert(user_id, connection_id, input).await
}
pub async fn copilot_realtime_delegated_editor_release(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.delegated_editor_release(user_id, input).await
}
pub async fn copilot_realtime_delegated_tool_respond(
&self,
user_id: &str,
input: serde_json::Value,
) -> Result<serde_json::Value, SyncError> {
let Some(handler) = &self.copilot_realtime else {
return Err(SyncError::CopilotDisabled);
};
handler.delegated_tool_respond(user_id, input).await
}
}
#[cfg(test)]
@@ -546,10 +589,7 @@ mod tests {
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!(external_plan_name(LicenseTier::SelfhostEnterprise), "selfhost_team");
assert_eq!(escape_like_pattern(r"a%b_c\d"), r"a\%b\_c\\d");
}
@@ -156,8 +156,9 @@ fn protocol_parsing_and_validation_rules_match_v0275() {
},
Some("req-1".into()),
);
assert_eq!(err_env.error.status, 400);
assert_eq!(err_env.error.status, 403);
assert_eq!(err_env.error.code, "NOT_IN_SPACE");
assert_eq!(err_env.error.error_type, "ACTION_FORBIDDEN");
assert_eq!(err_env.error.request_id.as_deref(), Some("req-1"));
}
@@ -952,6 +952,27 @@ function emitAck(socket, eventName, payload) {
lifecycle: 'trash',
});
const deleteUnaliasedActive = await emitAck(s, 'space:doc-lifecycle', {
spaceType: 'workspace',
spaceId: workspaceId,
docId: 'logical-doc-b',
physicalDocId: 'physical-doc-a',
lifecycle: 'delete',
});
await emitAck(s, 'space:doc-lifecycle', {
spaceType: 'workspace',
spaceId: workspaceId,
docId: 'logical-doc-b',
lifecycle: 'delete',
});
await emitAck(s, 'space:doc-lifecycle', {
spaceType: 'workspace',
spaceId: workspaceId,
docId: 'physical-doc-a',
lifecycle: 'delete',
});
const deleteBoth = await emitAck(s, 'space:doc-lifecycle', {
spaceType: 'workspace',
spaceId: workspaceId,
@@ -972,6 +993,7 @@ function emitAck(socket, eventName, payload) {
joinRoot,
pushRoot,
trashWithPhysical,
deleteUnaliasedActive,
deleteBoth,
zombieSid: openJson.sid,
}));
@@ -1004,12 +1026,14 @@ function emitAck(socket, eventName, payload) {
.unwrap();
assert_eq!(root_updates, 1);
// 2. Non-delete lifecycle with physicalDocId rejected; delete deletes both & tombstones both.
// 2. Non-delete lifecycle with physicalDocId rejected; unaliased active delete requires tombstones;
// once tombstoned, delete with physicalDocId returns both deletedDocIds.
assert_eq!(out["trashWithPhysical"]["error"]["code"], json!("BAD_REQUEST"));
assert_eq!(
out["trashWithPhysical"]["error"]["message"],
json!("logical document identity is only valid for deletion")
);
assert_eq!(out["deleteUnaliasedActive"]["error"]["code"], json!("DOC_NOT_FOUND"));
assert_eq!(
out["deleteBoth"]["data"]["deletedDocIds"],
json!(["logical-doc-b", "physical-doc-a"])
@@ -3463,7 +3487,7 @@ async fn userspace_mutex_invalid_session_redis_url_fails_closed() {
);
assert_eq!(ws_err.error.status, 500);
assert_eq!(ws_err.error.code, "INTERNAL_SERVER_ERROR");
assert_eq!(ws_err.error.error_type, "INTERNAL_ERROR");
assert_eq!(ws_err.error.error_type, "INTERNAL_SERVER_ERROR");
assert_eq!(ws_err.error.name, "INTERNAL_SERVER_ERROR");
assert_eq!(ws_err.error.message, "Internal Server Error");