mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-06 19:52:24 +03:00
fix(backend): close final v0.27.5 server parity gaps
Close remaining v0.27.5 behavior gaps across server-blob, server-search, server-domain, server-mail, server-spi, server-sync, server-http, and affine-server, and align intentional-v0275-divergences.md with current runtime behavior.
This commit is contained in:
1 parent
4be978f7ab
commit
75b75191b2
44 files changed
+2359
-718
No files matched your search
@@ -51,10 +51,10 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work
|
||||
- `server-mail` (library `server_mail`): 30 compiled `v0.27.5` HTML email templates, `SmtpMailer` (`lettre` + `rustls`), and `process_ready_mail_deliveries`.
|
||||
The worker filters direct-render rows, releases unsupported leases cleanly, reaps expired rows, redacts PII in errors, and anonymizes terminal rows.
|
||||
|
||||
- `server-blob` (library `server_blob`): `BlobStorageBackend` (`LocalFsBlobStorage`, `S3BlobStorage`, `AssetpackBlobStorage`), `DynamicBlobStorage` (`ArcSwap` hot reload with active multipart protection), `BlobService` over `public.blobs`, multipart upload lifecycle (`init_blob_upload`, `get_blob_upload_part_url`, `proxy_upload_object`, `proxy_upload_part`, `complete_blob_upload`, `abort_blob_upload`), storage reconciliation (`cleanup_expired_reservations`, `reconcile_storage_orphans` via `storage_reconciliation_checkpoints`), and `refs` (`y-octo` source-scoped blob reference extraction and cursor-paginated readable manifests).
|
||||
- `server-blob` (library `server_blob`): `BlobStorageBackend` (`LocalFsBlobStorage`, `S3BlobStorage`, `AssetpackBlobStorage`), `DynamicBlobStorage` (`ArcSwap` hot reload with active multipart protection), `BlobService` over `public.blobs`, multipart upload lifecycle (`init_blob_upload`, `get_blob_upload_part_url`, `proxy_upload_object`, `proxy_upload_part`, `complete_blob_upload`, `abort_blob_upload`), storage reconciliation (`cleanup_expired_reservations`, `reconcile_storage_orphans` via `storage_reconciliation_checkpoints`, covering orphan storage objects, ownerless workspaces older than 24h, and orphan database rows), and `refs` (`y-octo` source-scoped blob reference extraction and cursor-paginated readable manifests).
|
||||
Writes and deletes hold `StorageObjectLock` session advisory locks outside the `PgPool` and never hold a database transaction during object storage I/O.
|
||||
`list_blobs_authorized`, `delete_blob_authorized`, and `release_deleted_blobs_authorized` require `Owner` or commercial-grant `Admin` plus `!users.disabled` in one transaction.
|
||||
`put_blob` reserves under `workspaces ... FOR UPDATE`, checks `QuotaGate::resolve_workspace_grant`, writes the object, and completes its reservation.
|
||||
`put_blob` locks `users` then `workspaces` with `FOR UPDATE` on Owner-billed workspaces (or `workspaces` with `FOR UPDATE`), checks `QuotaGate::resolve_workspace_grant`, writes the object, and completes its reservation.
|
||||
Storage failures surface only as `Unavailable("blob storage unavailable")`.
|
||||
|
||||
- `server-sync` (library `server_sync`): pure-Rust Engine.IO v4 / Socket.IO v4 sync gateway mounted at `/socket.io/`.
|
||||
|
||||
@@ -990,42 +990,6 @@ async fn build_server_with_bound_port(
|
||||
_ => cli.deployment_mode.into(),
|
||||
};
|
||||
|
||||
let external_url = cli
|
||||
.external_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.trim_end_matches('/').to_owned())
|
||||
.unwrap_or_else(|| format!("http://localhost:{effective_port}"));
|
||||
|
||||
let (https, external_path, allowed_origins) = match url::Url::parse(&external_url) {
|
||||
Ok(parsed) => {
|
||||
let https = parsed.scheme().eq_ignore_ascii_case("https");
|
||||
let path = match parsed.path() {
|
||||
"/" | "" => String::new(),
|
||||
other => other.trim_end_matches('/').to_owned(),
|
||||
};
|
||||
let mut origins = vec![parsed.origin().ascii_serialization()];
|
||||
let scheme = if https { "https" } else { "http" };
|
||||
for host in &server_hosts {
|
||||
let host = host.trim().trim_end_matches('/');
|
||||
if host.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if host.starts_with("http://") || host.starts_with("https://") {
|
||||
origins.push(host.to_owned());
|
||||
} else {
|
||||
origins.push(format!("{scheme}://{host}"));
|
||||
}
|
||||
}
|
||||
(https, path, origins)
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(ServerError::InvalidConfig(format!(
|
||||
"invalid AFFINE_SERVER_EXTERNAL_URL `{external_url}`: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let normalize_sub_path = |raw: &str| -> Option<String> {
|
||||
let trimmed = raw.trim().trim_end_matches('/');
|
||||
if trimmed.is_empty() || trimmed == "/" {
|
||||
@@ -1043,8 +1007,56 @@ async fn build_server_with_bound_port(
|
||||
.pointer("/server/path")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(normalize_sub_path);
|
||||
let _ = external_path;
|
||||
let external_path = resolve_server_sub_path(file_sub_path, env_sub_path);
|
||||
|
||||
let external_url = cli
|
||||
.external_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.trim_end_matches('/').to_owned())
|
||||
.unwrap_or_else(|| format!("http://localhost:{effective_port}{external_path}"));
|
||||
|
||||
let (https, _parsed_path, allowed_origins) = match url::Url::parse(&external_url) {
|
||||
Ok(parsed) => {
|
||||
let https = parsed.scheme().eq_ignore_ascii_case("https");
|
||||
let path = match parsed.path() {
|
||||
"/" | "" => String::new(),
|
||||
other => other.trim_end_matches('/').to_owned(),
|
||||
};
|
||||
let mut origins = vec![parsed.origin().ascii_serialization()];
|
||||
let scheme = if https { "https" } else { "http" };
|
||||
let default_port = parsed.port();
|
||||
for host in &server_hosts {
|
||||
let host = host.trim().trim_end_matches('/');
|
||||
if host.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if host.starts_with("http://") || host.starts_with("https://") {
|
||||
origins.push(host.to_owned());
|
||||
} else {
|
||||
let formatted = if host.matches(':').count() > 1 && !host.starts_with('[') {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
host.to_owned()
|
||||
};
|
||||
let has_explicit_port = formatted.rsplit_once(':').is_some_and(|(base, port)| {
|
||||
!base.ends_with(':') && !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit())
|
||||
});
|
||||
origins.push(format!("{scheme}://{formatted}"));
|
||||
if !has_explicit_port && let Some(port) = default_port {
|
||||
origins.push(format!("{scheme}://{formatted}:{port}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
(https, path, origins)
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(ServerError::InvalidConfig(format!(
|
||||
"invalid AFFINE_SERVER_EXTERNAL_URL `{external_url}`: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut file_json = file_json;
|
||||
if !external_path.is_empty() {
|
||||
if !file_json.is_object() {
|
||||
@@ -1431,22 +1443,20 @@ async fn build_server_with_bound_port(
|
||||
.map_err(|e| ServerError::InvalidConfig(format!("invalid copilot storage config: {e}")))?,
|
||||
)
|
||||
};
|
||||
let file_indexer = app_config_baseline.file_json.get("indexer").cloned();
|
||||
let app_config = AppConfigService::new(db.clone(), app_config_baseline, Arc::clone(&event_bus));
|
||||
let blobs = BlobService::new(db.clone(), storage, ext.quota_gate());
|
||||
if cli.search_enabled && cli.search_provider == "embedded" && role != ServerRole::Allinone {
|
||||
let blobs = BlobService::new(db.clone(), storage, ext.quota_gate()).with_invalidation(Arc::clone(&invalidation));
|
||||
let env_enabled_set =
|
||||
std::env::var("AFFINE_INDEXER_ENABLED").is_ok() || std::env::var("AFFINE_SEARCH_ENABLED").is_ok();
|
||||
let env_provider_set =
|
||||
std::env::var("AFFINE_INDEXER_PROVIDER").is_ok() || std::env::var("AFFINE_SEARCH_PROVIDER").is_ok();
|
||||
let search_cfg =
|
||||
resolve_search_config_from_cli_and_file(cli, file_indexer.as_ref(), env_enabled_set, env_provider_set);
|
||||
if search_cfg.enabled && search_cfg.provider == "embedded" && role != ServerRole::Allinone {
|
||||
return Err(ServerError::InvalidConfig(
|
||||
"embedded search provider is in-process and only supported with --role allinone; use elasticsearch/manticoresearch or --search-enabled=false for split roles".to_owned(),
|
||||
));
|
||||
}
|
||||
let search_cfg = SearchConfig {
|
||||
enabled: cli.search_enabled,
|
||||
provider: cli.search_provider.clone(),
|
||||
endpoint: cli.search_endpoint.clone(),
|
||||
api_key: cli.search_api_key.clone(),
|
||||
username: cli.search_username.clone(),
|
||||
password: cli.search_password.clone(),
|
||||
..SearchConfig::default()
|
||||
};
|
||||
let search = Arc::new(SearchRuntime::new(db.pool().clone(), ext.quota_gate(), search_cfg)?);
|
||||
|
||||
let state = AppState::with_services(
|
||||
@@ -1491,6 +1501,7 @@ async fn build_server_with_bound_port(
|
||||
.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();
|
||||
sync_cfg.redis_key_prefix = state.app_config.internal_redis_key_prefix();
|
||||
let authenticator = Arc::new(AuthServiceSyncAuthenticator {
|
||||
auth: state.auth.clone(),
|
||||
app_config: state.app_config.clone(),
|
||||
@@ -1517,7 +1528,8 @@ async fn build_server_with_bound_port(
|
||||
})
|
||||
}
|
||||
|
||||
/// Nests `router` under `server_path` when a non-root subpath prefix (e.g. `"/affine"`) is configured.
|
||||
/// Always mounts `router` at root `/socket.io`, and additionally nests it under `server_path`
|
||||
/// when a non-root subpath prefix (e.g. `"/affine"`) is configured.
|
||||
fn mount_router_with_server_path(router: Router, server_path: &str) -> Router {
|
||||
let trimmed = server_path.trim().trim_end_matches('/');
|
||||
if trimmed.is_empty() || trimmed == "/" {
|
||||
@@ -1528,7 +1540,7 @@ fn mount_router_with_server_path(router: Router, server_path: &str) -> Router {
|
||||
} else {
|
||||
format!("/{trimmed}")
|
||||
};
|
||||
Router::new().nest(&prefix, router)
|
||||
Router::new().merge(router.clone()).nest(&prefix, router)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1562,7 +1574,7 @@ impl server_mail::WorkspaceMailMetaResolver for AffineWorkspaceMailResolver {
|
||||
let Some((raw_name, avatar_key)) = meta else {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = raw_name.unwrap_or_else(|| "Untitled".to_owned());
|
||||
let name = raw_name.unwrap_or_else(|| "Untitled Workspace".to_owned());
|
||||
let name_contains_domain = server_domain::content_policy::contains_url_or_domain(&name);
|
||||
let avatar = match avatar_key
|
||||
.as_deref()
|
||||
@@ -1588,11 +1600,31 @@ impl server_mail::WorkspaceMailMetaResolver for AffineWorkspaceMailResolver {
|
||||
}
|
||||
}
|
||||
|
||||
struct DynamicMailWorkerConfig {
|
||||
primary: SmtpMailer,
|
||||
fallback: Option<SmtpMailer>,
|
||||
fallback_domains: Vec<String>,
|
||||
batch_size: i64,
|
||||
lease_ms: i64,
|
||||
}
|
||||
|
||||
async fn load_dynamic_mailers(
|
||||
app_config: &AppConfigService,
|
||||
startup_smtp: Option<&SmtpConfig>,
|
||||
) -> Result<Option<(SmtpMailer, Option<SmtpMailer>, Vec<String>)>, server_types::DomainError> {
|
||||
) -> Result<Option<DynamicMailWorkerConfig>, server_types::DomainError> {
|
||||
let mailer_cfg = app_config.get_internal_mailer_config().await?;
|
||||
let batch_size = mailer_cfg
|
||||
.pointer("/deliveryWorker/batchSize")
|
||||
.and_then(|v| v.as_i64())
|
||||
.filter(|&n| n > 0)
|
||||
.unwrap_or(50)
|
||||
.clamp(1, 500);
|
||||
let lease_ms = mailer_cfg
|
||||
.pointer("/deliveryWorker/leaseMs")
|
||||
.and_then(|v| v.as_i64())
|
||||
.filter(|&n| n >= 2_000)
|
||||
.unwrap_or(120_000);
|
||||
let smtp_timeout = Duration::from_millis((lease_ms.saturating_sub(1000)).clamp(1_000, 30_000) as u64);
|
||||
let raw_smtp = mailer_cfg.get("SMTP");
|
||||
let mut cfg = startup_smtp.cloned().unwrap_or_else(|| SmtpConfig {
|
||||
port: 465,
|
||||
@@ -1634,7 +1666,7 @@ async fn load_dynamic_mailers(
|
||||
if cfg.host.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let primary = match SmtpMailer::new(&cfg) {
|
||||
let primary = match SmtpMailer::with_timeout(&cfg, smtp_timeout) {
|
||||
Ok(mailer) => mailer,
|
||||
Err(err) => {
|
||||
tracing::warn!(error = %err, "invalid dynamic primary SMTP configuration");
|
||||
@@ -1652,7 +1684,7 @@ async fn load_dynamic_mailers(
|
||||
if c.sender.trim().is_empty() {
|
||||
c.sender = cfg.sender.clone();
|
||||
}
|
||||
match SmtpMailer::new(&c) {
|
||||
match SmtpMailer::with_timeout(&c, smtp_timeout) {
|
||||
Ok(mailer) => Some(mailer),
|
||||
Err(err) => {
|
||||
tracing::warn!(error = %err, "invalid dynamic fallback SMTP configuration");
|
||||
@@ -1670,7 +1702,13 @@ async fn load_dynamic_mailers(
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Ok(Some((primary, fallback, fallback_domains)))
|
||||
Ok(Some(DynamicMailWorkerConfig {
|
||||
primary,
|
||||
fallback,
|
||||
fallback_domains,
|
||||
batch_size,
|
||||
lease_ms,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn spawn_dynamic_mail_delivery_worker(
|
||||
@@ -1694,7 +1732,7 @@ async fn spawn_dynamic_mail_delivery_worker(
|
||||
);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut last_gen: Option<u64> = None;
|
||||
let mut cached_mailers: Option<(SmtpMailer, Option<SmtpMailer>, Vec<String>)> = None;
|
||||
let mut cached_mailers: Option<DynamicMailWorkerConfig> = None;
|
||||
let ws_resolver = AffineWorkspaceMailResolver {
|
||||
state: Arc::clone(&state),
|
||||
};
|
||||
@@ -1714,15 +1752,23 @@ async fn spawn_dynamic_mail_delivery_worker(
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((mailer, fallback, fallback_domains)) = cached_mailers.as_ref() {
|
||||
if let Some(cfg) = cached_mailers.as_ref() {
|
||||
let opts = MailDeliveryOptions {
|
||||
base_url: &base_url,
|
||||
fallback_mailer: fallback.as_ref(),
|
||||
fallback_domains: fallback_domains.as_slice(),
|
||||
fallback_mailer: cfg.fallback.as_ref(),
|
||||
fallback_domains: cfg.fallback_domains.as_slice(),
|
||||
workspace_resolver: Some(&ws_resolver),
|
||||
};
|
||||
if let Err(err) =
|
||||
process_ready_mail_deliveries_with_options(state.db.pool(), mailer, &worker_id, 50, 120_000, &opts).await
|
||||
process_ready_mail_deliveries_with_options(
|
||||
state.db.pool(),
|
||||
&cfg.primary,
|
||||
&worker_id,
|
||||
cfg.batch_size,
|
||||
cfg.lease_ms,
|
||||
&opts,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %err, "mail delivery worker tick failed");
|
||||
}
|
||||
@@ -2195,6 +2241,56 @@ async fn wait_for_shutdown_signal() {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_search_config_from_cli_and_file(
|
||||
cli: &ServerCli,
|
||||
file_indexer: Option<&serde_json::Value>,
|
||||
env_enabled_set: bool,
|
||||
env_provider_set: bool,
|
||||
) -> SearchConfig {
|
||||
let search_enabled = if env_enabled_set || cli.search_enabled {
|
||||
cli.search_enabled
|
||||
} else {
|
||||
file_indexer
|
||||
.and_then(|v| v.get("enabled").and_then(serde_json::Value::as_bool))
|
||||
.unwrap_or(cli.search_enabled)
|
||||
};
|
||||
let file_provider_obj = file_indexer
|
||||
.and_then(|v| v.get("provider"))
|
||||
.and_then(serde_json::Value::as_object);
|
||||
let search_provider = if env_provider_set || cli.search_provider != "embedded" {
|
||||
cli.search_provider.clone()
|
||||
} else {
|
||||
file_provider_obj
|
||||
.and_then(|obj| obj.get("type").and_then(serde_json::Value::as_str))
|
||||
.or_else(|| file_indexer.and_then(|v| v.get("provider").and_then(serde_json::Value::as_str)))
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.unwrap_or_else(|| cli.search_provider.clone())
|
||||
};
|
||||
let pick_search_str = |cli_val: &str, json_key: &str| -> String {
|
||||
if !cli_val.trim().is_empty() {
|
||||
cli_val.to_owned()
|
||||
} else {
|
||||
file_provider_obj
|
||||
.and_then(|obj| obj.get(json_key).and_then(serde_json::Value::as_str))
|
||||
.or_else(|| file_indexer.and_then(|v| v.get(json_key).and_then(serde_json::Value::as_str)))
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
SearchConfig {
|
||||
enabled: search_enabled,
|
||||
provider: search_provider,
|
||||
endpoint: pick_search_str(&cli.search_endpoint, "endpoint"),
|
||||
api_key: pick_search_str(&cli.search_api_key, "apiKey"),
|
||||
username: pick_search_str(&cli.search_username, "username"),
|
||||
password: pick_search_str(&cli.search_password, "password"),
|
||||
..SearchConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::Ipv4Addr;
|
||||
@@ -2350,7 +2446,33 @@ mod tests {
|
||||
assert!(prefixed_line.contains(" 200 "), "got: {prefixed_line}");
|
||||
|
||||
let root_line = get_status("/socket.io/?EIO=4&transport=polling").await;
|
||||
assert!(root_line.contains(" 404 "), "got: {root_line}");
|
||||
assert!(root_line.contains(" 200 "), "got: {root_line}");
|
||||
server.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_config_parses_v0275_nested_provider_object_and_respects_env_disable() {
|
||||
let cli = ServerCli::default();
|
||||
let v0275_indexer = serde_json::json!({
|
||||
"enabled": true,
|
||||
"provider": {
|
||||
"type": "elasticsearch",
|
||||
"endpoint": "http://es:9200",
|
||||
"apiKey": "k",
|
||||
"username": "u",
|
||||
"password": "p"
|
||||
}
|
||||
});
|
||||
let cfg = resolve_search_config_from_cli_and_file(&cli, Some(&v0275_indexer), false, false);
|
||||
assert!(cfg.enabled);
|
||||
assert_eq!(cfg.provider, "elasticsearch");
|
||||
assert_eq!(cfg.endpoint, "http://es:9200");
|
||||
assert_eq!(cfg.api_key, "k");
|
||||
assert_eq!(cfg.username, "u");
|
||||
assert_eq!(cfg.password, "p");
|
||||
|
||||
// Explicit AFFINE_INDEXER_ENABLED=false must not be overridden by file enabled=true.
|
||||
let disabled_cfg = resolve_search_config_from_cli_and_file(&cli, Some(&v0275_indexer), true, false);
|
||||
assert!(!disabled_cfg.enabled);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ This document lists intentional improvements in the native Rust backend. Each en
|
||||
- Native behavior: JSON request bodies allow up to 16 MiB. Parsed `query` strings enforce a 100 KiB limit and a 64-level depth limit.
|
||||
|
||||
- `POST /graphql` rejects missing, empty, or non-JSON `Content-Type` headers.
|
||||
- Cookie multipart requests without a preflight header require a trusted `Origin` or `Referer` header and reject `cross-site` and untrusted `same-site` requests.
|
||||
- Cookie multipart requests require a preflight header. Requests without that header return `400` (`BAD_REQUEST`).
|
||||
- `GET /graphql?query=...` requires a non-`Content-Type` preflight header and allows read-only queries only.
|
||||
|
||||
- Test: `http_auth_graphql_and_rest_parity` in `packages/backend/server-http/tests/http_auth_sync_parity.rs`.
|
||||
@@ -55,7 +55,7 @@ This document lists intentional improvements in the native Rust backend. Each en
|
||||
- Native behavior: Derives a deterministic HMAC-SHA256 token from the configured private key when `webhookVerificationToken` has no value.
|
||||
|
||||
- Database updates to `crypto.privateKey` take effect live without restarting the server.
|
||||
- Rotating `crypto.privateKey` live invalidates existing calendar credentials and Google webhook tokens. Session signing keys switch on restart.
|
||||
- Rotating `crypto.privateKey` live invalidates existing calendar credentials and Google webhook tokens.
|
||||
|
||||
- Test: `calendar_private_key_raw_bytes_and_db_override_interop` in `packages/backend/server-domain/src/calendar/mod.rs`.
|
||||
|
||||
|
||||
@@ -295,14 +295,7 @@ impl StorageObjectLock {
|
||||
self.object_key.clone(),
|
||||
),
|
||||
] {
|
||||
while !sqlx::query_scalar::<_, bool>(statement)
|
||||
.bind(&name)
|
||||
.fetch_one(&mut self.connection)
|
||||
.await
|
||||
.map_err(db_error("take storage lifecycle lock"))?
|
||||
{
|
||||
tokio::time::sleep(STORAGE_LOCK_POLL).await;
|
||||
}
|
||||
poll_advisory_lock(&mut self.connection, statement, &name).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -331,12 +324,96 @@ impl StorageObjectLock {
|
||||
}
|
||||
}
|
||||
|
||||
async fn poll_advisory_lock(conn: &mut PgConnection, statement: &str, name: &str) -> Result<(), DomainError> {
|
||||
while !sqlx::query_scalar::<_, bool>(statement)
|
||||
.bind(name)
|
||||
.fetch_one(&mut *conn)
|
||||
.await
|
||||
.map_err(db_error("take storage lifecycle lock"))?
|
||||
{
|
||||
tokio::time::sleep(STORAGE_LOCK_POLL).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Exclusive workspace-wide session lock (`storage-workspace:<workspace_id>`)
|
||||
/// that serializes whole-workspace cleanup against shared object operations
|
||||
/// (`StorageObjectLock`).
|
||||
pub(crate) struct StorageWorkspaceLock {
|
||||
connection: PgConnection,
|
||||
workspace_key: String,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
|
||||
impl StorageWorkspaceLock {
|
||||
pub(crate) async fn acquire(
|
||||
db: &ServerDb,
|
||||
permits: &Arc<Semaphore>,
|
||||
workspace_id: &str,
|
||||
) -> Result<Self, DomainError> {
|
||||
let deadline = tokio::time::Instant::now() + STORAGE_LOCK_TIMEOUT;
|
||||
let timed_out = || DomainError::Unavailable("storage_lifecycle_lock_timeout".into());
|
||||
let (permit, connection) = tokio::time::timeout_at(deadline, async {
|
||||
let permit = Arc::clone(permits)
|
||||
.acquire_owned()
|
||||
.await
|
||||
.map_err(|_| DomainError::Unavailable("storage lock permits closed".into()))?;
|
||||
let connection = db
|
||||
.dedicated_session_conn()
|
||||
.await
|
||||
.map_err(|err| DomainError::Unavailable(format!("storage lock session: {err}")))?;
|
||||
Ok::<_, DomainError>((permit, connection))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| timed_out())??;
|
||||
let mut lock = Self {
|
||||
connection,
|
||||
workspace_key: format!("storage-workspace:{workspace_id}"),
|
||||
_permit: permit,
|
||||
};
|
||||
let locked = tokio::time::timeout_at(
|
||||
deadline,
|
||||
poll_advisory_lock(
|
||||
&mut lock.connection,
|
||||
"SELECT pg_try_advisory_lock(hashtextextended($1,0))",
|
||||
&lock.workspace_key,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
match locked {
|
||||
Ok(Ok(())) => Ok(lock),
|
||||
Ok(Err(err)) => {
|
||||
let _ = lock.connection.close().await;
|
||||
Err(err)
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = lock.connection.close().await;
|
||||
Err(timed_out())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn release(mut self) {
|
||||
if let Err(error) = sqlx::query("SELECT pg_advisory_unlock(hashtextextended($1,0))")
|
||||
.bind(&self.workspace_key)
|
||||
.execute(&mut self.connection)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %error, workspace_key = %self.workspace_key, "failed to release storage workspace lock");
|
||||
}
|
||||
if let Err(error) = self.connection.close().await {
|
||||
tracing::debug!(error = %error, "storage workspace lock session did not close cleanly");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlobService {
|
||||
pub(crate) db: ServerDb,
|
||||
pub(crate) boot_storage: Arc<dyn BlobStorageBackend>,
|
||||
pub(crate) dynamic_storage: Arc<DynamicBlobStorage>,
|
||||
storage: Arc<dyn BlobStorageBackend>,
|
||||
quota: Arc<dyn QuotaGate>,
|
||||
pub(crate) invalidation: Option<Arc<dyn server_domain::events::InvalidationPublisher>>,
|
||||
pub(crate) lock_permits: Arc<Semaphore>,
|
||||
ref_cache: Arc<std::sync::Mutex<refs::BlobRefCache>>,
|
||||
}
|
||||
@@ -352,11 +429,17 @@ impl BlobService {
|
||||
dynamic_storage,
|
||||
storage,
|
||||
quota,
|
||||
invalidation: None,
|
||||
lock_permits: Arc::new(Semaphore::new(DEFAULT_STORAGE_LOCK_CONCURRENCY)),
|
||||
ref_cache: Arc::new(std::sync::Mutex::new(refs::BlobRefCache::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_invalidation(mut self, invalidation: Arc<dyn server_domain::events::InvalidationPublisher>) -> Self {
|
||||
self.invalidation = Some(invalidation);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dynamic_storage(&self) -> &Arc<DynamicBlobStorage> {
|
||||
&self.dynamic_storage
|
||||
}
|
||||
@@ -849,8 +932,10 @@ impl BlobService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Locks the workspace row and the key's ledger row, classifies the ledger
|
||||
/// row, checks the grant, and records a pending reservation.
|
||||
/// Locks the workspace owner (`users`), then the workspace row (`workspaces`),
|
||||
/// re-verifies the active owner (matching `strict_quota/authorization.rs`),
|
||||
/// classifies the ledger row, checks the grant and seat/storage quotas using
|
||||
/// PostgreSQL `clock_timestamp()`, and records or resumes a pending reservation.
|
||||
pub(crate) async fn reserve(
|
||||
&self,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
@@ -859,6 +944,20 @@ impl BlobService {
|
||||
mime: &str,
|
||||
size: i64,
|
||||
) -> Result<Admission, DomainError> {
|
||||
let owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id=$1 AND role='owner' AND state='active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load workspace quota owner"))?;
|
||||
if let Some(ref oid) = owner_id {
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE")
|
||||
.bind(oid)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("lock quota owner"))?;
|
||||
}
|
||||
let locked: Option<String> = sqlx::query_scalar("SELECT id FROM workspaces WHERE id = $1 FOR UPDATE")
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
@@ -867,18 +966,35 @@ impl BlobService {
|
||||
if locked.is_none() {
|
||||
return Err(DomainError::NotFound(format!("workspace {workspace_id}")));
|
||||
}
|
||||
let locked_owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id=$1 AND role='owner' AND state='active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("verify storage quota owner"))?;
|
||||
if locked_owner_id != owner_id {
|
||||
return Err(DomainError::Conflict("storage_quota_subject_changed".into()));
|
||||
}
|
||||
|
||||
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load db clock for quota"))?;
|
||||
|
||||
let existing = sqlx::query(
|
||||
"SELECT size::bigint AS size, mime, status::text AS status, created_at, deleted_at IS NOT NULL AS deleted, \
|
||||
reservation_id::text AS reservation_id, upload_id, \
|
||||
COALESCE(reservation_expires_at > clock_timestamp(), false) AS live_reservation FROM blobs WHERE \
|
||||
COALESCE(reservation_expires_at > $3, false) AS live_reservation FROM blobs WHERE \
|
||||
workspace_id=$1 AND key=$2 FOR UPDATE",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(key)
|
||||
.bind(now)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load blob ledger row"))?;
|
||||
let mut resumable_reservation_id: Option<String> = None;
|
||||
if let Some(row) = existing {
|
||||
let status: String = row.get("status");
|
||||
let deleted: bool = row.get("deleted");
|
||||
@@ -902,18 +1018,43 @@ impl BlobService {
|
||||
}));
|
||||
}
|
||||
"pending" if !deleted && row.get::<bool, _>("live_reservation") => {
|
||||
return Err(DomainError::Conflict("blob upload is pending".into()));
|
||||
let existing_size: i64 = row.get("size");
|
||||
let existing_mime: String = row.get("mime");
|
||||
let upload_id: Option<String> = row.get("upload_id");
|
||||
let reservation_id: Option<String> = row.get("reservation_id");
|
||||
if upload_id.is_none()
|
||||
&& existing_size == size
|
||||
&& existing_mime == mime
|
||||
&& let Some(rid) = reservation_id
|
||||
{
|
||||
resumable_reservation_id = Some(rid);
|
||||
} else {
|
||||
return Err(DomainError::Conflict("blob upload is pending".into()));
|
||||
}
|
||||
}
|
||||
"pending" => {}
|
||||
other => return Err(DomainError::Conflict(format!("storage key is not reusable ({other})"))),
|
||||
}
|
||||
}
|
||||
|
||||
let now = Utc::now();
|
||||
let grant = self.quota.resolve_workspace_grant(tx, workspace_id, now).await?;
|
||||
if grant.limits.seat_limit <= 0 || grant.expires_at.is_some_and(|expires_at| now >= expires_at) {
|
||||
let charged_seats: i64 = sqlx::query_scalar(
|
||||
r#"SELECT
|
||||
(SELECT count(*) FROM workspace_members WHERE workspace_id=$1 AND state='active')
|
||||
+ (SELECT count(*) FROM workspace_invitations WHERE workspace_id=$1
|
||||
AND status::text = ANY($2))"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(server_domain::workspaces::CHARGEABLE_INVITATION_STATUSES.as_slice())
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load strict storage seat usage"))?;
|
||||
if grant.limits.seat_limit <= 0
|
||||
|| charged_seats > i64::from(grant.limits.seat_limit)
|
||||
|| grant.expires_at.is_some_and(|expires_at| now >= expires_at)
|
||||
{
|
||||
return Err(DomainError::QuotaExceeded {
|
||||
kind: "blob_limit",
|
||||
kind: "storage_quota",
|
||||
message: "workspace is in fail-closed readonly state".into(),
|
||||
});
|
||||
}
|
||||
@@ -926,24 +1067,14 @@ impl BlobService {
|
||||
),
|
||||
});
|
||||
}
|
||||
if let Some(rid) = resumable_reservation_id {
|
||||
return Ok(Admission::Reserved(rid));
|
||||
}
|
||||
let charged_workspaces: Vec<String> = if grant.billing_subject == server_types::BillingSubject::Workspace {
|
||||
vec![workspace_id.to_owned()]
|
||||
} else {
|
||||
let owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id=$1 AND role='owner' AND state='active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load workspace owner for quota"))?;
|
||||
let mut list = vec![workspace_id.to_owned()];
|
||||
if let Some(owner_id) = owner_id {
|
||||
let lock_key = format!("owner-storage-quota:{owner_id}");
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
.bind(&lock_key)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("lock workspace owner for quota"))?;
|
||||
if let Some(owner_id) = locked_owner_id {
|
||||
let owned: Vec<(String, bool)> = sqlx::query_as(
|
||||
r#"SELECT
|
||||
wm.workspace_id,
|
||||
@@ -993,11 +1124,12 @@ impl BlobService {
|
||||
let used: i64 = sqlx::query_scalar(
|
||||
r#"SELECT
|
||||
COALESCE((SELECT SUM(size)::bigint FROM blobs WHERE workspace_id=ANY($1) AND deleted_at IS NULL
|
||||
AND (status='completed' OR (status='pending' AND reservation_expires_at > clock_timestamp()))),0)
|
||||
AND (status='completed' OR (status='pending' AND reservation_expires_at > $2))),0)
|
||||
+ COALESCE((SELECT SUM(size)::bigint FROM comment_attachments WHERE workspace_id=ANY($1) AND deleted_at IS NULL
|
||||
AND (status='completed' OR (status='pending' AND reservation_expires_at > clock_timestamp()))),0)"#,
|
||||
AND (status='completed' OR (status='pending' AND reservation_expires_at > $2))),0)"#,
|
||||
)
|
||||
.bind(&charged_workspaces)
|
||||
.bind(now)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("load workspace storage usage"))?;
|
||||
@@ -1020,7 +1152,7 @@ impl BlobService {
|
||||
r#"INSERT INTO blobs
|
||||
(workspace_id, key, size, mime, status, reservation_id, reservation_expires_at, upload_id, deleted_at,
|
||||
created_at)
|
||||
VALUES ($1, $2, $3, $4, 'pending', gen_random_uuid(), clock_timestamp() + make_interval(mins => $5), NULL,
|
||||
VALUES ($1, $2, $3, $4, 'pending', gen_random_uuid(), $6 + make_interval(mins => $5), NULL,
|
||||
NULL, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (workspace_id, key) DO UPDATE SET
|
||||
size = EXCLUDED.size, mime = EXCLUDED.mime, status = 'pending', reservation_id = EXCLUDED.reservation_id,
|
||||
@@ -1034,6 +1166,7 @@ impl BlobService {
|
||||
.bind(size_i32)
|
||||
.bind(mime)
|
||||
.bind(STORAGE_RESERVATION_MINUTES)
|
||||
.bind(now)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(db_error("reserve blob"))?
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,13 +29,17 @@ use crate::storage::{
|
||||
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
fn is_s3_missing_object_404(body: &str) -> bool {
|
||||
let trimmed = body.trim();
|
||||
if trimmed.is_empty() {
|
||||
let Some(err_open) = trimmed.find("<Error") else {
|
||||
return false;
|
||||
}
|
||||
if let Some(start) = trimmed.find("<Code>")
|
||||
&& let Some(end) = trimmed[start + 6..].find("</Code>")
|
||||
};
|
||||
let Some(err_close) = trimmed[err_open..].find("</Error>") else {
|
||||
return false;
|
||||
};
|
||||
let err_block = &trimmed[err_open..err_open + err_close];
|
||||
if let Some(start) = err_block.find("<Code>")
|
||||
&& let Some(end) = err_block[start + 6..].find("</Code>")
|
||||
{
|
||||
let code = trimmed[start + 6..start + 6 + end].trim();
|
||||
let code = err_block[start + 6..start + 6 + end].trim();
|
||||
return matches!(code, "NoSuchKey" | "NotFound");
|
||||
}
|
||||
false
|
||||
@@ -577,8 +581,8 @@ impl BlobStorageBackend for S3BlobStorage {
|
||||
let mut action = PutObject::new(&self.bucket, Some(&self.credentials), k);
|
||||
let len_str = len.to_string();
|
||||
let headers = BTreeMap::from([
|
||||
("content-type".into(), ct.into()),
|
||||
("content-length".into(), len_str.clone()),
|
||||
("Content-Type".into(), ct.into()),
|
||||
("Content-Length".into(), len_str.clone()),
|
||||
]);
|
||||
if self.upload_options.sign_content_type_for_put {
|
||||
action.headers_mut().insert("content-type", ct);
|
||||
@@ -604,7 +608,7 @@ impl BlobStorageBackend for S3BlobStorage {
|
||||
.ok_or_else(|| StorageError::Metadata("missing UploadId in S3 response".into()))?;
|
||||
Ok(Some(MultipartUploadInit {
|
||||
upload_id,
|
||||
expires_at: Utc::now() + chrono::Duration::hours(24),
|
||||
expires_at: Utc::now() + chrono::Duration::seconds(self.presign_expires.as_secs() as i64),
|
||||
}))
|
||||
}
|
||||
async fn presign_upload_part(&self, k: &str, uid: &str, pn: i32) -> Result<Option<PresignedUpload>, StorageError> {
|
||||
@@ -836,6 +840,9 @@ 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>"));
|
||||
assert!(!is_s3_missing_object_404(
|
||||
"<Error><Code>NoSuchKey</Code><Message>truncated"
|
||||
));
|
||||
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>"));
|
||||
@@ -892,10 +899,10 @@ mod tests {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
presigned.headers.get("content-type").map(String::as_str),
|
||||
presigned.headers.get("Content-Type").map(String::as_str),
|
||||
Some("image/png")
|
||||
);
|
||||
assert_eq!(presigned.headers.get("content-length").map(String::as_str), Some("42"));
|
||||
assert_eq!(presigned.headers.get("Content-Length").map(String::as_str), Some("42"));
|
||||
assert!(!presigned.url.contains("content-type"), "{}", presigned.url);
|
||||
}
|
||||
}
|
||||
@@ -736,7 +736,7 @@ impl BlobStorageBackend for LocalFsBlobStorage {
|
||||
}
|
||||
normalize_storage_key(key)?;
|
||||
let (dir, key_owned) = (self.multipart_dir(uid)?, key.to_owned());
|
||||
let etag = format!("\"{}\"", hex::encode(Sha256::digest(&body)));
|
||||
let etag = hex::encode(Sha256::digest(&body));
|
||||
let etag_meta = etag.clone();
|
||||
blocking(move || {
|
||||
read_fs_manifest(&dir, &key_owned)?;
|
||||
@@ -768,7 +768,7 @@ impl BlobStorageBackend for LocalFsBlobStorage {
|
||||
{
|
||||
parts.push(UploadedPart {
|
||||
part_number: pn,
|
||||
etag: etag.trim().to_owned(),
|
||||
etag: etag.trim().trim_matches('"').to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,14 +411,18 @@ fn quota_admission_rejects_blob_limit_storage_quota_readonly_and_missing_workspa
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
service.put_blob(&ws, "pending", "a/b", vec![0; 5]).await,
|
||||
service.put_blob(&ws, "pending", "c/d", vec![0; 5]).await,
|
||||
Err(DomainError::Conflict(message)) if message == "blob upload is pending"
|
||||
));
|
||||
assert!(matches!(
|
||||
service.put_blob(&ws, "pending", "a/b", vec![0; 5]).await,
|
||||
Ok(PutBlobOutcome::Created(_))
|
||||
));
|
||||
|
||||
let readonly = fx.service(1 << 20, 1 << 30, 0);
|
||||
assert_eq!(
|
||||
quota_kind(readonly.put_blob(&ws, "ro", "a/b", vec![1]).await),
|
||||
"blob_limit"
|
||||
"storage_quota"
|
||||
);
|
||||
|
||||
let missing = uuid::Uuid::new_v4().to_string();
|
||||
@@ -768,13 +772,26 @@ fn reconcile_storage_orphans_exempts_copilot_and_artifact_prefixes() {
|
||||
inner: LocalFsBlobStorage::new(dir.to_str().unwrap(), "blobs").unwrap(),
|
||||
age_backdate: chrono::Duration::hours(48),
|
||||
});
|
||||
sqlx::query("INSERT INTO users (id, name, email) VALUES ('u-1', 'Copilot User', 'u1@example.com')")
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO workspaces (id) VALUES ('ws-1')")
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let exempted = [
|
||||
"copilot/transcript/ws-1/u-1/t-1/0",
|
||||
"copilot/artifacts/ws-1/doc-1/art-1",
|
||||
"copilot-attachments/ws-1/att-1",
|
||||
"artifacts/ws-1/art-2",
|
||||
];
|
||||
for key in exempted {
|
||||
let live_copilot = [
|
||||
"artifacts/ws-1/art-2",
|
||||
"workspace-files/ws-1/file-1",
|
||||
"context-files/ws-1/ctx-1",
|
||||
"u-1/ws-1/chat-att-1",
|
||||
];
|
||||
for key in exempted.into_iter().chain(live_copilot) {
|
||||
storage
|
||||
.put(key, b"keep-me".to_vec(), "application/octet-stream")
|
||||
.await
|
||||
@@ -802,10 +819,10 @@ fn reconcile_storage_orphans_exempts_copilot_and_artifact_prefixes() {
|
||||
assert!(report.leased);
|
||||
assert_eq!(report.deleted_objects, 1);
|
||||
assert_eq!(report.skipped_unknown_prefix, exempted.len());
|
||||
for key in exempted {
|
||||
for key in exempted.into_iter().chain(live_copilot) {
|
||||
assert!(
|
||||
storage.get(key).await.unwrap().is_some(),
|
||||
"exempted key must survive orphan reconciliation: {key}"
|
||||
"live/exempted key must survive orphan reconciliation: {key}"
|
||||
);
|
||||
}
|
||||
assert!(storage.get("deleted-ws-999/stale-orphan").await.unwrap().is_none());
|
||||
@@ -897,3 +914,126 @@ fn owner_storage_quota_aggregates_past_64_personal_workspaces() {
|
||||
assert_eq!(quota_kind(err), "storage_quota");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_cleans_only_ownerless_workspaces_older_than_24h_and_their_orphan_rows() {
|
||||
let lease = leased_0275_database();
|
||||
runtime().block_on(async {
|
||||
let db = ServerDb::connect(DbConfig::new(lease.url())).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 dir = std::env::temp_dir().join(format!("server-blob-ownerless-{}", uuid::Uuid::new_v4().simple()));
|
||||
let _guard = TempDir(dir.clone());
|
||||
let storage = Arc::new(LocalFsBlobStorage::new(dir.to_str().unwrap(), "blobs").unwrap());
|
||||
|
||||
let owner_id = "u-owner-live";
|
||||
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, 'Owner', 'owner-live@example.test')")
|
||||
.bind(owner_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let ws_owned_old = "ws-owned-old";
|
||||
let ws_ownerless_new = "ws-ownerless-new";
|
||||
let ws_ownerless_old = "ws-ownerless-old";
|
||||
|
||||
// (a) Active owner + older than 24h -> must be retained.
|
||||
sqlx::query("INSERT INTO workspaces (id, created_at) VALUES ($1, clock_timestamp() - interval '48 hours')")
|
||||
.bind(ws_owned_old)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_members (id, workspace_id, user_id, role, source, state, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, 'owner', 'legacy', 'active', now(), now())",
|
||||
)
|
||||
.bind(uuid::Uuid::new_v4().to_string())
|
||||
.bind(ws_owned_old)
|
||||
.bind(owner_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// (b) Ownerless + younger than 24h -> must be retained.
|
||||
sqlx::query("INSERT INTO workspaces (id, created_at) VALUES ($1, clock_timestamp() - interval '2 hours')")
|
||||
.bind(ws_ownerless_new)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// (c) Ownerless + older than 24h + dependent rows -> must be deleted with its rows.
|
||||
sqlx::query("INSERT INTO workspaces (id, created_at) VALUES ($1, clock_timestamp() - interval '48 hours')")
|
||||
.bind(ws_ownerless_old)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO blobs (workspace_id, key, mime, size, status, created_at)
|
||||
VALUES ($1, 'orphan-blob-1', 'application/octet-stream', 10, 'completed', now())",
|
||||
)
|
||||
.bind(ws_ownerless_old)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, metadata, updated_at)
|
||||
VALUES ('doc_blob_refs', $1, 'running', '{}'::jsonb, now())",
|
||||
)
|
||||
.bind(ws_ownerless_old)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let service = BlobService::new(
|
||||
db.clone(),
|
||||
storage,
|
||||
Arc::new(FixedQuotaGate {
|
||||
blob_limit: 1 << 20,
|
||||
storage_quota: 1 << 30,
|
||||
seat_limit: 10,
|
||||
}),
|
||||
);
|
||||
|
||||
let report = service
|
||||
.reconcile_storage_orphans(100, &|| false)
|
||||
.await
|
||||
.expect("reconcile ownerless workspaces");
|
||||
assert_eq!(report.deleted_ownerless_workspaces, 1);
|
||||
assert!(report.deleted_orphan_rows >= 1);
|
||||
|
||||
let exists = |ws: &str| {
|
||||
let pool = db.pool().clone();
|
||||
let ws = ws.to_owned();
|
||||
async move {
|
||||
sqlx::query_scalar::<_, bool>("SELECT EXISTS(SELECT 1 FROM workspaces WHERE id = $1)")
|
||||
.bind(ws)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
assert!(exists(ws_owned_old).await, "owned >24h workspace must be retained");
|
||||
assert!(
|
||||
exists(ws_ownerless_new).await,
|
||||
"ownerless <24h workspace must be retained"
|
||||
);
|
||||
assert!(
|
||||
!exists(ws_ownerless_old).await,
|
||||
"ownerless >24h workspace must be deleted"
|
||||
);
|
||||
|
||||
let remaining_blobs: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM blobs WHERE workspace_id = $1")
|
||||
.bind(ws_ownerless_old)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
remaining_blobs, 0,
|
||||
"orphan blob rows of deleted ownerless workspace must be cleaned"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -603,6 +603,13 @@ fn expired_reservation_cleanup_and_orphan_reconciliation_are_idempotent() {
|
||||
// 2. Live comment-attachments/ws-live/doc-1/att.png (>24h old) -> NOT deleted
|
||||
// 3. Within-24h grace orphan ws-deleted/fresh-orphan.bin -> skipped, NOT deleted
|
||||
// 4. >24h real orphan ws-deleted/old-orphan.bin -> DELETED
|
||||
sqlx::query(
|
||||
"INSERT INTO comment_attachments (workspace_id, doc_id, key, name, size, mime, status) \
|
||||
VALUES ('ws-live', 'doc-1', 'att.png', 'att.png', 3, 'image/png', 'completed')",
|
||||
)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
fs.put("ws-live/keep.bin", b"keep".to_vec(), "application/octet-stream").await.unwrap();
|
||||
fs.put("tmp/unknown.bin", b"u".to_vec(), "application/octet-stream").await.unwrap();
|
||||
fs.put("comment-attachments/ws-live/doc-1/att.png", b"att".to_vec(), "image/png").await.unwrap();
|
||||
@@ -651,7 +658,7 @@ fn expired_reservation_cleanup_and_orphan_reconciliation_are_idempotent() {
|
||||
"copilot-attachments/ws-deleted/u-1/k1",
|
||||
"copilot/artifacts/ws-deleted/a1",
|
||||
"copilot/transcript/ws-deleted/t1",
|
||||
"artifacts/ws-deleted/a2",
|
||||
"artifacts/ws-live/a2",
|
||||
];
|
||||
for key in exempt_keys {
|
||||
fs.put(key, b"keep-exempt".to_vec(), "application/octet-stream").await.unwrap();
|
||||
|
||||
@@ -836,13 +836,13 @@ impl AdminService {
|
||||
.map_err(|e| DomainError::Internal(format!("admin get_dashboard clock: {e}")))?;
|
||||
let sync_to = floor_minute(now);
|
||||
let sync_from = sync_to - Duration::hours(i64::from(sync_hours));
|
||||
let current_day = jiff::tz::TimeZone::get(&timezone)
|
||||
let (effective_timezone, resolved_tz) = match jiff::tz::TimeZone::get(&timezone) {
|
||||
Ok(tz) => (timezone.clone(), tz),
|
||||
Err(_) => ("UTC".to_owned(), jiff::tz::TimeZone::UTC),
|
||||
};
|
||||
let current_day = jiff::Timestamp::from_second(now.timestamp())
|
||||
.ok()
|
||||
.and_then(|tz| {
|
||||
jiff::Timestamp::from_second(now.timestamp())
|
||||
.ok()
|
||||
.map(|ts| ts.to_zoned(tz).date())
|
||||
})
|
||||
.map(|ts| ts.to_zoned(resolved_tz.clone()).date())
|
||||
.and_then(|d| {
|
||||
NaiveDate::from_ymd_opt(
|
||||
i32::from(d.year()),
|
||||
@@ -854,7 +854,15 @@ impl AdminService {
|
||||
let storage_from_day = current_day - Duration::days(i64::from(storage_days - 1));
|
||||
let shared_from_day = current_day - Duration::days(i64::from(shared_days - 1));
|
||||
let copilot_from_day = current_day - Duration::days(i64::from(copilot_days - 1));
|
||||
let copilot_from = naive_date_to_utc(copilot_from_day);
|
||||
let copilot_from = jiff::civil::Date::new(
|
||||
chrono::Datelike::year(&copilot_from_day) as i16,
|
||||
chrono::Datelike::month(&copilot_from_day) as i8,
|
||||
chrono::Datelike::day(&copilot_from_day) as i8,
|
||||
)
|
||||
.ok()
|
||||
.and_then(|d| d.at(0, 0, 0, 0).to_zoned(resolved_tz).ok())
|
||||
.and_then(|z| DateTime::<Utc>::from_timestamp(z.timestamp().as_second(), z.timestamp().subsec_nanosecond() as u32))
|
||||
.unwrap_or_else(|| naive_date_to_utc(copilot_from_day));
|
||||
|
||||
let sync_active_users: i32 = sqlx::query_scalar(
|
||||
r#"SELECT COALESCE(
|
||||
@@ -1029,7 +1037,7 @@ impl AdminService {
|
||||
sync_window: AdminTimeWindow {
|
||||
from: sync_from,
|
||||
to: sync_to,
|
||||
timezone: timezone.clone(),
|
||||
timezone: effective_timezone.clone(),
|
||||
bucket: AdminTimeBucket::Minute,
|
||||
requested_size: query.sync_history_hours.unwrap_or(DEFAULT_SYNC_HISTORY_HOURS),
|
||||
effective_size: sync_hours,
|
||||
@@ -1038,7 +1046,7 @@ impl AdminService {
|
||||
copilot_window: AdminTimeWindow {
|
||||
from: copilot_from,
|
||||
to: now,
|
||||
timezone: timezone.clone(),
|
||||
timezone: effective_timezone.clone(),
|
||||
bucket: AdminTimeBucket::Day,
|
||||
requested_size: query.copilot_window_days.unwrap_or(DEFAULT_COPILOT_WINDOW_DAYS),
|
||||
effective_size: copilot_days,
|
||||
@@ -1050,7 +1058,7 @@ impl AdminService {
|
||||
storage_window: AdminTimeWindow {
|
||||
from: naive_date_to_utc(storage_from_day),
|
||||
to: naive_date_to_utc(current_day),
|
||||
timezone: timezone.clone(),
|
||||
timezone: effective_timezone.clone(),
|
||||
bucket: AdminTimeBucket::Day,
|
||||
requested_size: query.storage_history_days.unwrap_or(DEFAULT_STORAGE_HISTORY_DAYS),
|
||||
effective_size: storage_days,
|
||||
@@ -1059,7 +1067,7 @@ impl AdminService {
|
||||
top_shared_links_window: AdminTimeWindow {
|
||||
from: naive_date_to_utc(shared_from_day),
|
||||
to: naive_date_to_utc(current_day),
|
||||
timezone,
|
||||
timezone: effective_timezone,
|
||||
bucket: AdminTimeBucket::Day,
|
||||
requested_size: query.shared_link_window_days.unwrap_or(DEFAULT_SHARED_LINK_WINDOW_DAYS),
|
||||
effective_size: shared_days,
|
||||
|
||||
@@ -93,8 +93,10 @@ pub const NATIVE_MANAGED_CONFIG_KEYS: &[&str] = &[
|
||||
"copilot.byok.allowPrivateEndpoint",
|
||||
"copilot.byok.enabled",
|
||||
"copilot.enabled",
|
||||
"copilot.exa",
|
||||
"copilot.providers.profiles",
|
||||
"copilot.storage",
|
||||
"copilot.unsplash",
|
||||
"oauth.providers.apple",
|
||||
"oauth.providers.github",
|
||||
"oauth.providers.google",
|
||||
@@ -103,6 +105,7 @@ pub const NATIVE_MANAGED_CONFIG_KEYS: &[&str] = &[
|
||||
"payment.revenuecat",
|
||||
"payment.showLifetimePrice",
|
||||
"payment.stripe",
|
||||
"storages.avatar.publicPath",
|
||||
"storages.avatar.storage",
|
||||
"storages.blob.storage",
|
||||
];
|
||||
@@ -533,6 +536,18 @@ impl AppConfigService {
|
||||
let mut root = json!({
|
||||
"mailer": baseline.get("mailer").cloned().unwrap_or_else(|| json!({})),
|
||||
});
|
||||
for (config_key, env_var) in [
|
||||
("mailer.SMTP.password", "MAILER_PASSWORD"),
|
||||
("mailer.fallbackSMTP.password", "FALLBACK_MAILER_PASSWORD"),
|
||||
] {
|
||||
if let Some(file_val) = self.baseline.lookup_file_config_value(config_key)
|
||||
&& file_val.as_str().is_some_and(|s| !s.is_empty())
|
||||
{
|
||||
set_nested_path(&mut root, config_key, file_val.clone());
|
||||
} else if let Some(pw) = std::env::var(env_var).ok().filter(|v| !v.is_empty()) {
|
||||
set_nested_path(&mut root, config_key, Value::String(pw));
|
||||
}
|
||||
}
|
||||
let mut conn = self
|
||||
.db
|
||||
.acquire_tiered(WorkloadTier::InteractiveRead)
|
||||
@@ -551,12 +566,10 @@ impl AppConfigService {
|
||||
Ok(root.get("mailer").cloned().unwrap_or_else(|| json!({})))
|
||||
}
|
||||
|
||||
/// Internal-only reader for the startup file baseline `redis.ioredis.keyPrefix`
|
||||
/// (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
|
||||
/// Synchronous internal-only reader for the startup file baseline `redis.ioredis.keyPrefix`
|
||||
/// (falling back to `redis.keyPrefix`, then CLI `redis_key_prefix`).
|
||||
pub fn internal_redis_key_prefix(&self) -> String {
|
||||
self
|
||||
.baseline
|
||||
.lookup_file_config_value("redis.ioredis")
|
||||
.and_then(|v| v.get("keyPrefix").and_then(Value::as_str))
|
||||
@@ -570,8 +583,15 @@ impl AppConfigService {
|
||||
})
|
||||
.or_else(|| (!self.baseline.redis_key_prefix.is_empty()).then_some(self.baseline.redis_key_prefix.as_str()))
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
Ok(resolved)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Internal-only reader for the startup file baseline `redis.ioredis.keyPrefix`
|
||||
/// (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> {
|
||||
Ok(self.internal_redis_key_prefix())
|
||||
}
|
||||
|
||||
/// Builds the exact `v0.27.5` `appConfig` JSON object by combining runtime
|
||||
|
||||
@@ -516,14 +516,14 @@ impl AuthService {
|
||||
.and_then(Value::as_i64)
|
||||
.filter(|&v| v > 0)
|
||||
{
|
||||
rt.session_ttl_seconds = ttl;
|
||||
rt.session_ttl_seconds = ttl.clamp(60, 86_400 * 365 * 5);
|
||||
}
|
||||
if let Some(ttr) = eff
|
||||
.pointer("/auth/session/ttr")
|
||||
.and_then(Value::as_i64)
|
||||
.filter(|&v| v >= 0)
|
||||
{
|
||||
rt.session_ttr_seconds = ttr;
|
||||
rt.session_ttr_seconds = ttr.clamp(0, 86_400 * 365 * 5);
|
||||
}
|
||||
return rt;
|
||||
}
|
||||
@@ -586,20 +586,20 @@ impl AuthService {
|
||||
}
|
||||
"auth.session.ttl" => {
|
||||
if let Some(ttl) = val.as_i64().filter(|&v| v > 0) {
|
||||
rt.session_ttl_seconds = ttl;
|
||||
rt.session_ttl_seconds = ttl.clamp(60, 86_400 * 365 * 5);
|
||||
}
|
||||
}
|
||||
"auth.session.ttr" => {
|
||||
if let Some(ttr) = val.as_i64().filter(|&v| v >= 0) {
|
||||
rt.session_ttr_seconds = ttr;
|
||||
rt.session_ttr_seconds = ttr.clamp(0, 86_400 * 365 * 5);
|
||||
}
|
||||
}
|
||||
"auth.session" => {
|
||||
if let Some(ttl) = val.get("ttl").and_then(Value::as_i64).filter(|&v| v > 0) {
|
||||
rt.session_ttl_seconds = ttl;
|
||||
rt.session_ttl_seconds = ttl.clamp(60, 86_400 * 365 * 5);
|
||||
}
|
||||
if let Some(ttr) = val.get("ttr").and_then(Value::as_i64).filter(|&v| v >= 0) {
|
||||
rt.session_ttr_seconds = ttr;
|
||||
rt.session_ttr_seconds = ttr.clamp(0, 86_400 * 365 * 5);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -880,6 +880,21 @@ impl CommentService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("begin reserve_comment_attachment: {e}")))?;
|
||||
|
||||
let owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id = $1 AND role = 'owner' AND state = 'active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("load owner for comment attachment quota lock: {e}")))?;
|
||||
if let Some(ref oid) = owner_id {
|
||||
let _ = sqlx::query_scalar::<_, String>("SELECT id FROM users WHERE id = $1 FOR UPDATE")
|
||||
.bind(oid)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("lock owner user for comment attachment quota: {e}")))?;
|
||||
}
|
||||
|
||||
let ws_exists: Option<String> = sqlx::query_scalar("SELECT id FROM workspaces WHERE id = $1 FOR UPDATE")
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
@@ -889,6 +904,17 @@ impl CommentService {
|
||||
return Err(DomainError::NotFound("workspace_not_found".to_owned()));
|
||||
}
|
||||
|
||||
let locked_owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id = $1 AND role = 'owner' AND state = 'active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("recheck owner for comment attachment quota lock: {e}")))?;
|
||||
if locked_owner_id != owner_id {
|
||||
return Err(DomainError::Conflict("storage_quota_subject_changed".to_owned()));
|
||||
}
|
||||
|
||||
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
|
||||
.fetch_one(&mut **tx.tx_mut())
|
||||
.await
|
||||
@@ -919,23 +945,6 @@ impl CommentService {
|
||||
.quota_gate
|
||||
.resolve_workspace_grant(tx.tx_mut(), workspace_id, now)
|
||||
.await?;
|
||||
if grant.billing_subject == server_types::BillingSubject::Owner {
|
||||
let owner_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id = $1 AND role = 'owner' AND state = 'active' LIMIT 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("load owner for comment attachment quota lock: {e}")))?;
|
||||
if let Some(ref oid) = owner_id {
|
||||
let lock_key = format!("owner-storage-quota:{oid}");
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
.bind(&lock_key)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("lock owner user for comment attachment quota: {e}")))?;
|
||||
}
|
||||
}
|
||||
let used = crate::workspaces::load_effective_storage_usage_in_tx(
|
||||
tx.tx_mut(),
|
||||
self.quota_gate.as_ref(),
|
||||
@@ -1293,9 +1302,22 @@ async fn create_comment_notifications_in(
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let query_str = {
|
||||
let mut qs = url::form_urlencoded::Serializer::new(String::new());
|
||||
if !notification.doc_mode.is_empty() {
|
||||
qs.append_pair("mode", ¬ification.doc_mode);
|
||||
}
|
||||
qs.append_pair("commentId", &comment.id);
|
||||
if let Some(rid) = reply_id
|
||||
&& !rid.is_empty()
|
||||
{
|
||||
qs.append_pair("replyId", rid);
|
||||
}
|
||||
qs.finish()
|
||||
};
|
||||
let doc_url = format!(
|
||||
"{base}/workspace/{}/{}?commentId={}",
|
||||
comment.workspace_id, comment.doc_id, comment.id
|
||||
"{base}/workspace/{}/{}?{query_str}",
|
||||
comment.workspace_id, comment.doc_id
|
||||
);
|
||||
|
||||
let mut notified = Vec::new();
|
||||
@@ -1341,11 +1363,7 @@ async fn create_comment_notifications_in(
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("insert comment notification: {e}")))?;
|
||||
|
||||
let (mail_class, pref_field) = if is_mention {
|
||||
("comment_mention", "receiveMentionEmail")
|
||||
} else {
|
||||
("comment", "receiveCommentEmail")
|
||||
};
|
||||
let (mail_class, pref_field) = ("collaboration_notice", "receiveCommentEmail");
|
||||
crate::notifications::enqueue_notification_mail_in_tx(
|
||||
tx,
|
||||
crate::notifications::EnqueueNotificationMail {
|
||||
|
||||
@@ -820,12 +820,14 @@ impl DocSharingService {
|
||||
return Err(DomainError::Conflict("doc_role_targets_changed".to_owned()));
|
||||
}
|
||||
|
||||
for target_user_id in &target_user_ids {
|
||||
let base_now = Utc::now();
|
||||
for (idx, target_user_id) in target_user_ids.iter().enumerate() {
|
||||
let row_ts = base_now + chrono::Duration::milliseconds(idx as i64);
|
||||
let affected = sqlx::query(
|
||||
r#"INSERT INTO doc_grants (workspace_id, doc_id, principal_type, principal_id, role, granted_by)
|
||||
VALUES ($1, $2, 'user', $3, $4, $5)
|
||||
r#"INSERT INTO doc_grants (workspace_id, doc_id, principal_type, principal_id, role, granted_by, created_at, updated_at)
|
||||
VALUES ($1, $2, 'user', $3, $4, $5, $6, $6)
|
||||
ON CONFLICT (workspace_id, doc_id, principal_type, principal_id)
|
||||
DO UPDATE SET role = EXCLUDED.role, granted_by = EXCLUDED.granted_by, updated_at = now()
|
||||
DO UPDATE SET role = EXCLUDED.role, granted_by = EXCLUDED.granted_by, updated_at = EXCLUDED.updated_at
|
||||
WHERE doc_grants.role <> 'owner'"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
@@ -833,6 +835,7 @@ impl DocSharingService {
|
||||
.bind(target_user_id)
|
||||
.bind(new_role.as_str())
|
||||
.bind(actor_user_id)
|
||||
.bind(row_ts)
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("grant doc role: {e}")))?
|
||||
|
||||
@@ -364,7 +364,23 @@ impl NotificationService {
|
||||
.map_err(|e| DomainError::Internal(format!("insert mention notification: {e}")))?;
|
||||
|
||||
let base = self.base_url.trim_end_matches('/');
|
||||
let doc_url = format!("{base}/workspace/{workspace_id}/{}", doc.id);
|
||||
let query_str = {
|
||||
let mut qs = url::form_urlencoded::Serializer::new(String::new());
|
||||
if !doc.mode.is_empty() {
|
||||
qs.append_pair("mode", &doc.mode);
|
||||
}
|
||||
if let Some(ref block_id) = doc.block_id
|
||||
&& !block_id.is_empty()
|
||||
{
|
||||
qs.append_pair("blockIds", block_id);
|
||||
}
|
||||
qs.finish()
|
||||
};
|
||||
let doc_url = if query_str.is_empty() {
|
||||
format!("{base}/workspace/{workspace_id}/{}", doc.id)
|
||||
} else {
|
||||
format!("{base}/workspace/{workspace_id}/{}?{query_str}", doc.id)
|
||||
};
|
||||
let actor_email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
|
||||
.bind(actor_user_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
@@ -376,7 +392,7 @@ impl NotificationService {
|
||||
EnqueueNotificationMail {
|
||||
private_key: &private_key,
|
||||
mail_name: "Mention",
|
||||
mail_class: "doc_mention",
|
||||
mail_class: "collaboration_notice",
|
||||
recipient_user_id: target_user_id,
|
||||
actor_user_id: Some(actor_user_id),
|
||||
workspace_id: Some(workspace_id),
|
||||
@@ -495,7 +511,7 @@ async fn load_workspace_display_name_in_tx(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok("Untitled".to_owned())
|
||||
Ok("Untitled Workspace".to_owned())
|
||||
}
|
||||
|
||||
pub fn compute_recipient_hash(private_key: &str, email: &str) -> String {
|
||||
|
||||
@@ -1370,16 +1370,38 @@ impl SelfhostLicenseService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("touch denied license validated_at: {e}")))?;
|
||||
|
||||
let had_active_or_grace: bool = sqlx::query_scalar(
|
||||
r#"SELECT EXISTS(
|
||||
SELECT 1 FROM entitlements
|
||||
WHERE source = 'selfhost_license'
|
||||
AND target_type = 'workspace'
|
||||
AND target_id = $1
|
||||
AND subject_id = $2
|
||||
AND status IN ('active', 'grace')
|
||||
)"#,
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
.fetch_one(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("check pre-denial license status: {e}")))?;
|
||||
|
||||
let before_grant = self
|
||||
.quota_gate
|
||||
.resolve_workspace_grant(tx.tx_mut(), &row.workspace_id, now)
|
||||
.await?;
|
||||
|
||||
let updated = sqlx::query(
|
||||
r#"UPDATE entitlements
|
||||
SET status = $3,
|
||||
metadata = COALESCE(metadata, '{}'::jsonb) || jsonb_build_object('errorCode', $4::text, 'errorMessage', $4::text),
|
||||
validated_at = $5,
|
||||
updated_at = $5
|
||||
WHERE source = 'selfhost_license'
|
||||
AND target_type = 'workspace'
|
||||
AND target_id = $1
|
||||
AND subject_id = $2
|
||||
AND status IN ('active', 'grace')"#,
|
||||
AND status <> 'revoked'"#,
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
@@ -1391,14 +1413,24 @@ impl SelfhostLicenseService {
|
||||
.map_err(|e| DomainError::Internal(format!("update denied license entitlement: {e}")))?
|
||||
.rows_affected();
|
||||
|
||||
if updated > 0 {
|
||||
let after_grant = self
|
||||
.quota_gate
|
||||
.resolve_workspace_grant(tx.tx_mut(), &row.workspace_id, now)
|
||||
.await?;
|
||||
|
||||
let downgraded = updated > 0
|
||||
&& ((had_active_or_grace && !matches!(status, "active" | "grace"))
|
||||
|| before_grant.tier != after_grant.tier
|
||||
|| before_grant.limits.seat_limit > after_grant.limits.seat_limit);
|
||||
|
||||
if downgraded {
|
||||
downgrade_workspace_after_license_loss_in_tx(tx.tx_mut(), &row.workspace_id, now).await?;
|
||||
}
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("commit license denial: {e}")))?;
|
||||
if updated > 0 {
|
||||
if downgraded {
|
||||
self.publish_license_invalidation(&row.workspace_id).await;
|
||||
Ok(true)
|
||||
} else {
|
||||
|
||||
@@ -912,9 +912,7 @@ impl WorkspaceService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("check existing workspace member: {e}")))?;
|
||||
if already_member {
|
||||
slots[idx] = Some(Err(DomainError::Conflict(
|
||||
"user is already a workspace member".to_owned(),
|
||||
)));
|
||||
slots[idx] = Some(Err(DomainError::Conflict(format!("already_in_space:{workspace_id}"))));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -968,7 +966,8 @@ impl WorkspaceService {
|
||||
candidates.len() as i32,
|
||||
now,
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| map_seat_limit_err(workspace_id, err))?;
|
||||
|
||||
let mut notified_invitees: Vec<String> = Vec::new();
|
||||
for (idx, email, mut invitee_user_id) in candidates {
|
||||
@@ -1158,7 +1157,7 @@ impl WorkspaceService {
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("lock invitation: {e}")))?
|
||||
.ok_or_else(|| DomainError::NotFound("invitation not found".to_owned()))?;
|
||||
.ok_or_else(|| DomainError::NotFound("invalid_invitation".to_owned()))?;
|
||||
|
||||
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
|
||||
.fetch_one(&mut **tx.tx_mut())
|
||||
@@ -1200,7 +1199,7 @@ impl WorkspaceService {
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case(&user_email))
|
||||
};
|
||||
if !matches_user {
|
||||
return Err(DomainError::Forbidden("invitation does not belong to user".to_owned()));
|
||||
return Err(DomainError::Forbidden("invitation_account_mismatch".to_owned()));
|
||||
}
|
||||
|
||||
let already_member: bool = sqlx::query_scalar(
|
||||
@@ -1212,14 +1211,15 @@ impl WorkspaceService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("check existing member on accept: {e}")))?;
|
||||
if already_member {
|
||||
return Err(DomainError::Conflict("user is already a workspace member".to_owned()));
|
||||
return Err(DomainError::Conflict(format!("already_in_space:{inv_workspace_id}")));
|
||||
}
|
||||
|
||||
let current_charged_excluding_this = (count_charged_seats_in_tx(tx.tx_mut(), &inv_workspace_id).await? - 1).max(0);
|
||||
self
|
||||
.quota_gate
|
||||
.check_seat_admission(tx.tx_mut(), &inv_workspace_id, current_charged_excluding_this, 1, now)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| map_seat_limit_err(&inv_workspace_id, err))?;
|
||||
|
||||
let source: String = inv_row.get("kind");
|
||||
let inserted = sqlx::query(
|
||||
@@ -1354,9 +1354,7 @@ impl WorkspaceService {
|
||||
}
|
||||
let effective_actor_role = actor_role.effective(grant.rights.commercial);
|
||||
if !matches!(effective_actor_role, WorkspaceRole::Owner | WorkspaceRole::Admin) {
|
||||
return Err(DomainError::Forbidden(
|
||||
"insufficient permissions to change member role".to_owned(),
|
||||
));
|
||||
return Err(DomainError::Forbidden(format!("space_access_denied:{workspace_id}")));
|
||||
}
|
||||
if new_role == WorkspaceRole::Owner {
|
||||
return Err(DomainError::Forbidden("workspace_owner_must_transfer".to_owned()));
|
||||
@@ -1451,7 +1449,7 @@ impl WorkspaceService {
|
||||
FROM workspace_invitations
|
||||
WHERE workspace_id = $1
|
||||
AND (invitee_user_id = $2 OR id = $2)
|
||||
AND status::text IN ('pending', 'waiting_review')
|
||||
AND status::text IN ('pending', 'waiting_review', 'waiting_seat')
|
||||
FOR UPDATE"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
@@ -1514,10 +1512,6 @@ impl WorkspaceService {
|
||||
workspace_id: &str,
|
||||
target_user_id: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
if actor_user_id == target_user_id {
|
||||
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
|
||||
@@ -1538,9 +1532,10 @@ impl WorkspaceService {
|
||||
.await?;
|
||||
let effective_actor_role = actor_role.effective(grant.rights.commercial);
|
||||
if !matches!(effective_actor_role, WorkspaceRole::Owner | WorkspaceRole::Admin) {
|
||||
return Err(DomainError::Forbidden(
|
||||
"insufficient permissions to revoke member".to_owned(),
|
||||
));
|
||||
return Err(DomainError::Forbidden(format!("space_access_denied:{workspace_id}")));
|
||||
}
|
||||
if actor_user_id == target_user_id {
|
||||
return Err(DomainError::Forbidden("cannot_revoke_self".to_owned()));
|
||||
}
|
||||
|
||||
let target_member_role: Option<String> = sqlx::query_scalar(
|
||||
@@ -1562,6 +1557,32 @@ impl WorkspaceService {
|
||||
}
|
||||
}
|
||||
|
||||
let target_email: Option<String> = sqlx::query_scalar("SELECT lower(email) FROM users WHERE id = $1")
|
||||
.bind(target_user_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("load target email for revoke: {e}")))?;
|
||||
|
||||
let matching_invite_roles: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT requested_role::text
|
||||
FROM workspace_invitations
|
||||
WHERE workspace_id = $1
|
||||
AND (
|
||||
invitee_user_id = $2
|
||||
OR (invitee_user_id IS NULL AND $3::text IS NOT NULL AND lower(normalized_email) = lower($3))
|
||||
)
|
||||
FOR UPDATE",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(target_user_id)
|
||||
.bind(target_email.as_deref())
|
||||
.fetch_all(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("lock matching workspace invitations: {e}")))?;
|
||||
if effective_actor_role == WorkspaceRole::Admin && matching_invite_roles.iter().any(|r| r == "admin") {
|
||||
return Err(DomainError::Forbidden("admin cannot revoke another admin".to_owned()));
|
||||
}
|
||||
|
||||
let deleted_members =
|
||||
sqlx::query("DELETE FROM workspace_members WHERE workspace_id = $1 AND user_id = $2 AND state = 'active'")
|
||||
.bind(workspace_id)
|
||||
@@ -1571,12 +1592,6 @@ impl WorkspaceService {
|
||||
.map_err(|e| DomainError::Internal(format!("delete workspace member: {e}")))?
|
||||
.rows_affected();
|
||||
|
||||
let target_email: Option<String> = sqlx::query_scalar("SELECT lower(email) FROM users WHERE id = $1")
|
||||
.bind(target_user_id)
|
||||
.fetch_optional(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("load target email for revoke: {e}")))?;
|
||||
|
||||
let deleted_invites_rows = sqlx::query(
|
||||
"DELETE FROM workspace_invitations
|
||||
WHERE workspace_id = $1
|
||||
@@ -1961,10 +1976,14 @@ impl WorkspaceService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("acquire list_workspace_members: {e}")))?;
|
||||
|
||||
let pattern = query
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| format!("%{}%", s.to_ascii_lowercase()));
|
||||
let pattern = query.map(str::trim).filter(|s| !s.is_empty()).map(|s| {
|
||||
let escaped = s
|
||||
.to_lowercase()
|
||||
.replace('\\', "\\\\")
|
||||
.replace('%', "\\%")
|
||||
.replace('_', "\\_");
|
||||
format!("%{escaped}%")
|
||||
});
|
||||
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT * FROM (
|
||||
@@ -1986,7 +2005,7 @@ impl WorkspaceService {
|
||||
(u.email_verified IS NOT NULL) AS email_verified,
|
||||
COALESCE(u.disabled, false) AS disabled,
|
||||
i.requested_role::text AS role,
|
||||
i.id AS invite_id,
|
||||
COALESCE(u.id, i.id) AS invite_id,
|
||||
CASE i.status::text
|
||||
WHEN 'pending' THEN 'Pending'
|
||||
WHEN 'waiting_review' THEN 'UnderReview'
|
||||
@@ -1999,7 +2018,7 @@ impl WorkspaceService {
|
||||
WHERE i.workspace_id = $1
|
||||
AND i.status::text = ANY($5)
|
||||
) combined
|
||||
WHERE ($2::text IS NULL OR lower(combined.name) LIKE $2 OR lower(combined.email) LIKE $2)
|
||||
WHERE ($2::text IS NULL OR lower(combined.name) LIKE $2 ESCAPE '\' OR lower(combined.email) LIKE $2 ESCAPE '\')
|
||||
ORDER BY combined.sort_at ASC, combined.user_id ASC
|
||||
OFFSET $3 LIMIT $4"#,
|
||||
)
|
||||
@@ -2444,7 +2463,8 @@ impl WorkspaceService {
|
||||
self
|
||||
.quota_gate
|
||||
.check_seat_admission(tx.tx_mut(), workspace_id, current_charged_excluding_this, 1, now)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| map_seat_limit_err(workspace_id, err))?;
|
||||
|
||||
sqlx::query(
|
||||
r#"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source, created_at, updated_at)
|
||||
@@ -2572,12 +2592,13 @@ impl WorkspaceService {
|
||||
let ttl_ms = expire_ms.max(1_000);
|
||||
|
||||
if let Some(client) = &self.redis {
|
||||
let prefix = self.redis_key_prefix();
|
||||
let mut conn = client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis invite link connect: {e}")))?;
|
||||
let ws_key = format!("workspace:inviteLink:{workspace_id}");
|
||||
let id_key = format!("workspace:inviteLinkId:{candidate_id}");
|
||||
let ws_key = format!("{prefix}workspace:inviteLink:{workspace_id}");
|
||||
let id_key = format!("{prefix}workspace:inviteLinkId:{candidate_id}");
|
||||
let ws_val = serde_json::json!({ "inviteId": candidate_id }).to_string();
|
||||
let id_val = serde_json::json!({
|
||||
"workspaceId": workspace_id,
|
||||
@@ -2657,11 +2678,12 @@ impl WorkspaceService {
|
||||
}
|
||||
|
||||
if let Some(client) = &self.redis {
|
||||
let prefix = self.redis_key_prefix();
|
||||
let mut conn = client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis get invite link connect: {e}")))?;
|
||||
let ws_key = format!("workspace:inviteLink:{workspace_id}");
|
||||
let ws_key = format!("{prefix}workspace:inviteLink:{workspace_id}");
|
||||
let raw: Option<String> = redis::cmd("GET")
|
||||
.arg(&ws_key)
|
||||
.query_async(&mut conn)
|
||||
@@ -2720,14 +2742,16 @@ impl WorkspaceService {
|
||||
}
|
||||
|
||||
if let Some(client) = &self.redis {
|
||||
let prefix = self.redis_key_prefix();
|
||||
let mut conn = client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis revoke invite link connect: {e}")))?;
|
||||
let ws_key = format!("workspace:inviteLink:{workspace_id}");
|
||||
let ws_key = format!("{prefix}workspace:inviteLink:{workspace_id}");
|
||||
let id_prefix = format!("{prefix}workspace:inviteLinkId:");
|
||||
let deleted: i64 = redis::Script::new(REVOKE_INVITE_LINK_LUA)
|
||||
.key(&ws_key)
|
||||
.arg("workspace:inviteLinkId:")
|
||||
.arg(&id_prefix)
|
||||
.invoke_async(&mut conn)
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis atomic revoke invite link: {e}")))?;
|
||||
@@ -2801,7 +2825,7 @@ impl WorkspaceService {
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("check existing member on link accept: {e}")))?;
|
||||
if already_member {
|
||||
return Err(DomainError::Conflict("already_in_space".to_owned()));
|
||||
return Err(DomainError::Conflict(format!("already_in_space:{ws_id}")));
|
||||
}
|
||||
|
||||
let user_email: String = sqlx::query_scalar("SELECT lower(email) FROM users WHERE id = $1")
|
||||
@@ -2812,7 +2836,7 @@ impl WorkspaceService {
|
||||
.ok_or_else(|| DomainError::NotFound("user not found".to_owned()))?;
|
||||
|
||||
let existing_inv = sqlx::query(
|
||||
r#"SELECT id, requested_role::text AS requested_role, kind::text AS kind, status::text AS status
|
||||
r#"SELECT id, inviter_user_id, requested_role::text AS requested_role, kind::text AS kind, status::text AS status
|
||||
FROM workspace_invitations
|
||||
WHERE workspace_id = $1
|
||||
AND (invitee_user_id = $2 OR (invitee_user_id IS NULL AND lower(normalized_email) = lower($3)))
|
||||
@@ -2829,13 +2853,15 @@ impl WorkspaceService {
|
||||
let status: String = inv.get("status");
|
||||
if status == "pending" {
|
||||
let inv_id: String = inv.get("id");
|
||||
let inviter_user_id: Option<String> = inv.get("inviter_user_id");
|
||||
let role = WorkspaceRole::parse(&inv.get::<String, _>("requested_role"))?;
|
||||
let source: String = inv.get("kind");
|
||||
let current_charged_excl = (count_charged_seats_in_tx(tx.tx_mut(), &ws_id).await? - 1).max(0);
|
||||
self
|
||||
.quota_gate
|
||||
.check_seat_admission(tx.tx_mut(), &ws_id, current_charged_excl, 1, now)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| map_seat_limit_err(&ws_id, err))?;
|
||||
sqlx::query(
|
||||
r#"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, 'active', $5, $6, $6)
|
||||
@@ -2855,9 +2881,36 @@ impl WorkspaceService {
|
||||
.execute(&mut **tx.tx_mut())
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("consume pending invite via link: {e}")))?;
|
||||
if let Some(ref inviter_id) = inviter_user_id
|
||||
&& inviter_id != invitee_user_id
|
||||
{
|
||||
crate::notifications::insert_invitation_notification_with_key_in_tx(
|
||||
tx.tx_mut(),
|
||||
inviter_id,
|
||||
invitee_user_id,
|
||||
&ws_id,
|
||||
&inv_id,
|
||||
"InvitationAccepted",
|
||||
&self.base_url,
|
||||
&private_key,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("commit pending invite via link: {e}")))?;
|
||||
if let Some(ref inviter_id) = inviter_user_id
|
||||
&& inviter_id != invitee_user_id
|
||||
{
|
||||
crate::notifications::publish_notification_count_changed(
|
||||
&self.db,
|
||||
self.event_bus.as_ref(),
|
||||
inviter_id,
|
||||
"created",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.publish_workspace_members_changed(&ws_id, "member-accepted").await;
|
||||
let _ = self
|
||||
.invalidation
|
||||
.publish_invalidation(&InvalidationHintV1::QuotaSeatUsage {
|
||||
@@ -2877,7 +2930,7 @@ impl WorkspaceService {
|
||||
});
|
||||
}
|
||||
if status == "waiting_review" || status == "waiting_seat" {
|
||||
return Err(DomainError::Conflict("already_in_space".to_owned()));
|
||||
return Err(DomainError::Conflict(format!("already_in_space:{ws_id}")));
|
||||
}
|
||||
// Clear stale non-chargeable invitation row before inserting waiting_review.
|
||||
let stale_id: String = inv.get("id");
|
||||
@@ -2892,7 +2945,8 @@ impl WorkspaceService {
|
||||
self
|
||||
.quota_gate
|
||||
.check_seat_admission(tx.tx_mut(), &ws_id, current_charged, 1, now)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| map_seat_limit_err(&ws_id, err))?;
|
||||
|
||||
let review_id = format!("inv_{}", Uuid::new_v4().simple());
|
||||
let inviter_opt = (!inviter_id.is_empty()).then_some(inviter_id.as_str());
|
||||
@@ -2966,14 +3020,23 @@ impl WorkspaceService {
|
||||
})
|
||||
}
|
||||
|
||||
fn redis_key_prefix(&self) -> String {
|
||||
self
|
||||
.app_config
|
||||
.as_ref()
|
||||
.map(|cfg| cfg.internal_redis_key_prefix())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn lookup_invite_link_by_id(&self, invite_id: &str) -> Result<Option<(String, String)>, DomainError> {
|
||||
if let Some(client) = &self.redis {
|
||||
let prefix = self.redis_key_prefix();
|
||||
let mut conn = client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis lookup invite link: {e}")))?;
|
||||
let raw: Option<String> = redis::cmd("GET")
|
||||
.arg(format!("workspace:inviteLinkId:{invite_id}"))
|
||||
.arg(format!("{prefix}workspace:inviteLinkId:{invite_id}"))
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(|e| DomainError::Unavailable(format!("redis get invite link id: {e}")))?;
|
||||
@@ -3443,6 +3506,15 @@ async fn lock_workspace_row(tx: &mut Transaction<'_, Postgres>, workspace_id: &s
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_seat_limit_err(workspace_id: &str, err: DomainError) -> DomainError {
|
||||
match err {
|
||||
DomainError::QuotaExceeded { kind: "seat_limit", .. } => {
|
||||
DomainError::Forbidden(format!("no_more_seat:{workspace_id}"))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
async fn require_active_member_role(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
@@ -3457,9 +3529,7 @@ async fn require_active_member_role(
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(format!("load active member role: {e}")))?;
|
||||
let Some(role) = role else {
|
||||
return Err(DomainError::Forbidden(
|
||||
"user is not an active workspace member".to_owned(),
|
||||
));
|
||||
return Err(DomainError::Forbidden(format!("space_access_denied:{workspace_id}")));
|
||||
};
|
||||
WorkspaceRole::parse(&role)
|
||||
}
|
||||
|
||||
@@ -576,7 +576,7 @@ fn auth_rollback_workspace_parity_quota_gate_and_redis_invalidation() {
|
||||
.invite_member(&admin.user.id, &ws.id, "member2@affine.test", WorkspaceRole::Member)
|
||||
.await
|
||||
.expect_err("3rd seat must be rejected by TwoSeatQuotaGate");
|
||||
assert!(matches!(over, DomainError::QuotaExceeded { kind: "seat_limit", .. }));
|
||||
assert!(matches!(&over, DomainError::Forbidden(msg) if msg == &format!("no_more_seat:{}", ws.id)));
|
||||
|
||||
let accepted = ws_service.accept_invitation(&member1.user.id, &inv1.id).await.unwrap();
|
||||
assert_eq!(accepted.role, WorkspaceRole::Member);
|
||||
|
||||
@@ -1663,3 +1663,224 @@ fn offline_repair_conflict_skip_and_strict_remote_denial_whitelist() {
|
||||
});
|
||||
drop(lease);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_expired_license_denial_does_not_wipe_new_pending_invites_or_admins() {
|
||||
let cluster = test_db_harness::pg::PgCluster::from_env_or_docker().expect("test postgres cluster");
|
||||
let migrations_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
|
||||
let migrations = test_db_harness::migrations::MigrationSet::load(&migrations_dir).expect("load migrations");
|
||||
let template = cluster.ensure_template(&migrations).expect("ensure template");
|
||||
let lease = cluster
|
||||
.lease(&template, test_db_harness::pg::DEFAULT_LEASE_TTL)
|
||||
.expect("lease test db");
|
||||
let db_url = lease.url().to_owned();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
rt.block_on(async move {
|
||||
let db = ServerDb::connect(DbConfig {
|
||||
database_url: db_url,
|
||||
channel: "canary".into(),
|
||||
role: server_types::ServerRole::Allinone,
|
||||
selfhosted: true,
|
||||
max_connections: 4,
|
||||
statement_timeout_ms: 5_000,
|
||||
tier_permits: [8, 4, 2, 2],
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let (signing_key, pro_pem) = test_keypair(77);
|
||||
let keyring = Keyring::with_pro_public_key(pro_pem);
|
||||
let gate = Arc::new(CommunityQuotaGate::with_keyring(keyring.clone()));
|
||||
let inv = Arc::new(NoopEventPublisher::default());
|
||||
|
||||
let owner_id = format!("u-owner-{}", Uuid::new_v4().simple());
|
||||
let admin_id = format!("u-admin-{}", Uuid::new_v4().simple());
|
||||
let ws_id = format!("ws-exp-repeat-{}", Uuid::new_v4().simple());
|
||||
for (uid, email) in [(&owner_id, "owner-rep@example.test"), (&admin_id, "admin-rep@example.test")] {
|
||||
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, $2, $3)")
|
||||
.bind(uid)
|
||||
.bind("User")
|
||||
.bind(email)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
|
||||
.bind(&ws_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source) VALUES ($1, $2, $3, 'owner', 'active', 'legacy')",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(&ws_id)
|
||||
.bind(&owner_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_members (id, workspace_id, user_id, role, state, source) VALUES ($1, $2, $3, 'admin', 'active', 'legacy')",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(&ws_id)
|
||||
.bind(&admin_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let vk = Uuid::new_v4().to_string();
|
||||
let stale_at = Utc::now() - Duration::hours(2);
|
||||
let claims = LicenseClaimsV2 {
|
||||
format_version: 2,
|
||||
kid: PRO_KID.to_owned(),
|
||||
license_id: "lic-exp-repeat".to_owned(),
|
||||
audience: LICENSE_AUDIENCE_SELFHOST.to_owned(),
|
||||
scope: LicenseScopeV2 {
|
||||
kind: "workspace".to_owned(),
|
||||
workspace_id: Some(ws_id.clone()),
|
||||
},
|
||||
tier: "selfhost_team".to_owned(),
|
||||
limits: LicenseLimitsV2 {
|
||||
blob_limit_bytes: 524_288_000,
|
||||
storage_quota_bytes: 1_099_511_627_776,
|
||||
seat_limit: 30,
|
||||
seat_quota_bytes: None,
|
||||
history_period_seconds: 31_536_000,
|
||||
copilot_action_limit: None,
|
||||
},
|
||||
rights: LicenseRightsV2 {
|
||||
commercial: true,
|
||||
copilot_byok: true,
|
||||
unlimited_copilot: false,
|
||||
},
|
||||
recurring: Some("monthly".to_owned()),
|
||||
issued_at: (Utc::now() - Duration::days(30)).to_rfc3339(),
|
||||
not_before: (Utc::now() - Duration::days(30)).to_rfc3339(),
|
||||
expires_at: Some((Utc::now() + Duration::days(10)).to_rfc3339()),
|
||||
};
|
||||
let sig: DerSignature = signing_key.sign(&serde_json::to_vec(&claims).unwrap());
|
||||
let env_bytes = serde_json::to_vec(&LicenseEnvelopeV2 {
|
||||
claims,
|
||||
signature: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, sig.as_bytes()),
|
||||
})
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO installed_licenses (key, workspace_id, quantity, recurring, variant, installed_at, validate_key, validated_at, expired_at, license)
|
||||
VALUES ('lic-exp-repeat', $1, 30, 'monthly', 'recurring', $2, $3, $2, $4, $5)",
|
||||
)
|
||||
.bind(&ws_id)
|
||||
.bind(stale_at)
|
||||
.bind(&vk)
|
||||
.bind(Utc::now() + Duration::days(10))
|
||||
.bind(&env_bytes)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO entitlements (id, target_type, target_id, source, subject_id, plan, status, quantity, signed_payload, expires_at, validated_at, updated_at)
|
||||
VALUES ($1, 'workspace', $2, 'selfhost_license', 'lic-exp-repeat', 'selfhost_team', 'active', 30, $3, $4, $5, $5)",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(&ws_id)
|
||||
.bind(&env_bytes)
|
||||
.bind(Utc::now() + Duration::days(10))
|
||||
.bind(stale_at)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
struct ExpiredHealthClient;
|
||||
#[async_trait::async_trait]
|
||||
impl SelfhostLicenseClient for ExpiredHealthClient {
|
||||
async fn activate(&self, _key: &str, _ws: &str, _op: &str) -> Result<RemoteLicensePayload, DomainError> {
|
||||
Err(DomainError::Unavailable("unused".into()))
|
||||
}
|
||||
async fn health(&self, _key: &str, _vk: &str, _ws: &str) -> Result<RemoteHealthOutcome, DomainError> {
|
||||
Ok(RemoteHealthOutcome::Denied {
|
||||
status: "expired",
|
||||
reason: "license_expired".to_owned(),
|
||||
error: DomainError::Forbidden("license_expired".to_owned()),
|
||||
})
|
||||
}
|
||||
async fn update_seats(&self, _key: &str, _vk: &str, _qty: u32) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn create_customer_portal(&self, _key: &str, _vk: &str) -> Result<String, DomainError> {
|
||||
Ok(String::new())
|
||||
}
|
||||
async fn deactivate(&self, _key: &str, _vk: &str) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let svc = SelfhostLicenseService::new(db.clone(), gate.clone(), inv.clone())
|
||||
.with_keyring(keyring)
|
||||
.with_client(Arc::new(ExpiredHealthClient));
|
||||
|
||||
// First denial transitions active -> expired and downgrades the admin to member.
|
||||
svc.check_licenses().await.unwrap();
|
||||
let role_after_first: String = sqlx::query_scalar(
|
||||
"SELECT role::text FROM workspace_members WHERE workspace_id = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(&ws_id)
|
||||
.bind(&admin_id)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(role_after_first, "member");
|
||||
|
||||
// On the fallback community grant, the owner promotes an admin and creates a new pending invitation.
|
||||
sqlx::query("UPDATE workspace_members SET role = 'admin' WHERE workspace_id = $1 AND user_id = $2")
|
||||
.bind(&ws_id)
|
||||
.bind(&admin_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let inv_id = Uuid::new_v4().to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_invitations (id, workspace_id, normalized_email, requested_role, status, kind, created_at, updated_at)
|
||||
VALUES ($1, $2, 'pending-after-exp@example.test', 'member', 'pending', 'email', now(), now())",
|
||||
)
|
||||
.bind(&inv_id)
|
||||
.bind(&ws_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Make the license due for the next hourly health scan.
|
||||
sqlx::query("UPDATE installed_licenses SET validated_at = $1 WHERE workspace_id = $2")
|
||||
.bind(stale_at)
|
||||
.bind(&ws_id)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Second denial on already-expired entitlement must NOT wipe pending invite or demote admin.
|
||||
svc.check_licenses().await.unwrap();
|
||||
let role_after_second: String = sqlx::query_scalar(
|
||||
"SELECT role::text FROM workspace_members WHERE workspace_id = $1 AND user_id = $2",
|
||||
)
|
||||
.bind(&ws_id)
|
||||
.bind(&admin_id)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(role_after_second, "admin");
|
||||
let inv_still_exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM workspace_invitations WHERE id = $1 AND status = 'pending')",
|
||||
)
|
||||
.bind(&inv_id)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
inv_still_exists,
|
||||
"pending invitation must survive repeated expired-license health scans"
|
||||
);
|
||||
});
|
||||
drop(lease);
|
||||
}
|
||||
@@ -968,22 +968,46 @@ pub(crate) async fn mutate_update_app_config(
|
||||
.await
|
||||
.map_err(|e| domain_error_to_graphql(&e))?;
|
||||
}
|
||||
let touched_modules: std::collections::BTreeSet<String> = domain_updates
|
||||
.iter()
|
||||
.filter_map(|u| u.key.split('.').next())
|
||||
.map(str::trim)
|
||||
.filter(|m| !m.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let mut filtered = serde_json::Map::new();
|
||||
if let Some(obj) = effective.as_object() {
|
||||
for module in touched_modules {
|
||||
if let Some(val) = obj.get(&module) {
|
||||
filtered.insert(module, val.clone());
|
||||
let mut filtered = serde_json::Value::Object(serde_json::Map::new());
|
||||
for update in &domain_updates {
|
||||
if server_domain::app_config::is_secret_config_key(&update.key) {
|
||||
continue;
|
||||
}
|
||||
let segments: Vec<&str> = update.key.split('.').map(str::trim).filter(|s| !s.is_empty()).collect();
|
||||
if segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut cur = &effective;
|
||||
let mut found = true;
|
||||
for seg in &segments {
|
||||
if let Some(next) = cur.get(*seg) {
|
||||
cur = next;
|
||||
} else {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found {
|
||||
let mut dst = &mut filtered;
|
||||
for (i, seg) in segments.iter().enumerate() {
|
||||
if i + 1 == segments.len() {
|
||||
if let Some(map) = dst.as_object_mut() {
|
||||
map.insert((*seg).to_owned(), cur.clone());
|
||||
}
|
||||
} else {
|
||||
if !dst.is_object() {
|
||||
*dst = serde_json::Value::Object(serde_json::Map::new());
|
||||
}
|
||||
dst = dst
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.entry((*seg).to_owned())
|
||||
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(JsonObjectScalar(serde_json::Value::Object(filtered)))
|
||||
Ok(JsonObjectScalar(filtered))
|
||||
}
|
||||
|
||||
pub(crate) async fn mutate_send_test_email(ctx: &Context<'_>, config: JsonObjectScalar) -> Result<bool> {
|
||||
|
||||
@@ -116,13 +116,22 @@ pub(crate) fn mcp_read_write_available(state: &AppState) -> bool {
|
||||
let cfg = state.config.load();
|
||||
cfg.dev_mode || cfg.channel == "canary"
|
||||
}
|
||||
/// Checks `@CopilotEnabled()` strictly through [`server_spi::CopilotRuntimeSpi`].
|
||||
pub(crate) fn assert_copilot_enabled(state: &AppState) -> std::result::Result<(), DomainError> {
|
||||
if state.extension.copilot_runtime().is_enabled() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(DomainError::Forbidden("Copilot is disabled.".to_owned()))
|
||||
/// Checks `@CopilotEnabled()` dynamically via `app_configs` and [`server_spi::CopilotRuntimeSpi`].
|
||||
pub(crate) async fn assert_copilot_enabled(state: &AppState) -> std::result::Result<(), DomainError> {
|
||||
let cfg = state.app_config.get_effective_app_config_arc().await?;
|
||||
let cfg_enabled = cfg
|
||||
.pointer("/copilot/enabled")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
if !cfg_enabled {
|
||||
return Err(DomainError::Forbidden("Copilot is disabled.".to_owned()));
|
||||
}
|
||||
state
|
||||
.extension
|
||||
.copilot_runtime()
|
||||
.assert_enabled(cfg_enabled)
|
||||
.await
|
||||
.map_err(|_| DomainError::Forbidden("Copilot is disabled.".to_owned()))
|
||||
}
|
||||
fn gql_err(e: DomainError) -> async_graphql::Error {
|
||||
domain_error_to_graphql(&e)
|
||||
@@ -130,7 +139,7 @@ fn gql_err(e: DomainError) -> async_graphql::Error {
|
||||
async fn auth_copilot_workspace(ctx: &Context<'_>, workspace_id: &str) -> Result<(String, Arc<AppState>)> {
|
||||
let user = require_authenticated_user(ctx).await?;
|
||||
let state = Arc::clone(ctx.data_unchecked::<Arc<AppState>>());
|
||||
assert_copilot_enabled(&state).map_err(gql_err)?;
|
||||
assert_copilot_enabled(&state).await.map_err(gql_err)?;
|
||||
let perms = state
|
||||
.workspaces
|
||||
.resolve_workspace_permissions(&user.id, workspace_id)
|
||||
@@ -163,7 +172,7 @@ impl McpQuery {
|
||||
async fn mcp_credential_read_write_available(&self, ctx: &Context<'_>) -> Result<bool> {
|
||||
let _user = require_authenticated_user(ctx).await?;
|
||||
let state = ctx.data_unchecked::<Arc<AppState>>();
|
||||
assert_copilot_enabled(state).map_err(gql_err)?;
|
||||
assert_copilot_enabled(state).await.map_err(gql_err)?;
|
||||
Ok(mcp_read_write_available(state))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1276,7 +1276,9 @@ mod tests {
|
||||
assert_eq!(items[2]["error"]["status"], 403);
|
||||
assert_eq!(items[2]["error"]["type"], "ACTION_FORBIDDEN");
|
||||
assert!(items[3]["inviteId"].is_null());
|
||||
assert_eq!(items[3]["error"]["type"], "RESOURCE_ALREADY_EXISTS");
|
||||
assert_eq!(items[3]["error"]["status"], 403);
|
||||
assert_eq!(items[3]["error"]["type"], "ACTION_FORBIDDEN");
|
||||
assert_eq!(items[3]["error"]["name"], "ALREADY_IN_SPACE");
|
||||
assert_eq!(rl_calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
db.pool().close().await;
|
||||
|
||||
@@ -914,7 +914,7 @@ fn camel_case_object(map: Option<&Map<String, JsonValue>>) -> Map<String, JsonVa
|
||||
.map(|v| {
|
||||
v.as_i64()
|
||||
.and_then(DateTime::from_timestamp_millis)
|
||||
.map(|dt| JsonValue::String(dt.to_rfc3339()))
|
||||
.map(|dt| JsonValue::String(dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)))
|
||||
.unwrap_or_else(|| v.clone())
|
||||
})
|
||||
.collect(),
|
||||
|
||||
@@ -347,14 +347,14 @@ async fn enforce_copilot_enabled(state: &AppState) -> std::result::Result<(), Do
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
if !cfg_enabled {
|
||||
return Err(DomainError::Forbidden("copilot_disabled".to_owned()));
|
||||
return Err(DomainError::Forbidden("Copilot is disabled.".to_owned()));
|
||||
}
|
||||
state
|
||||
.extension
|
||||
.copilot_runtime()
|
||||
.assert_enabled(cfg_enabled)
|
||||
.await
|
||||
.map_err(|_| DomainError::Forbidden("copilot_disabled".to_owned()))
|
||||
.map_err(|_| DomainError::Forbidden("Copilot is disabled.".to_owned()))
|
||||
}
|
||||
|
||||
/// Keeps the upload in its multipart temporary file. The transcript runtime
|
||||
|
||||
@@ -302,7 +302,7 @@ pub fn domain_error_to_envelope(err: &DomainError) -> LegacyErrorEnvelope {
|
||||
data: Some(serde_json::json!({ "name": prompt_name })),
|
||||
};
|
||||
}
|
||||
if msg == "invalid_invitation" || msg == "Invitation not found" {
|
||||
if msg == "invalid_invitation" || msg.eq_ignore_ascii_case("invitation not found") {
|
||||
return LegacyErrorEnvelope {
|
||||
status: StatusCode::BAD_REQUEST.as_u16(),
|
||||
code: "Bad Request".into(),
|
||||
|
||||
@@ -319,14 +319,7 @@ 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 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 redis_key_prefix = services.app_config.internal_redis_key_prefix();
|
||||
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))
|
||||
@@ -1106,50 +1099,11 @@ async fn handle_graphql_post(
|
||||
rest::extract_cookie(&rest::parse_cookies(&headers), rest::SESSION_COOKIE_NAME).is_some_and(|s| !s.is_empty());
|
||||
let has_preflight = has_apollo_csrf_header(&headers);
|
||||
if has_session_cookie && !has_preflight {
|
||||
let csrf_blocked = || {
|
||||
graphql_bad_request_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"BAD_REQUEST",
|
||||
"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF).",
|
||||
)
|
||||
};
|
||||
let sec_fetch_site = headers
|
||||
.get("sec-fetch-site")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let origin = headers
|
||||
.get(header::ORIGIN)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let referer_origin = headers
|
||||
.get(header::REFERER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(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();
|
||||
let allow_loopback = cfg_snap.dev_mode;
|
||||
let origin_ok = origin.is_some_and(|o| rest::worker_proxy::is_cors_origin_allowed(o, &allowed, allow_loopback));
|
||||
let referer_ok = referer_origin
|
||||
.as_deref()
|
||||
.is_some_and(|r| rest::worker_proxy::is_cors_origin_allowed(r, &allowed, allow_loopback));
|
||||
if let Some(sfs) = sec_fetch_site
|
||||
&& (sfs.eq_ignore_ascii_case("cross-site")
|
||||
|| (sfs.eq_ignore_ascii_case("same-site") && !(origin_ok || referer_ok)))
|
||||
{
|
||||
return csrf_blocked();
|
||||
}
|
||||
if origin.is_some() && !origin_ok {
|
||||
return csrf_blocked();
|
||||
}
|
||||
if referer_origin.is_some() && !referer_ok {
|
||||
return csrf_blocked();
|
||||
}
|
||||
if !(origin_ok || referer_ok) {
|
||||
return csrf_blocked();
|
||||
}
|
||||
return graphql_bad_request_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"BAD_REQUEST",
|
||||
"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF).",
|
||||
);
|
||||
}
|
||||
}
|
||||
let inner = match read_graphql_post(&headers, body).await {
|
||||
|
||||
@@ -4,12 +4,12 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::Router;
|
||||
use axum::extract::{ConnectInfo, Path, State};
|
||||
use axum::http::header::{self, HeaderName, HeaderValue};
|
||||
use axum::http::{Extensions, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde_json::{Map, Value, json};
|
||||
use server_domain::mcp::{McpAccessMode, clamp_throttle_tracker, is_reserved_doc_id};
|
||||
use server_search::{
|
||||
@@ -256,7 +256,7 @@ fn rpc_err_resp(status: StatusCode, code: i64, msg: impl Into<String>) -> Respon
|
||||
json_utf8_response(status, rpc_error(Value::Null, code, msg), true)
|
||||
}
|
||||
async fn handle_method_not_allowed(State(state): State<RouterState>) -> Response {
|
||||
if let Err(err) = assert_copilot_enabled(&state.app) {
|
||||
if let Err(err) = assert_copilot_enabled(&state.app).await {
|
||||
return domain_error_to_http_response(&err);
|
||||
}
|
||||
rpc_err_resp(StatusCode::METHOD_NOT_ALLOWED, -32000, "Method not allowed.")
|
||||
@@ -266,8 +266,12 @@ async fn handle_mcp_post(
|
||||
Path(workspace_id): Path<String>,
|
||||
extensions: Extensions,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
raw_body: axum::body::Bytes,
|
||||
) -> Response {
|
||||
let body: Value = match serde_json::from_slice(&raw_body) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return rpc_err_resp(StatusCode::BAD_REQUEST, -32700, "Parse error"),
|
||||
};
|
||||
let throttle_decision = if let Some((limit, ttl_ms)) = load_default_throttle_config(&state.app).await {
|
||||
let peer_addr = extensions.get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
|
||||
let tracker = clamp_throttle_tracker(&extract_throttle_tracker(&headers, peer_addr));
|
||||
@@ -281,7 +285,7 @@ async fn handle_mcp_post(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let resp = match assert_copilot_enabled(&state.app) {
|
||||
let resp = match assert_copilot_enabled(&state.app).await {
|
||||
Err(err) => domain_error_to_http_response(&err),
|
||||
Ok(()) => handle_mcp_post_inner(state, workspace_id, headers, body).await,
|
||||
};
|
||||
@@ -511,7 +515,10 @@ async fn handle_rpc_message(
|
||||
return Some(rpc_error(response_id, -32602, format!("Tool not found: {tool_name}")));
|
||||
}
|
||||
let result = execute_tool(state, workspace_id, user_id, can_create_doc, tool_name, &args).await;
|
||||
(!is_notification).then(|| rpc_success(response_id, result))
|
||||
(!is_notification).then(|| match result {
|
||||
Ok(val) => rpc_success(response_id, val),
|
||||
Err((code, msg)) => rpc_error(response_id, code, msg),
|
||||
})
|
||||
}
|
||||
_ => (!is_notification).then(|| rpc_error(response_id, -32601, "Method not found")),
|
||||
}
|
||||
@@ -657,36 +664,38 @@ async fn execute_tool(
|
||||
can_create_doc: bool,
|
||||
tool_name: &str,
|
||||
args: &Map<String, Value>,
|
||||
) -> Value {
|
||||
) -> Result<Value, (i64, String)> {
|
||||
let mcp_svc = &state.app.mcp;
|
||||
match tool_name {
|
||||
"read_document" => {
|
||||
let Some(doc_id) = args.get("docId").and_then(Value::as_str) else {
|
||||
return tool_error("Invalid arguments: docId: Required");
|
||||
return Ok(tool_error("Invalid arguments: docId: Required"));
|
||||
};
|
||||
if let Err(e) = require_doc_perm(state, workspace_id, user_id, doc_id, false).await {
|
||||
return e;
|
||||
return Ok(e);
|
||||
}
|
||||
match mcp_svc.read_document_markdown(workspace_id, doc_id).await {
|
||||
Ok(match mcp_svc.read_document_markdown(workspace_id, doc_id).await {
|
||||
Ok(Some(md)) => tool_text(md),
|
||||
Ok(None) => tool_error(format!("Doc with id {doc_id} not found.")),
|
||||
Err(_) => tool_error("Failed to read document."),
|
||||
}
|
||||
})
|
||||
}
|
||||
"doc_search" => {
|
||||
let Some(raw_query) = args.get("query").and_then(Value::as_str) else {
|
||||
return tool_error("Invalid arguments: query: Required");
|
||||
return Ok(tool_error("Invalid arguments: query: Required"));
|
||||
};
|
||||
let query_str = raw_query.trim();
|
||||
let query_u16 = query_str.encode_utf16().count();
|
||||
if query_u16 == 0 || query_u16 > 2000 {
|
||||
return tool_error("Invalid arguments: query must be 1..=2000 characters");
|
||||
return Ok(tool_error("Invalid arguments: query must be 1..=2000 characters"));
|
||||
}
|
||||
let mut explicit_empty_doc_ids = false;
|
||||
let mut doc_ids: Vec<String> = Vec::new();
|
||||
if let Some(raw_doc_ids) = args.get("doc_ids") {
|
||||
let Some(arr) = raw_doc_ids.as_array().filter(|a| a.len() <= 50) else {
|
||||
return tool_error("Invalid arguments: doc_ids must be an array of at most 50 strings");
|
||||
return Ok(tool_error(
|
||||
"Invalid arguments: doc_ids must be an array of at most 50 strings",
|
||||
));
|
||||
};
|
||||
explicit_empty_doc_ids = arr.is_empty();
|
||||
for item in arr {
|
||||
@@ -695,7 +704,9 @@ async fn execute_tool(
|
||||
.map(str::trim)
|
||||
.filter(|s| matches!(s.encode_utf16().count(), 1..=128))
|
||||
else {
|
||||
return tool_error("Invalid arguments: each doc_ids entry must be 1..=128 characters");
|
||||
return Ok(tool_error(
|
||||
"Invalid arguments: each doc_ids entry must be 1..=128 characters",
|
||||
));
|
||||
};
|
||||
doc_ids.push(s.to_owned());
|
||||
}
|
||||
@@ -704,13 +715,17 @@ async fn execute_tool(
|
||||
None => 10,
|
||||
Some(v) => match v.as_u64() {
|
||||
Some(n) if (1..=20).contains(&n) => n as u32,
|
||||
_ => return tool_error("Invalid arguments: limit must be an integer between 1 and 20"),
|
||||
_ => {
|
||||
return Ok(tool_error(
|
||||
"Invalid arguments: limit must be an integer between 1 and 20",
|
||||
));
|
||||
}
|
||||
},
|
||||
};
|
||||
if explicit_empty_doc_ids {
|
||||
return tool_text(
|
||||
return Ok(tool_text(
|
||||
json!({ "retrieval_mode": "lexical", "degraded_reason": "VECTOR_UNAVAILABLE", "hits": [] }).to_string(),
|
||||
);
|
||||
));
|
||||
}
|
||||
let candidate_limit = (limit * 3).max(20);
|
||||
let fields: Vec<String> = BLOCK_SEARCH_FIELDS.split_whitespace().map(str::to_owned).collect();
|
||||
@@ -763,7 +778,7 @@ async fn execute_tool(
|
||||
.map(|v| select_fallback_search_nodes(&v, candidate_limit as usize)),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
let lexical_hits: Result<Vec<Value>, ()> = async {
|
||||
let lexical_hits: Result<Vec<(String, String, Value)>, ()> = async {
|
||||
let raw_nodes = block_nodes.map_err(|_| ())?;
|
||||
let mut missing_ids = Vec::new();
|
||||
let mut missing_set = HashSet::new();
|
||||
@@ -775,75 +790,65 @@ async fn execute_tool(
|
||||
missing_ids.push(d.to_owned());
|
||||
}
|
||||
}
|
||||
let mut page_titles = mcp_svc
|
||||
let page_titles = mcp_svc
|
||||
.load_page_titles(workspace_id, &missing_ids)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let mut ranked = Vec::new();
|
||||
let mut seen_docs = HashSet::new();
|
||||
for node in raw_nodes {
|
||||
let mut out = Vec::new();
|
||||
let mut seen_keys = HashSet::new();
|
||||
for (idx, node) in raw_nodes.into_iter().enumerate() {
|
||||
if !has_projection_metadata(&node) {
|
||||
continue;
|
||||
}
|
||||
let Some(doc_id) = search_node_non_empty(&node, "doc_id").map(str::to_owned) else {
|
||||
continue;
|
||||
};
|
||||
if !seen_docs.insert(doc_id.clone()) {
|
||||
let unit_id = search_node_non_empty(&node, "unit_id")
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("lex-{idx}"));
|
||||
let dedupe_key = format!("{doc_id}:{unit_id}");
|
||||
if !seen_keys.insert(dedupe_key) {
|
||||
continue;
|
||||
}
|
||||
let title = inline_page_title(&node).map(str::to_owned);
|
||||
ranked.push((
|
||||
1.0 / (60.0 + (ranked.len() + 1) as f64),
|
||||
search_node_non_empty(&node, "unit_id").unwrap_or_default().to_owned(),
|
||||
doc_id,
|
||||
title,
|
||||
node
|
||||
.pointer("/highlights/content/0")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
search_node_non_empty(&node, "visibility").unwrap_or("page").to_owned(),
|
||||
search_node_non_empty(&node, "source_block_id")
|
||||
.or_else(|| search_node_non_empty(&node, "block_id"))
|
||||
.map(str::to_owned),
|
||||
search_node_non_empty(&node, "element_id").map(str::to_owned),
|
||||
search_node_non_empty(&node, "frame_id").map(str::to_owned),
|
||||
));
|
||||
let title = inline_page_title(&node)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| page_titles.get(&doc_id).cloned())
|
||||
.unwrap_or_default();
|
||||
let excerpt = node
|
||||
.pointer("/highlights/content/0")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let visibility = search_node_non_empty(&node, "visibility").unwrap_or("page").to_owned();
|
||||
let block_id = search_node_non_empty(&node, "source_block_id")
|
||||
.or_else(|| search_node_non_empty(&node, "block_id"))
|
||||
.map(str::to_owned);
|
||||
let element_id = search_node_non_empty(&node, "element_id").map(str::to_owned);
|
||||
let frame_id = search_node_non_empty(&node, "frame_id").map(str::to_owned);
|
||||
let mut obj = Map::from_iter([
|
||||
("doc_id".to_owned(), json!(doc_id)),
|
||||
("title".to_owned(), json!(title)),
|
||||
("excerpt".to_owned(), json!(excerpt)),
|
||||
("visibility".to_owned(), json!(visibility)),
|
||||
]);
|
||||
for (k, v) in [
|
||||
("block_id", block_id),
|
||||
("element_id", element_id),
|
||||
("frame_id", frame_id),
|
||||
] {
|
||||
if let Some(val) = v {
|
||||
obj.insert(k.to_owned(), json!(val));
|
||||
}
|
||||
}
|
||||
out.push((doc_id, unit_id, Value::Object(obj)));
|
||||
}
|
||||
ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
|
||||
ranked.truncate(limit as usize);
|
||||
Ok(
|
||||
ranked
|
||||
.into_iter()
|
||||
.map(
|
||||
|(_, _, doc_id, title, excerpt, visibility, block_id, element_id, frame_id)| {
|
||||
let title = title.or_else(|| page_titles.remove(&doc_id)).unwrap_or_default();
|
||||
let mut obj = Map::from_iter([
|
||||
("doc_id".to_owned(), json!(doc_id)),
|
||||
("title".to_owned(), json!(title)),
|
||||
("excerpt".to_owned(), json!(excerpt)),
|
||||
("visibility".to_owned(), json!(visibility)),
|
||||
]);
|
||||
for (k, v) in [
|
||||
("block_id", block_id),
|
||||
("element_id", element_id),
|
||||
("frame_id", frame_id),
|
||||
] {
|
||||
if let Some(val) = v {
|
||||
obj.insert(k.to_owned(), json!(val));
|
||||
}
|
||||
}
|
||||
Value::Object(obj)
|
||||
},
|
||||
)
|
||||
.collect(),
|
||||
)
|
||||
Ok(out)
|
||||
}
|
||||
.await;
|
||||
let embedding_spi = state.app.extension.copilot_embedding_spi();
|
||||
let vector_hits: Option<Vec<server_spi::VectorDocSearchHit>> = if embedding_spi.is_enabled() {
|
||||
embedding_spi
|
||||
.search_workspace_docs_vector(workspace_id, query_str, &doc_ids, limit)
|
||||
.search_workspace_docs_vector(workspace_id, query_str, &doc_ids, candidate_limit)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
@@ -851,75 +856,143 @@ async fn execute_tool(
|
||||
None
|
||||
};
|
||||
|
||||
let doc_id_filter: Option<HashSet<&str>> =
|
||||
(!doc_ids.is_empty()).then(|| doc_ids.iter().map(String::as_str).collect());
|
||||
let filter_vector_hits = |raw: Vec<server_spi::VectorDocSearchHit>| async move {
|
||||
let mut authorized = Vec::new();
|
||||
for hit in raw {
|
||||
if is_reserved_doc_id(workspace_id, &hit.doc_id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(ref allowed) = doc_id_filter
|
||||
&& !allowed.contains(hit.doc_id.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if matches!(
|
||||
check_doc_perm(state, workspace_id, user_id, &hit.doc_id, false).await,
|
||||
Ok(true)
|
||||
) {
|
||||
authorized.push(hit);
|
||||
}
|
||||
}
|
||||
let missing_ids: Vec<String> = authorized
|
||||
.iter()
|
||||
.filter(|h| h.title.as_deref().is_none_or(|t| t.trim().is_empty()))
|
||||
.map(|h| h.doc_id.clone())
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let mut titles = if missing_ids.is_empty() {
|
||||
HashMap::new()
|
||||
} else {
|
||||
mcp_svc
|
||||
.load_page_titles(workspace_id, &missing_ids)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let mut out = Vec::with_capacity(authorized.len());
|
||||
for (idx, vh) in authorized.into_iter().enumerate() {
|
||||
let title = vh
|
||||
.title
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.or_else(|| titles.get(&vh.doc_id).cloned())
|
||||
.unwrap_or_default();
|
||||
let visibility = if vh.visibility.trim().is_empty() {
|
||||
"page".to_owned()
|
||||
} else {
|
||||
vh.visibility
|
||||
};
|
||||
let unit_id = if vh.unit_id.trim().is_empty() {
|
||||
format!("vec-{idx}")
|
||||
} else {
|
||||
vh.unit_id
|
||||
};
|
||||
let mut obj = Map::from_iter([
|
||||
("doc_id".to_owned(), json!(vh.doc_id)),
|
||||
("title".to_owned(), json!(title)),
|
||||
("excerpt".to_owned(), json!(vh.excerpt)),
|
||||
("visibility".to_owned(), json!(visibility)),
|
||||
]);
|
||||
for (k, v) in [
|
||||
("block_id", vh.block_id),
|
||||
("element_id", vh.element_id),
|
||||
("frame_id", vh.frame_id),
|
||||
] {
|
||||
if let Some(val) = v {
|
||||
obj.insert(k.to_owned(), json!(val));
|
||||
}
|
||||
}
|
||||
out.push((vh.doc_id, unit_id, Value::Object(obj)));
|
||||
}
|
||||
let _ = titles.drain();
|
||||
out
|
||||
};
|
||||
let cap_per_doc = |items: Vec<(String, Value)>, max_total: usize| -> Vec<Value> {
|
||||
let mut counts: HashMap<String, usize> = HashMap::new();
|
||||
let mut out = Vec::new();
|
||||
for (doc_id, val) in items {
|
||||
let entry = counts.entry(doc_id).or_insert(0);
|
||||
if *entry >= 3 {
|
||||
continue;
|
||||
}
|
||||
*entry += 1;
|
||||
out.push(val);
|
||||
if out.len() >= max_total {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
match (lexical_hits, vector_hits) {
|
||||
(Ok(lex_hits), Some(vec_hits)) => {
|
||||
let mut authorized_vec = Vec::new();
|
||||
for hit in vec_hits {
|
||||
if matches!(
|
||||
check_doc_perm(state, workspace_id, user_id, &hit.doc_id, false).await,
|
||||
Ok(true)
|
||||
) {
|
||||
authorized_vec.push(hit);
|
||||
}
|
||||
}
|
||||
let mut fused: HashMap<String, (f64, Value)> = HashMap::new();
|
||||
for (idx, h) in lex_hits.into_iter().enumerate() {
|
||||
let did = h.get("doc_id").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
if did.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let authorized_vec = filter_vector_hits(vec_hits).await;
|
||||
let mut fused: HashMap<String, (f64, String, String, Value)> = HashMap::new();
|
||||
for (idx, (doc_id, unit_id, h)) in lex_hits.into_iter().enumerate() {
|
||||
let key = format!("{doc_id}:{unit_id}");
|
||||
let rrf = 1.0 / (60.0 + (idx + 1) as f64);
|
||||
fused.insert(did, (rrf, h));
|
||||
fused.insert(key, (rrf, unit_id, doc_id, h));
|
||||
}
|
||||
for (idx, vh) in authorized_vec.into_iter().enumerate() {
|
||||
for (idx, (doc_id, unit_id, vh)) in authorized_vec.into_iter().enumerate() {
|
||||
let key = format!("{doc_id}:{unit_id}");
|
||||
let rrf = 1.0 / (60.0 + (idx + 1) as f64);
|
||||
fused
|
||||
.entry(vh.doc_id.clone())
|
||||
.and_modify(|(score, _)| *score += rrf)
|
||||
.or_insert_with(|| {
|
||||
(
|
||||
rrf,
|
||||
json!({
|
||||
"doc_id": vh.doc_id,
|
||||
"title": vh.title.unwrap_or_default(),
|
||||
"excerpt": vh.excerpt,
|
||||
"visibility": "page",
|
||||
}),
|
||||
)
|
||||
});
|
||||
.entry(key)
|
||||
.and_modify(|(score, _, _, _)| *score += rrf)
|
||||
.or_insert((rrf, unit_id, doc_id, vh));
|
||||
}
|
||||
let mut items: Vec<(String, f64, Value)> = fused.into_iter().map(|(k, (s, v))| (k, s, v)).collect();
|
||||
items.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
items.truncate(limit as usize);
|
||||
let hits: Vec<Value> = items.into_iter().map(|(_, _, v)| v).collect();
|
||||
tool_text(json!({ "retrieval_mode": "hybrid", "hits": hits }).to_string())
|
||||
let mut items: Vec<(f64, String, String, Value)> = fused.into_values().collect();
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
|
||||
let hits = cap_per_doc(items.into_iter().map(|(_, _, d, v)| (d, v)).collect(), limit as usize);
|
||||
Ok(tool_text(
|
||||
json!({ "retrieval_mode": "hybrid", "hits": hits }).to_string(),
|
||||
))
|
||||
}
|
||||
(Err(()), Some(vec_hits)) => {
|
||||
let mut hits = Vec::new();
|
||||
for vh in vec_hits {
|
||||
if matches!(
|
||||
check_doc_perm(state, workspace_id, user_id, &vh.doc_id, false).await,
|
||||
Ok(true)
|
||||
) {
|
||||
hits.push(json!({
|
||||
"doc_id": vh.doc_id,
|
||||
"title": vh.title.unwrap_or_default(),
|
||||
"excerpt": vh.excerpt,
|
||||
"visibility": "page",
|
||||
}));
|
||||
if hits.len() >= limit as usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
tool_text(json!({ "retrieval_mode": "vector", "hits": hits }).to_string())
|
||||
let authorized_vec = filter_vector_hits(vec_hits).await;
|
||||
let hits = cap_per_doc(
|
||||
authorized_vec.into_iter().map(|(d, _, v)| (d, v)).collect(),
|
||||
limit as usize,
|
||||
);
|
||||
Ok(tool_text(
|
||||
json!({
|
||||
"retrieval_mode": "vector",
|
||||
"degraded_reason": "LEXICAL_UNAVAILABLE",
|
||||
"hits": hits
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
(Ok(lex_hits), None) => {
|
||||
let hits = cap_per_doc(lex_hits.into_iter().map(|(d, _, v)| (d, v)).collect(), limit as usize);
|
||||
Ok(tool_text(
|
||||
json!({ "retrieval_mode": "lexical", "degraded_reason": "VECTOR_UNAVAILABLE", "hits": hits }).to_string(),
|
||||
))
|
||||
}
|
||||
(Ok(hits), None) => tool_text(
|
||||
json!({ "retrieval_mode": "lexical", "degraded_reason": "VECTOR_UNAVAILABLE", "hits": hits }).to_string(),
|
||||
),
|
||||
(Err(()), None) => {
|
||||
if doc_ids.is_empty() {
|
||||
return tool_error("SEARCH_UNAVAILABLE");
|
||||
return Ok(tool_error("SEARCH_UNAVAILABLE"));
|
||||
}
|
||||
let mut seen_ids = HashSet::new();
|
||||
let mut readable = Vec::new();
|
||||
@@ -938,7 +1011,7 @@ async fn execute_tool(
|
||||
let mut scoped_hits = Vec::with_capacity(readable.len());
|
||||
for did in readable {
|
||||
let Ok(Some((title, md))) = mcp_svc.read_document_title_and_markdown(workspace_id, &did).await else {
|
||||
return tool_error("SEARCH_UNAVAILABLE");
|
||||
return Ok(tool_error("SEARCH_UNAVAILABLE"));
|
||||
};
|
||||
scoped_hits.push(json!({
|
||||
"doc_id": did,
|
||||
@@ -947,53 +1020,55 @@ async fn execute_tool(
|
||||
"visibility": "page",
|
||||
}));
|
||||
}
|
||||
tool_text(
|
||||
Ok(tool_text(
|
||||
json!({ "retrieval_mode": "scoped", "degraded_reason": "SEARCH_UNAVAILABLE", "hits": scoped_hits })
|
||||
.to_string(),
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
"create_document" => {
|
||||
if !can_create_doc {
|
||||
return tool_error("Failed to create document: Workspace.CreateDoc permission required");
|
||||
return Ok(tool_error(
|
||||
"Failed to create document: Workspace.CreateDoc permission required",
|
||||
));
|
||||
}
|
||||
let Some(raw_title) = args.get("title").and_then(Value::as_str) else {
|
||||
return tool_error("Invalid arguments: title: Required");
|
||||
return Ok(tool_error("Invalid arguments: title: Required"));
|
||||
};
|
||||
let Some(content) = args.get("content").and_then(Value::as_str) else {
|
||||
return tool_error("Invalid arguments: content: Required");
|
||||
return Ok(tool_error("Invalid arguments: content: Required"));
|
||||
};
|
||||
let sanitized_title: String = raw_title.replace(['\r', '\n'], " ").trim().to_owned();
|
||||
if sanitized_title.is_empty() {
|
||||
return tool_error("Failed to create document: Title cannot be empty");
|
||||
return Ok(tool_error("Failed to create document: Title cannot be empty"));
|
||||
}
|
||||
let explicit_doc_id = match args.get("docId") {
|
||||
None | Some(Value::Null) => None,
|
||||
None => None,
|
||||
Some(Value::String(raw)) => {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return tool_error("Invalid arguments: docId cannot be empty");
|
||||
return Ok(tool_error("Invalid arguments: docId cannot be empty"));
|
||||
}
|
||||
Some(trimmed)
|
||||
}
|
||||
Some(_) => return tool_error("Invalid arguments: docId must be a string"),
|
||||
Some(_) => return Ok(tool_error("Invalid arguments: docId must be a string")),
|
||||
};
|
||||
if let Some(doc_id) = explicit_doc_id {
|
||||
if is_reserved_doc_id(workspace_id, doc_id) {
|
||||
return tool_error("Failed to create document: Invalid document ID.");
|
||||
return Ok(tool_error("Failed to create document: Invalid document ID."));
|
||||
}
|
||||
match check_doc_perm(state, workspace_id, user_id, doc_id, true).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
return tool_error(format!(
|
||||
return Ok(tool_error(format!(
|
||||
"Failed to create document: Doc.Update permission required for {doc_id}"
|
||||
));
|
||||
)));
|
||||
}
|
||||
Err(e) => return e,
|
||||
Err(e) => return Ok(e),
|
||||
}
|
||||
}
|
||||
match mcp_svc
|
||||
Ok(match mcp_svc
|
||||
.create_document(workspace_id, &sanitized_title, content, user_id, explicit_doc_id)
|
||||
.await
|
||||
{
|
||||
@@ -1002,51 +1077,55 @@ async fn execute_tool(
|
||||
.to_string(),
|
||||
),
|
||||
Err(e) => map_doc_write_err("create document", e),
|
||||
}
|
||||
})
|
||||
}
|
||||
"update_document" => {
|
||||
let (Some(doc_id), Some(content)) = (
|
||||
args.get("docId").and_then(Value::as_str),
|
||||
args.get("content").and_then(Value::as_str),
|
||||
) else {
|
||||
return tool_error("Invalid arguments: docId and content required");
|
||||
return Ok(tool_error("Invalid arguments: docId and content required"));
|
||||
};
|
||||
if let Err(e) = require_doc_perm(state, workspace_id, user_id, doc_id, true).await {
|
||||
return e;
|
||||
}
|
||||
match mcp_svc.update_document(workspace_id, doc_id, content, user_id).await {
|
||||
Ok(true) => {
|
||||
tool_text(json!({ "success": true, "docId": doc_id, "message": "Document updated successfully" }).to_string())
|
||||
}
|
||||
Ok(false) => tool_error(format!("Doc with id {doc_id} not found.")),
|
||||
Err(e) => map_doc_write_err("update document", e),
|
||||
return Ok(e);
|
||||
}
|
||||
Ok(
|
||||
match mcp_svc.update_document(workspace_id, doc_id, content, user_id).await {
|
||||
Ok(true) => tool_text(
|
||||
json!({ "success": true, "docId": doc_id, "message": "Document updated successfully" }).to_string(),
|
||||
),
|
||||
Ok(false) => tool_error(format!("Doc with id {doc_id} not found.")),
|
||||
Err(e) => map_doc_write_err("update document", e),
|
||||
},
|
||||
)
|
||||
}
|
||||
"update_document_meta" => {
|
||||
let (Some(doc_id), Some(raw_title)) = (
|
||||
args.get("docId").and_then(Value::as_str),
|
||||
args.get("title").and_then(Value::as_str),
|
||||
) else {
|
||||
return tool_error("Invalid arguments: docId and title required");
|
||||
return Ok(tool_error("Invalid arguments: docId and title required"));
|
||||
};
|
||||
if let Err(e) = require_doc_perm(state, workspace_id, user_id, doc_id, true).await {
|
||||
return e;
|
||||
return Ok(e);
|
||||
}
|
||||
let sanitized_title: String = raw_title.replace(['\r', '\n'], " ").trim().to_owned();
|
||||
if sanitized_title.is_empty() {
|
||||
return tool_error(format!("Doc with id {doc_id} not found."));
|
||||
}
|
||||
match mcp_svc
|
||||
.update_document_title(workspace_id, doc_id, &sanitized_title, user_id)
|
||||
.await
|
||||
{
|
||||
Ok(true) => tool_text(
|
||||
json!({ "success": true, "docId": doc_id, "message": "Document title updated successfully" }).to_string(),
|
||||
),
|
||||
Ok(false) => tool_error(format!("Doc with id {doc_id} not found.")),
|
||||
Err(e) => map_doc_write_err("update document metadata", e),
|
||||
return Ok(tool_error(format!("Doc with id {doc_id} not found.")));
|
||||
}
|
||||
Ok(
|
||||
match mcp_svc
|
||||
.update_document_title(workspace_id, doc_id, &sanitized_title, user_id)
|
||||
.await
|
||||
{
|
||||
Ok(true) => tool_text(
|
||||
json!({ "success": true, "docId": doc_id, "message": "Document title updated successfully" }).to_string(),
|
||||
),
|
||||
Ok(false) => tool_error(format!("Doc with id {doc_id} not found.")),
|
||||
Err(e) => map_doc_write_err("update document metadata", e),
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => tool_error(format!("Tool not found: {tool_name}")),
|
||||
_ => Ok(tool_error(format!("Tool not found: {tool_name}"))),
|
||||
}
|
||||
}
|
||||
@@ -241,17 +241,7 @@ 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 redis_key_prefix = app.app_config.get_internal_redis_key_prefix().await.unwrap_or_default();
|
||||
let prefixed_key = format!("{redis_key_prefix}{key}");
|
||||
let (hits, pttl_ms, block_ttl_ms) = app
|
||||
.strict_throttler
|
||||
|
||||
@@ -561,8 +561,8 @@ fn http_auth_graphql_and_rest_parity() {
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st_csrf_trusted_origin, StatusCode::OK);
|
||||
assert!(trusted_origin_json.get("errors").is_none());
|
||||
assert_eq!(st_csrf_trusted_origin, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(trusted_origin_json["errors"][0]["extensions"]["type"], "BAD_REQUEST");
|
||||
|
||||
let (st_csrf_preflight, _, preflight_json, _) = send(
|
||||
&router,
|
||||
|
||||
@@ -76,6 +76,14 @@ async fn setup_http_state(
|
||||
..RuntimeConfig::default()
|
||||
};
|
||||
let ext: Arc<dyn ServerExtension> = if copilot_enabled {
|
||||
sqlx::query(
|
||||
r#"INSERT INTO app_configs (id, value, created_at, updated_at)
|
||||
VALUES ('copilot.enabled', 'true'::jsonb, clock_timestamp(), clock_timestamp())
|
||||
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = clock_timestamp()"#,
|
||||
)
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.expect("enable copilot in app_configs");
|
||||
Arc::new(TestCopilotExtension {
|
||||
inner: CommunityExtension::new(),
|
||||
})
|
||||
@@ -737,6 +745,15 @@ fn mcp_doc_search_lexical_hits_real_search_runtime() {
|
||||
.await
|
||||
.expect("reset schema for fresh ensure_schema_ready");
|
||||
state.db.ensure_schema_ready().await.expect("ensure v2 search schema");
|
||||
sqlx::query(
|
||||
r#"INSERT INTO app_configs (id, value, created_at, updated_at)
|
||||
VALUES ('copilot.enabled', 'true'::jsonb, clock_timestamp(), clock_timestamp())
|
||||
ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value, updated_at = clock_timestamp()"#,
|
||||
)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.expect("re-enable copilot in app_configs after schema reset");
|
||||
state.app_config.invalidate_cache();
|
||||
let (uid, ws_id) = insert_user_and_workspace(&state, "lex-search@example.com").await;
|
||||
let created = state
|
||||
.mcp
|
||||
|
||||
@@ -521,8 +521,13 @@ async fn workspace_doc_notification_config_and_error_parity() {
|
||||
);
|
||||
assert_eq!(
|
||||
submit_transcript_res["errors"][0]["extensions"]["name"].as_str(),
|
||||
Some("COPILOT_DISABLED"),
|
||||
"community submitTranscriptTask must return COPILOT_DISABLED: {submit_transcript_res}"
|
||||
Some("ACTION_FORBIDDEN"),
|
||||
"community submitTranscriptTask must return ACTION_FORBIDDEN: {submit_transcript_res}"
|
||||
);
|
||||
assert_eq!(
|
||||
submit_transcript_res["errors"][0]["extensions"]["message"].as_str(),
|
||||
Some("Copilot is disabled."),
|
||||
"community submitTranscriptTask must fail closed: {submit_transcript_res}"
|
||||
);
|
||||
|
||||
// 13. invoices rejects negative take/skip with 400.
|
||||
|
||||
@@ -215,7 +215,7 @@ impl SmtpMailer {
|
||||
related = related.singlepart(
|
||||
SinglePart::builder()
|
||||
.header(ct)
|
||||
.header(ContentDisposition::inline())
|
||||
.header(ContentDisposition::inline_with_name("workspaceAvatar"))
|
||||
.header(ContentId::from(cid))
|
||||
.header(ContentTransferEncoding::Base64)
|
||||
.body(att.data.clone()),
|
||||
@@ -271,10 +271,25 @@ impl SmtpMailer {
|
||||
response.message().collect::<Vec<_>>().join(" ")
|
||||
),
|
||||
},
|
||||
Err(err) if err.is_permanent() => MailSendResult::Rejected {
|
||||
provider_response: Some(err.to_string()),
|
||||
error_code: "provider_rejected",
|
||||
},
|
||||
Err(err)
|
||||
if err.is_permanent()
|
||||
&& err.status().is_some_and(|s| {
|
||||
matches!(
|
||||
(s.category, s.detail),
|
||||
(
|
||||
lettre::transport::smtp::response::Category::MailSystem,
|
||||
lettre::transport::smtp::response::Detail::Zero
|
||||
| lettre::transport::smtp::response::Detail::One
|
||||
| lettre::transport::smtp::response::Detail::Three
|
||||
)
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
MailSendResult::Rejected {
|
||||
provider_response: Some(err.to_string()),
|
||||
error_code: "provider_rejected",
|
||||
}
|
||||
}
|
||||
Err(err) => MailSendResult::Failed {
|
||||
retryable: true,
|
||||
error_code: "transport_failed",
|
||||
|
||||
@@ -265,6 +265,20 @@ pub struct MailDeliveryOptions<'a> {
|
||||
pub workspace_resolver: Option<&'a dyn WorkspaceMailMetaResolver>,
|
||||
}
|
||||
|
||||
pub fn workspace_name_contains_domain(name: &str) -> bool {
|
||||
let normalized: String = name
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'。' | '.' | '。' => '.',
|
||||
other => other,
|
||||
})
|
||||
.collect();
|
||||
normalized.contains("://")
|
||||
|| normalized
|
||||
.split_whitespace()
|
||||
.any(|tok| tok.contains('.') && tok.len() >= 4 && !tok.starts_with('.') && !tok.ends_with('.'))
|
||||
}
|
||||
|
||||
async fn resolve_dynamic_payload_props(
|
||||
pool: &PgPool,
|
||||
payload: &mut Value,
|
||||
@@ -310,11 +324,8 @@ async fn resolve_dynamic_payload_props(
|
||||
.await?
|
||||
};
|
||||
exists.then(|| {
|
||||
let name = ws_name.unwrap_or_else(|| "Untitled".to_owned());
|
||||
let name_contains_domain = name.contains("://")
|
||||
|| name
|
||||
.split_whitespace()
|
||||
.any(|tok| tok.contains('.') && tok.len() >= 4 && !tok.starts_with('.') && !tok.ends_with('.'));
|
||||
let name = ws_name.unwrap_or_else(|| "Untitled Workspace".to_owned());
|
||||
let name_contains_domain = workspace_name_contains_domain(&name);
|
||||
ResolvedWorkspaceMailMeta {
|
||||
name,
|
||||
avatar: None,
|
||||
@@ -323,7 +334,7 @@ async fn resolve_dynamic_payload_props(
|
||||
})
|
||||
};
|
||||
let Some(meta) = resolved else {
|
||||
return Ok((Some("workspace_not_found"), inline_attachments));
|
||||
return Ok((Some("dynamic_props_missing"), inline_attachments));
|
||||
};
|
||||
if mail_name == "MemberInvitation" && meta.name_contains_domain {
|
||||
return Ok((Some("workspace_name_contains_domain"), inline_attachments));
|
||||
@@ -338,13 +349,20 @@ async fn resolve_dynamic_payload_props(
|
||||
props.insert(key, Value::Object(merged));
|
||||
continue;
|
||||
}
|
||||
if mail_name == "MemberInvitation"
|
||||
&& key == "workspace"
|
||||
&& let Some(ws_name) = obj.get("name").and_then(Value::as_str)
|
||||
&& workspace_name_contains_domain(ws_name)
|
||||
{
|
||||
return Ok((Some("workspace_name_contains_domain"), inline_attachments));
|
||||
}
|
||||
if let Some(uid) = obj.get("$$userId").and_then(Value::as_str) {
|
||||
let email: Option<String> = sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
|
||||
.bind(uid)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
let Some(email) = email else {
|
||||
return Ok((Some("user_not_found"), inline_attachments));
|
||||
return Ok((Some("dynamic_props_missing"), inline_attachments));
|
||||
};
|
||||
let mut merged = obj;
|
||||
merged.remove("$$userId");
|
||||
@@ -561,6 +579,7 @@ pub async fn process_ready_mail_deliveries_with_options(
|
||||
.await?;
|
||||
|
||||
let Some(next_attempt) = attempt_started else {
|
||||
mark_terminal(pool, &item.id, worker_id, "failed", None, None, Some("expired"), None).await?;
|
||||
continue;
|
||||
};
|
||||
processed += 1;
|
||||
|
||||
@@ -241,18 +241,12 @@ pub async fn cleanup_retired_generation(
|
||||
let retain_failure_marker: bool = row
|
||||
.try_get("retain_failure_marker")
|
||||
.map_err(|error| SearchError::database("decode retired search generation state", error))?;
|
||||
let schema_version: i32 = row
|
||||
.try_get("schema_version")
|
||||
.map_err(|error| SearchError::database("decode retired search generation schema", error))?;
|
||||
let generation = decode(row)?;
|
||||
if let Some(provider) = remote {
|
||||
// Preserve schema_version <= 1 remote physical tables for cross-generation v0.27.5 read coexistence.
|
||||
if schema_version > 1 {
|
||||
for table in [SearchTable::Doc, SearchTable::Block] {
|
||||
provider
|
||||
.drop_generation_asset(generation.physical_table(table)?)
|
||||
.await?;
|
||||
}
|
||||
for table in [SearchTable::Doc, SearchTable::Block] {
|
||||
provider
|
||||
.drop_generation_asset(generation.physical_table(table)?)
|
||||
.await?;
|
||||
}
|
||||
} else {
|
||||
embedded.remove_generation(generation.id).await;
|
||||
|
||||
@@ -35,7 +35,7 @@ use sqlx::PgConnection;
|
||||
|
||||
/// The search projection schema. Raise it when extraction changes indexed
|
||||
/// fields, so that startup builds a new generation and reprojects every doc.
|
||||
pub const SCHEMA_FINGERPRINT: i32 = 2;
|
||||
pub const SCHEMA_FINGERPRINT: i32 = 1;
|
||||
pub(crate) const WORKSPACE_RECONCILE_FAILED: &str = "search_workspace_reconcile_failed";
|
||||
pub(crate) const DOCUMENT_PROJECTION_FAILED: &str = "search_document_projection_failed";
|
||||
pub(crate) const EMBEDDED_GENERATION_LOST: &str = "search_embedded_generation_lost";
|
||||
|
||||
@@ -452,6 +452,9 @@ impl SearchRuntime {
|
||||
workspace_id: &str,
|
||||
request: SearchRequest,
|
||||
) -> SearchResult<Value> {
|
||||
if !self.config.enabled {
|
||||
return Err(SearchError::ProviderUnavailable);
|
||||
}
|
||||
for attempt in 0..=1 {
|
||||
let (scope, legacy, generation, required_permission_version) = self
|
||||
.prepare_authorized_query_snapshot(actor_user_id, workspace_id)
|
||||
@@ -483,6 +486,9 @@ impl SearchRuntime {
|
||||
workspace_id: &str,
|
||||
request: AggregateRequest,
|
||||
) -> SearchResult<Value> {
|
||||
if !self.config.enabled {
|
||||
return Err(SearchError::ProviderUnavailable);
|
||||
}
|
||||
for attempt in 0..=1 {
|
||||
let (scope, legacy, generation, required_permission_version) = self
|
||||
.prepare_authorized_query_snapshot(actor_user_id, workspace_id)
|
||||
|
||||
@@ -1515,7 +1515,7 @@ fn schema_upgrade_reprojects_unchanged_docs_and_retires_previous_generation() {
|
||||
// No doc changes after this point.
|
||||
sqlx::query("UPDATE search_projection.generations SET schema_version = $2 WHERE id = $1")
|
||||
.bind(previous)
|
||||
.bind(SCHEMA_FINGERPRINT - 1)
|
||||
.bind(SCHEMA_FINGERPRINT + 1)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -69,12 +69,17 @@ pub struct AddWorkspaceArtifactInput {
|
||||
}
|
||||
|
||||
/// Vector search hit returned by [`CopilotEmbeddingSpi::search_workspace_docs_vector`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct VectorDocSearchHit {
|
||||
pub doc_id: String,
|
||||
pub unit_id: String,
|
||||
pub visibility: String,
|
||||
pub title: Option<String>,
|
||||
pub excerpt: String,
|
||||
pub score: f64,
|
||||
pub block_id: Option<String>,
|
||||
pub element_id: Option<String>,
|
||||
pub frame_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Commercial SPI for workspace embedding config, artifacts, and ignored documents.
|
||||
|
||||
@@ -10,6 +10,9 @@ pub enum SyncError {
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
|
||||
#[error("validation error: {0}")]
|
||||
ValidationError(String),
|
||||
|
||||
#[error("query is too long (max {max})")]
|
||||
QueryTooLong { max: usize },
|
||||
|
||||
|
||||
@@ -366,19 +366,34 @@ impl SpaceSyncGateway {
|
||||
"sentAt": chrono::Utc::now().timestamp_millis(),
|
||||
"event": event_val,
|
||||
});
|
||||
let mut auth_cache: HashMap<String, RealtimeAuthDecision> = HashMap::new();
|
||||
for (sid, user_id_opt) in recipients_with_users {
|
||||
if needs_auth_check {
|
||||
let allowed = match user_id_opt.as_deref() {
|
||||
Some(uid) => gateway.is_realtime_room_authorized(&room, uid).await,
|
||||
None => false,
|
||||
let decision = match user_id_opt.as_deref() {
|
||||
Some(uid) => {
|
||||
if let Some(&cached) = auth_cache.get(uid) {
|
||||
cached
|
||||
} else {
|
||||
let d = gateway.is_realtime_room_authorized(&room, uid).await;
|
||||
auth_cache.insert(uid.to_owned(), d);
|
||||
d
|
||||
}
|
||||
}
|
||||
None => RealtimeAuthDecision::Denied,
|
||||
};
|
||||
if !allowed {
|
||||
let mut rooms = gateway.rooms.write().await;
|
||||
rooms
|
||||
.realtime_subscriptions
|
||||
.retain(|_, (other_sid, other_room)| !(other_sid == &sid && other_room == &room));
|
||||
rooms.leave_room(&sid, &room);
|
||||
continue;
|
||||
match decision {
|
||||
RealtimeAuthDecision::Allowed => {}
|
||||
RealtimeAuthDecision::Denied => {
|
||||
let mut rooms = gateway.rooms.write().await;
|
||||
rooms
|
||||
.realtime_subscriptions
|
||||
.retain(|_, (other_sid, other_room)| !(other_sid == &sid && other_room == &room));
|
||||
rooms.leave_room(&sid, &room);
|
||||
continue;
|
||||
}
|
||||
RealtimeAuthDecision::TransientError => {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
engine.emit_to_socket(&sid, "realtime:event", &body).await;
|
||||
@@ -647,9 +662,17 @@ impl SpaceSyncGateway {
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut rt_auth_cache: HashMap<(String, String), RealtimeAuthDecision> = HashMap::new();
|
||||
for (sub_id, sid, user_id, room) in rt_candidates {
|
||||
let still_allowed = self.is_realtime_room_authorized(&room, &user_id).await;
|
||||
if !still_allowed {
|
||||
let cache_key = (user_id.clone(), room.clone());
|
||||
let decision = if let Some(&cached) = rt_auth_cache.get(&cache_key) {
|
||||
cached
|
||||
} else {
|
||||
let res = self.is_realtime_room_authorized(&room, &user_id).await;
|
||||
rt_auth_cache.insert(cache_key, res);
|
||||
res
|
||||
};
|
||||
if decision == RealtimeAuthDecision::Denied {
|
||||
let mut rooms = self.rooms.write().await;
|
||||
if rooms.realtime_subscriptions.remove(&sub_id).is_some() {
|
||||
let still_in_room = rooms
|
||||
@@ -775,47 +798,40 @@ 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) {
|
||||
async fn is_realtime_room_authorized(&self, room: &str, user_id: &str) -> RealtimeAuthDecision {
|
||||
let res = 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,
|
||||
"config" => {
|
||||
self
|
||||
.storage
|
||||
.assert_space_accessible(SpaceType::Workspace, ws_id, user_id)
|
||||
.await
|
||||
}
|
||||
"access" | "quota-state" => self.storage.assert_workspace_readable(ws_id, user_id).await,
|
||||
"members" => self.storage.assert_workspace_members_readable(ws_id, user_id).await,
|
||||
"invite-link" => self.storage.assert_workspace_invite_manage(ws_id, user_id).await,
|
||||
"embedding-progress" => {
|
||||
self
|
||||
.storage
|
||||
.copilot_realtime_authorize_embedding_progress(user_id, ws_id)
|
||||
.await
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
classify_realtime_auth_result(res)
|
||||
}
|
||||
|
||||
async fn on_join_batch(&self, socket_id: &str, user: &SyncUser, payload: &Value) -> Result<EventResponse, SyncError> {
|
||||
@@ -1210,13 +1226,24 @@ impl SpaceSyncGateway {
|
||||
}
|
||||
|
||||
if msg.space_type == SpaceType::Workspace {
|
||||
let aliases = self.storage.get_doc_id_aliases(&msg.space_id).await?;
|
||||
let (storage_doc_id, logical_doc_id, require_deleted, has_storage_identity_conflict) =
|
||||
resolve_delete_doc_target(&doc_id, None, &aliases);
|
||||
self
|
||||
.storage
|
||||
.apply_doc_lifecycle(&msg.space_id, &doc_id, None, &user.id, DocLifecycleAction::Delete)
|
||||
.apply_doc_lifecycle_with_options(
|
||||
&msg.space_id,
|
||||
&storage_doc_id,
|
||||
logical_doc_id.as_deref(),
|
||||
&user.id,
|
||||
DocLifecycleAction::Delete,
|
||||
require_deleted,
|
||||
has_storage_identity_conflict,
|
||||
)
|
||||
.await?;
|
||||
self
|
||||
.eventbus
|
||||
.publish_workspace_inventory_changed(&msg.space_id, Some(&doc_id))
|
||||
.publish_workspace_inventory_changed(&msg.space_id, Some(&storage_doc_id))
|
||||
.await;
|
||||
} else {
|
||||
if msg.space_id != user.id {
|
||||
@@ -1261,22 +1288,17 @@ impl SpaceSyncGateway {
|
||||
}
|
||||
|
||||
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 (storage_doc_id, logical_doc_id, require_deleted, has_storage_identity_conflict) =
|
||||
if action == DocLifecycleAction::Delete {
|
||||
resolve_delete_doc_target(&doc_id, phys_canonical.as_deref(), &aliases)
|
||||
} else {
|
||||
let resolved_doc_id = aliases.get(&doc_id).cloned().unwrap_or_else(|| doc_id.clone());
|
||||
(resolved_doc_id, None, false, false)
|
||||
};
|
||||
|
||||
let result = self
|
||||
.storage
|
||||
@@ -1438,7 +1460,7 @@ impl SpaceSyncGateway {
|
||||
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()));
|
||||
return Err(SyncError::ValidationError("skip and take must be non-negative".into()));
|
||||
}
|
||||
let skip = raw_skip;
|
||||
let take = raw_take.clamp(1, 100);
|
||||
@@ -2055,6 +2077,30 @@ fn realtime_input_key(input: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum RealtimeAuthDecision {
|
||||
Allowed,
|
||||
Denied,
|
||||
TransientError,
|
||||
}
|
||||
|
||||
fn classify_realtime_auth_result(res: Result<(), SyncError>) -> RealtimeAuthDecision {
|
||||
match res {
|
||||
Ok(()) => RealtimeAuthDecision::Allowed,
|
||||
Err(
|
||||
SyncError::SpaceAccessDenied { .. }
|
||||
| SyncError::NotInSpace { .. }
|
||||
| SyncError::AccessDenied(_)
|
||||
| SyncError::DocActionDenied { .. }
|
||||
| SyncError::DocNotFound { .. }
|
||||
| SyncError::UserNotFound
|
||||
| SyncError::SpaceOwnerNotFound { .. }
|
||||
| SyncError::CopilotDisabled,
|
||||
) => RealtimeAuthDecision::Denied,
|
||||
Err(_) => RealtimeAuthDecision::TransientError,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -2075,3 +2121,82 @@ fn is_supported_realtime_client_version(ver: &str, allow_canary: bool) -> bool {
|
||||
};
|
||||
(maj == 0 && min >= 26) || (maj > 0 && maj < 2000)
|
||||
}
|
||||
|
||||
fn resolve_delete_doc_target(
|
||||
doc_id: &str,
|
||||
physical_doc_id: Option<&str>,
|
||||
aliases: &HashMap<String, String>,
|
||||
) -> (String, Option<String>, bool, bool) {
|
||||
let resolved_doc_id = aliases.get(doc_id).cloned().unwrap_or_else(|| doc_id.to_owned());
|
||||
let storage_doc_id = physical_doc_id
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| resolved_doc_id.clone());
|
||||
let logical_doc_id = (storage_doc_id != doc_id).then(|| doc_id.to_owned());
|
||||
let has_storage_identity_conflict =
|
||||
storage_doc_id != doc_id && aliases.iter().any(|(l, s)| l != doc_id && s == doc_id);
|
||||
let require_deleted =
|
||||
has_storage_identity_conflict || (physical_doc_id.is_some() && storage_doc_id != resolved_doc_id);
|
||||
(
|
||||
storage_doc_id,
|
||||
logical_doc_id,
|
||||
require_deleted,
|
||||
has_storage_identity_conflict,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod realtime_auth_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn delete_doc_target_flags_storage_identity_conflict_when_another_alias_owns_logical_id() {
|
||||
let mut aliases = HashMap::new();
|
||||
aliases.insert("doc-a".to_owned(), "doc-b".to_owned());
|
||||
aliases.insert("doc-other".to_owned(), "doc-a".to_owned());
|
||||
|
||||
let (storage_id, logical_id, require_deleted, has_conflict) = resolve_delete_doc_target("doc-a", None, &aliases);
|
||||
assert_eq!(storage_id, "doc-b");
|
||||
assert_eq!(logical_id.as_deref(), Some("doc-a"));
|
||||
assert!(has_conflict);
|
||||
assert!(require_deleted);
|
||||
|
||||
let mut clean_aliases = HashMap::new();
|
||||
clean_aliases.insert("doc-a".to_owned(), "doc-b".to_owned());
|
||||
let (storage_id, logical_id, require_deleted, has_conflict) =
|
||||
resolve_delete_doc_target("doc-a", None, &clean_aliases);
|
||||
assert_eq!(storage_id, "doc-b");
|
||||
assert_eq!(logical_id.as_deref(), Some("doc-a"));
|
||||
assert!(!has_conflict);
|
||||
assert!(!require_deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn realtime_auth_classification_distinguishes_denied_from_transient_errors() {
|
||||
assert_eq!(classify_realtime_auth_result(Ok(())), RealtimeAuthDecision::Allowed);
|
||||
for denied in [
|
||||
SyncError::SpaceAccessDenied {
|
||||
space_id: "ws-1".to_owned(),
|
||||
},
|
||||
SyncError::NotInSpace {
|
||||
space_id: "ws-1".to_owned(),
|
||||
},
|
||||
SyncError::AccessDenied("forbidden".to_owned()),
|
||||
SyncError::DocActionDenied {
|
||||
space_id: "ws-1".to_owned(),
|
||||
doc_id: "doc-1".to_owned(),
|
||||
action: "Doc.Read".to_owned(),
|
||||
},
|
||||
SyncError::DocNotFound {
|
||||
space_id: "ws-1".to_owned(),
|
||||
doc_id: "doc-1".to_owned(),
|
||||
},
|
||||
SyncError::UserNotFound,
|
||||
] {
|
||||
assert_eq!(classify_realtime_auth_result(Err(denied)), RealtimeAuthDecision::Denied);
|
||||
}
|
||||
assert_eq!(
|
||||
classify_realtime_auth_result(Err(SyncError::Database("connection reset".to_owned()))),
|
||||
RealtimeAuthDecision::TransientError
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,10 +48,19 @@ pub fn sync_error_to_ws_envelope(err: &SyncError, request_id: Option<String>) ->
|
||||
data: None,
|
||||
request_id,
|
||||
},
|
||||
SyncError::ValidationError(msg) => WebsocketErrorBody {
|
||||
status: StatusCode::BAD_REQUEST.as_u16(),
|
||||
code: "VALIDATION_ERROR".into(),
|
||||
error_type: "INVALID_INPUT".into(),
|
||||
name: "VALIDATION_ERROR".into(),
|
||||
message: msg.clone(),
|
||||
data: None,
|
||||
request_id,
|
||||
},
|
||||
SyncError::QueryTooLong { max } => WebsocketErrorBody {
|
||||
status: StatusCode::BAD_REQUEST.as_u16(),
|
||||
code: "QUERY_TOO_LONG".into(),
|
||||
error_type: "BAD_REQUEST".into(),
|
||||
error_type: "INVALID_INPUT".into(),
|
||||
name: "QUERY_TOO_LONG".into(),
|
||||
message: format!("Query is too long, max length is {max}."),
|
||||
data: Some(json!({ "max": max })),
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct SyncConfig {
|
||||
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],
|
||||
/// Redis key prefix (`redis.ioredis.keyPrefix` / `redis.keyPrefix`).
|
||||
pub redis_key_prefix: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SyncConfig {
|
||||
@@ -93,6 +95,7 @@ impl SyncConfig {
|
||||
allow_canary,
|
||||
copilot_realtime: None,
|
||||
available_user_features: &["administrator"],
|
||||
redis_key_prefix: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +165,9 @@ impl SyncServer {
|
||||
if let Some(handler) = config.copilot_realtime {
|
||||
storage = storage.with_copilot_realtime(handler);
|
||||
}
|
||||
if !config.redis_key_prefix.is_empty() {
|
||||
storage = storage.with_redis_key_prefix(config.redis_key_prefix);
|
||||
}
|
||||
storage = storage.with_available_user_features(config.available_user_features);
|
||||
let eventbus = match config.origin_id {
|
||||
Some(origin_id) => {
|
||||
|
||||
@@ -380,6 +380,7 @@ pub struct SyncStorage {
|
||||
session_redis: UserspaceRedisLockBackend,
|
||||
pub(super) cache_redis: Option<redis::Client>,
|
||||
pub(super) cache_redis_conn: Arc<tokio::sync::Mutex<Option<redis::aio::MultiplexedConnection>>>,
|
||||
pub(super) redis_key_prefix: String,
|
||||
pub(super) external_url: String,
|
||||
pub(super) copilot_realtime: Option<Arc<dyn CopilotRealtimeHandler>>,
|
||||
pub(super) available_user_features: &'static [&'static str],
|
||||
@@ -423,6 +424,7 @@ impl SyncStorage {
|
||||
session_redis: UserspaceRedisLockBackend::Disabled,
|
||||
cache_redis: None,
|
||||
cache_redis_conn: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
redis_key_prefix: String::new(),
|
||||
external_url: String::new(),
|
||||
copilot_realtime: None,
|
||||
available_user_features: &["administrator"],
|
||||
@@ -445,6 +447,11 @@ impl SyncStorage {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_redis_key_prefix(mut self, prefix: impl Into<String>) -> Self {
|
||||
self.redis_key_prefix = prefix.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_copilot_realtime(mut self, handler: Arc<dyn CopilotRealtimeHandler>) -> Self {
|
||||
self.copilot_realtime = Some(handler);
|
||||
self
|
||||
@@ -1761,11 +1768,11 @@ impl SyncStorage {
|
||||
.map(|dt| dt.with_timezone(&Utc));
|
||||
|
||||
let (take, explicit_limit) = match first {
|
||||
Some(raw) => {
|
||||
let limit = raw.clamp(0, 10_000);
|
||||
Some(raw) if raw > 0 => {
|
||||
let limit = raw.min(10_000);
|
||||
(limit.saturating_add(1), Some(limit))
|
||||
}
|
||||
None => (10_000, None),
|
||||
_ => (10_000, None),
|
||||
};
|
||||
let mut changes = svc
|
||||
.list_comment_changes(
|
||||
|
||||
@@ -225,7 +225,7 @@ impl SyncStorage {
|
||||
let Some(mut conn) = conn else {
|
||||
return Ok(serde_json::Value::Null);
|
||||
};
|
||||
let ws_key = format!("workspace:inviteLink:{workspace_id}");
|
||||
let ws_key = format!("{}workspace:inviteLink:{workspace_id}", self.redis_key_prefix);
|
||||
let raw_res = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
redis::cmd("GET").arg(&ws_key).query_async::<Option<String>>(&mut conn),
|
||||
|
||||
Reference in new issue
Block a user