From d66b6b2d4240a89181a8bf119ca5bd5552a19dbc Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Sun, 29 Nov 2026 11:41:52 +0100 Subject: [PATCH 01/14] Fix self-host, spec, review, and webhook issues Self-hosting: - Add SIGNUP_ENABLED to turn off self-service sign-up; reported as signupEnabled in /capabilities/auth - Report the worst component status from readiness, so one unhealthy dependency makes the server unhealthy - Stop publishing Postgres and NATS ports in the prod compose, bind them to loopback in dev, and document the deployment settings OpenAPI spec: - Mark optional request bodies as not required, and reject a body sent without a Content-Type instead of treating it as absent - Declare bearer auth on the invite preview - Match pagination, detection source, and redaction key bounds to the server Reviews: - Bind each approval to a redaction; quorum counts approvals of the same redaction, and the review's output is the redaction it approved - Remove the point-detection endpoint and the redetected event Webhooks: - Split the request from its camelCase payload, add a delivery id sent as X-Webhook-Delivery-Id, and drop the message field Update elide-runtime to 296f2db: restore audits and artifact sets through the built-in restorer, without the engine. Co-Authored-By: Claude Opus 5.5 --- .env.example | 6 + Cargo.lock | 85 ++- Cargo.toml | 2 +- crates/nvisy-core/src/health.rs | 49 +- crates/nvisy-object-store/src/provider/mod.rs | 2 +- crates/nvisy-postgres/src/model/mod.rs | 2 +- .../src/model/workspace_review_links.rs | 26 +- .../src/model/workspace_reviews.rs | 32 +- .../src/query/workspace_reviews.rs | 600 ++++++++---------- crates/nvisy-postgres/src/schema.rs | 16 +- .../src/types/enums/review_event_kind.rs | 14 +- crates/nvisy-server/src/args.rs | 8 +- .../src/domain/workspace_detections.rs | 38 +- .../src/domain/workspace_redactions.rs | 6 +- .../src/domain/workspace_reviews.rs | 125 +--- .../src/domain/workspace_webhooks.rs | 11 +- crates/nvisy-server/src/extract/mod.rs | 2 + .../nvisy-server/src/extract/optional_body.rs | 86 +++ .../src/extract/reject/json_with_rej.rs | 31 +- .../src/handler/authentication.rs | 4 +- .../nvisy-server/src/handler/capabilities.rs | 20 +- .../src/handler/request/paginations.rs | 1 + .../handler/request/workspace_detections.rs | 2 + .../src/handler/request/workspace_reviews.rs | 32 +- .../src/handler/response/capabilities.rs | 10 +- .../src/handler/response/workspace_reviews.rs | 61 +- .../src/handler/utility/redaction_key.rs | 5 +- .../src/handler/workspace_connections.rs | 4 +- .../src/handler/workspace_detections.rs | 6 +- .../src/handler/workspace_invites.rs | 7 +- .../src/handler/workspace_reviews.rs | 92 +-- .../nvisy-server/src/response/auth/session.rs | 7 +- .../src/service/auth/account_provisioner.rs | 39 +- .../src/service/auth/auth_flow.rs | 21 +- crates/nvisy-server/src/service/auth/mod.rs | 4 +- .../nvisy-server/src/service/auth/oidc/mod.rs | 4 +- .../nvisy-server/src/service/auth/signup.rs | 47 ++ .../nvisy-server/src/service/blob/reader.rs | 59 +- crates/nvisy-server/src/service/di.rs | 29 +- .../src/service/emitter/webhook.rs | 1 + .../src/service/health/service.rs | 7 +- crates/nvisy-server/src/service/mod.rs | 14 +- crates/nvisy-server/src/test_util.rs | 22 +- crates/nvisy-server/src/worker/webhook/job.rs | 3 + .../nvisy-server/src/worker/webhook/worker.rs | 16 +- crates/nvisy-server/tests/openapi.rs | 100 +++ crates/nvisy-server/tests/signup.rs | 53 ++ crates/nvisy-webhook/src/provider/context.rs | 1 + crates/nvisy-webhook/src/provider/request.rs | 117 ++-- crates/nvisy-webhook/src/provider/response.rs | 14 +- crates/nvisy-webhook/src/reqwest/client.rs | 20 +- docker/README.md | 15 +- docker/compose.prod.yaml | 13 +- docker/compose.yaml | 6 +- migrations/2026-09-11-040235_reviews/down.sql | 1 + migrations/2026-09-11-040235_reviews/up.sql | 104 +-- 56 files changed, 1151 insertions(+), 951 deletions(-) create mode 100644 crates/nvisy-server/src/extract/optional_body.rs create mode 100644 crates/nvisy-server/src/service/auth/signup.rs create mode 100644 crates/nvisy-server/tests/signup.rs diff --git a/.env.example b/.env.example index f926a3e7..46e52b3e 100644 --- a/.env.example +++ b/.env.example @@ -240,6 +240,12 @@ MAX_FILE_BODY_BYTES=524288000 # Whether session cookies carry the Secure attribute (HTTPS-only) COOKIE_SECURE=true +# ─── Sign-up ─── + +# Whether new accounts can be created, by password sign-up or by a first OIDC sign-in. +# Existing accounts can sign in either way +SIGNUP_ENABLED=true + # ─── Webhook HTTP client ─── # HTTP request timeout (e.g. 30s); falls back to the default when unset diff --git a/Cargo.lock b/Cargo.lock index 117a32fd..cf9c6b73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -210,7 +210,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -221,7 +221,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2987,7 +2987,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3142,7 +3142,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "elide" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-audio", @@ -3167,7 +3167,7 @@ dependencies = [ [[package]] name = "elide-audio" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3184,7 +3184,7 @@ dependencies = [ [[package]] name = "elide-backend" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3197,7 +3197,7 @@ dependencies = [ [[package]] name = "elide-bentoml" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "async-trait", "base64 0.23.1", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "elide-codec" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3226,7 +3226,7 @@ dependencies = [ [[package]] name = "elide-core" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "blake3", @@ -3245,7 +3245,7 @@ dependencies = [ [[package]] name = "elide-deployment" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "hipstr", @@ -3257,7 +3257,7 @@ dependencies = [ [[package]] name = "elide-detection" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3271,7 +3271,7 @@ dependencies = [ [[package]] name = "elide-engine" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "bytes", "elide-audio", @@ -3293,7 +3293,7 @@ dependencies = [ [[package]] name = "elide-export" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "csv", "elide", @@ -3305,7 +3305,7 @@ dependencies = [ [[package]] name = "elide-fake" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3317,7 +3317,7 @@ dependencies = [ [[package]] name = "elide-format" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "elide-audio", "elide-codec", @@ -3332,7 +3332,7 @@ dependencies = [ [[package]] name = "elide-image" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3350,7 +3350,7 @@ dependencies = [ [[package]] name = "elide-lingua" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3361,7 +3361,7 @@ dependencies = [ [[package]] name = "elide-llm" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "base64 0.23.1", @@ -3385,7 +3385,7 @@ dependencies = [ [[package]] name = "elide-macros" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -3396,7 +3396,7 @@ dependencies = [ [[package]] name = "elide-markup" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-codec", @@ -3407,7 +3407,7 @@ dependencies = [ [[package]] name = "elide-ner" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3419,7 +3419,7 @@ dependencies = [ [[package]] name = "elide-office" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3434,7 +3434,7 @@ dependencies = [ [[package]] name = "elide-pattern" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "aho-corasick", "async-trait", @@ -3455,7 +3455,7 @@ dependencies = [ [[package]] name = "elide-pdf" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3474,7 +3474,7 @@ dependencies = [ [[package]] name = "elide-pipeline" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "bytes", "elide", @@ -3495,7 +3495,7 @@ dependencies = [ [[package]] name = "elide-plain" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "anstream", "async-trait", @@ -3508,7 +3508,7 @@ dependencies = [ [[package]] name = "elide-provider" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-bentoml", @@ -3525,7 +3525,7 @@ dependencies = [ [[package]] name = "elide-redaction" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "aes-gcm", "async-trait", @@ -3551,7 +3551,7 @@ dependencies = [ [[package]] name = "elide-review" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-schema", @@ -3563,7 +3563,7 @@ dependencies = [ [[package]] name = "elide-schema" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "hipstr", @@ -3576,7 +3576,7 @@ dependencies = [ [[package]] name = "elide-template" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-schema", @@ -3723,7 +3723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6616,7 +6616,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7552,7 +7552,7 @@ dependencies = [ "regex-cache", "serde", "serde_derive", - "strum 0.27.2", + "strum 0.26.3", "thiserror 2.0.21", ] @@ -8003,7 +8003,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9068,7 +9068,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9127,7 +9127,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9747,7 +9747,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9913,9 +9913,6 @@ name = "strum" version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" -dependencies = [ - "strum_macros 0.27.2", -] [[package]] name = "strum" @@ -10145,7 +10142,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -11310,7 +11307,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -11825,7 +11822,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index d9aaa80a..cf98005e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ debug = true # See for more details: https://github.com/rust-lang/cargo/issues/11329 # Elide crates -elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "6712316061b4497098ba5a7b61f7c0a7e70ca5b0", default-features = false, features = [] } +elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "296f2db896f750393da47bb849156bfc83bcf4f4", default-features = false, features = [] } # Internal crates nvisy-core = { path = "./crates/nvisy-core", version = "0.1.0" } diff --git a/crates/nvisy-core/src/health.rs b/crates/nvisy-core/src/health.rs index 7c81ece9..8b393a96 100644 --- a/crates/nvisy-core/src/health.rs +++ b/crates/nvisy-core/src/health.rs @@ -12,8 +12,9 @@ use serde::Serialize; use crate::TRACING_TARGET; -/// Operational status of a service component. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +/// Operational status of a service component, ordered from best to worst, so the +/// worst of several is their `max`. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "snake_case")] @@ -34,28 +35,19 @@ impl HealthStatus { matches!(self, Self::Healthy) } - /// Aggregates per-component results into an overall status: [`Unhealthy`] - /// when there are no components or none are healthy, [`Healthy`] when all - /// are, and [`Degraded`] otherwise. + /// Aggregates per-component results into an overall status: the worst + /// component status, or [`Unhealthy`] when there are no components. Every + /// component is a dependency the server needs, so one being down makes the + /// whole server unhealthy. /// /// [`Unhealthy`]: Self::Unhealthy - /// [`Healthy`]: Self::Healthy - /// [`Degraded`]: Self::Degraded #[must_use] pub fn from_components(components: &[ComponentHealth]) -> Self { - if components.is_empty() { - return Self::Unhealthy; - } - - let healthy = components.iter().filter(|c| c.status.is_healthy()).count(); - - if healthy == 0 { - Self::Unhealthy - } else if healthy == components.len() { - Self::Healthy - } else { - Self::Degraded - } + components + .iter() + .map(|component| component.status) + .max() + .unwrap_or(Self::Unhealthy) } } @@ -168,11 +160,26 @@ mod tests { } #[test] - fn some_healthy_is_degraded() { + fn one_unhealthy_component_is_unhealthy() { let components = [ ComponentHealth::healthy("a"), ComponentHealth::unhealthy("b"), ]; + assert_eq!( + HealthStatus::from_components(&components), + HealthStatus::Unhealthy + ); + } + + #[test] + fn one_degraded_component_is_degraded() { + let components = [ + ComponentHealth::healthy("a"), + ComponentHealth { + name: "b".into(), + status: HealthStatus::Degraded, + }, + ]; assert_eq!( HealthStatus::from_components(&components), HealthStatus::Degraded diff --git a/crates/nvisy-object-store/src/provider/mod.rs b/crates/nvisy-object-store/src/provider/mod.rs index 1f35001f..937bdb24 100644 --- a/crates/nvisy-object-store/src/provider/mod.rs +++ b/crates/nvisy-object-store/src/provider/mod.rs @@ -22,7 +22,7 @@ use crate::client::ObjectStoreClient; /// an S3 connection cannot carry Azure credentials. Each variant carries a /// shared optional `root_path` and a nested `credentials` object, giving a wire /// shape like -/// `{ "provider": "s3", "rootPath": "in/", "credentials": { "bucket": "b", "accessKeyId": "..." } }`. +/// `{ "provider": "s3", "rootPath": "in/", "credentials": { "bucket": "b", "accessKeyId": "...", "secretAccessKey": "..." } }`. /// /// Secrets are masked in [`Debug`]; serialization exists only to persist the /// config encrypted at rest, never to return it in API responses. diff --git a/crates/nvisy-postgres/src/model/mod.rs b/crates/nvisy-postgres/src/model/mod.rs index d306c0a1..89f27156 100644 --- a/crates/nvisy-postgres/src/model/mod.rs +++ b/crates/nvisy-postgres/src/model/mod.rs @@ -68,7 +68,7 @@ pub use workspace_review_comments::{ NewWorkspaceReviewComment, UpdateWorkspaceReviewComment, WorkspaceReviewComment, }; pub use workspace_review_events::{NewWorkspaceReviewEvent, WorkspaceReviewEvent}; -pub use workspace_review_links::NewReviewAssignee; +pub use workspace_review_links::{NewReviewAssignee, WorkspaceReviewApproval}; pub use workspace_reviews::{NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceReview}; pub use workspace_webhooks::{NewWorkspaceWebhook, UpdateWorkspaceWebhook, WorkspaceWebhook}; pub use workspaces::{NewWorkspace, UpdateWorkspace, Workspace}; diff --git a/crates/nvisy-postgres/src/model/workspace_review_links.rs b/crates/nvisy-postgres/src/model/workspace_review_links.rs index 795b9bb6..49940415 100644 --- a/crates/nvisy-postgres/src/model/workspace_review_links.rs +++ b/crates/nvisy-postgres/src/model/workspace_review_links.rs @@ -1,13 +1,13 @@ -//! Review assignee model: the many-to-many rows tying a review to its reviewers, -//! each carrying that reviewer's approval (`approved_at`). +//! Review link models: the many-to-many rows tying a review to its reviewers, and +//! each reviewer's approval of one specific redaction. use diesel::prelude::*; +use jiff_diesel::Timestamp; use uuid::Uuid; -use crate::schema::workspace_review_assignees; +use crate::schema::{workspace_review_approvals, workspace_review_assignees}; -/// A link assigning an account as a reviewer of a review. A new assignee starts -/// unapproved (`approved_at` defaults to NULL). +/// A link assigning an account as a reviewer of a review. #[derive(Debug, Clone, Insertable)] #[diesel(table_name = workspace_review_assignees)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -18,3 +18,19 @@ pub struct NewReviewAssignee { /// The assigned reviewer. pub account_id: Uuid, } + +/// An assignee's approval of one redaction of the review's document. At most one +/// per assignee; approving another redaction replaces it. +#[derive(Debug, Clone, PartialEq, Queryable, Selectable, Insertable)] +#[diesel(table_name = workspace_review_approvals)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct WorkspaceReviewApproval { + /// The review. + pub review_id: Uuid, + /// The approving assignee. + pub account_id: Uuid, + /// The redaction this approval endorses. + pub redaction_id: Uuid, + /// When the assignee approved it. + pub approved_at: Timestamp, +} diff --git a/crates/nvisy-postgres/src/model/workspace_reviews.rs b/crates/nvisy-postgres/src/model/workspace_reviews.rs index 2ead4f42..29a7254b 100644 --- a/crates/nvisy-postgres/src/model/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/model/workspace_reviews.rs @@ -1,13 +1,13 @@ //! Workspace review model: a named discussion on a document with an explicit //! approval lifecycle. A document has 0..N reviews, which may run concurrently (one -//! per audience). A review carries its [`ReviewStatus`], the detection it is -//! currently reviewing and the redaction it has approved (direct columns), owns a -//! stream of [`WorkspaceReviewComment`] messages and [`WorkspaceReviewEvent`] -//! timeline entries, and references its assignees — whose stamped `approved_at` -//! drive sign-off — via [`NewReviewAssignee`](super::NewReviewAssignee). +//! per audience). A review carries its [`ReviewStatus`] and the redaction its quorum +//! approved, owns a stream of [`WorkspaceReviewComment`] messages and +//! [`WorkspaceReviewEvent`] timeline entries, and references its assignees, whose +//! [`WorkspaceReviewApproval`]s of specific redactions drive sign-off. //! //! [`WorkspaceReviewComment`]: super::WorkspaceReviewComment //! [`WorkspaceReviewEvent`]: super::WorkspaceReviewEvent +//! [`WorkspaceReviewApproval`]: super::WorkspaceReviewApproval use diesel::prelude::*; use jiff_diesel::Timestamp; @@ -16,9 +16,9 @@ use uuid::Uuid; use crate::schema::workspace_reviews; use crate::types::ReviewStatus; -/// A review: a named discussion on a document, carrying its [`ReviewStatus`], the -/// detection it is currently reviewing, and the redaction it approved. Its assignees -/// and approvals live in link tables; its comments and timeline events belong to it. +/// A review: a named discussion on a document, carrying its [`ReviewStatus`] and the +/// redaction its quorum approved. Its assignees and approvals live in link tables; +/// its comments and timeline events belong to it. #[derive(Debug, Clone, PartialEq, Queryable, Selectable)] #[diesel(table_name = workspace_reviews)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -29,9 +29,8 @@ pub struct WorkspaceReview { pub workspace_id: Uuid, /// Document under review (a document may have many concurrent reviews). pub document_id: Uuid, - /// The detection currently under review; `None` before one is linked. - pub detection_id: Option, - /// The redaction bound by an approval; `None` until an approver names one. + /// The redaction the quorum approved (the output); set exactly while the + /// review is `approved`. pub redaction_id: Option, /// Account that opened the review. pub author_account_id: Uuid, @@ -57,8 +56,6 @@ pub struct NewWorkspaceReview { pub workspace_id: Uuid, /// Document under review (required). pub document_id: Uuid, - /// The detection the review opens against; `None` for a draft without one yet. - pub detection_id: Option, /// Opening author account ID (required). pub author_account_id: Uuid, /// Title (required). @@ -72,7 +69,6 @@ impl NewWorkspaceReview { Self { workspace_id, document_id, - detection_id: None, author_account_id, display_name: "A test review.".to_owned(), } @@ -81,9 +77,9 @@ impl NewWorkspaceReview { /// Data for updating a review's mutable fields. /// -/// The two id fields are doubly optional: the outer `None` leaves the column +/// `redaction_id` is doubly optional: the outer `None` leaves the column /// unchanged, an inner `Some` sets it, and an inner `None` clears it to `NULL` (so a -/// reopen can clear `redaction_id`). +/// reopen can clear it). #[derive(Debug, Clone, Default, AsChangeset)] #[diesel(table_name = workspace_reviews)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -93,8 +89,6 @@ pub struct UpdateWorkspaceReview { pub display_name: Option, /// The new review status; `None` leaves it unchanged. pub review_status: Option, - /// The detection under review; outer `None` leaves it, inner `None` clears it. - pub detection_id: Option>, - /// The bound redaction; outer `None` leaves it, inner `None` clears it. + /// The approved output; outer `None` leaves it, inner `None` clears it. pub redaction_id: Option>, } diff --git a/crates/nvisy-postgres/src/query/workspace_reviews.rs b/crates/nvisy-postgres/src/query/workspace_reviews.rs index e8ac03c8..9efcc490 100644 --- a/crates/nvisy-postgres/src/query/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/query/workspace_reviews.rs @@ -2,11 +2,11 @@ //! an explicit approval lifecycle (0..N per document, concurrent per audience): an author, //! a title, a stream of comments and timeline events, and a status (`draft` → //! `in_review` → `changes_requested`/`partially_approved` → `approved`, reopen). It -//! is anchored to its document and points at the detection it is currently reviewing -//! and the redaction it approves (direct columns, not link tables). A review is +//! is anchored to its document; each assignee's approval names the redaction it +//! endorses, and the redaction a quorum approved is the review's output. A review is //! created explicitly (not auto-created by detection/redaction). Opening a review -//! records the `review.opened` event; renaming, repointing, assignment, and each -//! lifecycle decision (`submitted`, `changes_requested`, `approved`, `reopened`) +//! records the `review.opened` event; renaming, assignment, and each lifecycle +//! decision (`submitted`, `changes_requested`, `approved`, `reopened`) //! record their own event on the review's one timeline ([`WorkspaceReviewEvent`]), //! which the reader interleaves with the comments. //! @@ -22,7 +22,7 @@ use uuid::Uuid; use super::workspace_review_events::record_event; use crate::model::{ NewReviewAssignee, NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceReview, - WorkspaceReviewEvent, + WorkspaceReviewApproval, WorkspaceReviewEvent, }; use crate::types::{ AccountRefRow, CursorPage, CursorPagination, DocumentReviewFilter, ReviewEventKind, @@ -30,7 +30,8 @@ use crate::types::{ }; use crate::{AsyncConnection, Error, PgConnection, Result, schema}; -/// A review with the people on it: its author and its assigned reviewers. +/// A review with the people on it: its author, its assigned reviewers, and their +/// approvals. #[derive(Debug, Clone)] pub struct ReviewDetails { /// The review. @@ -39,13 +40,15 @@ pub struct ReviewDetails { pub author: AccountRefRow, /// The assigned reviewers' account references (empty when unassigned). pub assignees: Vec, + /// The assignees' approvals, each naming the redaction it endorses, oldest + /// first. + pub approvals: Vec, } /// Read and write operations on document reviews. pub trait WorkspaceReviewRepository { /// Opens a new review on a document at [`ReviewStatus::Draft`], recording the - /// `review.opened` timeline event (whose target carries the detection id when it - /// opens against one), in one transaction, and returns the review. + /// `review.opened` timeline event in one transaction, and returns the review. /// `display_name` is the review's title. A document may have many concurrent /// reviews (one per audience). fn create_review( @@ -102,19 +105,6 @@ pub trait WorkspaceReviewRepository { /// hidden with the review). fn delete_review(&mut self, review_id: Uuid) -> impl Future> + Send; - /// Points a review at a detection (its current subject), recording a - /// `review.redetected` event when the target changes. Idempotent when the review - /// already points at `detection_id`. Moving an `approved` or - /// `partially_approved` review to a different detection clears its approvals - /// and approved redaction and returns it to `in_review`, since those approvals - /// endorsed the previous detection's output. Returns the review. - fn point_detection( - &mut self, - review_id: Uuid, - detection_id: Uuid, - actor: Uuid, - ) -> impl Future> + Send; - /// Assigns a reviewer to a review (idempotent). Records an `assigned` event on /// first assignment. Assignment is metadata only (who is responsible); it does /// not change the review's status. The [`AssignmentOutcome`] reports the review @@ -126,16 +116,14 @@ pub trait WorkspaceReviewRepository { actor: Uuid, ) -> impl Future> + Send; - /// Removes a reviewer from a review. Records an `unassigned` event when a link - /// existed. Does not change the review's status. The [`AssignmentOutcome`] reports - /// the review and whether a link was actually removed (`false` when the reviewer - /// was not assigned). /// Removes `account_id` from the review's assignees, recording an `unassigned` - /// event when a row was removed. If the removed reviewer had approved, their - /// approval is removed with the row, so the review's status is reconciled under - /// the same lock: should the remaining approvals fall below `required_approvals`, - /// an `approved` review is demoted (clearing its approved output) and a - /// `partially_approved` review with no approvals left returns to `in_review`. + /// event when a row was removed. The [`AssignmentOutcome`] reports whether a + /// link was removed (`false` when the reviewer was not assigned). If the removed + /// reviewer had approved, their approval goes with the row, so the review's + /// status is reconciled under the same lock, only ever downward: an `approved` + /// review whose output falls below `required_approvals` is demoted (clearing + /// its output), and a `partially_approved` review with no approvals left + /// returns to `in_review`. fn remove_assignee( &mut self, review_id: Uuid, @@ -150,7 +138,8 @@ pub trait WorkspaceReviewRepository { review_id: Uuid, ) -> impl Future>> + Send; - /// Loads the people on a review: its author and its assignees. + /// Loads the people on a review: its author, its assignees, and their + /// approvals. fn review_details( &mut self, review: WorkspaceReview, @@ -177,25 +166,25 @@ pub trait WorkspaceReviewRepository { actor: Uuid, ) -> impl Future> + Send; - /// Stamps `actor`'s approval on their assignee row (idempotent per reviewer) and - /// advances the status: once the count of approved assignees reaches - /// `required_approvals` the review becomes `approved`, otherwise - /// `partially_approved`. A given `output` binds `redaction_id` on either - /// outcome, and once bound a later approval naming a different redaction is - /// rejected (`rebind_rejected`). Records an `approved` - /// event on a new approval. Locks the review first. The caller must already be an - /// assignee (the domain layer enforces this); an un-assigned actor stamps nothing - /// and the [`ApprovalOutcome`] reports `recorded = false` with the unchanged count. + /// Records `actor`'s approval of `redaction_id` and advances the status: once + /// `required_approvals` assignees approve that same redaction the review becomes + /// `approved` with it as the output, otherwise `partially_approved`. An + /// assignee holds one approval, so approving a different redaction moves it; + /// re-approving the same one is a no-op. Records an `approved` event on a new + /// approval. Locks the review first and re-checks under the lock that it is + /// awaiting a decision. The caller must be an assignee (the domain layer + /// enforces this); an un-assigned actor records nothing, and the + /// [`ApprovalOutcome`] reports `recorded = false`. fn approve_review( &mut self, review_id: Uuid, actor: Uuid, required_approvals: u32, - output: Option, + redaction_id: Uuid, ) -> impl Future> + Send; - /// Reopens an approved review back to `in_review`, clearing its approvals and its - /// approved `redaction_id`, and recording a `reopened` event. Locks the review + /// Reopens an approved review back to `in_review`, deleting its approvals and + /// clearing its output `redaction_id`, and recording a `reopened` event. Locks the review /// first and re-checks the status under the lock: a review that is not approved is /// returned unchanged (`changed = false`), so a concurrent /// reopen that lost the race does not re-fire the event. @@ -244,19 +233,17 @@ pub struct StatusOutcome { } /// The result of an approval: the (possibly status-advanced) review, whether this -/// approval was newly recorded (`false` when the reviewer had already approved), and -/// how many distinct approvals the review now holds. +/// approval was newly recorded (`false` when the reviewer had already approved the +/// same redaction, or is not assigned), and how many approvals the named redaction +/// now holds. #[derive(Debug, Clone)] pub struct ApprovalOutcome { /// The review after the approval. pub review: WorkspaceReview, - /// Whether a new approval row was inserted (vs an idempotent re-approval). + /// Whether an approval was recorded or moved (vs an idempotent no-op). pub recorded: bool, - /// The count of distinct approvals on the review after the operation. + /// The count of approvals of the named redaction after the operation. pub approvals: u32, - /// `true` when the approval named a different output than the one already bound - /// to the review, so nothing was stamped. The domain layer maps this to a 409. - pub rebind_rejected: bool, } impl WorkspaceReviewRepository for PgConnection { @@ -269,18 +256,13 @@ impl WorkspaceReviewRepository for PgConnection { .await?; // Record the review's opening as the first timeline event, so the stream - // begins with an explicit `review.opened` entry. When the review opens - // against a detection, its target carries that detection id — the - // timeline shows the review's initial subject without a separate event. - let opened_target = review - .detection_id - .map(|detection_id| serde_json::json!({ "detectionId": detection_id })); + // begins with an explicit `review.opened` entry. record_event( conn, &review, ReviewEventKind::Opened, review.author_account_id, - opened_target, + None, ) .await?; @@ -469,58 +451,6 @@ impl WorkspaceReviewRepository for PgConnection { .await } - async fn point_detection( - &mut self, - review_id: Uuid, - detection_id: Uuid, - actor: Uuid, - ) -> Result { - self.transaction(async |conn| { - let review = lock_review(conn, review_id).await?; - - // Idempotent: already pointing at this detection records nothing. - if review.detection_id == Some(detection_id) { - return Ok(review); - } - - // Approvals endorse the previous detection's output, so moving to a - // different detection drops them (and the approved redaction) and - // returns the review to in_review, as a reopen does. - let drops_approvals = matches!( - review.review_status, - ReviewStatus::Approved | ReviewStatus::PartiallyApproved - ); - if drops_approvals { - clear_approvals(conn, review_id).await?; - } - let review = apply_update( - conn, - review_id, - UpdateWorkspaceReview { - detection_id: Some(Some(detection_id)), - review_status: drops_approvals.then_some(ReviewStatus::InReview), - redaction_id: drops_approvals.then_some(None), - ..Default::default() - }, - ) - .await?; - - record_event( - conn, - &review, - ReviewEventKind::Redetected, - actor, - Some(serde_json::json!({ - "detectionId": detection_id, - "approvalsCleared": drops_approvals, - })), - ) - .await?; - Ok(review) - }) - .await - } - async fn add_assignee( &mut self, review_id: Uuid, @@ -580,16 +510,15 @@ impl WorkspaceReviewRepository for PgConnection { let review = lock_review(conn, review_id).await?; - // Capture whether this assignee had approved before deleting the row: an - // approved reviewer's removal drops one approval, so the review's status may - // need to be recomputed below. - let had_approved: Option> = wra::table - .filter(wra::review_id.eq(review_id)) - .filter(wra::account_id.eq(account_id)) - .select(wra::approved_at) - .first(conn) - .await - .optional()?; + // Whether the reviewer held an approval: deleting the assignee row + // cascades it away, which may drop the review below quorum. + let had_approval = diesel::select(diesel::dsl::exists( + schema::workspace_review_approvals::table + .filter(schema::workspace_review_approvals::review_id.eq(review_id)) + .filter(schema::workspace_review_approvals::account_id.eq(account_id)), + )) + .get_result::(conn) + .await?; let deleted = diesel::delete( wra::table @@ -616,36 +545,38 @@ impl WorkspaceReviewRepository for PgConnection { ) .await?; - // Removing an assignee who had not approved cannot change the decision, so - // the status stands. Removing one who had approved drops an approval: if the - // remaining count no longer meets quorum, demote the review under the same - // lock so it never sits `approved` (or keeps an approved output) on fewer - // approvals than the policy requires. - let removed_an_approval = matches!(had_approved, Some(Some(_))); + // Losing an approval can only demote: an approved review whose output + // falls below quorum returns to partially_approved (or in_review when no + // approvals are left) and drops its output, and a partially approved + // review with none left returns to in_review. Reconciled under the same + // lock, and never a promotion, since no one approved anything here. let mut review = review; - if removed_an_approval - && matches!( - review.review_status, - ReviewStatus::Approved | ReviewStatus::PartiallyApproved - ) - { - let approvals = count_approvals(conn, review_id).await?; - if approvals < required_approvals.max(1) { - // Below quorum: an approved review returns to in_review and drops its - // approved output; a partially-approved review with approvals left - // stays partial, and one with none left returns to in_review. - let status = if approvals == 0 { - ReviewStatus::InReview - } else { - ReviewStatus::PartiallyApproved - }; - let clear_output = review.review_status == ReviewStatus::Approved; + if had_approval { + let demoted = match (review.review_status, review.redaction_id) { + (ReviewStatus::Approved, Some(output)) + if count_approvals(conn, review_id, output).await? + < required_approvals.max(1) => + { + Some(if has_approvals(conn, review_id).await? { + ReviewStatus::PartiallyApproved + } else { + ReviewStatus::InReview + }) + } + (ReviewStatus::PartiallyApproved, _) + if !has_approvals(conn, review_id).await? => + { + Some(ReviewStatus::InReview) + } + _ => None, + }; + if let Some(status) = demoted { review = apply_update( conn, review_id, UpdateWorkspaceReview { review_status: Some(status), - redaction_id: clear_output.then_some(None), + redaction_id: Some(None), ..Default::default() }, ) @@ -757,10 +688,10 @@ impl WorkspaceReviewRepository for PgConnection { review_id: Uuid, actor: Uuid, required_approvals: u32, - output: Option, + redaction_id: Uuid, ) -> Result { self.transaction(async |conn| { - use schema::workspace_review_assignees as wra; + use schema::{workspace_review_approvals as wrap, workspace_review_assignees as wra}; let review = lock_review(conn, review_id).await?; @@ -773,91 +704,82 @@ impl WorkspaceReviewRepository for PgConnection { review.review_status, ReviewStatus::InReview | ReviewStatus::PartiallyApproved ) { - let approvals = count_approvals(conn, review_id).await?; - return Ok(ApprovalOutcome { - review, - recorded: false, - approvals, - rebind_rejected: false, - }); - } - - // Once an earlier approval has bound an output, every later approval must - // name that same redaction (or name none and inherit it). A quorum is only - // meaningful if all its approvals endorse the same output; allowing a later - // approver to rebind would mark the review approved for a redaction an - // earlier approver never saw. Checked under the lock so the binding cannot - // change between this read and the stamp below; the domain layer maps the - // rejection to a 409. - if let (Some(bound), Some(named)) = (review.redaction_id, output) - && bound != named - { - let approvals = count_approvals(conn, review_id).await?; + let approvals = count_approvals(conn, review_id, redaction_id).await?; return Ok(ApprovalOutcome { review, recorded: false, approvals, - rebind_rejected: true, }); } - // Stamp the caller's own assignee row, but only if they are assigned and - // have not already approved (approved_at IS NULL). The row count tells us - // whether this was a new approval; an un-assigned or already-approved - // caller stamps nothing. - let stamped = diesel::update( + // Only an assignee approves. The review lock serializes this check with + // the write below, so an assignee removed concurrently cannot slip in. + let assigned = diesel::select(diesel::dsl::exists( wra::table .filter(wra::review_id.eq(review_id)) - .filter(wra::account_id.eq(actor)) - .filter(wra::approved_at.is_null()), - ) - .set(wra::approved_at.eq(now)) - .execute(conn) + .filter(wra::account_id.eq(actor)), + )) + .get_result::(conn) .await?; - // Count approved assignees now on the review (including any just stamped). - let approvals = count_approvals(conn, review_id).await?; + // The caller's current approval, if any. Approving the redaction they + // already approved is a no-op; approving another moves their approval. + let current: Option = wrap::table + .filter(wrap::review_id.eq(review_id)) + .filter(wrap::account_id.eq(actor)) + .select(wrap::redaction_id) + .first(conn) + .await + .optional()?; - // Nothing stamped: the caller was not an assignee, or had already - // approved. Idempotent, no event, no status move. - if stamped == 0 { + if !assigned || current == Some(redaction_id) { + let approvals = count_approvals(conn, review_id, redaction_id).await?; return Ok(ApprovalOutcome { review, recorded: false, approvals, - rebind_rejected: false, }); } - // The approval event carries the output redaction the approver named (if - // any), so the timeline shows which redaction was approved without a - // separate event. Binding the output on each approval (partial or quorum) - // means a later approver passing no output cannot drop an earlier binding. - let approved_target = - output.map(|redaction_id| serde_json::json!({ "redactionId": redaction_id })); + diesel::insert_into(wrap::table) + .values(( + wrap::review_id.eq(review_id), + wrap::account_id.eq(actor), + wrap::redaction_id.eq(redaction_id), + )) + .on_conflict((wrap::review_id, wrap::account_id)) + .do_update() + .set(( + wrap::redaction_id.eq(redaction_id), + wrap::approved_at.eq(now), + )) + .execute(conn) + .await?; + record_event( conn, &review, ReviewEventKind::Approved, actor, - approved_target, + Some(serde_json::json!({ "redactionId": redaction_id })), ) .await?; - // Quorum met → approved; otherwise it rests at partially_approved. The - // output binding (if any) is applied either way; an absent output leaves - // the current `redaction_id` untouched. - let status = if approvals >= required_approvals.max(1) { - ReviewStatus::Approved + // Quorum on the redaction just approved → approved with it as the output; + // otherwise it rests at partially_approved with no output. Only this + // redaction is judged, so an approval never promotes a different one. + let approvals = count_approvals(conn, review_id, redaction_id).await?; + let (status, output) = if approvals >= required_approvals.max(1) { + (ReviewStatus::Approved, Some(redaction_id)) } else { - ReviewStatus::PartiallyApproved + (ReviewStatus::PartiallyApproved, None) }; let review = apply_update( conn, review_id, UpdateWorkspaceReview { review_status: Some(status), - redaction_id: output.map(Some), + redaction_id: Some(output), ..Default::default() }, ) @@ -867,7 +789,6 @@ impl WorkspaceReviewRepository for PgConnection { review, recorded: true, approvals, - rebind_rejected: false, }) }) .await @@ -1003,33 +924,47 @@ async fn apply_update( ) } -/// Counts the review's assignees that have approved (a stamped `approved_at`). -async fn count_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result { - use schema::workspace_review_assignees as wra; +/// Counts the approvals of `redaction_id` on a review. +async fn count_approvals( + conn: &mut PgConnection, + review_id: Uuid, + redaction_id: Uuid, +) -> Result { + use schema::workspace_review_approvals as wrap; - let count: i64 = wra::table - .filter(wra::review_id.eq(review_id)) - .filter(wra::approved_at.is_not_null()) + let count: i64 = wrap::table + .filter(wrap::review_id.eq(review_id)) + .filter(wrap::redaction_id.eq(redaction_id)) .count() .get_result(conn) .await?; Ok(u32::try_from(count).unwrap_or(u32::MAX)) } -/// Clears every approval on a review (a pushback or reopen invalidates them), +/// Whether a review holds any approval. +async fn has_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result { + use schema::workspace_review_approvals as wrap; + + Ok(diesel::select(diesel::dsl::exists( + wrap::table.filter(wrap::review_id.eq(review_id)), + )) + .get_result::(conn) + .await?) +} + +/// Deletes every approval on a review (a pushback or reopen invalidates them), /// leaving the assignments themselves in place. async fn clear_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result<()> { - use schema::workspace_review_assignees as wra; + use schema::workspace_review_approvals as wrap; - diesel::update(wra::table.filter(wra::review_id.eq(review_id))) - .set(wra::approved_at.eq(None::)) + diesel::delete(wrap::table.filter(wrap::review_id.eq(review_id))) .execute(conn) .await?; Ok(()) } -/// Pairs each review with its author and its assignees, in one grouped query -/// each (no N+1), preserving the input order. A review whose author no longer +/// Pairs each review with its author, its assignees, and their approvals, in one +/// grouped query each (no N+1), preserving the input order. A review whose author no longer /// resolves is a broken invariant (the author is a live account). async fn attach_people( conn: &mut PgConnection, @@ -1063,6 +998,20 @@ async fn attach_people( by_review.entry(review_id).or_default().push(account); } + let approval_rows: Vec = schema::workspace_review_approvals::table + .filter(schema::workspace_review_approvals::review_id.eq_any(&review_ids)) + .order(schema::workspace_review_approvals::approved_at.asc()) + .select(WorkspaceReviewApproval::as_select()) + .load(conn) + .await?; + let mut approvals_by_review: HashMap> = HashMap::new(); + for approval in approval_rows { + approvals_by_review + .entry(approval.review_id) + .or_default() + .push(approval); + } + reviews .into_iter() .map(|item| { @@ -1073,10 +1022,12 @@ async fn attach_people( Error::unexpected(format!("review {} has no author account", item.id)) })?; let assignees = by_review.remove(&item.id).unwrap_or_default(); + let approvals = approvals_by_review.remove(&item.id).unwrap_or_default(); Ok(ReviewDetails { item, author, assignees, + approvals, }) }) .collect() @@ -1087,13 +1038,13 @@ mod tests { use super::count_approvals; use crate::PgConn; use crate::model::{ - NewAccount, NewWorkspaceDetection, NewWorkspaceRedaction, NewWorkspaceReview, - NewWorkspaceReviewComment, UpdateWorkspaceReviewComment, + NewAccount, NewWorkspaceRedaction, NewWorkspaceReview, NewWorkspaceReviewComment, + UpdateWorkspaceReviewComment, }; use crate::query::{ - AccountRepository, TimelineCursor, TimelineSource, WorkspaceDetectionRepository, - WorkspaceRedactionRepository, WorkspaceReviewCommentRepository, - WorkspaceReviewEventRepository, WorkspaceReviewRepository, + AccountRepository, TimelineCursor, TimelineSource, WorkspaceRedactionRepository, + WorkspaceReviewCommentRepository, WorkspaceReviewEventRepository, + WorkspaceReviewRepository, }; use crate::test_util::TestDatabase; use crate::types::{ @@ -1111,7 +1062,6 @@ mod tests { .create_review(NewWorkspaceReview { workspace_id: seeded.workspace_id, document_id: seeded.document_id, - detection_id: None, author_account_id: seeded.account_id, display_name: "Public release".to_owned(), }) @@ -1123,7 +1073,6 @@ mod tests { .create_review(NewWorkspaceReview { workspace_id: seeded.workspace_id, document_id: seeded.document_id, - detection_id: None, author_account_id: seeded.account_id, display_name: "Court filing".to_owned(), }) @@ -1507,13 +1456,13 @@ mod tests { assert!(resubmitted.changed); assert_eq!(resubmitted.review.review_status, ReviewStatus::InReview); - // approve with a single required approval: -> approved, output recorded. A - // reviewer approves by stamping their own assignee row, so assign first. + // approve with a single required approval: -> approved, output recorded. Only + // an assignee approves, so assign first. conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; let redaction_id = fixture.redaction_id; let outcome = conn - .approve_review(review.id, seeded.account_id, 1, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 1, redaction_id) .await?; assert!(outcome.recorded); assert_eq!(outcome.approvals, 1); @@ -1572,44 +1521,39 @@ mod tests { .await?; conn.submit_review(review.id, seeded.account_id).await?; - // Both reviewers must be assigned to approve (approval stamps the assignee - // row). + // Both reviewers must be assigned to approve. conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; conn.add_assignee(review.id, bob, seeded.account_id).await?; - // First of two required approvals: partially_approved, and the named output - // is bound immediately (so a later approver passing none cannot drop it). + // First of two required approvals: partially_approved, with no output until + // quorum. let first = conn - .approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert!(first.recorded); assert_eq!(first.approvals, 1); assert_eq!(first.review.review_status, ReviewStatus::PartiallyApproved); - assert_eq!(first.review.redaction_id, Some(redaction_id)); + assert_eq!(first.review.redaction_id, None); // The same reviewer approving again is an idempotent no-op. let again = conn - .approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert!(!again.recorded); assert_eq!(again.approvals, 1); assert_eq!(again.review.review_status, ReviewStatus::PartiallyApproved); - // Requesting changes while partially approved clears the accumulated approval - // (and its bound output), so quorum must be met afresh. + // Requesting changes while partially approved deletes the accumulated + // approval, so quorum must be met afresh. let pushed_back = conn.request_changes(review.id, seeded.account_id).await?; assert_eq!( pushed_back.review.review_status, ReviewStatus::ChangesRequested ); - assert_eq!( - pushed_back.review.redaction_id, None, - "the invalidated approval's output is cleared" - ); conn.submit_review(review.id, seeded.account_id).await?; let after = conn - .approve_review(review.id, seeded.account_id, 2, None) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert_eq!( after.approvals, 1, @@ -1617,16 +1561,18 @@ mod tests { ); assert_eq!(after.review.review_status, ReviewStatus::PartiallyApproved); - // The second distinct approval now meets quorum again: approved. - let second = conn.approve_review(review.id, bob, 2, None).await?; + // The second approval of the same redaction meets quorum: approved, with it + // as the output. + let second = conn.approve_review(review.id, bob, 2, redaction_id).await?; assert!(second.recorded); assert_eq!(second.approvals, 2); assert_eq!(second.review.review_status, ReviewStatus::Approved); + assert_eq!(second.review.redaction_id, Some(redaction_id)); Ok(()) } #[tokio::test] - async fn a_quorum_approval_without_output_keeps_an_earlier_one() -> anyhow::Result<()> { + async fn approvals_of_different_redactions_do_not_combine() -> anyhow::Result<()> { let db = TestDatabase::start().await; let fixture = db.seed_detection_and_redaction().await; let seeded = fixture.seeded; @@ -1637,6 +1583,15 @@ mod tests { }; let mut conn = db.client.get_connection().await?; + // A second redaction of the same detection: a different, equally valid output. + let other_redaction = conn + .create_redaction(NewWorkspaceRedaction::test( + fixture.detection_id, + seeded.account_id, + )) + .await? + .id; + let review = conn .create_review(NewWorkspaceReview::test( seeded.workspace_id, @@ -1649,32 +1604,47 @@ mod tests { .await?; conn.add_assignee(review.id, bob, seeded.account_id).await?; - // The first approver names the output; the quorum-meeting approver names none. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + // Two approvals of two different redactions are not a quorum of two: each + // redaction has one, so the review stays partially approved with no output. + conn.approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; - let approved = conn.approve_review(review.id, bob, 2, None).await?; + let split = conn + .approve_review(review.id, bob, 2, other_redaction) + .await?; + assert!(split.recorded); + assert_eq!(split.approvals, 1); + assert_eq!(split.review.review_status, ReviewStatus::PartiallyApproved); + assert_eq!(split.review.redaction_id, None); - // The review is approved and keeps the output the first approver bound; the - // absent output on the final approval does not clear it. - assert_eq!(approved.review.review_status, ReviewStatus::Approved); - assert_eq!(approved.review.redaction_id, Some(redaction_id)); + // Bob approving the first redaction moves his approval to it: quorum. + let agreed = conn.approve_review(review.id, bob, 2, redaction_id).await?; + assert!(agreed.recorded); + assert_eq!(agreed.approvals, 2); + assert_eq!(agreed.review.review_status, ReviewStatus::Approved); + assert_eq!(agreed.review.redaction_id, Some(redaction_id)); + assert_eq!( + count_approvals(&mut conn, review.id, other_redaction).await?, + 0, + "the moved approval no longer counts for the other redaction" + ); Ok(()) } #[tokio::test] - async fn a_later_approval_cannot_rebind_the_output() -> anyhow::Result<()> { + async fn a_lowered_quorum_promotes_only_the_redaction_approved() -> anyhow::Result<()> { let db = TestDatabase::start().await; let fixture = db.seed_detection_and_redaction().await; let seeded = fixture.seeded; - let redaction_id = fixture.redaction_id; - let bob = { + let leading = fixture.redaction_id; + let mut reviewers = Vec::new(); + for _ in 0..3 { let mut conn = db.client.get_connection().await?; - conn.create_account(NewAccount::test()).await?.id - }; + reviewers.push(conn.create_account(NewAccount::test()).await?.id); + } + let (alice, bob, carol) = (reviewers[0], reviewers[1], reviewers[2]); let mut conn = db.client.get_connection().await?; - // A second redaction of the same detection: a valid, different output. - let other_redaction = conn + let other = conn .create_redaction(NewWorkspaceRedaction::test( fixture.detection_id, seeded.account_id, @@ -1690,32 +1660,38 @@ mod tests { )) .await?; conn.submit_review(review.id, seeded.account_id).await?; - conn.add_assignee(review.id, seeded.account_id, seeded.account_id) - .await?; - conn.add_assignee(review.id, bob, seeded.account_id).await?; + for reviewer in [alice, bob, carol] { + conn.add_assignee(review.id, reviewer, seeded.account_id) + .await?; + } - // The first approver binds one output. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) - .await?; + // Under a quorum of three, two approvals of one redaction leave it partial. + conn.approve_review(review.id, alice, 3, leading).await?; + conn.approve_review(review.id, bob, 3, leading).await?; - // A second approver naming a different output is rejected under the lock: - // nothing is stamped, the binding stands, and the status does not advance. - let rebind = conn - .approve_review(review.id, bob, 2, Some(other_redaction)) - .await?; - assert!(rebind.rebind_rejected); - assert!(!rebind.recorded); - assert_eq!(rebind.approvals, 1); - assert_eq!(rebind.review.review_status, ReviewStatus::PartiallyApproved); - assert_eq!(rebind.review.redaction_id, Some(redaction_id)); + // The quorum is lowered to two, and Carol approves a different redaction. + // Only Carol's redaction is judged: one approval is not a quorum, so the + // review stays partial rather than approving the other redaction. + let outcome = conn.approve_review(review.id, carol, 2, other).await?; + assert!(outcome.recorded); + assert_eq!(outcome.approvals, 1); + assert_eq!( + outcome.review.review_status, + ReviewStatus::PartiallyApproved + ); + assert_eq!(outcome.review.redaction_id, None); - // The second approver endorsing the already-bound output meets quorum. - let agreed = conn - .approve_review(review.id, bob, 2, Some(redaction_id)) + // Unassigning a reviewer never promotes: Carol held the only approval of + // the other redaction, and the leading one stays short of an approval. + let removed = conn + .remove_assignee(review.id, carol, seeded.account_id, 2) .await?; - assert!(agreed.recorded); - assert_eq!(agreed.review.review_status, ReviewStatus::Approved); - assert_eq!(agreed.review.redaction_id, Some(redaction_id)); + assert!(removed.changed); + assert_eq!( + removed.review.review_status, + ReviewStatus::PartiallyApproved + ); + assert_eq!(removed.review.redaction_id, None); Ok(()) } @@ -1737,7 +1713,7 @@ mod tests { conn.submit_review(review.id, seeded.account_id).await?; conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; - conn.approve_review(review.id, seeded.account_id, 1, Some(redaction_id)) + conn.approve_review(review.id, seeded.account_id, 1, redaction_id) .await?; // A submit racing in after the review is approved finds it in a non-submittable @@ -1747,9 +1723,9 @@ mod tests { assert_eq!(outcome.review.review_status, ReviewStatus::Approved); assert_eq!(outcome.review.redaction_id, Some(redaction_id)); assert_eq!( - count_approvals(&mut conn, review.id).await?, + count_approvals(&mut conn, review.id, redaction_id).await?, 1, - "the approval stamp survives the no-op submit" + "the approval survives the no-op submit" ); Ok(()) } @@ -1779,9 +1755,9 @@ mod tests { conn.add_assignee(review.id, bob, seeded.account_id).await?; // Two approvals meet a quorum of two: approved, output bound. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + conn.approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; - let approved = conn.approve_review(review.id, bob, 2, None).await?; + let approved = conn.approve_review(review.id, bob, 2, redaction_id).await?; assert_eq!(approved.review.review_status, ReviewStatus::Approved); // Removing one approver drops to one approval, below the quorum of two: the @@ -1971,74 +1947,4 @@ mod tests { assert_eq!(paged, all); Ok(()) } - - #[tokio::test] - async fn pointing_at_another_detection_drops_approvals() -> anyhow::Result<()> { - let db = TestDatabase::start().await; - let fixture = db.seed_detection_and_redaction().await; - let seeded = fixture.seeded; - let mut conn = db.client.get_connection().await?; - - let review = conn - .create_review(NewWorkspaceReview::test( - seeded.workspace_id, - seeded.document_id, - seeded.account_id, - )) - .await?; - conn.point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - conn.submit_review(review.id, seeded.account_id).await?; - conn.add_assignee(review.id, seeded.account_id, seeded.account_id) - .await?; - let approved = conn - .approve_review(review.id, seeded.account_id, 1, Some(fixture.redaction_id)) - .await?; - assert_eq!(approved.review.review_status, ReviewStatus::Approved); - - // Re-pointing at the same detection is a no-op: the approval stands. - let same = conn - .point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - assert_eq!(same.review_status, ReviewStatus::Approved); - assert_eq!(same.redaction_id, Some(fixture.redaction_id)); - - // A different detection drops the approvals and the approved output. - let redetected = conn - .create_workspace_detection(NewWorkspaceDetection::test( - seeded.workspace_id, - seeded.account_id, - seeded.document_id, - )) - .await?; - let moved = conn - .point_detection(review.id, redetected.id, seeded.account_id) - .await?; - assert_eq!(moved.detection_id, Some(redetected.id)); - assert_eq!(moved.review_status, ReviewStatus::InReview); - assert_eq!(moved.redaction_id, None); - assert_eq!(count_approvals(&mut conn, review.id).await?, 0); - Ok(()) - } - - #[tokio::test] - async fn pointing_an_unapproved_review_keeps_its_status() -> anyhow::Result<()> { - let db = TestDatabase::start().await; - let fixture = db.seed_detection_and_redaction().await; - let seeded = fixture.seeded; - let mut conn = db.client.get_connection().await?; - - let review = conn - .create_review(NewWorkspaceReview::test( - seeded.workspace_id, - seeded.document_id, - seeded.account_id, - )) - .await?; - let moved = conn - .point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - assert_eq!(moved.review_status, ReviewStatus::Draft); - Ok(()) - } } diff --git a/crates/nvisy-postgres/src/schema.rs b/crates/nvisy-postgres/src/schema.rs index 04523284..c2ff7d32 100644 --- a/crates/nvisy-postgres/src/schema.rs +++ b/crates/nvisy-postgres/src/schema.rs @@ -478,6 +478,17 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + + workspace_review_approvals (review_id, account_id) { + review_id -> Uuid, + account_id -> Uuid, + redaction_id -> Uuid, + approved_at -> Timestamptz, + } +} + diesel::table! { use diesel::sql_types::*; @@ -485,7 +496,6 @@ diesel::table! { review_id -> Uuid, account_id -> Uuid, created_at -> Timestamptz, - approved_at -> Nullable, } } @@ -526,7 +536,6 @@ diesel::table! { id -> Uuid, workspace_id -> Uuid, document_id -> Uuid, - detection_id -> Nullable, redaction_id -> Nullable, author_account_id -> Uuid, display_name -> Text, @@ -619,6 +628,7 @@ diesel::joinable!(workspace_redactions -> accounts (account_id)); diesel::joinable!(workspace_redactions -> workspace_blobs (review_audit_blob_id)); diesel::joinable!(workspace_redactions -> workspace_detections (detection_id)); diesel::joinable!(workspace_redactions -> workspace_documents (output_document_id)); +diesel::joinable!(workspace_review_approvals -> workspace_redactions (redaction_id)); diesel::joinable!(workspace_review_assignees -> accounts (account_id)); diesel::joinable!(workspace_review_assignees -> workspace_reviews (review_id)); diesel::joinable!(workspace_review_comments -> accounts (author_account_id)); @@ -626,7 +636,6 @@ diesel::joinable!(workspace_review_comments -> workspace_reviews (review_id)); diesel::joinable!(workspace_review_events -> accounts (actor_account_id)); diesel::joinable!(workspace_review_events -> workspace_reviews (review_id)); diesel::joinable!(workspace_reviews -> accounts (author_account_id)); -diesel::joinable!(workspace_reviews -> workspace_detections (detection_id)); diesel::joinable!(workspace_reviews -> workspace_redactions (redaction_id)); diesel::joinable!(workspace_reviews -> workspaces (workspace_id)); diesel::joinable!(workspace_webhooks -> accounts (created_by)); @@ -657,6 +666,7 @@ diesel::allow_tables_to_appear_in_same_query!( workspace_policy_versions, workspace_providers, workspace_redactions, + workspace_review_approvals, workspace_review_assignees, workspace_review_comments, workspace_review_events, diff --git a/crates/nvisy-postgres/src/types/enums/review_event_kind.rs b/crates/nvisy-postgres/src/types/enums/review_event_kind.rs index 43cf4bc2..d93fdc33 100644 --- a/crates/nvisy-postgres/src/types/enums/review_event_kind.rs +++ b/crates/nvisy-postgres/src/types/enums/review_event_kind.rs @@ -7,17 +7,13 @@ db_enum! { /// /// Corresponds to the `REVIEW_EVENT_KIND` `PostgreSQL` enum. A review's stream /// interleaves comments (messages) with these events: the lifecycle (opened, - /// renamed, submitted, changes requested, approved, reopened), re-detection, and - /// assignment changes. + /// renamed, submitted, changes requested, approved, reopened) and assignment + /// changes. pub enum ReviewEventKind = "crate::schema::sql_types::ReviewEventKind" { - /// The review was opened. Its target carries the initial detection id, when - /// the review was opened against one. + /// The review was opened. Opened = "review.opened", /// The review's display name was changed. Renamed = "review.renamed", - /// The review was repointed at a newer detection (the document was - /// re-detected). Its target carries the new detection id. - Redetected = "review.redetected", /// The review was assigned to a reviewer. Assigned = "review.assigned", /// A reviewer was unassigned. @@ -26,8 +22,8 @@ db_enum! { Submitted = "review.submitted", /// A reviewer requested changes. ChangesRequested = "review.changes_requested", - /// A reviewer approved the review (quorum may require more approvals). Its - /// target carries the approved output redaction id, when one was named. + /// A reviewer approved one redaction of the review's document (quorum may + /// require more approvals of it). Its target carries that redaction id. Approved = "review.approved", /// An approved review was reopened (back to `in_review`). Reopened = "review.reopened", diff --git a/crates/nvisy-server/src/args.rs b/crates/nvisy-server/src/args.rs index e12400f6..17272919 100644 --- a/crates/nvisy-server/src/args.rs +++ b/crates/nvisy-server/src/args.rs @@ -21,7 +21,7 @@ use crate::middleware::UploadConfig; use crate::response::CookieConfig; use crate::service::{ AuthKeysConfig, CryptoConfig, EngineConfig, FileConnectorsConfig, HealthConfig, - IntegrationConfig, OidcConfig, S3Config, + IntegrationConfig, OidcConfig, S3Config, SignupConfig, }; use crate::worker::purge::PurgeConfig; @@ -30,7 +30,7 @@ pub(crate) const TRACING_TARGET_CONFIG: &str = "nvisy_server::args"; /// Every external-service and resource config [`ServiceState`] is built from. /// -/// Grouped so a binary flattens one struct rather than the ten configs it wraps; +/// Grouped so a binary flattens one struct rather than every config it wraps; /// [`ServiceState::from_config`] consumes it. The `clap::Args` derive is gated on /// the `cli` feature. /// @@ -100,6 +100,10 @@ pub struct ServiceArgs { /// Session-cookie policy (the `Secure` attribute) for browser clients. #[cfg_attr(feature = "cli", clap(flatten, next_help_heading = "Session cookies"))] pub cookie: CookieConfig, + + /// Sign-up policy (whether new accounts can be created). + #[cfg_attr(feature = "cli", clap(flatten, next_help_heading = "Sign-up"))] + pub signup: SignupConfig, } impl ServiceArgs { diff --git a/crates/nvisy-server/src/domain/workspace_detections.rs b/crates/nvisy-server/src/domain/workspace_detections.rs index 7b879871..f1caafaf 100644 --- a/crates/nvisy-server/src/domain/workspace_detections.rs +++ b/crates/nvisy-server/src/domain/workspace_detections.rs @@ -36,7 +36,7 @@ use crate::domain::output::{CreatedDetection, FoundDetection}; use crate::domain::workspace_policies::resolve_derived_policy; use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::event::EventEmitter; -use crate::service::{ArtifactReader, DetectionQueue, EngineService, event}; +use crate::service::{ArtifactReader, DetectionQueue, event}; use crate::worker::detection::DetectionJob; /// Tracing target for detection domain operations. @@ -71,7 +71,7 @@ enum CommitPolicies { /// /// Holds the Postgres client (acquiring its own connection per call), the detection /// queue (to broadcast the initial status and wake the outbox drainer after a create -/// commits), and the blob reader + engine (to load a detection's base analysis when +/// commits), and the blob reader (to load a detection's base analysis when /// validating reviewer edits against it). Resolved per request from [`ServiceState`]. /// /// [`ServiceState`]: crate::service::ServiceState @@ -80,36 +80,26 @@ pub struct WorkspaceDetectionService { postgres: PgClient, detection: DetectionQueue, reader: ArtifactReader, - engine: EngineService, } impl WorkspaceDetectionService { /// Creates a [`WorkspaceDetectionService`] over its clients. #[must_use] - pub fn new( - postgres: PgClient, - detection: DetectionQueue, - reader: ArtifactReader, - engine: EngineService, - ) -> Self { + pub fn new(postgres: PgClient, detection: DetectionQueue, reader: ArtifactReader) -> Self { Self { postgres, detection, reader, - engine, } } - /// Starts a detection for a document: validates the request synchronously, - /// snapshots the retention override from the request, and commits the detection - /// row, its start event, its review thread, and its analysis job in one - /// transaction, then broadcasts `Pending` and wakes the drainer. - /// /// Starts a detection over a document, against named policies or a label list. /// /// Validates the document and every named policy synchronously, or finds or - /// creates the derived policy for a label list, then commits and enqueues the - /// detection. An idempotency key that matches an existing detection replays it + /// creates the derived policy for a label list, and snapshots the retention + /// override from the request. Then commits the detection row, its start event, + /// and its analysis job in one transaction, broadcasts `Pending`, and wakes the + /// drainer. An idempotency key that matches an existing detection replays it /// instead of creating a new one. /// /// # Errors @@ -306,9 +296,7 @@ impl WorkspaceDetectionService { .resolve_audit_blob(&mut conn, &detection) .await? }; - self.reader - .load_audit(&self.engine, workspace_id, &blob) - .await + self.reader.load_audit(workspace_id, &blob).await } /// Loads a detection's enrichment intermediates (an image's OCR layout, an @@ -334,9 +322,7 @@ impl WorkspaceDetectionService { .resolve_intermediates_blob(&mut conn, &detection) .await? }; - self.reader - .load_intermediates(&self.engine, workspace_id, &blob) - .await + self.reader.load_intermediates(workspace_id, &blob).await } /// Persists a detection's accumulated reviewer edits (`edit_set`) under an @@ -402,7 +388,7 @@ impl WorkspaceDetectionService { /// Loads a detection's base analysis (its [`Audit`]), for validating reviewer /// edits against its report. Resolves the audit blob under a short-lived - /// connection, then decodes it with the engine (no connection held across the + /// connection, then restores it from storage (no connection held across the /// object-store round-trip). /// /// [`Audit`]: elide_pipeline::Audit @@ -422,9 +408,7 @@ impl WorkspaceDetectionService { let mut conn = self.postgres.get_connection().await?; self.reader.resolve_audit_blob(&mut conn, detection).await? }; - self.reader - .load_audit(self.engine.engine(), workspace_id, &audit_blob) - .await + self.reader.load_audit(workspace_id, &audit_blob).await } /// Loads the exact policy definitions a detection was analyzed with, from the diff --git a/crates/nvisy-server/src/domain/workspace_redactions.rs b/crates/nvisy-server/src/domain/workspace_redactions.rs index 913de9e9..d762261e 100644 --- a/crates/nvisy-server/src/domain/workspace_redactions.rs +++ b/crates/nvisy-server/src/domain/workspace_redactions.rs @@ -180,7 +180,7 @@ impl WorkspaceRedactionService { // detection analysis immutable and re-redactable. let mut reviewed = self .reader - .load_audit(&self.engine, workspace.id, &inputs.audit_blob) + .load_audit(workspace.id, &inputs.audit_blob) .await?; // Layer the detection's accumulated reviewer edits onto the working audit's @@ -442,9 +442,7 @@ impl WorkspaceRedactionService { .resolve_review_blob(&mut conn, &redaction) .await? }; - self.reader - .load_audit(&self.engine, workspace_id, &review_blob) - .await + self.reader.load_audit(workspace_id, &review_blob).await } } diff --git a/crates/nvisy-server/src/domain/workspace_reviews.rs b/crates/nvisy-server/src/domain/workspace_reviews.rs index 06cd740f..f091964e 100644 --- a/crates/nvisy-server/src/domain/workspace_reviews.rs +++ b/crates/nvisy-server/src/domain/workspace_reviews.rs @@ -1,7 +1,6 @@ //! Review domain logic: opening a review, its discussion (comments, mentions, the -//! assistant), renaming, deletion, pointing at the detection under review, the -//! approval lifecycle (submit, request changes, approve, reopen), assignment, and -//! the review queue. +//! assistant), renaming, deletion, the approval lifecycle (submit, request +//! changes, approve, reopen), assignment, and the review queue. //! //! A review is a named discussion on a document with an explicit approval lifecycle. //! Its discussion and its approval workflow share one aggregate — mention @@ -63,23 +62,19 @@ impl WorkspaceReviewService { } } - /// Opens a new review on a document with the given title, optionally against the - /// detection it will review, recording the `review.opened` event (and - /// the detection id in the opened event's target when a detection is given). + /// Opens a new review on a document with the given title, recording the + /// `review.opened` event. /// /// A document may have many concurrent reviews (one per audience). /// /// # Errors /// - /// - `NotFound` if the document, or the given detection, does not exist in the - /// workspace. - /// - `BadRequest` if the detection is for a different document than the review. + /// - `NotFound` if the document does not exist in the workspace. /// - A database error if the query fails. pub async fn open( &self, origin: event::EventOrigin<'_>, document_id: Uuid, - detection_id: Option, display_name: String, ) -> Result { let mut conn = self.postgres.get_connection().await?; @@ -89,18 +84,12 @@ impl WorkspaceReviewService { .await? .ok_or_else(|| Error::not_found(Resource::Document))?; - // A detection the review opens against must analyze the review's document. - if let Some(detection_id) = detection_id { - ensure_detection_on(&mut conn, workspace_id, detection_id, document_id).await?; - } - let review = conn .transaction(async |conn| { let review = conn .create_review(NewWorkspaceReview { workspace_id, document_id, - detection_id, author_account_id: origin.account_id, display_name, }) @@ -415,34 +404,6 @@ impl WorkspaceReviewService { Ok(()) } - /// Points a review at the detection it is currently reviewing (its subject). Used - /// on open and whenever the document is re-detected. Idempotent when the review - /// already points at the detection; moving an approved or partially approved - /// review to a different one clears its approvals and returns it to - /// `in_review`. - /// - /// # Errors - /// - /// - `NotFound` if the review or the detection does not exist in the workspace. - /// - `BadRequest` if the detection is for a different document than the review. - /// - A database error if the query fails. - pub async fn point_detection( - &self, - workspace_id: Uuid, - review_id: Uuid, - detection_id: Uuid, - actor: Uuid, - ) -> Result { - let mut conn = self.postgres.get_connection().await?; - let review = find_review(&mut conn, workspace_id, review_id).await?; - // A review's subject is always its own document's detection. - ensure_detection_on(&mut conn, workspace_id, detection_id, review.document_id).await?; - - let review = conn.point_detection(review_id, detection_id, actor).await?; - tracing::info!(target: TRACING_TARGET, "Review pointed at detection"); - Ok(conn.review_details(review).await?) - } - /// Submits (or resubmits) a review for review, moving it to `in_review` and /// raising the review-submitted event. Allowed from `draft` or /// `changes_requested`. @@ -478,17 +439,17 @@ impl WorkspaceReviewService { .await } - /// Records the caller's approval of a review (by stamping their assignee row), - /// optionally recording the approved redaction as its output. The review reaches - /// `approved` once the number of approved assignees meets the workspace's - /// `min_approvals`, otherwise it rests at `partially_approved`. Raises the - /// review-approved event only when the quorum is reached. Honors the workspace's - /// `author_can_approve` policy. + /// Records the caller's approval of `redaction_id`, a redaction of the review's + /// document. The review reaches `approved`, with that redaction as its output, + /// once the workspace's `min_approvals` assignees approve the same redaction; + /// until then it rests at `partially_approved`. A reviewer holds one approval, + /// so approving another redaction moves theirs. Raises the review-approved event + /// only when the quorum is reached. Honors the workspace's `author_can_approve` + /// policy. /// /// # Errors /// - /// - `NotFound` if the review, or the given redaction, does not exist in the - /// workspace. + /// - `NotFound` if the review or the redaction does not exist in the workspace. /// - `Conflict` if the review is not awaiting a decision. /// - `Forbidden` if the caller is not an assigned reviewer, or is the author /// approving their own review where the workspace forbids it. @@ -498,7 +459,7 @@ impl WorkspaceReviewService { &self, origin: event::EventOrigin<'_>, review_id: Uuid, - redaction_id: Option, + redaction_id: Uuid, ) -> Result { let mut conn = self.postgres.get_connection().await?; let workspace_id = origin.workspace_id; @@ -511,8 +472,8 @@ impl WorkspaceReviewService { .with_message("Only a review awaiting a decision can be approved")); } - // A reviewer approves by stamping their own assignee row, so the caller must - // be an assigned reviewer of this review. + // Only an assigned reviewer approves; their approval is recorded against + // their assignee row in the approvals table. let assignees = conn.list_review_assignees(review_id).await?; if !assignees.iter().any(|a| a.id == origin.account_id) { return Err(ErrorKind::Forbidden @@ -525,21 +486,18 @@ impl WorkspaceReviewService { .with_message("The author of a review cannot approve it in this workspace")); } - // The approved output, when given, must be a redaction of the review's own - // document. - if let Some(redaction_id) = redaction_id { - let redaction = conn - .find_redaction_in_workspace(workspace_id, redaction_id) - .await? - .ok_or_else(|| Error::not_found(Resource::Redaction))?; - let detection = conn - .find_workspace_detection_by_id(workspace_id, redaction.detection_id) - .await? - .ok_or_else(|| Error::not_found(Resource::Detection))?; - if detection.input_document_id != review.document_id { - return Err(ErrorKind::BadRequest - .with_message("Redaction is for a different document than this review")); - } + // The approved redaction must be one of the review's own document. + let redaction = conn + .find_redaction_in_workspace(workspace_id, redaction_id) + .await? + .ok_or_else(|| Error::not_found(Resource::Redaction))?; + let detection = conn + .find_workspace_detection_by_id(workspace_id, redaction.detection_id) + .await? + .ok_or_else(|| Error::not_found(Resource::Detection))?; + if detection.input_document_id != review.document_id { + return Err(ErrorKind::BadRequest + .with_message("Redaction is for a different document than this review")); } let document = review_document(&mut conn, &review).await?; @@ -550,14 +508,6 @@ impl WorkspaceReviewService { let outcome = conn .approve_review(review_id, origin.account_id, required, redaction_id) .await?; - // A later approval that names a different output than the one already - // bound is rejected under the lock: the quorum must endorse one - // redaction, so the approver either approves the bound one or reopens. - if outcome.rebind_rejected { - return Err(ErrorKind::Conflict.with_message( - "This review already has an approved redaction; approve that one or reopen the review to change it", - )); - } // Announce approval only when this call recorded a new approval that // reached quorum. `recorded` guards the lost-race case: if a concurrent // request-changes won between the unlocked pre-check and the row lock, @@ -886,25 +836,6 @@ async fn review_document(conn: &mut PgConn, review: &WorkspaceReview) -> Result< .ok_or_else(|| Error::not_found(Resource::Document)) } -/// Requires the detection to exist in the workspace and to be of `document_id` -/// (a review's subject is always its own document's detection). -async fn ensure_detection_on( - conn: &mut PgConn, - workspace_id: Uuid, - detection_id: Uuid, - document_id: Uuid, -) -> Result<()> { - let detection = conn - .find_workspace_detection_by_id(workspace_id, detection_id) - .await? - .ok_or_else(|| Error::not_found(Resource::Detection))?; - if detection.input_document_id != document_id { - return Err(ErrorKind::BadRequest - .with_message("Detection is for a different document than this review")); - } - Ok(()) -} - /// A review status transition driven by an explicit reviewer action. #[derive(Debug, Clone, Copy)] enum Transition { diff --git a/crates/nvisy-server/src/domain/workspace_webhooks.rs b/crates/nvisy-server/src/domain/workspace_webhooks.rs index 29d7ac0d..1dd35184 100644 --- a/crates/nvisy-server/src/domain/workspace_webhooks.rs +++ b/crates/nvisy-server/src/domain/workspace_webhooks.rs @@ -13,7 +13,7 @@ use nvisy_postgres::query::WorkspaceWebhookRepository; use nvisy_postgres::types::{CursorPage, CursorPagination, TimeCursor, WithAccountRef}; use nvisy_postgres::{AsyncConnection, PgClient, PgConn}; use nvisy_webhook::WebhookService; -use nvisy_webhook::provider::{WebhookContext, WebhookRequest, WebhookResponse}; +use nvisy_webhook::provider::{WebhookContext, WebhookPayload, WebhookRequest, WebhookResponse}; use url::Url; use uuid::Uuid; @@ -261,13 +261,8 @@ impl WorkspaceWebhookService { context = context.with_metadata(payload); } - let mut webhook_request = WebhookRequest::new( - url, - "webhook:test", - "This is a test webhook delivery", - context, - ) - .with_secret(secret); + let mut webhook_request = + WebhookRequest::new(url, WebhookPayload::test(context)).with_secret(secret); let headers = webhook.parsed_headers(); if !headers.is_empty() { webhook_request = diff --git a/crates/nvisy-server/src/extract/mod.rs b/crates/nvisy-server/src/extract/mod.rs index 5f6e6fe1..833266c7 100644 --- a/crates/nvisy-server/src/extract/mod.rs +++ b/crates/nvisy-server/src/extract/mod.rs @@ -8,6 +8,7 @@ mod auth; mod avatar_upload; mod idempotency_key; +mod optional_body; mod reject; mod security_context; mod valid; @@ -19,6 +20,7 @@ pub use crate::extract::auth::{ }; pub use crate::extract::avatar_upload::AvatarUpload; pub use crate::extract::idempotency_key::IdempotencyKey; +pub use crate::extract::optional_body::OptionalBody; pub use crate::extract::reject::{Json, Multipart, Path, Query}; pub use crate::extract::security_context::SecurityContext; pub use crate::extract::valid::{ValidateJson, validators}; diff --git a/crates/nvisy-server/src/extract/optional_body.rs b/crates/nvisy-server/src/extract/optional_body.rs new file mode 100644 index 00000000..b142a25f --- /dev/null +++ b/crates/nvisy-server/src/extract/optional_body.rs @@ -0,0 +1,86 @@ +//! An optional request body, documented as optional. + +use aide::OperationInput; +use aide::generate::GenContext; +use aide::openapi::{Operation, ReferenceOr, Response, StatusCode}; +use axum::extract::{FromRequest, OptionalFromRequest, Request}; + +/// Extracts body extractor `E` when the request has a body, and `None` when it +/// has none. +/// +/// A present body that fails `E`'s extraction, including one sent without its +/// content type, is still rejected, so a broken payload is never mistaken for an +/// absent one. In the `OpenAPI` spec the request +/// body is marked not required; aide's `Option` would leave it required. +#[must_use] +#[derive(Debug, Clone, Copy, Default)] +pub struct OptionalBody(pub Option); + +impl FromRequest for OptionalBody +where + E: OptionalFromRequest, + S: Send + Sync, +{ + type Rejection = E::Rejection; + + async fn from_request(req: Request, state: &S) -> Result { + E::from_request(req, state).await.map(Self) + } +} + +impl OperationInput for OptionalBody { + fn operation_input(ctx: &mut GenContext, operation: &mut Operation) { + E::operation_input(ctx, operation); + if let Some(ReferenceOr::Item(body)) = &mut operation.request_body { + body.required = false; + } + } + + fn inferred_early_responses( + ctx: &mut GenContext, + operation: &mut Operation, + ) -> Vec<(Option, Response)> { + E::inferred_early_responses(ctx, operation) + } +} + +#[cfg(test)] +mod tests { + use aide::axum::ApiRouter; + use aide::axum::routing::post; + use aide::openapi::{OpenApi, ReferenceOr}; + use schemars::JsonSchema; + use serde::Deserialize; + + use super::OptionalBody; + use crate::extract::Json; + + #[derive(Deserialize, JsonSchema)] + struct Body { + value: u32, + } + + async fn handler(OptionalBody(body): OptionalBody>) -> String { + body.map_or(0, |Json(body)| body.value).to_string() + } + + #[test] + fn documents_the_body_as_optional() { + let mut api = OpenApi::default(); + let _router: axum::Router = ApiRouter::new() + .api_route("/x", post(handler)) + .finish_api(&mut api); + + let paths = api.paths.expect("paths"); + let Some(ReferenceOr::Item(item)) = paths.paths.get("/x") else { + panic!("missing /x"); + }; + let Some(ReferenceOr::Item(body)) = + item.post.as_ref().and_then(|op| op.request_body.clone()) + else { + panic!("missing request body"); + }; + assert!(!body.required); + assert!(body.content.contains_key("application/json")); + } +} diff --git a/crates/nvisy-server/src/extract/reject/json_with_rej.rs b/crates/nvisy-server/src/extract/reject/json_with_rej.rs index d6181b72..60c1b86a 100644 --- a/crates/nvisy-server/src/extract/reject/json_with_rej.rs +++ b/crates/nvisy-server/src/extract/reject/json_with_rej.rs @@ -64,14 +64,13 @@ where return Ok(None); } - // Otherwise delegate to axum's optional JSON extraction, which still - // distinguishes no Content-Type (`None`) from a present-but-broken body - // (wrong content-type or malformed JSON → error). A broken body is - // propagated as our `Error`, not silently treated as absent. + // A non-empty body is present, so it must be JSON: a missing or wrong + // Content-Type and malformed JSON are all rejected, never read as absent + // (a body sent without its Content-Type would otherwise be ignored). let req = Request::from_parts(parts, Body::from(bytes)); - as OptionalFromRequest>::from_request(req, state) + as FromRequest>::from_request(req, state) .await - .map(|opt| opt.map(|AxumJson(value)| Self(value))) + .map(|AxumJson(value)| Some(Self(value))) .map_err(Into::into) } } @@ -200,4 +199,24 @@ mod tests { "malformed JSON is still rejected" ); } + + #[tokio::test] + async fn a_body_without_a_content_type_is_rejected_not_absent() { + let request = Request::builder() + .body(Body::from(r#"{"acceptInvite": false}"#)) + .unwrap(); + let extracted = + as OptionalFromRequest<()>>::from_request(request, &()).await; + assert!( + extracted.is_err(), + "a present body needs its JSON content type" + ); + + let empty = Request::builder().body(Body::empty()).unwrap(); + let extracted = as OptionalFromRequest<()>>::from_request(empty, &()).await; + assert!( + extracted.unwrap().is_none(), + "no body at all is still absent" + ); + } } diff --git a/crates/nvisy-server/src/handler/authentication.rs b/crates/nvisy-server/src/handler/authentication.rs index 4a64c7c9..f60642d1 100644 --- a/crates/nvisy-server/src/handler/authentication.rs +++ b/crates/nvisy-server/src/handler/authentication.rs @@ -61,9 +61,11 @@ fn signup_docs(op: TransformOperation) -> TransformOperation { op.summary("Signup") .description( "Creates a new account and starts a browser session: sets an HttpOnly session cookie \ - and a CSRF cookie, returning no body.", + and a CSRF cookie, returning no body. Returns 403 when the deployment has sign-up \ + disabled; `/capabilities/auth` reports this as `signupEnabled`.", ) .response::<204, ()>() + .response::<403, Json>() .response::<409, Json>() } diff --git a/crates/nvisy-server/src/handler/capabilities.rs b/crates/nvisy-server/src/handler/capabilities.rs index b94677a7..e0510462 100644 --- a/crates/nvisy-server/src/handler/capabilities.rs +++ b/crates/nvisy-server/src/handler/capabilities.rs @@ -24,7 +24,7 @@ use crate::handler::response::{ AuthCapabilities, ConnectorCapabilities, FileProviders, FormatCapabilities, InferenceCapabilities, RecognizerCatalog, SupportedFormat, }; -use crate::service::{EngineService, OidcService, ServiceState, format_modality}; +use crate::service::{EngineService, OidcService, ServiceState, SignupConfig, format_modality}; /// Lists the deployment's supported labels (the built-in taxonomy). async fn list_labels(_: AuthState) -> Json { @@ -134,20 +134,28 @@ fn list_formats_docs(op: TransformOperation) -> TransformOperation { .response::<200, Json>() } -/// Reports the deployment's available sign-in methods. -async fn list_auth(State(oidc): State) -> Json { +/// Reports the deployment's available sign-in methods and whether sign-up is +/// enabled. +async fn list_auth( + State(oidc): State, + State(signup): State, +) -> Json { // Password is always available; the configured OIDC providers follow. let mut methods = vec![IdentityProvider::Password]; methods.extend(oidc.configured_providers()); - Json(AuthCapabilities { methods }) + Json(AuthCapabilities { + methods, + signup_enabled: signup.enabled, + }) } fn list_auth_docs(op: TransformOperation) -> TransformOperation { op.summary("List sign-in methods") .description( "Returns the deployment's available sign-in methods: whether password sign-in is \ - enabled and which OIDC providers are configured. Unauthenticated, so a login screen \ - can render the right buttons before anyone signs in.", + enabled and which OIDC providers are configured, and whether new accounts can be \ + created (`signupEnabled`). Unauthenticated, so a login screen can render the right \ + buttons, and hide sign-up when it is disabled, before anyone signs in.", ) .response::<200, Json>() } diff --git a/crates/nvisy-server/src/handler/request/paginations.rs b/crates/nvisy-server/src/handler/request/paginations.rs index b1f1af1f..ea45060b 100644 --- a/crates/nvisy-server/src/handler/request/paginations.rs +++ b/crates/nvisy-server/src/handler/request/paginations.rs @@ -22,6 +22,7 @@ const MAX_LIMIT: u32 = 100; pub struct CursorPagination { /// The maximum number of records to return (1-100, default: 20). #[serde(skip_serializing_if = "Option::is_none")] + #[schemars(range(min = 1, max = 100))] pub limit: Option, /// Cursor pointing to the last item of the previous page. diff --git a/crates/nvisy-server/src/handler/request/workspace_detections.rs b/crates/nvisy-server/src/handler/request/workspace_detections.rs index c4caefab..7b6c7cef 100644 --- a/crates/nvisy-server/src/handler/request/workspace_detections.rs +++ b/crates/nvisy-server/src/handler/request/workspace_detections.rs @@ -52,6 +52,7 @@ pub enum DetectionSource { #[serde(rename_all = "camelCase")] Policies { /// The policies to run against. + #[schemars(length(min = 1, max = 128))] policy_ids: Vec, }, /// Built-in labels to detect and remove (e.g. `person_name`, @@ -60,6 +61,7 @@ pub enum DetectionSource { /// permission to run detections. Labels { /// The built-in labels to detect and remove. + #[schemars(length(min = 1, max = 128))] labels: Vec, }, } diff --git a/crates/nvisy-server/src/handler/request/workspace_reviews.rs b/crates/nvisy-server/src/handler/request/workspace_reviews.rs index 0a006cf1..cd1e527b 100644 --- a/crates/nvisy-server/src/handler/request/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/request/workspace_reviews.rs @@ -1,9 +1,9 @@ //! Review request types: open a review, rename it, address one by id, post and -//! edit comments, point at a detection, approve, assign/unassign, and filter the -//! review queue. +//! edit comments, approve a redaction, assign/unassign, and filter the review +//! queue. use garde::Validate; -use nvisy_postgres::types::{DetectionId, DocumentReviewFilter, RedactionId, ReviewStatus}; +use nvisy_postgres::types::{DocumentReviewFilter, RedactionId, ReviewStatus}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -19,17 +19,6 @@ pub struct WorkspaceReviewPathParams { pub review_id: Uuid, } -/// Path parameters addressing a review-to-detection link. -#[must_use] -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "camelCase")] -pub struct WorkspaceReviewDetectionPathParams { - /// Unique identifier of the review. - pub review_id: Uuid, - /// Opaque identifier of the detection to reference. - pub detection_id: DetectionId, -} - /// Request payload to open a review on a document. #[must_use] #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Validate)] @@ -39,22 +28,17 @@ pub struct CreateWorkspaceReview { /// The review's title (1-255 characters). #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank))] pub display_name: String, - /// The detection the review opens against (its subject); omit to open a draft - /// with no detection yet. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub detection_id: Option, } -/// Request payload to approve a review. +/// Request payload to approve a review: the redaction the reviewer endorses. #[must_use] -#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, Validate)] +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Validate)] #[serde(rename_all = "camelCase")] #[garde(allow_unvalidated)] pub struct ApproveWorkspaceReview { - /// The approved redaction to record as the review's output. Omit to approve - /// without (yet) binding an output. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub redaction_id: Option, + /// The redaction of the review's document being approved. Once enough + /// reviewers approve the same redaction, it becomes the review's output. + pub redaction_id: RedactionId, } /// Request payload to rename a review (set its title). diff --git a/crates/nvisy-server/src/handler/response/capabilities.rs b/crates/nvisy-server/src/handler/response/capabilities.rs index 5de2d5ce..1ca8b44f 100644 --- a/crates/nvisy-server/src/handler/response/capabilities.rs +++ b/crates/nvisy-server/src/handler/response/capabilities.rs @@ -131,17 +131,21 @@ pub struct FormatCapabilities { pub formats: Vec, } -/// The sign-in methods this deployment offers. +/// The sign-in methods this deployment offers, and whether it accepts sign-ups. /// /// Lets a client render the login screen without probing: one ordered list of /// the identity providers a person can sign in with — `password`, plus exactly /// the OIDC providers (`google`, `microsoft`, ...) whose apps are configured on -/// the server. This is pre-authentication reference data, so the endpoint is -/// unauthenticated. +/// the server — and whether new accounts can be created. This is +/// pre-authentication reference data, so the endpoint is unauthenticated. #[derive(Debug, Serialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct AuthCapabilities { /// The available sign-in methods, in the order a client should present them: /// `password` first, then each configured OIDC provider. pub methods: Vec, + /// Whether new accounts can be created, by password sign-up or by a first + /// sign-in with an OIDC provider. When `false`, only existing accounts can + /// sign in, so a client should hide its sign-up form. + pub signup_enabled: bool, } diff --git a/crates/nvisy-server/src/handler/response/workspace_reviews.rs b/crates/nvisy-server/src/handler/response/workspace_reviews.rs index 7e5317b4..cee3e91d 100644 --- a/crates/nvisy-server/src/handler/response/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/response/workspace_reviews.rs @@ -3,11 +3,11 @@ use jiff::Timestamp; use nvisy_postgres::model::{ - WorkspaceReview as ReviewModel, WorkspaceReviewComment as CommentModel, - WorkspaceReviewEvent as ReviewEventModel, + WorkspaceReview as ReviewModel, WorkspaceReviewApproval as ApprovalModel, + WorkspaceReviewComment as CommentModel, WorkspaceReviewEvent as ReviewEventModel, }; use nvisy_postgres::query::TimelineEntry; -use nvisy_postgres::types::{DetectionId, RedactionId, ReviewEventKind, ReviewStatus}; +use nvisy_postgres::types::{RedactionId, ReviewEventKind, ReviewStatus}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -16,9 +16,9 @@ use super::{AccountRef, Page}; /// Response type for a review: a named discussion on a document with an explicit /// approval lifecycle (0..N per document, concurrent per audience), opened explicitly. It -/// carries a `reviewStatus`, a `displayName`, its `assignees` (0..N reviewers), the -/// `detectionId` it is currently reviewing, and the `redactionId` it approved, if any; its -/// stream is a [`WorkspaceReviewEntry`] timeline. +/// carries a `reviewStatus`, a `displayName`, its `assignees` (0..N reviewers), their +/// `approvals` (each of one redaction), and the `redactionId` its quorum approved, if +/// any; its stream is a [`WorkspaceReviewEntry`] timeline. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct WorkspaceReview { @@ -26,12 +26,8 @@ pub struct WorkspaceReview { pub id: Uuid, /// Document under review. pub document_id: Uuid, - /// The detection the review is currently reviewing, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub detection_id: Option, - /// The redaction bound by an approval: the first approver to name one binds - /// it, so it may be present on a `partially_approved` review as well as an - /// `approved` one, and an approved review may have none. + /// The redaction the review's quorum approved: its output. Present exactly + /// when the review is `approved`. #[serde(skip_serializing_if = "Option::is_none")] pub redaction_id: Option, /// The review's title. @@ -42,33 +38,64 @@ pub struct WorkspaceReview { pub review_status: ReviewStatus, /// The reviewers assigned to this review (empty when unassigned). pub assignees: Vec, + /// The assignees' current approvals, oldest first. Each names the redaction + /// it endorses; the review is approved once enough name the same one. + pub approvals: Vec, /// When the review was created. pub created_at: Timestamp, /// When the review was last updated. pub updated_at: Timestamp, } +/// One assignee's approval of a redaction of the review's document. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceReviewApproval { + /// The approving assignee. + pub account_id: Uuid, + /// The redaction this approval endorses. + pub redaction_id: RedactionId, + /// When the assignee approved it. + pub approved_at: Timestamp, +} + +impl WorkspaceReviewApproval { + /// Creates an approval response from the database model. + #[must_use] + pub fn from_model(approval: &ApprovalModel) -> Self { + Self { + account_id: approval.account_id, + redaction_id: RedactionId::from_uuid(approval.redaction_id), + approved_at: approval.approved_at.into(), + } + } +} + /// Paginated response for reviews (the review queue, or a document's reviews). pub type WorkspaceReviewsPage = Page; impl WorkspaceReview { - /// Creates a review response from the database model, its author, and its - /// resolved assignee references (empty when unassigned). + /// Creates a review response from the database model, its author, its resolved + /// assignee references (empty when unassigned), and their approvals. #[must_use] pub fn from_model( review: &ReviewModel, author: AccountRef, assignees: Vec, + approvals: &[ApprovalModel], ) -> Self { Self { id: review.id, document_id: review.document_id, - detection_id: review.detection_id.map(DetectionId::from_uuid), redaction_id: review.redaction_id.map(RedactionId::from_uuid), display_name: review.display_name.clone(), author, review_status: review.review_status, assignees, + approvals: approvals + .iter() + .map(WorkspaceReviewApproval::from_model) + .collect(), created_at: review.created_at.into(), updated_at: review.updated_at.into(), } @@ -109,8 +136,8 @@ impl WorkspaceComment { } } -/// One non-message entry in a review timeline (opened, renamed, redetected, an -/// assignment change, submitted, changes requested, approved, or reopened). +/// One non-message entry in a review timeline (opened, renamed, an assignment +/// change, submitted, changes requested, approved, or reopened). #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct WorkspaceReviewEvent { diff --git a/crates/nvisy-server/src/handler/utility/redaction_key.rs b/crates/nvisy-server/src/handler/utility/redaction_key.rs index c8e2c4a3..e40cbe39 100644 --- a/crates/nvisy-server/src/handler/utility/redaction_key.rs +++ b/crates/nvisy-server/src/handler/utility/redaction_key.rs @@ -57,9 +57,12 @@ impl JsonSchema for RedactionKey { schemars::json_schema!({ "type": "string", "format": "byte", - "description": "A 32-byte key, base64-encoded.", + "description": "A 32-byte key, base64-encoded with padding.", "minLength": 44, "maxLength": 44, + // 32 bytes encode to 43 characters and one `=`; the last character + // carries 2 bits of the final byte and 4 zero bits. + "pattern": "^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$", }) } } diff --git a/crates/nvisy-server/src/handler/workspace_connections.rs b/crates/nvisy-server/src/handler/workspace_connections.rs index dca380aa..50cad329 100644 --- a/crates/nvisy-server/src/handler/workspace_connections.rs +++ b/crates/nvisy-server/src/handler/workspace_connections.rs @@ -25,7 +25,7 @@ use axum::http::{HeaderMap, HeaderValue, StatusCode}; use crate::domain; use crate::domain::output::ConnectionCheck; -use crate::extract::{Authorized, Json, Path, Query, ValidateJson, markers}; +use crate::extract::{Authorized, Json, OptionalBody, Path, Query, ValidateJson, markers}; use crate::handler::request::{ CreateWorkspaceConnection, CursorPagination, UpdateWorkspaceConnection, WorkspaceConnectionPathParams, WorkspaceConnectionsQuery, WorkspacePickerTokenRequest, @@ -280,7 +280,7 @@ async fn mint_picker_token( Path(path_params): Path, // Optional body: a picker that names a resource per `authenticate` command // (OneDrive) sends `{ resource }`; single-token pickers send no body. - request: Option>, + OptionalBody(request): OptionalBody>, ) -> Result<(HeaderMap, Json)> { tracing::debug!(target: TRACING_TARGET, "Minting picker token"); let resource = request.and_then(|ValidateJson(body)| body.resource); diff --git a/crates/nvisy-server/src/handler/workspace_detections.rs b/crates/nvisy-server/src/handler/workspace_detections.rs index 3facf0e2..297b3a91 100644 --- a/crates/nvisy-server/src/handler/workspace_detections.rs +++ b/crates/nvisy-server/src/handler/workspace_detections.rs @@ -23,7 +23,9 @@ use tokio_util::sync::CancellationToken; use uuid::Uuid; use crate::domain; -use crate::extract::{Authorized, IdempotencyKey, Json, Path, Query, ValidateJson, markers}; +use crate::extract::{ + Authorized, IdempotencyKey, Json, OptionalBody, Path, Query, ValidateJson, markers, +}; use crate::handler::request::{ CreateWorkspaceDetection, CursorPagination, EditWorkspaceDetection, RedactWorkspaceDetection, WorkspaceDetectionPathParams, WorkspaceDetectionsQuery, @@ -338,7 +340,7 @@ async fn redact_detection( State(redactions): State, authz: Authorized, Path(path_params): Path, - request: Option>, + OptionalBody(request): OptionalBody>, ) -> Result<(StatusCode, Json)> { tracing::debug!(target: TRACING_TARGET, "Redacting detection"); diff --git a/crates/nvisy-server/src/handler/workspace_invites.rs b/crates/nvisy-server/src/handler/workspace_invites.rs index c3000ee2..50582af4 100644 --- a/crates/nvisy-server/src/handler/workspace_invites.rs +++ b/crates/nvisy-server/src/handler/workspace_invites.rs @@ -12,8 +12,8 @@ use axum::http::StatusCode; use crate::domain; use crate::extract::{ - AuthState, Authorized, Json, Path, Query, SecurityContext, ValidateJson, WorkspaceContext, - markers, + AuthState, Authorized, Json, OptionalBody, Path, Query, SecurityContext, ValidateJson, + WorkspaceContext, markers, }; use crate::handler::request::{ CreateWorkspaceInvite, CursorPagination, GenerateWorkspaceInviteCode, InviteCodePathParams, @@ -241,6 +241,7 @@ fn generate_invite_code_docs(op: TransformOperation) -> TransformOperation { #[tracing::instrument(skip_all)] async fn preview_invite_code( State(invites): State, + _: AuthState, Path(path_params): Path, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Previewing invite code"); @@ -272,7 +273,7 @@ async fn reply_to_invite_code( auth_state: AuthState, security: SecurityContext, Path(path_params): Path, - request: Option>, + OptionalBody(request): OptionalBody>, ) -> Result<(StatusCode, Json>)> { let accept = request.is_none_or(|Json(r)| r.accept_invite); diff --git a/crates/nvisy-server/src/handler/workspace_reviews.rs b/crates/nvisy-server/src/handler/workspace_reviews.rs index e2169601..88086807 100644 --- a/crates/nvisy-server/src/handler/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/workspace_reviews.rs @@ -1,13 +1,13 @@ //! Review handlers: opening reviews, the review queue, a document's reviews, the -//! discussion (comments), the interleaved timeline, pointing at the detection under -//! review, and the review transitions (rename, delete, submit, request-changes, -//! approve, reopen, assign). A thin HTTP layer over [`WorkspaceReviewService`]. +//! discussion (comments), the interleaved timeline, and the review transitions +//! (rename, delete, submit, request-changes, approve, reopen, assign). A thin HTTP +//! layer over [`WorkspaceReviewService`]. //! //! A review is a named discussion on a document with an explicit approval lifecycle //! (0..N per document, concurrent per audience), opened explicitly by a reviewer. It is -//! anchored to its document and points at the detection it reviews and the redaction -//! it approves. Viewing and reads (`ViewReviews`); opening, commenting, pointing, -//! and the approval transitions (`Review`); renaming and deleting (`ManageReviews`); +//! anchored to its document; each approval names the redaction it endorses, and the +//! redaction a quorum approved is its output. Viewing and reads (`ViewReviews`); +//! opening, commenting, and the approval transitions (`Review`); renaming and deleting (`ManageReviews`); //! assigning (`AssignReviews`). use aide::axum::ApiRouter; @@ -22,8 +22,7 @@ use crate::extract::{Authorized, Json, Path, Query, ValidateJson, markers}; use crate::handler::request::{ CreateWorkspaceComment, CreateWorkspaceReview, CursorPagination, RenameWorkspaceReview, UpdateWorkspaceComment, WorkspaceCommentPathParams, WorkspaceDocumentPathParams, - WorkspaceReviewAssigneePathParams, WorkspaceReviewDetectionPathParams, - WorkspaceReviewPathParams, WorkspaceReviewsQuery, + WorkspaceReviewAssigneePathParams, WorkspaceReviewPathParams, WorkspaceReviewsQuery, }; use crate::handler::response::{ AccountRef, WorkspaceComment, WorkspaceReview, WorkspaceReviewEntry, WorkspaceReviewEvent, @@ -56,7 +55,6 @@ async fn open_review( .open( authz.origin(), path_params.document_id, - request.detection_id.map(|id| id.as_uuid()), request.display_name, ) .await?; @@ -365,7 +363,7 @@ fn list_review_timeline_docs(op: TransformOperation) -> TransformOperation { op.summary("List a review's timeline") .description( "Returns the review's timeline — comments and lifecycle events (opened, \ - renamed, redetected, assigned, unassigned, submitted, changes \ + renamed, assigned, unassigned, submitted, changes \ requested, approved, reopened) interleaved, oldest first, with cursor \ pagination. Requires ViewReviews.", ) @@ -408,56 +406,13 @@ async fn list_review_events( fn list_review_events_docs(op: TransformOperation) -> TransformOperation { op.summary("List a review's events") .description( - "Returns a review's activity events only (re-detection, assignment, \ + "Returns a review's activity events only (assignment, \ submission, change requests, approvals, reopen), oldest first. Requires \ ViewReviews.", ) .response::<200, Json>() } -/// Points a review at the detection it is currently reviewing. Idempotent. Used on -/// open and when the document is re-detected. Requires `Review`. -#[tracing::instrument( - skip_all, - fields( - review_id = %path_params.review_id, - detection_id = %path_params.detection_id, - ) -)] -async fn point_detection( - State(reviews): State, - authz: Authorized, - Path(path_params): Path, -) -> Result> { - tracing::debug!(target: TRACING_TARGET, "Pointing review at detection"); - - let workspace = &authz.workspace; - let review = reviews - .point_detection( - workspace.id, - path_params.review_id, - path_params.detection_id.as_uuid(), - authz.account_id, - ) - .await?; - - let response = review_details_response(review); - - Ok(Json(response)) -} - -fn point_detection_docs(op: TransformOperation) -> TransformOperation { - op.summary("Point a review at a detection") - .description( - "Points a review at the detection it is currently reviewing (idempotent). \ - Re-detecting a document repoints the review. Moving an `approved` or \ - `partially_approved` review to a different detection clears its approvals \ - and approved redaction and returns it to `in_review`, since they endorsed \ - the previous detection's output. Requires Review.", - ) - .response::<200, Json>() -} - /// Submits a review for review (from `draft` or `changes_requested`), moving it to `in_review`. Requires /// `Review`. #[tracing::instrument( @@ -547,7 +502,7 @@ async fn approve_review( .approve( authz.origin(), path_params.review_id, - request.redaction_id.map(|id| id.as_uuid()), + request.redaction_id.as_uuid(), ) .await?; @@ -559,13 +514,19 @@ async fn approve_review( fn approve_review_docs(op: TransformOperation) -> TransformOperation { op.summary("Approve a review") .description( - "Records the caller's approval and, optionally, the approved output \ - redaction. The review reaches `approved` once the workspace's required \ - approvals are in, otherwise `partially_approved`. 409 unless it is \ - awaiting a decision; 403 if the author approves their own review where \ - the workspace forbids it. Requires Review.", + "Records the caller's approval of one redaction of the review's document \ + (`redactionId`), the exact output they reviewed. The review reaches \ + `approved`, with that redaction as its output, once the workspace's \ + required number of assignees approve the same redaction; until then it is \ + `partially_approved`. A reviewer holds one approval, so approving another \ + redaction moves theirs. 409 unless the review is awaiting a decision; 403 \ + unless the caller is an assignee, or if the author approves their own \ + review where the workspace forbids it; 400 if the redaction is of another \ + document. Requires Review.", ) .response::<200, Json>() + .response::<400, Json>() + .response::<403, Json>() .response::<409, Json>() } @@ -688,7 +649,12 @@ fn review_details_response(details: ReviewDetails) -> WorkspaceReview { .into_iter() .map(AccountRef::from) .collect(); - WorkspaceReview::from_model(&details.item, details.author.into(), assignees) + WorkspaceReview::from_model( + &details.item, + details.author.into(), + assignees, + &details.approvals, + ) } /// Returns an [`ApiRouter`] with the review routes. @@ -749,9 +715,5 @@ pub fn routes() -> ApiRouter { post_with(add_review_assignee, add_review_assignee_docs) .delete_with(remove_review_assignee, remove_review_assignee_docs), ) - .api_route( - "/workspaces/{workspaceId}/reviews/{reviewId}/detections/{detectionId}", - post_with(point_detection, point_detection_docs), - ) .with_path_items(|item| item.tag("Reviews")) } diff --git a/crates/nvisy-server/src/response/auth/session.rs b/crates/nvisy-server/src/response/auth/session.rs index b042c414..ba9bde1f 100644 --- a/crates/nvisy-server/src/response/auth/session.rs +++ b/crates/nvisy-server/src/response/auth/session.rs @@ -49,7 +49,12 @@ pub struct CookieConfig { /// the browser will not store the cookie. #[cfg_attr( feature = "cli", - arg(long = "cookie-secure", env = "COOKIE_SECURE", default_value_t = true) + arg( + long = "cookie-secure", + env = "COOKIE_SECURE", + default_value_t = true, + action = clap::ArgAction::Set + ) )] pub secure: bool, } diff --git a/crates/nvisy-server/src/service/auth/account_provisioner.rs b/crates/nvisy-server/src/service/auth/account_provisioner.rs index d285d418..597dcbea 100644 --- a/crates/nvisy-server/src/service/auth/account_provisioner.rs +++ b/crates/nvisy-server/src/service/auth/account_provisioner.rs @@ -14,7 +14,7 @@ use nvisy_postgres::{AsyncConnection, Error as PgError, PgConn}; use uuid::Uuid; use crate::response::{Error, ErrorKind, Resource, Result}; -use crate::service::OidcIdentity; +use crate::service::{OidcIdentity, SignupConfig}; /// Tracing target for account provisioning. const TRACING_TARGET: &str = "nvisy_server::service::account_provisioner"; @@ -26,14 +26,21 @@ const MAX_USERNAME_ATTEMPTS: u32 = 100; /// Resolves, links, and provisions accounts for verified OIDC identities. /// -/// Stateless: every method takes the connection to act on. Resolved per request -/// from [`ServiceState`]. -/// -/// [`ServiceState`]: crate::service::ServiceState -#[derive(Clone, Copy, Default)] -pub struct AccountProvisioner; +/// Holds only the deployment's [`SignupConfig`], which decides whether a new +/// account may be provisioned; every method takes the connection to act on. +#[derive(Clone, Copy)] +pub struct AccountProvisioner { + signup: SignupConfig, +} impl AccountProvisioner { + /// Creates a provisioner that provisions new accounts only when `signup` + /// allows it. + #[must_use] + pub fn new(signup: SignupConfig) -> Self { + Self { signup } + } + /// Resolves the account for a verified OIDC identity, in order of preference: /// /// 1. **Returning user** — an identity already exists for this `(provider, @@ -51,9 +58,9 @@ impl AccountProvisioner { /// /// # Errors /// - /// Rejects a missing email, an unverified email on a link/provision, or a - /// provider slot already taken on the matched account; propagates database - /// errors. + /// Rejects a missing email, an unverified email on a link/provision, a + /// provider slot already taken on the matched account, or a provision while + /// sign-up is disabled (`Forbidden`); propagates database errors. pub async fn resolve( &self, conn: &mut PgConn, @@ -129,8 +136,10 @@ impl AccountProvisioner { } // 3. Provision a new account and its OIDC identity together, so an account - // never exists without a way to authenticate. - // + // never exists without a way to authenticate. This creates an account, so + // it needs sign-up enabled. + self.signup.ensure_enabled()?; + // Only provision on a verified email: the address becomes the new account's // primary (and its future match key for step 2), so an unverified one could // seed an account under an address the signer does not control. @@ -205,7 +214,7 @@ impl AccountProvisioner { { if existing.account_id == account_id { // Already linked to this account: nothing to do. - return self.load_active(conn, account_id).await; + return Self::load_active(conn, account_id).await; } tracing::warn!( target: TRACING_TARGET, @@ -229,7 +238,7 @@ impl AccountProvisioner { "Linked OIDC identity to the authenticated account", ); - self.load_active(conn, account_id).await + Self::load_active(conn, account_id).await } /// Refuses a sign-in or credential change for a suspended or deleted account, @@ -255,7 +264,7 @@ impl AccountProvisioner { /// # Errors /// /// Returns not-found if no account has the id, or a database error. - pub async fn load_active(&self, conn: &mut PgConn, account_id: Uuid) -> Result { + pub async fn load_active(conn: &mut PgConn, account_id: Uuid) -> Result { conn.find_account_by_id(account_id) .await? .ok_or_else(|| Error::not_found(Resource::Account)) diff --git a/crates/nvisy-server/src/service/auth/auth_flow.rs b/crates/nvisy-server/src/service/auth/auth_flow.rs index 64f51381..f3c5d7a6 100644 --- a/crates/nvisy-server/src/service/auth/auth_flow.rs +++ b/crates/nvisy-server/src/service/auth/auth_flow.rs @@ -23,7 +23,7 @@ use nvisy_postgres::{AsyncConnection, Error as PgError, PgClient}; use crate::extract::SecurityContext; use crate::handler::request::{Login, Signup}; use crate::response::{ErrorKind, Result}; -use crate::service::{AccountProvisioner, AuthIssuer, PasswordService}; +use crate::service::{AccountProvisioner, AuthIssuer, PasswordService, SignupConfig}; /// Tracing target for authentication-flow operations. const TRACING_TARGET: &str = "nvisy_server::service::auth_flow"; @@ -34,7 +34,8 @@ const TRACING_TARGET_CLEANUP: &str = "nvisy_server::service::auth_flow::cleanup" /// Orchestrates password login, signup, and logout. /// /// Holds the Postgres client (own-connection-per-call), the password service (to -/// strength-check, hash, and verify), and the auth issuer (to mint the session). +/// strength-check, hash, and verify), the auth issuer (to mint the session), and +/// the sign-up policy. /// Resolved per request from [`ServiceState`]. /// /// [`ServiceState`]: crate::service::ServiceState @@ -43,16 +44,23 @@ pub struct SignInService { postgres: PgClient, password: PasswordService, issuer: AuthIssuer, + signup: SignupConfig, } impl SignInService { /// Creates a [`SignInService`] over its clients. #[must_use] - pub fn new(postgres: PgClient, password: PasswordService, issuer: AuthIssuer) -> Self { + pub fn new( + postgres: PgClient, + password: PasswordService, + issuer: AuthIssuer, + signup: SignupConfig, + ) -> Self { Self { postgres, password, issuer, + signup, } } @@ -129,6 +137,7 @@ impl SignInService { /// /// # Errors /// + /// - `Forbidden` if sign-up is disabled. /// - A password-strength error if the password fails the policy check (see /// [`PasswordService::validate_and_hash`]). /// - `Conflict` if the email or username is already in use. @@ -137,6 +146,8 @@ impl SignInService { /// /// [`PasswordService::validate_and_hash`]: crate::service::PasswordService::validate_and_hash pub async fn signup(&self, request: Signup, security: SecurityContext) -> Result { + self.signup.ensure_enabled()?; + // Strength-check and hash before touching the database; bind the check to // the account's own fields so a password derived from the username/email is // rejected. @@ -233,9 +244,7 @@ impl SignInService { .with_message("Desktop tokens can only be minted from a browser session")); } - let account = AccountProvisioner - .load_active(&mut conn, account_id) - .await?; + let account = AccountProvisioner::load_active(&mut conn, account_id).await?; AccountProvisioner::ensure_can_sign_in(&account)?; self.issuer .issue_app_token(&mut conn, &account, security) diff --git a/crates/nvisy-server/src/service/auth/mod.rs b/crates/nvisy-server/src/service/auth/mod.rs index 168749c7..744c8b9d 100644 --- a/crates/nvisy-server/src/service/auth/mod.rs +++ b/crates/nvisy-server/src/service/auth/mod.rs @@ -1,5 +1,5 @@ //! Authentication subsystem: sign-in flows, session-token issuance and keys, -//! password handling, OIDC, and OIDC account provisioning. +//! password handling, OIDC, OIDC account provisioning, and the sign-up policy. mod account_provisioner; mod auth_flow; @@ -7,6 +7,7 @@ mod auth_issuer; mod auth_keys; mod oidc; mod password; +mod signup; pub use account_provisioner::AccountProvisioner; pub use auth_flow::SignInService; @@ -18,3 +19,4 @@ pub use oidc::{ }; pub(crate) use oidc::{OidcStateBucket, ReauthProofBucket}; pub use password::PasswordService; +pub use signup::SignupConfig; diff --git a/crates/nvisy-server/src/service/auth/oidc/mod.rs b/crates/nvisy-server/src/service/auth/oidc/mod.rs index 2588fa04..26d73be5 100644 --- a/crates/nvisy-server/src/service/auth/oidc/mod.rs +++ b/crates/nvisy-server/src/service/auth/oidc/mod.rs @@ -700,7 +700,7 @@ impl OidcService { // A suspended or deleted account must not add a credential, so gate // its status before linking — mirroring the sign-in path. AccountProvisioner::ensure_can_sign_in( - &self.provisioner.load_active(&mut conn, account_id).await?, + &AccountProvisioner::load_active(&mut conn, account_id).await?, )?; self.provisioner .link(&mut conn, account_id, flow.provider, identity) @@ -712,7 +712,7 @@ impl OidcService { // would gate a later credential-adding action anyway), so refuse it // up front. AccountProvisioner::ensure_can_sign_in( - &self.provisioner.load_active(&mut conn, account_id).await?, + &AccountProvisioner::load_active(&mut conn, account_id).await?, )?; // The verified identity must belong to the account being re-authed: diff --git a/crates/nvisy-server/src/service/auth/signup.rs b/crates/nvisy-server/src/service/auth/signup.rs new file mode 100644 index 00000000..6ec05aee --- /dev/null +++ b/crates/nvisy-server/src/service/auth/signup.rs @@ -0,0 +1,47 @@ +//! The deployment's sign-up policy. + +use crate::response::{ErrorKind, Result}; + +/// Whether new accounts can be created. +/// +/// Gates both ways an account comes into existence: password sign-up, and a +/// first OIDC sign-in whose identity matches no account. Existing accounts sign +/// in either way, and an OIDC identity still links to an existing account with +/// the same verified email. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "cli", derive(clap::Args))] +pub struct SignupConfig { + /// Whether new accounts can be created, by password sign-up or by a first + /// OIDC sign-in. Existing accounts can sign in either way + #[cfg_attr( + feature = "cli", + arg( + long = "signup-enabled", + env = "SIGNUP_ENABLED", + default_value_t = true, + action = clap::ArgAction::Set + ) + )] + pub enabled: bool, +} + +impl Default for SignupConfig { + fn default() -> Self { + Self { enabled: true } + } +} + +impl SignupConfig { + /// Rejects account creation when sign-up is disabled. + /// + /// # Errors + /// + /// `Forbidden` if sign-up is disabled. + pub fn ensure_enabled(self) -> Result<()> { + if self.enabled { + Ok(()) + } else { + Err(ErrorKind::Forbidden.with_message("Sign-up is disabled on this server")) + } + } +} diff --git a/crates/nvisy-server/src/service/blob/reader.rs b/crates/nvisy-server/src/service/blob/reader.rs index 10d67b33..c4031b0f 100644 --- a/crates/nvisy-server/src/service/blob/reader.rs +++ b/crates/nvisy-server/src/service/blob/reader.rs @@ -2,7 +2,7 @@ use elide_pipeline::entity::AuditHash; use elide_pipeline::file::Document; -use elide_pipeline::{ArtifactSet, Audit, Engine}; +use elide_pipeline::{ArtifactSet, Audit, Restorer}; use nvisy_postgres::PgConn; use nvisy_postgres::model::{Blob, WorkspaceDetection, WorkspaceDocument, WorkspaceRedaction}; use nvisy_postgres::query::WorkspaceBlobRepository; @@ -13,8 +13,9 @@ use crate::response::{ErrorKind, Result}; use crate::service::{CryptoService, Infra}; /// Loads a pipeline run's staged outputs from the first-party blob store: reads -/// and decrypts audits and enrichment intermediates, and reconstructs them -/// through the engine. Its write counterpart is [`ArtifactWriter`]. +/// and decrypts audits and enrichment intermediates, restores them, and checks +/// them against their recorded digests. Its write counterpart is +/// [`ArtifactWriter`]. /// /// Cloneable and cheap to pass around: it holds the shared [`Infra`] clients /// (all `Arc`-backed) and takes the per-request database connection as a method @@ -72,25 +73,18 @@ impl ArtifactReader { /// no database connection: only object-store I/O and decryption, so a caller /// can run it after releasing its connection. /// - /// The `engine` reconstructs the audit's report from its serialized form: an - /// [`Audit`] serializes but does not `Deserialize`, since its report tags each - /// entity group by modality name and only the engine's registry can map those - /// back to concrete types. The decoded audit is checked against the digest - /// recorded on the blob when it was written. + /// The audit is restored through [`Audit::restore`], which maps each entity + /// group's modality name back to its built-in type and checks the decoded + /// audit against the digest recorded on the blob when it was written. /// /// # Errors /// /// - `InternalServerError` if the blob's storage path is not a valid audit /// key, if the blob has no valid recorded digest, if the object is missing /// from storage, if reading its bytes fails, if decrypting them fails, or if - /// the engine cannot decode the audit or it does not match its digest. + /// the audit cannot be decoded or does not match its digest. /// - A storage error if the object store rejects the read. - pub async fn load_audit( - &self, - engine: &Engine, - workspace_id: Uuid, - audit_blob: &Blob, - ) -> Result { + pub async fn load_audit(&self, workspace_id: Uuid, audit_blob: &Blob) -> Result { let expected = recorded_digest(audit_blob)?; let plaintext = self .read_decrypted::(workspace_id, &audit_blob.storage_path, "audit") @@ -98,16 +92,15 @@ impl ArtifactReader { .ok_or_else(|| { ErrorKind::InternalServerError.with_message("Audit is missing from storage") })?; - engine - .deserialize_audit( - &expected, - &mut serde_json::Deserializer::from_slice(&plaintext), - ) - .map_err(|err| { - ErrorKind::InternalServerError - .with_message("Failed to decode audit") - .with_context(err.to_string()) - }) + Audit::restore( + &expected, + &mut serde_json::Deserializer::from_slice(&plaintext), + ) + .map_err(|err| { + ErrorKind::InternalServerError + .with_message("Failed to decode audit") + .with_context(err.to_string()) + }) } /// Resolves the blob holding a detection's enrichment intermediates. @@ -141,22 +134,20 @@ impl ArtifactReader { /// already-resolved blob. Holds no database connection: only object-store I/O /// and decryption. /// - /// The `engine` reconstructs the [`ArtifactSet`] from its serialized form: it - /// serializes but does not `Deserialize`, since each group is tagged by - /// modality name and only the engine's registry can map those back to concrete - /// artifact types. + /// The [`ArtifactSet`] is restored through the built-in [`Restorer`], which + /// maps each group's modality name back to its concrete artifact type and + /// checks the decoded set against the digest recorded on the blob. /// /// # Errors /// /// - `InternalServerError` if the blob's storage path is not a valid /// intermediates key, if the blob has no valid recorded digest, if the /// object is missing from storage, if reading its bytes fails, if decrypting - /// them fails, or if the engine cannot decode the artifacts or they do not - /// match their digest. + /// them fails, or if the artifacts cannot be decoded or do not match their + /// digest. /// - A storage error if the object store rejects the read. pub async fn load_intermediates( &self, - engine: &Engine, workspace_id: Uuid, intermediates_blob: &Blob, ) -> Result { @@ -172,8 +163,8 @@ impl ArtifactReader { ErrorKind::InternalServerError .with_message("Intermediates are missing from storage") })?; - engine - .deserialize_artifacts( + Restorer::builtin() + .restore( &expected, &mut serde_json::Deserializer::from_slice(&plaintext), ) diff --git a/crates/nvisy-server/src/service/di.rs b/crates/nvisy-server/src/service/di.rs index 9b401cd2..e1a48b35 100644 --- a/crates/nvisy-server/src/service/di.rs +++ b/crates/nvisy-server/src/service/di.rs @@ -4,8 +4,7 @@ //! Stored fields get their `FromRef` from the `#[derive(FromRef)]` on //! [`ServiceState`] (each is a field clone). This module covers the rest: //! - ambient clients cloned out of the shared [`Infra`] ([`impl_di_infra`]); -//! - stateless services composed from `Infra` ([`impl_di_compose`]) or holding -//! nothing ([`impl_di_unit`]); +//! - stateless services composed from `Infra` ([`impl_di_compose`]); //! - per-resource domain services built over the pooled client //! ([`impl_di_domain`] for the Postgres-only ones, [`impl_di_new`] for those //! that also hold one or two extra handles); @@ -51,20 +50,6 @@ macro_rules! impl_di_compose { )+}; } -/// Derives [`FromRef`] for a stateless unit service that holds nothing and -/// operates entirely on the connection passed to each method. -/// -/// [`FromRef`]: axum::extract::FromRef -macro_rules! impl_di_unit { - ($($t:ident),+ $(,)?) => {$( - impl FromRef for $t { - fn from_ref(_state: &ServiceState) -> Self { - $t - } - } - )+}; -} - /// Derives [`FromRef`] for a per-resource domain service built over the Postgres /// client alone. Each holds only the client and acquires its own connection per /// call, so construction is a cheap clone. @@ -116,10 +101,6 @@ impl_di_compose!( NotificationEmitter => NotificationEmitter::new, ); -// Stateless unit services, holding nothing and acting on the connection passed to -// each method: -impl_di_unit!(AccountProvisioner); - // Per-resource domain services built over the Postgres client alone: impl_di_domain!( crate::domain::AccountService, @@ -176,11 +157,11 @@ impl_di_new! { // undecodable format). DocumentStager => |state| state.infra.blobs.clone(), state.crypto.clone(), state.engine.clone(); // The detection queue (broadcast status and wake the drainer after a create), - // plus the blob reader + engine (load a detection's base analysis to validate - // reviewer edits against it before storing them). + // plus the blob reader (load a detection's base analysis to validate reviewer + // edits against it before storing them). crate::domain::WorkspaceDetectionService => |state| state.infra.postgres.clone(), DetectionQueue::from_ref(state), - ArtifactReader::from_ref(state), state.engine.clone(); + ArtifactReader::from_ref(state); // The detection service (find a detection, resolve its pinned policies), the // blob reader/writer (load the analysis, stage the outputs), and the engine. crate::domain::WorkspaceRedactionService => @@ -202,7 +183,7 @@ impl FromRef for OidcService { state.infra.postgres.clone(), state.infra.nats.clone(), AuthIssuer::from_ref(state), - AccountProvisioner, + AccountProvisioner::new(state.signup), ) } } diff --git a/crates/nvisy-server/src/service/emitter/webhook.rs b/crates/nvisy-server/src/service/emitter/webhook.rs index bd6ddc18..b9c89d24 100644 --- a/crates/nvisy-server/src/service/emitter/webhook.rs +++ b/crates/nvisy-server/src/service/emitter/webhook.rs @@ -99,6 +99,7 @@ impl WebhookEmitter { let mut first_error = None; for webhook in &webhooks { let job = WebhookJob { + delivery_id: Uuid::now_v7(), webhook_id: webhook.id, workspace_id, event, diff --git a/crates/nvisy-server/src/service/health/service.rs b/crates/nvisy-server/src/service/health/service.rs index bf94c867..c26f5d78 100644 --- a/crates/nvisy-server/src/service/health/service.rs +++ b/crates/nvisy-server/src/service/health/service.rs @@ -160,12 +160,15 @@ mod tests { } #[tokio::test] - async fn some_healthy_is_degraded() { + async fn one_unhealthy_dependency_is_unhealthy() { let service = service(vec![ checker("a", HealthStatus::Healthy), checker("b", HealthStatus::Unhealthy), ]); - assert_eq!(service.report().await.report.status, HealthStatus::Degraded); + assert_eq!( + service.report().await.report.status, + HealthStatus::Unhealthy + ); } #[tokio::test] diff --git a/crates/nvisy-server/src/service/mod.rs b/crates/nvisy-server/src/service/mod.rs index 2b27ba08..203b704a 100644 --- a/crates/nvisy-server/src/service/mod.rs +++ b/crates/nvisy-server/src/service/mod.rs @@ -32,7 +32,7 @@ use crate::response::CookieConfig; pub use crate::service::auth::{ AccountProvisioner, AuthIssuer, AuthKeys, AuthKeysConfig, CallbackOutcome, ConsumedFlow, OidcAuthorization, OidcConfig, OidcConfigured, OidcError, OidcIdentity, OidcPurpose, - OidcService, PasswordService, RedirectKind, SignInService, + OidcService, PasswordService, RedirectKind, SignInService, SignupConfig, }; pub(crate) use crate::service::auth::{OidcStateBucket, ReauthProofBucket}; pub use crate::service::avatar::{ @@ -145,6 +145,10 @@ pub struct ServiceState { // Session-cookie policy (the `Secure` attribute) for browser clients. pub cookie: CookieConfig, + // Sign-up policy, held by the sign-in service and the OIDC account + // provisioner, and reported by the auth capabilities. + pub signup: SignupConfig, + // Workspace-purge policy (the soft-delete grace window), consumed by the // purge worker at spawn. Not an extractor, so it is skipped. #[from_ref(skip)] @@ -243,7 +247,12 @@ impl ServiceState { let password = PasswordService::new(); let user_agent_parser = UserAgentParser::new(); let issuer = AuthIssuer::new(session_keys.clone(), user_agent_parser.clone()); - let sign_in = SignInService::new(infra.postgres.clone(), password.clone(), issuer); + let sign_in = SignInService::new( + infra.postgres.clone(), + password.clone(), + issuer, + args.signup, + ); let service_state = Self { infra, @@ -265,6 +274,7 @@ impl ServiceState { user_agent_parser, upload: args.upload, cookie: args.cookie, + signup: args.signup, purge_config: args.purge, }; diff --git a/crates/nvisy-server/src/test_util.rs b/crates/nvisy-server/src/test_util.rs index 98a921e8..cf97f2e1 100644 --- a/crates/nvisy-server/src/test_util.rs +++ b/crates/nvisy-server/src/test_util.rs @@ -34,7 +34,7 @@ use crate::middleware::{OpenApiConfig, RouterOpenApiExt, UploadConfig}; use crate::response::CookieConfig; use crate::service::{ AuthKeys, AuthKeysConfig, CryptoConfig, CryptoService, EngineConfig, FileConnectorsConfig, - HealthConfig, IntegrationConfig, OidcConfig, ServiceState, + HealthConfig, IntegrationConfig, OidcConfig, ServiceState, SignupConfig, }; use crate::worker::purge::PurgeConfig; @@ -89,13 +89,25 @@ impl TestApp { /// Panics if any container fails to start or the service state cannot be /// assembled — a test cannot proceed otherwise. pub async fn spawn() -> Self { + Self::spawn_with(|_| {}).await + } + + /// Like [`spawn`](Self::spawn), but lets `configure` adjust the + /// [`ServiceArgs`] before the state is assembled, for a test that needs a + /// non-default deployment setting. + /// + /// # Panics + /// + /// Panics if any container fails to start or the service state cannot be + /// assembled. + pub async fn spawn_with(configure: impl FnOnce(&mut ServiceArgs)) -> Self { // The build future is large (it constructs the whole `ServiceArgs` and // `ServiceState` across several awaits); box it so a test holding a // `TestApp::spawn().await` does not inherit that size. - Box::pin(Self::spawn_inner()).await + Box::pin(Self::spawn_inner(configure)).await } - async fn spawn_inner() -> Self { + async fn spawn_inner(configure: impl FnOnce(&mut ServiceArgs)) -> Self { let db = TestDatabase::start().await; let nats = TestNats::start().await; let s3 = TestBlobStore::start().await; @@ -110,7 +122,7 @@ impl TestApp { // The key configs go unused by `assemble` (the built services above are // injected), so their defaults are placeholders. - let args = ServiceArgs { + let mut args = ServiceArgs { postgres: db.client.config().clone(), nats: nats.client.config().clone(), s3: s3.config.clone(), @@ -124,7 +136,9 @@ impl TestApp { oidc: OidcConfig::default(), upload: UploadConfig::default(), cookie: CookieConfig::default(), + signup: SignupConfig::default(), }; + configure(&mut args); let webhook = ReqwestClient::default().into_service(); let state = ServiceState::assemble(args, webhook, crypto, keys.clone()) diff --git a/crates/nvisy-server/src/worker/webhook/job.rs b/crates/nvisy-server/src/worker/webhook/job.rs index 4a813fc8..da139410 100644 --- a/crates/nvisy-server/src/worker/webhook/job.rs +++ b/crates/nvisy-server/src/worker/webhook/job.rs @@ -16,6 +16,9 @@ pub type WebhookStream = nvisy_nats::stream::WebhookStream; /// plaintext signing secret never travels over — or rests in — NATS. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WebhookJob { + /// Identifies this delivery across every attempt, sent to the receiver so it + /// can drop a redelivered duplicate. + pub delivery_id: Uuid, /// The webhook to deliver to. pub webhook_id: Uuid, /// The workspace the webhook belongs to (the decryption key scope). diff --git a/crates/nvisy-server/src/worker/webhook/worker.rs b/crates/nvisy-server/src/worker/webhook/worker.rs index 9596a193..e13f066f 100644 --- a/crates/nvisy-server/src/worker/webhook/worker.rs +++ b/crates/nvisy-server/src/worker/webhook/worker.rs @@ -11,7 +11,7 @@ use nvisy_postgres::PgConn; use nvisy_postgres::model::WorkspaceWebhook; use nvisy_postgres::query::WorkspaceWebhookRepository; use nvisy_webhook::WebhookService; -use nvisy_webhook::provider::{WebhookContext, WebhookRequest}; +use nvisy_webhook::provider::{WebhookContext, WebhookPayload, WebhookRequest}; use tokio_util::sync::CancellationToken; use url::Url; use uuid::Uuid; @@ -230,9 +230,9 @@ impl WebhookDeliveryWorker { tracing::debug!( target: TRACING_TARGET, - request_id = %request.request_id, + delivery_id = %request.payload.delivery_id, webhook_id = %webhook.id, - event = %request.event, + event = %request.payload.event, "Delivering webhook" ); @@ -255,7 +255,7 @@ impl WebhookDeliveryWorker { if response.is_success() { tracing::debug!( target: TRACING_TARGET, - request_id = %request.request_id, + delivery_id = %request.payload.delivery_id, webhook_id = %webhook.id, status_code = response.status_code, "Webhook delivered successfully" @@ -273,7 +273,7 @@ impl WebhookDeliveryWorker { if is_permanent_failure(response.status_code) { tracing::warn!( target: TRACING_TARGET, - request_id = %request.request_id, + delivery_id = %request.payload.delivery_id, webhook_id = %webhook.id, status_code = response.status_code, "Webhook delivery permanently rejected" @@ -282,7 +282,7 @@ impl WebhookDeliveryWorker { } else { tracing::warn!( target: TRACING_TARGET, - request_id = %request.request_id, + delivery_id = %request.payload.delivery_id, webhook_id = %webhook.id, status_code = response.status_code, "Webhook delivery returned non-success status" @@ -361,7 +361,6 @@ impl WebhookDeliveryWorker { let secret = self.decrypt_secret(webhook, job.workspace_id)?; - let event = job.event.to_string(); let mut context = WebhookContext::new(webhook.id, job.workspace_id, job.resource_id) .with_resource_type(job.event.category()); if let Some(account_id) = job.triggered_by { @@ -371,7 +370,8 @@ impl WebhookDeliveryWorker { context = context.with_metadata(metadata.clone()); } - let mut request = WebhookRequest::new(url, &event, format!("Event: {event}"), context) + let payload = WebhookPayload::new(job.delivery_id, job.event.to_string(), context); + let mut request = WebhookRequest::new(url, payload) .with_timeout(DEFAULT_DELIVERY_TIMEOUT) .with_secret(secret); diff --git a/crates/nvisy-server/tests/openapi.rs b/crates/nvisy-server/tests/openapi.rs index 43679b26..1199d9f6 100644 --- a/crates/nvisy-server/tests/openapi.rs +++ b/crates/nvisy-server/tests/openapi.rs @@ -70,3 +70,103 @@ async fn detection_create_declares_the_idempotency_key() { assert_eq!(header["schema"]["minLength"], 1); assert_eq!(header["schema"]["maxLength"], 255); } + +/// Operations whose body may be omitted document it as not required. +#[tokio::test] +async fn optional_request_bodies_are_not_required() { + let app = TestApp::spawn().await; + let spec = app.openapi().await; + + for path in [ + "/workspaces/{workspaceId}/detections/{detectionId}/redactions", + "/workspaces/{workspaceId}/connections/{connectionId}/picker-token", + "/invites/code/{inviteCode}", + ] { + let body = &spec["paths"][path]["post"]["requestBody"]; + assert!(body.is_object(), "{path} documents a request body"); + assert!( + body.get("required") + .is_none_or(|required| required == false), + "{path} marks its optional body as required", + ); + } +} + +/// Schema bounds match what the server enforces, so a generated client rejects +/// what the server would. +#[tokio::test] +async fn schema_bounds_match_the_server() { + let app = TestApp::spawn().await; + let spec = app.openapi().await; + let schemas = &spec["components"]["schemas"]; + + let limit = spec["paths"]["/workspaces"]["get"]["parameters"] + .as_array() + .expect("the operation has parameters") + .iter() + .find(|p| p["name"] == "limit") + .expect("the limit parameter is declared"); + assert_eq!(limit["schema"]["minimum"], 1); + assert_eq!(limit["schema"]["maximum"], 100); + + let sources = schemas["CreateWorkspaceDetection"]["oneOf"] + .as_array() + .expect("detection sources are a oneOf"); + for (source, field) in [(0, "policyIds"), (1, "labels")] { + let list = &sources[source]["properties"][field]; + assert_eq!(list["minItems"], 1, "{field} minItems"); + assert_eq!(list["maxItems"], 128, "{field} maxItems"); + } + + assert_eq!( + schemas["RedactionKey"]["pattern"], + "^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$" + ); +} + +/// The invite-code preview needs a signed-in caller, so it declares the bearer +/// scheme. +#[tokio::test] +async fn invite_preview_declares_bearer_auth() { + let app = TestApp::spawn().await; + let spec = app.openapi().await; + + let security = &spec["paths"]["/invites/code/{inviteCode}"]["get"]["security"]; + assert!( + security + .as_array() + .is_some_and(|requirements| requirements.iter().any(|r| r.get("BearerAuth").is_some())), + "the preview declares BearerAuth, got {security}", + ); +} + +/// An approval names the redaction it endorses, and a review no longer carries a +/// re-pointable detection. +#[tokio::test] +async fn review_approvals_are_bound_to_a_redaction() { + let app = TestApp::spawn().await; + let spec = app.openapi().await; + let schemas = &spec["components"]["schemas"]; + + let required = schemas["ApproveWorkspaceReview"]["required"] + .as_array() + .expect("the approve body declares required fields"); + assert!(required.iter().any(|field| field == "redactionId")); + + let review = &schemas["WorkspaceReview"]["properties"]; + assert!( + review.get("approvals").is_some(), + "reviews expose approvals" + ); + assert!( + review.get("detectionId").is_none(), + "reviews no longer carry a detection pointer" + ); + + assert!( + spec["paths"] + .get("/workspaces/{workspaceId}/reviews/{reviewId}/detections/{detectionId}") + .is_none(), + "the re-pointing route is gone" + ); +} diff --git a/crates/nvisy-server/tests/signup.rs b/crates/nvisy-server/tests/signup.rs new file mode 100644 index 00000000..d8de7e47 --- /dev/null +++ b/crates/nvisy-server/tests/signup.rs @@ -0,0 +1,53 @@ +//! End-to-end tests for the sign-up policy, run against a real containerized +//! server via [`TestApp`]. +//! +//! Requires the `test_util` feature (which brings up the container helpers) and +//! Docker; run with `cargo test -p nvisy-server --features test_util`. + +#![cfg(feature = "test_util")] + +use axum::http::StatusCode; +use nvisy_server::test_util::TestApp; +use serde_json::json; + +fn signup_body() -> serde_json::Value { + json!({ + "username": "new-user", + "emailAddress": "new-user@example.com", + "password": "a sturdy passphrase 4821", + }) +} + +/// With sign-up enabled (the default), a password sign-up creates the account. +#[tokio::test] +async fn signup_succeeds_when_enabled() { + let app = TestApp::spawn().await; + + let response = app.server().post("/auth/signup").json(&signup_body()).await; + + assert_eq!(response.status_code(), StatusCode::NO_CONTENT); +} + +/// With sign-up disabled, a password sign-up is refused before any account is +/// created. +#[tokio::test] +async fn signup_is_forbidden_when_disabled() { + let app = TestApp::spawn_with(|args| args.signup.enabled = false).await; + + let response = app.server().post("/auth/signup").json(&signup_body()).await; + + assert_eq!(response.status_code(), StatusCode::FORBIDDEN); +} + +/// The auth capabilities report the sign-up policy, so a client can hide its +/// sign-up form. +#[tokio::test] +async fn auth_capabilities_report_the_signup_policy() { + let enabled = TestApp::spawn().await; + let body: serde_json::Value = enabled.server().get("/capabilities/auth").await.json(); + assert_eq!(body["signupEnabled"], true); + + let disabled = TestApp::spawn_with(|args| args.signup.enabled = false).await; + let body: serde_json::Value = disabled.server().get("/capabilities/auth").await.json(); + assert_eq!(body["signupEnabled"], false); +} diff --git a/crates/nvisy-webhook/src/provider/context.rs b/crates/nvisy-webhook/src/provider/context.rs index 41f526fc..15410c17 100644 --- a/crates/nvisy-webhook/src/provider/context.rs +++ b/crates/nvisy-webhook/src/provider/context.rs @@ -6,6 +6,7 @@ use uuid::Uuid; /// Contextual data included with webhook payloads. #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] pub struct WebhookContext { /// Unique identifier for the webhook configuration that triggered this delivery. pub webhook_id: Uuid, diff --git a/crates/nvisy-webhook/src/provider/request.rs b/crates/nvisy-webhook/src/provider/request.rs index 4358a889..9178ebe6 100644 --- a/crates/nvisy-webhook/src/provider/request.rs +++ b/crates/nvisy-webhook/src/provider/request.rs @@ -11,7 +11,11 @@ use uuid::Uuid; use super::WebhookContext; -/// A webhook delivery request. +/// The event a test delivery carries. +const TEST_EVENT: &str = "webhook:test"; + +/// A webhook delivery request: the [`WebhookPayload`] to send, and where and how +/// to send it. /// /// This is the input to the delivery client, assembled at delivery time from a /// webhook's current configuration. It is never serialized onto NATS (the queued @@ -19,16 +23,10 @@ use super::WebhookContext; /// without ever crossing — or resting in — the message stream. #[derive(Debug, Clone)] pub struct WebhookRequest { - /// Unique identifier for this request. - pub request_id: Uuid, /// The webhook endpoint URL. pub url: Url, - /// The event type that triggered this webhook delivery. - pub event: String, - /// Human-readable message describing the event. - pub message: String, - /// Additional context about the event. - pub context: WebhookContext, + /// The payload sent as the JSON body, signed when a secret is set. + pub payload: WebhookPayload, /// Custom headers to include in the request. pub headers: HashMap, /// Optional request timeout (uses client default if not set). @@ -38,36 +36,19 @@ pub struct WebhookRequest { } impl WebhookRequest { - /// Creates a new webhook request. - pub fn new( - url: Url, - event: impl Into, - message: impl Into, - context: WebhookContext, - ) -> Self { + /// Creates a request delivering `payload` to `url`, with no custom headers, + /// the client's default timeout, and no signature. + #[must_use] + pub fn new(url: Url, payload: WebhookPayload) -> Self { Self { - request_id: Uuid::now_v7(), url, - event: event.into(), - message: message.into(), - context, + payload, headers: HashMap::new(), timeout: None, secret: None, } } - /// Creates a test request for webhook testing. - #[must_use] - pub fn test(url: Url, webhook_id: Uuid, workspace_id: Uuid) -> Self { - Self::new( - url, - "webhook:test", - "This is a test webhook delivery", - WebhookContext::test(webhook_id, workspace_id), - ) - } - /// Sets the request timeout. #[must_use] pub fn with_timeout(mut self, timeout: Duration) -> Self { @@ -95,31 +76,24 @@ impl WebhookRequest { self.secret = Some(Secret::new(secret.into())); self } - - /// Creates a payload from this request without consuming it. - #[must_use] - pub fn to_payload(&self) -> WebhookPayload { - WebhookPayload { - event: self.event.clone(), - message: self.message.clone(), - context: self.context.clone(), - timestamp: Timestamp::now(), - } - } } -/// The webhook payload structure sent to webhook endpoints. +/// The webhook payload sent to an endpoint as the JSON body. /// -/// This payload is signed with HMAC-SHA256 when a webhook secret is configured. +/// This payload is signed with HMAC-SHA256 when a webhook secret is configured, +/// so every field, the delivery id included, is covered by the signature. #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] pub struct WebhookPayload { + /// Identifies the delivery: the same on every attempt, so a receiver can + /// drop a retried duplicate. Also sent as the `X-Webhook-Delivery-Id` + /// header. + pub delivery_id: Uuid, + /// The event type that triggered this webhook delivery. pub event: String, - /// Human-readable message describing the event. - pub message: String, - /// Additional context about the event. pub context: WebhookContext, @@ -128,42 +102,59 @@ pub struct WebhookPayload { pub timestamp: Timestamp, } +impl WebhookPayload { + /// Creates the payload of delivery `delivery_id` for `event`, timestamped now. + #[must_use] + pub fn new(delivery_id: Uuid, event: impl Into, context: WebhookContext) -> Self { + Self { + delivery_id, + event: event.into(), + context, + timestamp: Timestamp::now(), + } + } + + /// Creates a test delivery's payload: the `webhook:test` event with `context`, + /// as a delivery of its own. + #[must_use] + pub fn test(context: WebhookContext) -> Self { + Self::new(Uuid::now_v7(), TEST_EVENT, context) + } +} + #[cfg(test)] mod tests { use super::*; #[test] - fn test_request_creation() { + fn a_request_carries_its_payload() { let webhook_id = Uuid::now_v7(); let workspace_id = Uuid::now_v7(); let resource_id = Uuid::now_v7(); + let delivery_id = Uuid::now_v7(); let url = Url::parse("https://example.com/webhook").unwrap(); let context = WebhookContext::new(webhook_id, workspace_id, resource_id); - let request = WebhookRequest::new( - url.clone(), - "file:created", - "A new file was created", - context, - ); + let payload = WebhookPayload::new(delivery_id, "file:created", context); + let request = WebhookRequest::new(url.clone(), payload); assert_eq!(request.url, url); - assert_eq!(request.event, "file:created"); - assert_eq!(request.context.webhook_id, webhook_id); + assert_eq!(request.payload.delivery_id, delivery_id); + assert_eq!(request.payload.event, "file:created"); + assert_eq!(request.payload.context.webhook_id, webhook_id); assert!(request.timeout.is_none()); } #[test] - fn test_request_to_payload() { + fn a_test_payload_is_its_own_delivery() { let webhook_id = Uuid::now_v7(); let workspace_id = Uuid::now_v7(); - let url = Url::parse("https://example.com/webhook").unwrap(); - let request = WebhookRequest::test(url, webhook_id, workspace_id); - let payload = request.to_payload(); + let first = WebhookPayload::test(WebhookContext::test(webhook_id, workspace_id)); + let second = WebhookPayload::test(WebhookContext::test(webhook_id, workspace_id)); - assert_eq!(payload.event, "webhook:test"); - assert_eq!(payload.context.webhook_id, webhook_id); - assert_eq!(payload.context.workspace_id, workspace_id); + assert_eq!(first.event, "webhook:test"); + assert_eq!(first.context.workspace_id, workspace_id); + assert_ne!(first.delivery_id, second.delivery_id); } } diff --git a/crates/nvisy-webhook/src/provider/response.rs b/crates/nvisy-webhook/src/provider/response.rs index e3f44c1c..0ff9c6a9 100644 --- a/crates/nvisy-webhook/src/provider/response.rs +++ b/crates/nvisy-webhook/src/provider/response.rs @@ -9,8 +9,8 @@ use uuid::Uuid; pub struct WebhookResponse { /// Unique identifier for this response. pub response_id: Uuid, - /// Request ID this response corresponds to. - pub request_id: Uuid, + /// The delivery this response answers. + pub delivery_id: Uuid, /// HTTP status code from the webhook endpoint (0 if request failed before response). pub status_code: u16, /// Timestamp when the request was initiated. @@ -22,10 +22,10 @@ pub struct WebhookResponse { impl WebhookResponse { /// Creates a new webhook response. #[must_use] - pub fn new(request_id: Uuid, status_code: u16, started_at: Timestamp) -> Self { + pub fn new(delivery_id: Uuid, status_code: u16, started_at: Timestamp) -> Self { Self { response_id: Uuid::now_v7(), - request_id, + delivery_id, status_code, started_at, finished_at: Timestamp::now(), @@ -51,12 +51,12 @@ mod tests { #[test] fn test_success_response() { - let request_id = Uuid::new_v4(); + let delivery_id = Uuid::new_v4(); let started_at = Timestamp::now(); - let response = WebhookResponse::new(request_id, 200, started_at); + let response = WebhookResponse::new(delivery_id, 200, started_at); assert!(response.is_success()); - assert_eq!(response.request_id, request_id); + assert_eq!(response.delivery_id, delivery_id); assert_eq!(response.status_code, 200); } diff --git a/crates/nvisy-webhook/src/reqwest/client.rs b/crates/nvisy-webhook/src/reqwest/client.rs index de16f222..6834e5f2 100644 --- a/crates/nvisy-webhook/src/reqwest/client.rs +++ b/crates/nvisy-webhook/src/reqwest/client.rs @@ -27,15 +27,16 @@ type HmacSha256 = Hmac; /// # Examples /// /// ```rust,ignore +/// use nvisy_webhook::provider::{WebhookContext, WebhookPayload, WebhookRequest}; /// use nvisy_webhook::reqwest::{ReqwestClient, ReqwestConfig}; -/// use nvisy_webhook::WebhookRequest; /// use url::Url; /// /// let config = ReqwestConfig::default(); /// let client = ReqwestClient::new(&config); /// /// let url = Url::parse("https://example.com/webhook")?; -/// let request = WebhookRequest::test(url, webhook_id, workspace_id); +/// let payload = WebhookPayload::test(WebhookContext::test(webhook_id, workspace_id)); +/// let request = WebhookRequest::new(url, payload); /// let response = client.deliver(&request).await?; /// ``` #[derive(Clone)] @@ -147,9 +148,8 @@ impl WebhookProvider for ReqwestClient { // the cloud metadata endpoint, and so on). check_outbound(&request.url).await?; - // Create the payload from the request - let payload = request.to_payload(); - let payload_bytes = serde_json::to_vec(&payload).map_err(|err| { + let payload = &request.payload; + let payload_bytes = serde_json::to_vec(payload).map_err(|err| { Error::internal("failed to serialize webhook payload").with_source(err) })?; @@ -158,9 +158,9 @@ impl WebhookProvider for ReqwestClient { .http .post(request.url.as_str()) .header("Content-Type", "application/json") - .header("X-Webhook-Event", &request.event) + .header("X-Webhook-Event", &payload.event) .header("X-Webhook-Timestamp", timestamp.to_string()) - .header("X-Webhook-Request-Id", request.request_id.to_string()); + .header("X-Webhook-Delivery-Id", payload.delivery_id.to_string()); // Override timeout if the request specifies one if let Some(timeout) = request.timeout { @@ -187,7 +187,7 @@ impl WebhookProvider for ReqwestClient { let http_response = http_request.body(payload_bytes).send().await?; let status_code = http_response.status().as_u16(); - let response = WebhookResponse::new(request.request_id, status_code, started_at); + let response = WebhookResponse::new(payload.delivery_id, status_code, started_at); Ok(response) } @@ -199,7 +199,7 @@ const RESERVED_HEADERS: [&str; 5] = [ "content-type", "x-webhook-event", "x-webhook-timestamp", - "x-webhook-request-id", + "x-webhook-delivery-id", "x-webhook-signature", ]; @@ -245,7 +245,7 @@ mod tests { assert!(is_reserved_header("X-Webhook-Signature")); assert!(is_reserved_header("x-webhook-signature")); assert!(is_reserved_header("Content-Type")); - assert!(is_reserved_header("X-Webhook-Request-Id")); + assert!(is_reserved_header("X-Webhook-Delivery-Id")); assert!(!is_reserved_header("X-Custom-Header")); assert!(!is_reserved_header("Authorization")); } diff --git a/docker/README.md b/docker/README.md index c2c2b4e1..9dc3dd6d 100644 --- a/docker/README.md +++ b/docker/README.md @@ -140,11 +140,15 @@ Run these from the `docker/` directory. Every command passes (`docker compose -f compose.prod.yaml restart server`). The production compose file starts every service on a private bridge network. -The server waits for the PostgreSQL, NATS, and RustFS health checks to pass, -and for the bucket-provisioning init container to finish, before starting. +Only the server's port is published on the host; PostgreSQL, NATS, and RustFS +are reachable only inside that network. The server waits for the PostgreSQL, +NATS, and RustFS health checks to pass, and for the bucket-provisioning init +container to finish, before starting. ## Services +Container ports; in the production stack only the server's is published. + | Service | Port(s) | Description | | ---------- | ---------- | -------------------------------- | | PostgreSQL | 5432 | Primary database | @@ -158,8 +162,8 @@ All configuration is provided through environment variables. See [`.env.example`](../.env.example) at the repository root for a complete reference with defaults and descriptions. -Two settings depend on the deployment topology and default to the -directly-exposed case: +Three settings depend on the deployment and default to an open, +directly-exposed instance: - `CLIENT_IP_SOURCE` decides where the caller's IP is read from for audit and security records. It defaults to `ConnectInfo` (the TCP peer). Behind a reverse @@ -167,6 +171,9 @@ directly-exposed case: source (e.g. `RightmostXForwardedFor`), or the recorded IP is the proxy's. - `COOKIE_SECURE` defaults to `true` (session cookies are HTTPS-only). Set it to `false` only for local HTTP development. +- `SIGNUP_ENABLED` defaults to `true`. Set it to `false` once your accounts + exist, so no one else can create one by password sign-up or a first OIDC + sign-in. `/capabilities/auth` reports it as `signupEnabled`. ## Key Generation diff --git a/docker/compose.prod.yaml b/docker/compose.prod.yaml index e2c818be..4a8feb57 100644 --- a/docker/compose.prod.yaml +++ b/docker/compose.prod.yaml @@ -10,8 +10,9 @@ services: image: postgres:18 container_name: nvisy-postgres restart: unless-stopped - ports: - - "${POSTGRES_PORT:-5432}:5432" + # No host ports: the server reaches PostgreSQL over the internal network at + # postgres:5432. Reach it from the host through `docker compose exec` or an + # SSH tunnel rather than publishing it. environment: POSTGRES_USER: ${POSTGRES_USER:-nvisy} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} @@ -36,9 +37,8 @@ services: image: nats:2.14.2-alpine container_name: nvisy-nats restart: unless-stopped - ports: - - "${NATS_PORT:-4222}:4222" - - "${NATS_MONITOR_PORT:-8222}:8222" + # No host ports: the server reaches NATS over the internal network at + # nats:4222, and the monitoring endpoint (8222) stays internal too. # Clients authenticate with NATS_TOKEN; the server presents the same token. command: - "-c" @@ -195,6 +195,9 @@ services: CORS_ORIGINS: ${CORS_ORIGINS:-} CORS_MAX_AGE: ${CORS_MAX_AGE:-1h} HEALTH_CACHE_DURATION: ${HEALTH_CACHE_DURATION:-30s} + CLIENT_IP_SOURCE: ${CLIENT_IP_SOURCE:-ConnectInfo} + COOKIE_SECURE: ${COOKIE_SECURE:-true} + SIGNUP_ENABLED: ${SIGNUP_ENABLED:-true} RUST_LOG: ${RUST_LOG:-info} RUST_BACKTRACE: ${RUST_BACKTRACE:-0} # The auth key pair, the encryption key, and engine.toml. The image runs as diff --git a/docker/compose.yaml b/docker/compose.yaml index 77767eb2..e4ac51d2 100644 --- a/docker/compose.yaml +++ b/docker/compose.yaml @@ -12,7 +12,7 @@ services: container_name: nvisy-postgres-dev restart: unless-stopped ports: - - "${POSTGRES_PORT:-5432}:5432" + - "127.0.0.1:${POSTGRES_PORT:-5432}:5432" environment: POSTGRES_USER: ${POSTGRES_USER:-postgres} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres} @@ -36,8 +36,8 @@ services: container_name: nvisy-nats-dev restart: unless-stopped ports: - - "${NATS_PORT:-4222}:4222" - - "${NATS_MONITOR_PORT:-8222}:8222" + - "127.0.0.1:${NATS_PORT:-4222}:4222" + - "127.0.0.1:${NATS_MONITOR_PORT:-8222}:8222" command: - "-c" - "/etc/nats/nats.conf" diff --git a/migrations/2026-09-11-040235_reviews/down.sql b/migrations/2026-09-11-040235_reviews/down.sql index 6c9cd5ce..556d6e3a 100644 --- a/migrations/2026-09-11-040235_reviews/down.sql +++ b/migrations/2026-09-11-040235_reviews/down.sql @@ -2,6 +2,7 @@ -- Objects are dropped in reverse order of creation (children reference reviews). DROP TABLE IF EXISTS workspace_review_events; +DROP TABLE IF EXISTS workspace_review_approvals; DROP TABLE IF EXISTS workspace_review_assignees; DROP TABLE IF EXISTS workspace_review_comments; DROP TABLE IF EXISTS workspace_reviews; diff --git a/migrations/2026-09-11-040235_reviews/up.sql b/migrations/2026-09-11-040235_reviews/up.sql index 94d3b65a..765dcc7e 100644 --- a/migrations/2026-09-11-040235_reviews/up.sql +++ b/migrations/2026-09-11-040235_reviews/up.sql @@ -3,11 +3,11 @@ -- A review is the unit of collaboration on a document: a named discussion (an -- author, a title, a stream of comments and timeline events) with a decision-driven -- approval lifecycle layered on top. A document has 0..N reviews — none when someone --- works alone, at most one open at a time when a formal sign-off is wanted. A review --- is anchored to its document, points at the detection it is currently reviewing and --- at the redaction it approves (direct columns, not link tables), and its activity --- (comments, status changes, detection/redaction repoints, assignment, approvals) is --- one timeline in workspace_review_events. +-- works alone, and possibly several at once, one per audience. A review is anchored +-- to its document. Each approval names the redaction it endorses, so sign-off is +-- always of one concrete, immutable output, and the redaction a quorum approved is +-- the review's output. Its activity (comments, status changes, assignment, +-- approvals) is one timeline in workspace_review_events. -- -- This subsystem sits on top of documents, detections, and redactions (all -- introduced by earlier migrations). @@ -30,9 +30,9 @@ COMMENT ON TYPE REVIEW_STATUS IS 'The state of a review: draft, in_review, chang -- Reviews: a named discussion on a document with an approval lifecycle. A document -- has 0..N reviews, which may run concurrently (one per audience). A review is --- anchored to its document and carries its state, the detection it is currently --- reviewing, and the redaction it approves as direct columns; its assignees (whose --- approvals drive sign-off), comments, and timeline events belong to it. +-- anchored to its document and carries its state and the redaction its quorum +-- approved; its assignees, their approvals, comments, and timeline events belong +-- to it. CREATE TABLE workspace_reviews ( -- Primary identifier id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -44,12 +44,9 @@ CREATE TABLE workspace_reviews ( workspace_id UUID NOT NULL REFERENCES workspaces (id) ON DELETE CASCADE, document_id UUID NOT NULL, - -- The detection the review is currently working from, and the redaction it has - -- approved as its output. Both are nullable: a draft review may have no detection - -- yet, and redaction_id is set only on approval. Re-detecting the document - -- repoints detection_id (recorded as a review.redetected event). ON DELETE SET - -- NULL keeps the review when a referenced detection or redaction is hard-deleted. - detection_id UUID DEFAULT NULL REFERENCES workspace_detections (id) ON DELETE SET NULL, + -- The redaction the review's quorum approved: its output. Set exactly when the + -- review reaches `approved`, and cleared when it leaves that state. ON DELETE SET + -- NULL keeps the review when the redaction is hard-deleted. redaction_id UUID DEFAULT NULL REFERENCES workspace_redactions (id) ON DELETE SET NULL, -- The account that opened the review. If it is removed, the review goes too. @@ -63,7 +60,7 @@ CREATE TABLE workspace_reviews ( -- The review state, and the whole lifecycle: a review opens at `draft`, moves to -- `in_review` on submit, through `changes_requested` / `partially_approved`, and -- `approved` once enough reviewers approve. State is set by explicit reviewer - -- decisions; approvals are the assignees' stamped `approved_at` values. + -- decisions; approvals are rows in workspace_review_approvals. review_status REVIEW_STATUS NOT NULL DEFAULT 'draft', -- Lifecycle timestamps @@ -92,12 +89,11 @@ CREATE INDEX workspace_reviews_workspace_idx -- Keep updated_at current on every row modification. SELECT setup_updated_at('workspace_reviews'); -COMMENT ON TABLE workspace_reviews IS 'A named discussion on a document with an approval lifecycle (0..N per document, concurrent per audience). Anchored to its document; points at the detection it reviews and the redaction it approves; owns its comments and timeline.'; +COMMENT ON TABLE workspace_reviews IS 'A named discussion on a document with an approval lifecycle (0..N per document, concurrent per audience). Anchored to its document; its output is the redaction its quorum approved; owns its assignees, approvals, comments, and timeline.'; COMMENT ON COLUMN workspace_reviews.id IS 'Unique review identifier'; COMMENT ON COLUMN workspace_reviews.workspace_id IS 'Denormalized workspace scope'; COMMENT ON COLUMN workspace_reviews.document_id IS 'Document under review (a document may have many concurrent reviews, one per audience)'; -COMMENT ON COLUMN workspace_reviews.detection_id IS 'The detection currently under review; NULL before a detection is linked'; -COMMENT ON COLUMN workspace_reviews.redaction_id IS 'The approved redaction output; NULL until approved'; +COMMENT ON COLUMN workspace_reviews.redaction_id IS 'The redaction the quorum approved (the output); set exactly while the review is approved'; COMMENT ON COLUMN workspace_reviews.author_account_id IS 'Account that opened the review'; COMMENT ON COLUMN workspace_reviews.display_name IS 'Human-readable title (1-255 chars)'; COMMENT ON COLUMN workspace_reviews.review_status IS 'Review state and lifecycle (draft/in_review/changes_requested/partially_approved/approved)'; @@ -163,20 +159,13 @@ COMMENT ON COLUMN workspace_review_comments.created_at IS 'Timestamp when the co COMMENT ON COLUMN workspace_review_comments.updated_at IS 'Timestamp of the last edit'; COMMENT ON COLUMN workspace_review_comments.deleted_at IS 'Soft-deletion timestamp; NULL means live'; --- Review assignees: the reviewers responsible for a review (0..N), and their --- approvals. Assignment is metadata (who is responsible) and does not change the --- review's status. A reviewer approves by stamping `approved_at` on their own row; --- the review reaches `approved` once the count of stamped rows meets the workspace's --- min_approvals. Requesting changes or reopening clears every `approved_at` (a --- pushback invalidates accumulated approvals), so a stamp always means "approved the --- state as it stands now." +-- Review assignees: the reviewers responsible for a review (0..N). Assignment is +-- metadata (who is responsible) and does not change the review's status; an +-- assignee's approval is a row in workspace_review_approvals. CREATE TABLE workspace_review_assignees ( review_id UUID NOT NULL REFERENCES workspace_reviews (id) ON DELETE CASCADE, account_id UUID NOT NULL REFERENCES accounts (id) ON DELETE CASCADE, created_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp, - -- When this reviewer approved the review in its current state; NULL means - -- assigned but not yet approved. - approved_at TIMESTAMPTZ DEFAULT NULL, PRIMARY KEY (review_id, account_id) ); @@ -184,30 +173,63 @@ CREATE TABLE workspace_review_assignees ( CREATE INDEX workspace_review_assignees_account_idx ON workspace_review_assignees (account_id); -COMMENT ON TABLE workspace_review_assignees IS 'The reviewers assigned to a review (many-to-many, 0..N) and their approvals (approved_at). Approval is reached when the count of stamped rows meets the workspace min_approvals.'; +COMMENT ON TABLE workspace_review_assignees IS 'The reviewers assigned to a review (many-to-many, 0..N). Their approvals are in workspace_review_approvals.'; COMMENT ON COLUMN workspace_review_assignees.review_id IS 'The review'; COMMENT ON COLUMN workspace_review_assignees.account_id IS 'The assigned reviewer'; -COMMENT ON COLUMN workspace_review_assignees.approved_at IS 'When this reviewer approved the current state; NULL means not yet approved. Cleared on request-changes/reopen'; COMMENT ON COLUMN workspace_review_assignees.created_at IS 'When the reviewer was assigned'; +-- Review approvals: an assignee's approval of one specific redaction of the +-- review's document. A redaction is immutable (one detection and its edits at the +-- time it was made), so an approval always endorses exactly the output the reviewer +-- saw. The review reaches `approved` once as many assignees as the workspace's +-- min_approvals approve the same redaction. At most one approval per assignee: +-- approving another redaction moves it. Requesting changes or reopening deletes the +-- review's approvals; unassigning a reviewer, or hard-deleting the redaction, +-- deletes theirs. +CREATE TABLE workspace_review_approvals ( + -- The approving assignee, referenced as their assignee row: unassigning the + -- reviewer deletes their approval with it. + review_id UUID NOT NULL, + account_id UUID NOT NULL, + + -- The redaction this approval endorses. Hard-deleting it deletes the approval. + redaction_id UUID NOT NULL REFERENCES workspace_redactions (id) ON DELETE CASCADE, + + -- When the assignee approved it. + approved_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp, + + PRIMARY KEY (review_id, account_id), + CONSTRAINT workspace_review_approvals_assignee_fkey FOREIGN KEY (review_id, account_id) + REFERENCES workspace_review_assignees (review_id, account_id) ON DELETE CASCADE +); + +-- A review's approvals per redaction (backs the quorum count). +CREATE INDEX workspace_review_approvals_redaction_idx + ON workspace_review_approvals (review_id, redaction_id); + +COMMENT ON TABLE workspace_review_approvals IS 'An assignee approval of one specific redaction; the review is approved once min_approvals assignees approve the same redaction.'; +COMMENT ON COLUMN workspace_review_approvals.review_id IS 'The review'; +COMMENT ON COLUMN workspace_review_approvals.account_id IS 'The approving assignee'; +COMMENT ON COLUMN workspace_review_approvals.redaction_id IS 'The redaction this approval endorses'; +COMMENT ON COLUMN workspace_review_approvals.approved_at IS 'When the assignee approved it'; + -- Kind of a review timeline event (a non-message entry in a review's stream): the -- lifecycle (opened, renamed, submitted, changes requested, approved, reopened) and --- the surrounding workflow (detection repoints, assignment changes). The approved --- event's target carries the output redaction id. +-- the surrounding workflow (assignment changes). The approved event's target +-- carries the approved redaction id. -- Comments are the message entries; these are everything else in the one timeline. CREATE TYPE REVIEW_EVENT_KIND AS ENUM ( - 'review.opened', -- The review was opened (target holds the initial detection id, if any) + 'review.opened', -- The review was opened 'review.renamed', -- The review's display name was changed - 'review.redetected', -- The review was repointed at a newer detection (target holds it) 'review.assigned', -- The review was assigned to a reviewer 'review.unassigned', -- A reviewer was unassigned 'review.submitted', -- The review was submitted (or resubmitted) for review 'review.changes_requested', -- A reviewer requested changes - 'review.approved', -- A reviewer approved (its target holds the output redaction id) + 'review.approved', -- A reviewer approved (its target holds the approved redaction id) 'review.reopened' -- An approved review was reopened (back to in_review) ); -COMMENT ON TYPE REVIEW_EVENT_KIND IS 'The kind of a non-message entry in a review timeline: the lifecycle (opened, renamed, submitted, changes_requested, approved, reopened) and the workflow (detection linked, assigned/unassigned).'; +COMMENT ON TYPE REVIEW_EVENT_KIND IS 'The kind of a non-message entry in a review timeline: the lifecycle (opened, renamed, submitted, changes_requested, approved, reopened) and the workflow (assigned/unassigned).'; -- Review timeline events: the non-message entries in a review's stream. Immutable — -- an event is a fact that happened, so there is no update or soft-delete; deleting @@ -229,8 +251,8 @@ CREATE TABLE workspace_review_events ( -- (the transition still happened). actor_account_id UUID DEFAULT NULL REFERENCES accounts (id) ON DELETE SET NULL, - -- Event-specific detail, when any: the new name for a rename, the linked - -- detection/redaction id, or the assignee for an assign. NULL otherwise. + -- Event-specific detail, when any: the new name for a rename, the approved + -- redaction id, or the assignee for an assign. NULL otherwise. target JSONB DEFAULT NULL, CONSTRAINT workspace_review_events_target_size CHECK (target IS NULL OR length(target::TEXT) <= 8192), @@ -242,12 +264,12 @@ CREATE TABLE workspace_review_events ( CREATE INDEX workspace_review_events_review_idx ON workspace_review_events (review_id, created_at); -COMMENT ON TABLE workspace_review_events IS 'An immutable non-message entry in a review timeline: the lifecycle (opened, renamed, verified, reopened) and the sign-off workflow (detection/redaction linked, assigned/unassigned).'; +COMMENT ON TABLE workspace_review_events IS 'An immutable non-message entry in a review timeline: the lifecycle (opened, renamed, submitted, changes_requested, approved, reopened) and the workflow (assigned/unassigned).'; COMMENT ON COLUMN workspace_review_events.id IS 'Unique event identifier'; COMMENT ON COLUMN workspace_review_events.review_id IS 'Review this event belongs to'; -COMMENT ON COLUMN workspace_review_events.kind IS 'What happened (review.opened/renamed/redetected, review.assigned/unassigned, review.submitted/changes_requested/approved/reopened)'; +COMMENT ON COLUMN workspace_review_events.kind IS 'What happened (review.opened/renamed, review.assigned/unassigned, review.submitted/changes_requested/approved/reopened)'; COMMENT ON COLUMN workspace_review_events.actor_account_id IS 'Account that performed the action; null if that account was removed'; -COMMENT ON COLUMN workspace_review_events.target IS 'Event-specific detail (the new name, a linked id, an assignee); NULL when none'; +COMMENT ON COLUMN workspace_review_events.target IS 'Event-specific detail (the new name, the approved redaction id, an assignee); NULL when none'; COMMENT ON COLUMN workspace_review_events.created_at IS 'Timestamp when the event happened'; -- Review lifecycle events feed the event sinks; each value is added by this From 61c35f33f4bc7cca0ab6775238216a3995f24ae4 Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Sun, 29 Nov 2026 12:19:24 +0100 Subject: [PATCH 02/14] Correct review and audit docs, and mark blank names invalid in the spec - Describe review statuses as approvals counted per redaction, with no re-pointing and no output-less approval - Document that unassigning an approver deletes their approval and can only demote the review - Tell a detection's base findings apart from a redaction's review audit - State that text edit spans are UTF-8 byte offsets - Give every non-blank name and comment field a `\S` schema pattern Co-Authored-By: Claude Opus 5.5 --- .../src/types/enums/review_status.rs | 21 +++++++++---------- .../src/handler/detection_audits.rs | 4 +++- .../src/handler/request/accounts.rs | 1 + .../handler/request/workspace_connections.rs | 3 +++ .../src/handler/request/workspace_policies.rs | 1 + .../src/handler/request/workspace_reviews.rs | 5 ++++- .../src/handler/request/workspaces.rs | 2 ++ .../src/handler/workspace_detections.rs | 3 ++- .../src/handler/workspace_redactions.rs | 6 ++++-- .../src/handler/workspace_reviews.rs | 8 +++++-- crates/nvisy-server/tests/openapi.rs | 13 ++++++++++++ 11 files changed, 49 insertions(+), 18 deletions(-) diff --git a/crates/nvisy-postgres/src/types/enums/review_status.rs b/crates/nvisy-postgres/src/types/enums/review_status.rs index 06ffe8f5..9a7455b9 100644 --- a/crates/nvisy-postgres/src/types/enums/review_status.rs +++ b/crates/nvisy-postgres/src/types/enums/review_status.rs @@ -10,11 +10,10 @@ db_enum! { /// explicit reviewer decisions, not by assignment: a review opens at `Draft`; /// `submit` moves it to `InReview`; a reviewer can `request-changes` /// (`ChangesRequested`, from which `submit` returns it to `InReview`) or - /// `approve`. An approval reaches `Approved` once the workspace's required number - /// of distinct approvals is met, and rests at `PartiallyApproved` in between - /// (only reachable when two or more approvals are required). Reopening an - /// `Approved` review returns it to `InReview`, as does pointing a review that - /// has approvals at a different detection. + /// `approve`. Each approval names one redaction of the document, and only + /// approvals of the same redaction count toward the workspace's required + /// number. Requesting changes and reopening clear every approval. Unassigning + /// an approver deletes their approval, which can only demote the review. pub enum ReviewStatus: Default = Draft, "crate::schema::sql_types::ReviewStatus" { /// Opened, edits being assembled; `submit` sends it for review. Draft = "draft", @@ -22,13 +21,13 @@ db_enum! { InReview = "in_review", /// A reviewer requested changes; `submit` returns it to `InReview`. ChangesRequested = "changes_requested", - /// Some, but not all, required approvals are in. Only reachable when the - /// workspace requires two or more approvals. An approver may already have - /// bound the redaction the remaining approvals must endorse. + /// At least one approval is in, but no redaction has the required number + /// of approvals yet. Only reachable when the workspace requires two or + /// more. Approvals of different redactions do not combine. PartiallyApproved = "partially_approved", - /// Signed off: the required approvals are in. When an approver named a - /// redaction, that redaction is the review's output; otherwise the review - /// has none. + /// Signed off: one redaction has the required number of approvals, and + /// it is the review's output (`redactionId`). Reopening returns the review + /// to `InReview`. Approved = "approved", } } diff --git a/crates/nvisy-server/src/handler/detection_audits.rs b/crates/nvisy-server/src/handler/detection_audits.rs index 84c9f0d5..903cfa85 100644 --- a/crates/nvisy-server/src/handler/detection_audits.rs +++ b/crates/nvisy-server/src/handler/detection_audits.rs @@ -57,7 +57,9 @@ async fn get_detection_analysis( fn get_detection_analysis_docs(op: TransformOperation) -> TransformOperation { op.summary("Get detection findings") .description( - "Returns the detection's detected findings (the analyzed document) for review.", + "Returns the detection's base analysis: what detection found, without reviewer \ + edits. The edits are stored on the detection (`editSet`) and applied at redact \ + time; a redaction's applied result is its review audit.", ) .response::<200, Json>() .response::<409, Json>() diff --git a/crates/nvisy-server/src/handler/request/accounts.rs b/crates/nvisy-server/src/handler/request/accounts.rs index 8c60794e..dbb65c85 100644 --- a/crates/nvisy-server/src/handler/request/accounts.rs +++ b/crates/nvisy-server/src/handler/request/accounts.rs @@ -21,6 +21,7 @@ pub struct UpdateAccount { /// New account handle. pub username: Option, /// New display name (2-32 characters). + #[schemars(pattern(r"\S"))] #[garde( length(chars, min = 2, max = 32), custom(validate_non_blank_opt), diff --git a/crates/nvisy-server/src/handler/request/workspace_connections.rs b/crates/nvisy-server/src/handler/request/workspace_connections.rs index 86130ec3..491f3494 100644 --- a/crates/nvisy-server/src/handler/request/workspace_connections.rs +++ b/crates/nvisy-server/src/handler/request/workspace_connections.rs @@ -80,6 +80,7 @@ impl From for SyncScheduleInputDomain { #[garde(allow_unvalidated)] pub struct CreateWorkspaceConnection { /// Human-readable connection display name. + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank))] pub display_name: String, /// Whether the connection is enabled. Omit to default to active; set `false` @@ -124,6 +125,7 @@ pub struct OAuthStartPathParams { #[garde(allow_unvalidated)] pub struct StartFileServiceOAuth { /// Human-readable name for the connection to be created on success. + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank))] pub display_name: String, /// Where to scope the sync: a folder id (Drive, `OneDrive`, Box) or a folder @@ -157,6 +159,7 @@ pub struct OAuthCallbackQuery { #[garde(allow_unvalidated)] pub struct UpdateWorkspaceConnection { /// Human-readable connection display name. + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank_opt))] pub display_name: Option, /// Whether the connection is enabled. `false` disables it (pausing scheduled diff --git a/crates/nvisy-server/src/handler/request/workspace_policies.rs b/crates/nvisy-server/src/handler/request/workspace_policies.rs index 5b6f3877..a7872f2f 100644 --- a/crates/nvisy-server/src/handler/request/workspace_policies.rs +++ b/crates/nvisy-server/src/handler/request/workspace_policies.rs @@ -183,6 +183,7 @@ impl From for UpdatePolicyInput { #[serde(rename_all = "camelCase")] pub struct PromoteWorkspacePolicy { /// Human-readable display name for the promoted policy (1-255 characters). + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank))] pub display_name: String, } diff --git a/crates/nvisy-server/src/handler/request/workspace_reviews.rs b/crates/nvisy-server/src/handler/request/workspace_reviews.rs index cd1e527b..206b2ae5 100644 --- a/crates/nvisy-server/src/handler/request/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/request/workspace_reviews.rs @@ -26,6 +26,7 @@ pub struct WorkspaceReviewPathParams { #[garde(allow_unvalidated)] pub struct CreateWorkspaceReview { /// The review's title (1-255 characters). + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 255), custom(validate_non_blank))] pub display_name: String, } @@ -52,7 +53,7 @@ pub struct RenameWorkspaceReview { // schemars ignores `garde(inner(..))` on an `Option`, so restate the bounds for // the generated schema; garde still enforces them at runtime. #[garde(inner(length(chars, min = 1, max = 255), custom(validate_non_blank)))] - #[schemars(length(min = 1, max = 255))] + #[schemars(length(min = 1, max = 255), pattern(r"\S"))] pub display_name: Option, } @@ -84,6 +85,7 @@ pub struct WorkspaceCommentPathParams { #[serde(rename_all = "camelCase")] pub struct CreateWorkspaceComment { /// The comment text (1-10000 characters). + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 10_000), custom(validate_non_blank))] pub body: String, } @@ -94,6 +96,7 @@ pub struct CreateWorkspaceComment { #[serde(rename_all = "camelCase")] pub struct UpdateWorkspaceComment { /// The new comment text (1-10000 characters). + #[schemars(pattern(r"\S"))] #[garde(length(chars, min = 1, max = 10_000), custom(validate_non_blank))] pub body: String, } diff --git a/crates/nvisy-server/src/handler/request/workspaces.rs b/crates/nvisy-server/src/handler/request/workspaces.rs index 3dd49c5e..686af0db 100644 --- a/crates/nvisy-server/src/handler/request/workspaces.rs +++ b/crates/nvisy-server/src/handler/request/workspaces.rs @@ -26,6 +26,7 @@ use crate::response::{ErrorKind, Result}; #[garde(allow_unvalidated)] pub struct CreateWorkspace { /// Display name of the workspace (2-32 characters). + #[schemars(pattern(r"\S"))] #[garde(length(min = 2, max = 32, chars), custom(validate_non_blank))] pub display_name: String, /// Optional handle. Derived from the display name when omitted. @@ -85,6 +86,7 @@ impl CreateWorkspace { #[garde(allow_unvalidated)] pub struct UpdateWorkspace { /// New display name for the workspace (2-32 characters). + #[schemars(pattern(r"\S"))] #[garde(length(min = 2, max = 32, chars), custom(validate_non_blank_opt))] pub display_name: Option, /// New description for the workspace (max 500 characters). diff --git a/crates/nvisy-server/src/handler/workspace_detections.rs b/crates/nvisy-server/src/handler/workspace_detections.rs index 297b3a91..f4ca94ee 100644 --- a/crates/nvisy-server/src/handler/workspace_detections.rs +++ b/crates/nvisy-server/src/handler/workspace_detections.rs @@ -434,7 +434,8 @@ fn edit_detection_docs(op: TransformOperation) -> TransformOperation { detection, or add one the analysis missed), or clears them when `edits` is omitted. \ The edits are validated against the detection's analysis before being stored (400 on \ an unknown target or modality mismatch), persist on the detection, and are layered \ - over its base analysis at redact time so they survive between redactions. Pass the \ + over its base analysis at redact time so they survive between redactions. Text spans \ + are UTF-8 byte offsets into the decoded text, not character offsets. Pass the \ `editSetRev` you last read; a stale value is rejected with 409. Requires \ RunRedactions.", ) diff --git a/crates/nvisy-server/src/handler/workspace_redactions.rs b/crates/nvisy-server/src/handler/workspace_redactions.rs index 9b66ca83..ea39c0cf 100644 --- a/crates/nvisy-server/src/handler/workspace_redactions.rs +++ b/crates/nvisy-server/src/handler/workspace_redactions.rs @@ -119,8 +119,10 @@ async fn get_redaction_review( fn get_redaction_review_docs(op: TransformOperation) -> TransformOperation { op.summary("Get redaction review") .description( - "Returns the redaction's review audit: the detection analysis with the reviewer's \ - edits applied and the per-entity redaction outcome recorded.", + "Returns the redaction's review audit: the detection's base analysis with the \ + reviewer edits in force at redact time applied, and the per-entity redaction \ + outcome recorded. Unlike the detection's findings, it is fixed once the redaction \ + is made.", ) .response::<200, Json>() .response::<409, Json>() diff --git a/crates/nvisy-server/src/handler/workspace_reviews.rs b/crates/nvisy-server/src/handler/workspace_reviews.rs index 88086807..30bc6a84 100644 --- a/crates/nvisy-server/src/handler/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/workspace_reviews.rs @@ -636,8 +636,12 @@ async fn remove_review_assignee( fn remove_review_assignee_docs(op: TransformOperation) -> TransformOperation { op.summary("Unassign a reviewer") .description( - "Removes a reviewer from a review. Assignment is metadata and does not \ - change the review's status. Requires AssignReviews.", + "Removes a reviewer from a review, deleting their approval if they gave \ + one. Losing an approval can only demote: an approved review whose \ + redaction falls below the required number of approvals returns to \ + partially_approved (or in_review when none are left) and drops its \ + output, and a partially_approved review with none left returns to \ + in_review. Requires AssignReviews.", ) .response::<200, Json>() } diff --git a/crates/nvisy-server/tests/openapi.rs b/crates/nvisy-server/tests/openapi.rs index 1199d9f6..29374d46 100644 --- a/crates/nvisy-server/tests/openapi.rs +++ b/crates/nvisy-server/tests/openapi.rs @@ -122,6 +122,19 @@ async fn schema_bounds_match_the_server() { schemas["RedactionKey"]["pattern"], "^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$" ); + + // A blank title or comment is rejected, so the schema requires a + // non-whitespace character. + for (schema, field) in [ + ("CreateWorkspaceReview", "displayName"), + ("RenameWorkspaceReview", "displayName"), + ("CreateWorkspaceComment", "body"), + ] { + assert_eq!( + schemas[schema]["properties"][field]["pattern"], "\\S", + "{schema}.{field} pattern" + ); + } } /// The invite-code preview needs a signed-in caller, so it declares the bearer From f4668e70272c38dd9f23bd58b0d3c965ac1b150a Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Sun, 29 Nov 2026 14:01:09 +0100 Subject: [PATCH 03/14] Reject a JSON body without a Content-Type with 415 Add an UnsupportedMediaType error kind and map a missing JSON content type to it, matching the 415 the spec declares. Co-Authored-By: Claude Opus 5.5 --- .../nvisy-server/src/extract/reject/json_with_rej.rs | 10 +++++----- crates/nvisy-server/src/response/error/http_error.rs | 7 +++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/nvisy-server/src/extract/reject/json_with_rej.rs b/crates/nvisy-server/src/extract/reject/json_with_rej.rs index 60c1b86a..3ab21367 100644 --- a/crates/nvisy-server/src/extract/reject/json_with_rej.rs +++ b/crates/nvisy-server/src/extract/reject/json_with_rej.rs @@ -105,7 +105,7 @@ impl From for Error { )) } JsonRejection::MissingJsonContentType(_) => { - ErrorKind::BadRequest + ErrorKind::UnsupportedMediaType .with_message("Invalid content type") .with_context("Request must have Content-Type header set to 'application/json'. Include the header: Content-Type: application/json") } @@ -207,10 +207,10 @@ mod tests { .unwrap(); let extracted = as OptionalFromRequest<()>>::from_request(request, &()).await; - assert!( - extracted.is_err(), - "a present body needs its JSON content type" - ); + let Err(error) = extracted else { + panic!("a present body needs its JSON content type"); + }; + assert_eq!(error.kind(), ErrorKind::UnsupportedMediaType); let empty = Request::builder().body(Body::empty()).unwrap(); let extracted = as OptionalFromRequest<()>>::from_request(empty, &()).await; diff --git a/crates/nvisy-server/src/response/error/http_error.rs b/crates/nvisy-server/src/response/error/http_error.rs index 75e215a1..0ea71bb1 100644 --- a/crates/nvisy-server/src/response/error/http_error.rs +++ b/crates/nvisy-server/src/response/error/http_error.rs @@ -267,6 +267,8 @@ pub enum ErrorKind { Conflict, /// 413 Payload Too Large - Request body exceeds the allowed size PayloadTooLarge, + /// 415 Unsupported Media Type - The request body is not in a supported format + UnsupportedMediaType, /// 429 Too Many Requests - Rate limit exceeded TooManyRequests, @@ -351,6 +353,11 @@ impl ErrorKind { "Payload too large", StatusCode::PAYLOAD_TOO_LARGE, ), + Self::UnsupportedMediaType => ErrorResponse::new( + "unsupported_media_type", + "Unsupported media type", + StatusCode::UNSUPPORTED_MEDIA_TYPE, + ), Self::TooManyRequests => ErrorResponse::new( "too_many_requests", "Rate limit exceeded", From 85e4960b212245cebe59bd03e419287ee3f69d48 Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Sun, 29 Nov 2026 14:01:09 +0100 Subject: [PATCH 04/14] Stop workers promptly and quietly on shutdown An unbiased select let a free permit or a due tick win over a fired cancellation, so a consumer kept starting new pulls and could take tens of seconds to stop. Bias the consume and timer loops toward cancellation, and drop the per-worker stop log. Co-Authored-By: Claude Opus 5.5 --- crates/nvisy-nats/src/stream/consume.rs | 3 +++ crates/nvisy-server/src/worker/set.rs | 17 +++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/nvisy-nats/src/stream/consume.rs b/crates/nvisy-nats/src/stream/consume.rs index c974aeab..f8d164ca 100644 --- a/crates/nvisy-nats/src/stream/consume.rs +++ b/crates/nvisy-nats/src/stream/consume.rs @@ -101,7 +101,10 @@ impl EventSubscriber { let mut tasks: JoinSet<()> = JoinSet::new(); loop { + // Biased so a fired cancellation wins over a free permit: unbiased, the + // loop would start another pull about half the time it should stop. let permit = tokio::select! { + biased; () = cancel.cancelled() => break, // Reap finished tasks so the set stays bounded by what is in flight. Some(_) = tasks.join_next() => continue, diff --git a/crates/nvisy-server/src/worker/set.rs b/crates/nvisy-server/src/worker/set.rs index 63ab59de..a4031add 100644 --- a/crates/nvisy-server/src/worker/set.rs +++ b/crates/nvisy-server/src/worker/set.rs @@ -21,8 +21,8 @@ const TRACING_TARGET: &str = "nvisy_server::worker"; /// A background worker: runs until cancelled. /// /// Implementors run a loop that stops when the passed [`CancellationToken`] is -/// cancelled and return once it has drained. The supervisor logs the start, the -/// stop, and a returned error under [`NAME`](Worker::NAME). +/// cancelled and return once it has drained. The supervisor logs the start and +/// a returned error under [`NAME`](Worker::NAME); a clean stop is silent. pub trait Worker: Send + Sync + 'static { /// A short, stable label for this worker, used in supervision logs. const NAME: &'static str; @@ -62,18 +62,13 @@ impl WorkerSet { } /// Spawns `worker` on the runtime, tied to this set's cancellation token, and - /// logs its start, stop, or failure. + /// logs its start or failure. pub fn spawn(&mut self, worker: W) { let cancel = self.cancel.clone(); let handle = tokio::spawn(async move { tracing::info!(target: TRACING_TARGET, worker = W::NAME, "Worker started"); - match worker.run(cancel).await { - Ok(()) => { - tracing::info!(target: TRACING_TARGET, worker = W::NAME, "Worker stopped"); - } - Err(err) => { - tracing::error!(target: TRACING_TARGET, worker = W::NAME, error = %err, "Worker failed"); - } + if let Err(err) = worker.run(cancel).await { + tracing::error!(target: TRACING_TARGET, worker = W::NAME, error = %err, "Worker failed"); } }); self.handles.push((W::NAME, handle)); @@ -126,7 +121,9 @@ pub(crate) async fn every( { let mut ticker = tokio::time::interval(interval); loop { + // Biased so a fired cancellation wins over a due tick or a stored wake. tokio::select! { + biased; () = cancel.cancelled() => break, _ = ticker.tick() => pass().await, () = async { From 32695665f4478e1d4219308b6ae5d27933cde0f6 Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Mon, 30 Nov 2026 04:02:35 +0100 Subject: [PATCH 05/14] Scope workspace analytics to an optional date window getAnalytics takes the same optional from/to as the time series. The detection status mix, error rate, and durations cover detections started in the window; with neither bound they cover all time. Storage stays the workspace's live files. Co-Authored-By: Claude Opus 5.5 --- crates/nvisy-postgres/src/query/analytics.rs | 147 +++++++++++++++--- .../src/domain/workspace_analytics.rs | 13 +- crates/nvisy-server/src/handler/analytics.rs | 9 +- .../src/handler/response/analytics.rs | 5 +- 4 files changed, 146 insertions(+), 28 deletions(-) diff --git a/crates/nvisy-postgres/src/query/analytics.rs b/crates/nvisy-postgres/src/query/analytics.rs index d2f83730..c939cb9d 100644 --- a/crates/nvisy-postgres/src/query/analytics.rs +++ b/crates/nvisy-postgres/src/query/analytics.rs @@ -12,7 +12,9 @@ use std::future::Future; use bigdecimal::BigDecimal; +use diesel::pg::Pg; use diesel::prelude::*; +use diesel::query_builder::{BoxedSelectStatement, FromClause}; use diesel::sql_types::Timestamptz; use diesel_async::RunQueryDsl; use uuid::Uuid; @@ -110,14 +112,18 @@ pub struct AnalyticsSnapshot { /// Read-only aggregate queries backing the workspace analytics endpoint. pub trait WorkspaceAnalyticsRepository { - /// A workspace's point-in-time analytics — storage by kind, detection counts - /// by status, and completed-detection durations — read in one read-only, - /// repeatable-read transaction so the parts reflect a single snapshot. Each - /// breakdown lists only the groups that have data; the caller zero-fills the - /// rest. + /// A workspace's analytics — storage by kind, detection counts by status, and + /// completed-detection durations — read in one read-only, repeatable-read + /// transaction so the parts reflect a single snapshot. Each breakdown lists + /// only the groups that have data; the caller zero-fills the rest. + /// + /// The detection parts cover detections started in `[from, to)`, each bound + /// applied only when given; storage is always the workspace's live files now. fn snapshot( &mut self, workspace_id: Uuid, + from: Option, + to: Option, ) -> impl Future> + Send; /// Daily detection activity for a workspace over `[from, to)` (UTC day @@ -135,7 +141,16 @@ pub trait WorkspaceAnalyticsRepository { } impl WorkspaceAnalyticsRepository for PgConnection { - async fn snapshot(&mut self, workspace_id: Uuid) -> Result { + async fn snapshot( + &mut self, + workspace_id: Uuid, + from: Option, + to: Option, + ) -> Result { + let window = StartedWindow { + from: from.map(jiff_diesel::Timestamp::from), + to: to.map(jiff_diesel::Timestamp::from), + }; // The three reads run in one read-only, repeatable-read transaction so the // snapshot is internally consistent: a write landing between two of the // reads cannot make the detection counts and durations disagree. @@ -145,8 +160,8 @@ impl WorkspaceAnalyticsRepository for PgConnection { .run(async |conn| { Ok(AnalyticsSnapshot { storage: load_storage_by_kind(conn, workspace_id).await?, - detections: load_detections_by_status(conn, workspace_id).await?, - durations: load_detection_durations(conn, workspace_id).await?, + detections: load_detections_by_status(conn, workspace_id, window).await?, + durations: load_detection_durations(conn, workspace_id, window).await?, }) }) .await @@ -217,29 +232,64 @@ async fn load_storage_by_kind( .collect()) } -/// Detection count per `status`, Only statuses -/// with a detection appear. +/// Optional bounds on when a detection started: `from` inclusive, `to` +/// exclusive, each applied only when given. +#[derive(Debug, Clone, Copy)] +struct StartedWindow { + from: Option, + to: Option, +} + +/// A boxed aggregate over the detections table. +type DetectionAggregate<'a, ST, GB> = + BoxedSelectStatement<'a, ST, FromClause, Pg, GB>; + +impl StartedWindow { + /// Narrows a boxed detection aggregate to the detections that started + /// within this window. Boxing after the select keeps `group_by` available, + /// which a boxed source table would not. + fn narrow( + self, + query: DetectionAggregate<'_, ST, GB>, + ) -> DetectionAggregate<'_, ST, GB> { + use schema::workspace_detections::dsl as detections; + + let mut query = query; + if let Some(from) = self.from { + query = query.filter(detections::started_at.ge(from)); + } + if let Some(to) = self.to { + query = query.filter(detections::started_at.lt(to)); + } + query + } +} + +/// Detection count per `status` within `window`. Only statuses with a detection +/// appear. async fn load_detections_by_status( conn: &mut PgConnection, workspace_id: Uuid, + window: StartedWindow, ) -> Result> { use diesel::dsl::count_star; use schema::workspace_detections; use schema::workspace_detections::dsl as detections; - Ok(workspace_detections::table + let query = workspace_detections::table .filter(detections::workspace_id.eq(workspace_id)) .group_by(detections::status) .select((detections::status, count_star())) - .load(conn) - .await?) + .into_boxed(); + Ok(window.narrow(query).load(conn).await?) } /// Mean and 95th-percentile duration (milliseconds) of the workspace's completed -/// detections. Both `None` when no detection has completed. +/// detections within `window`. Both `None` when none has completed. async fn load_detection_durations( conn: &mut PgConnection, workspace_id: Uuid, + window: StartedWindow, ) -> Result { use diesel::dsl::sql; use diesel::sql_types::{BigInt, Nullable}; @@ -261,15 +311,15 @@ async fn load_detection_durations( - workspace_detections.started_at))) * 1000)::bigint", ); - let (avg_ms, p95_ms): (Option, Option) = workspace_detections::table + let query = workspace_detections::table .filter(detections::workspace_id.eq(workspace_id)) // Durations describe successful analysis only. `completed_at` is stamped // on failure too, so filter on the terminal `Complete` status, not merely // on the timestamp being present. .filter(detections::status.eq(DetectionStatus::Complete)) .select((avg_ms, p95_ms)) - .first(conn) - .await?; + .into_boxed(); + let (avg_ms, p95_ms): (Option, Option) = window.narrow(query).first(conn).await?; Ok(DetectionDurations { avg_ms, p95_ms }) } @@ -411,7 +461,7 @@ mod tests { )) .await?; - let snapshot = conn.snapshot(seeded.workspace_id).await?; + let snapshot = conn.snapshot(seeded.workspace_id, None, None).await?; // Storage: 2 original documents + 1 redacted, grouped by kind. let original = snapshot @@ -445,6 +495,63 @@ mod tests { assert_eq!(snapshot.durations.avg_ms, Some(10_000)); Ok(()) } + #[tokio::test] + async fn snapshot_window_scopes_detections_but_not_storage() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + + // One detection ten days ago (10s), one two hours ago (20s). + let _old = completed_detection( + &mut conn, + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + Span::new().hours(240), + Span::new().seconds(10), + ) + .await?; + let _recent = completed_detection( + &mut conn, + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + Span::new().hours(2), + Span::new().seconds(20), + ) + .await?; + + // A window over the last day sees only the recent detection. + let from = Timestamp::now() - Span::new().hours(24); + let windowed = conn.snapshot(seeded.workspace_id, Some(from), None).await?; + let complete = |snapshot: &AnalyticsSnapshot| { + snapshot + .detections + .iter() + .find(|d| d.status == DetectionStatus::Complete) + .map(|d| d.count) + }; + assert_eq!(complete(&windowed), Some(1)); + assert_eq!(windowed.durations.avg_ms, Some(20_000)); + assert_eq!(windowed.durations.p95_ms, Some(20_000)); + + // A window ending before both sees no detections at all. + let to = Timestamp::now() - Span::new().hours(480); + let before = conn.snapshot(seeded.workspace_id, None, Some(to)).await?; + assert!(before.detections.is_empty()); + assert_eq!(before.durations.avg_ms, None); + + // Storage is the live files now, whatever the window. + assert_eq!(before.storage.len(), windowed.storage.len()); + assert!(!before.storage.is_empty()); + + // No window is all time. + let all = conn.snapshot(seeded.workspace_id, None, None).await?; + assert_eq!(complete(&all), Some(2)); + assert_eq!(all.durations.avg_ms, Some(15_000)); + Ok(()) + } + #[tokio::test] async fn snapshot_is_scoped_to_the_workspace() -> anyhow::Result<()> { let db = TestDatabase::start().await; @@ -462,14 +569,14 @@ mod tests { .await?; // The unrelated workspace sees none of it. - let snapshot = conn.snapshot(seeded.workspace_id).await?; + let snapshot = conn.snapshot(seeded.workspace_id, None, None).await?; assert!(snapshot.detections.is_empty()); assert!(snapshot.storage.is_empty()); // The owning workspace does. assert!( !conn - .snapshot(other.workspace_id) + .snapshot(other.workspace_id, None, None) .await? .detections .is_empty() diff --git a/crates/nvisy-server/src/domain/workspace_analytics.rs b/crates/nvisy-server/src/domain/workspace_analytics.rs index 2b6d157a..b4e2331a 100644 --- a/crates/nvisy-server/src/domain/workspace_analytics.rs +++ b/crates/nvisy-server/src/domain/workspace_analytics.rs @@ -26,14 +26,21 @@ impl WorkspaceAnalyticsService { Self { postgres } } - /// A workspace's stored-file and detection-health snapshot. + /// A workspace's stored-file and detection-health snapshot. Detection health + /// covers detections started in `[from, to)`, each bound applied only when + /// given; storage is the workspace's live files now. /// /// # Errors /// /// - A database error if the connection or query fails. - pub async fn snapshot(&self, workspace_id: Uuid) -> Result { + pub async fn snapshot( + &self, + workspace_id: Uuid, + from: Option, + to: Option, + ) -> Result { let mut conn = self.postgres.get_connection().await?; - Ok(conn.snapshot(workspace_id).await?) + Ok(conn.snapshot(workspace_id, from, to).await?) } /// A workspace's detection activity per day between `from` and `to`. diff --git a/crates/nvisy-server/src/handler/analytics.rs b/crates/nvisy-server/src/handler/analytics.rs index 701cb028..72b4631d 100644 --- a/crates/nvisy-server/src/handler/analytics.rs +++ b/crates/nvisy-server/src/handler/analytics.rs @@ -10,7 +10,7 @@ use crate::extract::{Authorized, Json, Query, markers}; use crate::handler::ServiceState; use crate::handler::request::DateWindow; use crate::handler::response::{WorkspaceAnalytics, WorkspaceDetectionTimeSeries}; -use crate::response::Result; +use crate::response::{ErrorResponse, Result}; /// Tracing target for workspace analytics operations. const TRACING_TARGET: &str = "nvisy_server::handler::analytics"; @@ -20,19 +20,22 @@ const TRACING_TARGET: &str = "nvisy_server::handler::analytics"; async fn get_analytics( State(analytics): State, authz: Authorized, + Query(window): Query, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Computing workspace analytics"); - let snapshot = analytics.snapshot(authz.workspace.id).await?; + let (from, to) = window.resolve_optional_bounds()?; + let snapshot = analytics.snapshot(authz.workspace.id, from, to).await?; Ok(Json(WorkspaceAnalytics::from_snapshot(snapshot))) } fn get_analytics_docs(op: TransformOperation) -> TransformOperation { op.summary("Workspace analytics") .description( - "Returns aggregate analytics for a workspace: stored-file totals with a per-kind breakdown, and detection health (status mix, error rate, and durations). Breakdowns list every kind/status, zero-filled, in a stable order.", + "Returns aggregate analytics for a workspace: stored-file totals with a per-kind breakdown, and detection health (status mix, error rate, and durations). Breakdowns list every kind/status, zero-filled, in a stable order. Detection health covers detections started within the optional `from`/`to` window (inclusive, YYYY-MM-DD, the same days as the time series); each bound applies only when given, and with neither it covers all time. Storage is always the workspace's live files now.", ) .response::<200, Json>() + .response::<400, Json>() } /// Returns a workspace's daily detection activity over a date window. diff --git a/crates/nvisy-server/src/handler/response/analytics.rs b/crates/nvisy-server/src/handler/response/analytics.rs index 6ceb296e..ace27295 100644 --- a/crates/nvisy-server/src/handler/response/analytics.rs +++ b/crates/nvisy-server/src/handler/response/analytics.rs @@ -50,11 +50,12 @@ pub struct WorkspaceStorageKindEntry { pub total_bytes: i64, } -/// Detection health for a workspace. +/// Detection health for a workspace, over the requested window (all time when +/// none was given). #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct WorkspaceDetectionAnalytics { - /// Total number of detections. + /// Number of detections started in the window. pub total: i64, /// Per-status breakdown, one entry per detection status (zero-filled), in a /// stable order. From b4a34ee4a1686dba8a519849079df015b2a02e96 Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Mon, 30 Nov 2026 04:03:12 +0100 Subject: [PATCH 06/14] Filter reviews awaiting an account's approval awaitingApprovalBy returns the reviews the account is assigned to, in in_review or partially_approved, that it has not approved yet. Co-Authored-By: Claude Opus 5.5 --- .../src/query/workspace_reviews.rs | 83 ++++++++++++++++++- .../src/types/filtering/reviews.rs | 4 + .../src/handler/request/workspace_reviews.rs | 5 ++ 3 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/nvisy-postgres/src/query/workspace_reviews.rs b/crates/nvisy-postgres/src/query/workspace_reviews.rs index 9efcc490..77ff07f6 100644 --- a/crates/nvisy-postgres/src/query/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/query/workspace_reviews.rs @@ -333,8 +333,8 @@ impl WorkspaceReviewRepository for PgConnection { ) -> Result> { use schema::workspace_reviews::{self, dsl}; - // The assignee filter is a membership test against the link table, so it - // is applied as an EXISTS subquery rather than a join. + // The assignee and awaiting-approval filters are membership tests against + // the link tables, so they are applied as EXISTS subqueries, not joins. let scoped = || { let mut query = workspace_reviews::table .filter(dsl::workspace_id.eq(workspace_id)) @@ -357,6 +357,26 @@ impl WorkspaceReviewRepository for PgConnection { if let Some(review_status) = filter.review_status { query = query.filter(dsl::review_status.eq(review_status)); } + if let Some(reviewer) = filter.awaiting_approval_by { + use schema::{ + workspace_review_approvals as wrp, workspace_review_assignees as wra, + }; + query = query + .filter( + dsl::review_status + .eq_any([ReviewStatus::InReview, ReviewStatus::PartiallyApproved]), + ) + .filter(diesel::dsl::exists( + wra::table + .filter(wra::review_id.eq(dsl::id)) + .filter(wra::account_id.eq(reviewer)), + )) + .filter(diesel::dsl::not(diesel::dsl::exists( + wrp::table + .filter(wrp::review_id.eq(dsl::id)) + .filter(wrp::account_id.eq(reviewer)), + ))); + } query }; @@ -1818,6 +1838,65 @@ mod tests { Ok(()) } + #[tokio::test] + async fn queue_filters_to_reviews_awaiting_an_approval() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let fixture = db.seed_detection_and_redaction().await; + let seeded = fixture.seeded; + let me = seeded.account_id; + let bob = { + let mut conn = db.client.get_connection().await?; + conn.create_account(NewAccount::test()).await?.id + }; + let mut conn = db.client.get_connection().await?; + let open = async |conn: &mut PgConn| { + conn.create_review(NewWorkspaceReview::test( + seeded.workspace_id, + seeded.document_id, + me, + )) + .await + }; + + // Awaiting me: assigned, submitted, and only bob has approved. + let waiting = open(&mut conn).await?; + conn.add_assignee(waiting.id, me, me).await?; + conn.add_assignee(waiting.id, bob, me).await?; + conn.submit_review(waiting.id, me).await?; + conn.approve_review(waiting.id, bob, 2, fixture.redaction_id) + .await?; + + // Not awaiting me: I already approved it. + let approved = open(&mut conn).await?; + conn.add_assignee(approved.id, me, me).await?; + conn.submit_review(approved.id, me).await?; + conn.approve_review(approved.id, me, 2, fixture.redaction_id) + .await?; + + // Not awaiting me: still a draft. + let draft = open(&mut conn).await?; + conn.add_assignee(draft.id, me, me).await?; + + // Not awaiting me: submitted, but assigned to bob only. + let elsewhere = open(&mut conn).await?; + conn.add_assignee(elsewhere.id, bob, me).await?; + conn.submit_review(elsewhere.id, me).await?; + + let queue = conn + .cursor_list_reviews( + seeded.workspace_id, + CursorPagination::new(50), + &DocumentReviewFilter { + awaiting_approval_by: Some(me), + ..Default::default() + }, + ) + .await?; + let ids: Vec<_> = queue.items.iter().map(|row| row.item.id).collect(); + assert_eq!(ids, vec![waiting.id]); + Ok(()) + } + /// A timeline entry's sort key: `(created_at, source, id)`. type Entry = (jiff::Timestamp, TimelineSource, uuid::Uuid); diff --git a/crates/nvisy-postgres/src/types/filtering/reviews.rs b/crates/nvisy-postgres/src/types/filtering/reviews.rs index 41621525..2ceba987 100644 --- a/crates/nvisy-postgres/src/types/filtering/reviews.rs +++ b/crates/nvisy-postgres/src/types/filtering/reviews.rs @@ -25,4 +25,8 @@ pub struct DocumentReviewFilter { /// Filter by review status. #[serde(skip_serializing_if = "Option::is_none")] pub review_status: Option, + /// Filter to the reviews awaiting this account's approval: it is assigned, + /// the review is `InReview` or `PartiallyApproved`, and it has not approved. + #[serde(skip_serializing_if = "Option::is_none")] + pub awaiting_approval_by: Option, } diff --git a/crates/nvisy-server/src/handler/request/workspace_reviews.rs b/crates/nvisy-server/src/handler/request/workspace_reviews.rs index 206b2ae5..4113306b 100644 --- a/crates/nvisy-server/src/handler/request/workspace_reviews.rs +++ b/crates/nvisy-server/src/handler/request/workspace_reviews.rs @@ -116,6 +116,10 @@ pub struct WorkspaceReviewsQuery { pub assignee: Option, /// Filter by review status. pub review_status: Option, + /// Filter to the reviews awaiting this account's approval (account id): it + /// is assigned, the review is `in_review` or `partially_approved`, and it has + /// not approved yet. + pub awaiting_approval_by: Option, } impl WorkspaceReviewsQuery { @@ -128,6 +132,7 @@ impl WorkspaceReviewsQuery { author_account_id: self.author, assignee_account_id: self.assignee, review_status: self.review_status, + awaiting_approval_by: self.awaiting_approval_by, } } } From c508c744aa4eacf660647ba8dc5e4a146d130a3a Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Mon, 30 Nov 2026 04:03:50 +0100 Subject: [PATCH 07/14] Credit each reviewer edit to the reviewer who made it A detection's edits are stored one decision per row in workspace_detection_edits, keyed by what the decision is about and attributed to the reviewer who last set it; a retag's label and location are separate decisions. Saving the set keeps the author of an unchanged decision and credits new or changed ones to the caller. Redaction applies each reviewer's decisions under their own account, so every audit event names the person who decided it. A detection's edits are returned as entries with their author, and the redaction review returns the audit with the accounts it names. Detection summaries carry their tags. The detections migration is edited in place: reset the database. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/nvisy-postgres/src/model/mod.rs | 2 + .../src/model/workspace_detection_edits.rs | 41 ++ .../src/model/workspace_detections.rs | 14 +- crates/nvisy-postgres/src/query/accounts.rs | 23 + crates/nvisy-postgres/src/query/mod.rs | 4 +- .../src/query/workspace_detection_edits.rs | 346 ++++++++++++ .../src/query/workspace_detections.rs | 189 ++----- crates/nvisy-postgres/src/schema.rs | 17 +- crates/nvisy-server/Cargo.toml | 3 + .../src/domain/detection_decisions.rs | 507 ++++++++++++++++++ crates/nvisy-server/src/domain/input/mod.rs | 4 +- crates/nvisy-server/src/domain/mod.rs | 1 + crates/nvisy-server/src/domain/output/mod.rs | 2 + .../src/domain/output/workspace_detections.rs | 8 +- .../src/domain/output/workspace_redactions.rs | 12 + .../src/domain/workspace_detections.rs | 135 +++-- .../src/domain/workspace_redactions.rs | 72 +-- .../src/handler/detection_audits.rs | 2 +- .../handler/request/workspace_detections.rs | 10 +- .../handler/response/workspace_detections.rs | 56 +- .../handler/response/workspace_redactions.rs | 28 + .../src/handler/workspace_detections.rs | 22 +- .../src/handler/workspace_redactions.rs | 21 +- .../2026-01-19-045016_detections/down.sql | 1 + .../2026-01-19-045016_detections/up.sql | 62 ++- 27 files changed, 1320 insertions(+), 264 deletions(-) create mode 100644 crates/nvisy-postgres/src/model/workspace_detection_edits.rs create mode 100644 crates/nvisy-postgres/src/query/workspace_detection_edits.rs create mode 100644 crates/nvisy-server/src/domain/detection_decisions.rs create mode 100644 crates/nvisy-server/src/domain/output/workspace_redactions.rs diff --git a/Cargo.lock b/Cargo.lock index cf9c6b73..e70c463e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6940,6 +6940,7 @@ dependencies = [ "csv", "derive_more", "dotenvy", + "elide", "elide-pipeline", "futures", "garde", diff --git a/Cargo.toml b/Cargo.toml index cf98005e..89458603 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,7 @@ debug = true # Elide crates elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "296f2db896f750393da47bb849156bfc83bcf4f4", default-features = false, features = [] } +elide = { git = "https://github.com/nvisycom/elide", branch = "main", default-features = false, features = [] } # Internal crates nvisy-core = { path = "./crates/nvisy-core", version = "0.1.0" } diff --git a/crates/nvisy-postgres/src/model/mod.rs b/crates/nvisy-postgres/src/model/mod.rs index 89f27156..9b6c2351 100644 --- a/crates/nvisy-postgres/src/model/mod.rs +++ b/crates/nvisy-postgres/src/model/mod.rs @@ -13,6 +13,7 @@ mod workspace_blobs; mod workspace_connection_schedule; mod workspace_connection_syncs; mod workspace_connections; +mod workspace_detection_edits; mod workspace_detection_jobs; mod workspace_detection_policy_versions; mod workspace_detections; @@ -49,6 +50,7 @@ pub use workspace_connection_syncs::{NewWorkspaceConnectionSync, WorkspaceConnec pub use workspace_connections::{ NewWorkspaceConnection, UpdateWorkspaceConnection, WorkspaceConnection, }; +pub use workspace_detection_edits::{NewDetectionDecision, WorkspaceDetectionEdit}; pub use workspace_detection_jobs::{NewWorkspaceDetectionJob, WorkspaceDetectionJob}; pub use workspace_detection_policy_versions::DetectionPolicyVersion; pub use workspace_detections::{ diff --git a/crates/nvisy-postgres/src/model/workspace_detection_edits.rs b/crates/nvisy-postgres/src/model/workspace_detection_edits.rs new file mode 100644 index 00000000..488d6d65 --- /dev/null +++ b/crates/nvisy-postgres/src/model/workspace_detection_edits.rs @@ -0,0 +1,41 @@ +//! Workspace detection edit model: one reviewer decision about a detection. +//! +//! A detection's edits are its rows here, each holding one decision and the +//! reviewer who last set it. Redaction applies each reviewer's decisions under +//! their own account, so every audit event names the person who decided it. + +use diesel::prelude::*; +use jiff_diesel::Timestamp; +use uuid::Uuid; + +use crate::schema::workspace_detection_edits; +use crate::types::Json; + +/// One reviewer decision about a detection. +#[derive(Debug, Clone, PartialEq, Queryable, Selectable)] +#[diesel(table_name = workspace_detection_edits)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct WorkspaceDetectionEdit { + /// Detection the decision is about. + pub detection_id: Uuid, + /// What the decision is about, derived by the server from the edit. + pub decision_key: String, + /// Reviewer who last set the decision. + pub account_id: Uuid, + /// The decision, as an engine `EditSet` holding exactly one edit. Stored + /// opaquely here; the engine type lives in the server layer. + pub edit: Json, + /// When the decision was first set. + pub created_at: Timestamp, + /// When the decision was last set. + pub updated_at: Timestamp, +} + +/// A decision to store for a detection, keyed by what it is about. +#[derive(Debug, Clone, PartialEq)] +pub struct NewDetectionDecision { + /// What the decision is about. + pub decision_key: String, + /// The decision, as an engine `EditSet` holding exactly one edit. + pub edit: Json, +} diff --git a/crates/nvisy-postgres/src/model/workspace_detections.rs b/crates/nvisy-postgres/src/model/workspace_detections.rs index 51df235a..135d1d17 100644 --- a/crates/nvisy-postgres/src/model/workspace_detections.rs +++ b/crates/nvisy-postgres/src/model/workspace_detections.rs @@ -49,13 +49,11 @@ pub struct WorkspaceDetection { pub retention_override: Option>, /// Non-encrypted metadata for filtering/display. pub metadata: Json, - /// Accumulated reviewer edits (the engine's `EditSet`) layered over the base - /// analysis at redact time, so manual corrections persist between redactions. - /// Stored opaquely as JSON here (the engine type lives in the server layer); - /// `None` means no edits yet. - pub edit_set: Option>, - /// Optimistic-concurrency version for `edit_set`, bumped on every edit write; an - /// edit names the revision it read and the write proceeds only if it still matches. + /// Optimistic-concurrency version of the detection's reviewer edits (held as + /// [`WorkspaceDetectionEdit`] rows), bumped on every edit write; an edit names + /// the revision it read and the write proceeds only if it still matches. + /// + /// [`WorkspaceDetectionEdit`]: crate::model::WorkspaceDetectionEdit pub edit_set_rev: i32, /// When a worker last claimed this detection. Acts as a lease: a redelivered /// job whose claim is still fresh is skipped, while a stale claim (a worker @@ -128,8 +126,6 @@ pub struct UpdateWorkspaceDetection { pub audit_expires_at: Option>, /// Non-encrypted metadata for filtering/display. pub metadata: Option>, - /// Accumulated reviewer edits; outer `None` leaves it, inner `None` clears it. - pub edit_set: Option>>, /// When a worker last claimed this detection (lease timestamp). pub claimed_at: Option>, /// When the detection completed analysis. diff --git a/crates/nvisy-postgres/src/query/accounts.rs b/crates/nvisy-postgres/src/query/accounts.rs index 0e19db5c..ab6110c0 100644 --- a/crates/nvisy-postgres/src/query/accounts.rs +++ b/crates/nvisy-postgres/src/query/accounts.rs @@ -32,6 +32,14 @@ pub trait AccountRepository { account_id: Uuid, ) -> impl Future>> + Send; + /// Finds the public references of `account_ids`, in the order given. As with + /// [`Self::find_account_ref`], a soft-deleted account still resolves; an id + /// matching no account is skipped. + fn find_account_refs( + &mut self, + account_ids: &[Uuid], + ) -> impl Future>> + Send; + /// Finds an account by its unique identifier. /// /// Retrieves a specific account using its UUID, automatically excluding @@ -157,6 +165,21 @@ impl AccountRepository for PgConnection { .optional()?) } + async fn find_account_refs(&mut self, account_ids: &[Uuid]) -> Result> { + use schema::accounts::{self, dsl}; + + if account_ids.is_empty() { + return Ok(Vec::new()); + } + let mut refs: Vec = accounts::table + .filter(dsl::id.eq_any(account_ids)) + .select(AccountRefRow::as_select()) + .load(self) + .await?; + refs.sort_by_key(|account| account_ids.iter().position(|id| *id == account.id)); + Ok(refs) + } + async fn find_account_by_id(&mut self, account_id: Uuid) -> Result> { use schema::accounts::{self, dsl}; diff --git a/crates/nvisy-postgres/src/query/mod.rs b/crates/nvisy-postgres/src/query/mod.rs index 2c672b84..e06f5e24 100644 --- a/crates/nvisy-postgres/src/query/mod.rs +++ b/crates/nvisy-postgres/src/query/mod.rs @@ -21,6 +21,7 @@ mod workspace_blobs; mod workspace_connection_schedule; mod workspace_connection_syncs; mod workspace_connections; +mod workspace_detection_edits; mod workspace_detection_policy_versions; mod workspace_detections; mod workspace_documents; @@ -56,9 +57,10 @@ pub use workspace_blobs::{ReclaimableBlob, WorkspaceBlobRepository}; pub use workspace_connection_schedule::WorkspaceConnectionScheduleRepository; pub use workspace_connection_syncs::WorkspaceConnectionSyncRepository; pub use workspace_connections::{ScheduledConnection, WorkspaceConnectionRepository}; +pub use workspace_detection_edits::{DetectionEditRepository, EditWriteOutcome}; pub use workspace_detection_policy_versions::DetectionPolicyVersionRepository; pub use workspace_detections::{ - DetectionDocuments, DetectionListRow, DetectionSummary, DetectionTreeRow, EditWriteOutcome, + DetectionDocuments, DetectionListRow, DetectionSummary, DetectionTreeRow, WorkspaceDetectionRepository, }; pub use workspace_documents::{DocumentWithBlob, ImportedDocumentRef, WorkspaceDocumentRepository}; diff --git a/crates/nvisy-postgres/src/query/workspace_detection_edits.rs b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs new file mode 100644 index 00000000..240300d5 --- /dev/null +++ b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs @@ -0,0 +1,346 @@ +//! Repository for a detection's reviewer decisions. +//! +//! A detection's edits are stored one decision per row, keyed by what the +//! decision is about and attributed to the reviewer who last set it. A write +//! replaces the whole set under the detection's `edit_set_rev` guard: a decision +//! the write leaves unchanged keeps its author, a new or changed one is +//! attributed to the writer, and one the write omits is deleted. + +use std::collections::{HashMap, HashSet}; +use std::future::Future; + +use diesel::dsl::now; +use diesel::prelude::*; +use diesel_async::{AsyncConnection, RunQueryDsl}; +use uuid::Uuid; + +use crate::model::{NewDetectionDecision, WorkspaceDetection, WorkspaceDetectionEdit}; +use crate::types::{AccountRefRow, Json, WithAccountRef}; +use crate::{PgConnection, Result, schema}; + +/// The outcome of a guarded write of a detection's edits. +#[derive(Debug, Clone)] +pub enum EditWriteOutcome { + /// The write landed; carries the updated detection (with the bumped revision). + Updated(Box), + /// The detection exists but its `edit_set_rev` no longer matches the expected + /// one: a concurrent edit won, so this write was not applied. + Stale, + /// No live detection matches in the workspace. + Absent, +} + +/// Repository for the detection edit table. +pub trait DetectionEditRepository { + /// Replaces a live detection's decisions, scoped to its workspace, under an + /// optimistic-concurrency guard. `expected_rev` is the `edit_set_rev` the + /// caller read; the write proceeds and bumps the revision only if it still + /// matches. An empty `decisions` clears the detection's edits. + /// + /// A decision whose key and content are unchanged keeps its author and + /// timestamps. A new or changed one is attributed to `account_id`. A stored + /// decision whose key is absent from `decisions` is deleted. Keys in + /// `decisions` must be distinct. + /// + /// Returns [`EditWriteOutcome::Updated`] with the detection, [`Stale`] when the + /// detection exists but its revision has moved on, or [`Absent`] when no live + /// detection matches. + /// + /// [`Stale`]: EditWriteOutcome::Stale + /// [`Absent`]: EditWriteOutcome::Absent + fn replace_detection_edits( + &mut self, + workspace_id: Uuid, + detection_id: Uuid, + account_id: Uuid, + expected_rev: i32, + decisions: Vec, + ) -> impl Future> + Send; + + /// Lists a detection's decisions with their authors, oldest-set first. + fn list_detection_edits( + &mut self, + detection_id: Uuid, + ) -> impl Future>>> + Send; +} + +impl DetectionEditRepository for PgConnection { + async fn replace_detection_edits( + &mut self, + workspace_id: Uuid, + detection_id: Uuid, + account_id: Uuid, + expected_rev: i32, + decisions: Vec, + ) -> Result { + use schema::workspace_detection_edits::{self as edits, dsl as edit}; + use schema::workspace_detections::{self, dsl}; + + self.transaction(async |conn| { + // Bump the revision only while it still matches, so the next writer's + // stale guard trips. The bump also locks the detection row, so the + // decision rewrite below cannot interleave with a concurrent writer. + let updated: Option = diesel::update( + workspace_detections::table + .filter(dsl::id.eq(detection_id)) + .filter(dsl::workspace_id.eq(workspace_id)) + .filter(dsl::deleted_at.is_null()) + .filter(dsl::edit_set_rev.eq(expected_rev)), + ) + .set(dsl::edit_set_rev.eq(dsl::edit_set_rev + 1)) + .returning(WorkspaceDetection::as_returning()) + .get_result(conn) + .await + .optional()?; + + let Some(detection) = updated else { + // No row updated: either the detection is gone (Absent) or its + // revision moved on (Stale). A scoped existence check separates them. + let exists: bool = diesel::select(diesel::dsl::exists( + workspace_detections::table + .filter(dsl::id.eq(detection_id)) + .filter(dsl::workspace_id.eq(workspace_id)) + .filter(dsl::deleted_at.is_null()), + )) + .get_result(conn) + .await?; + return Ok(if exists { + EditWriteOutcome::Stale + } else { + EditWriteOutcome::Absent + }); + }; + + let stored: HashMap = edits::table + .filter(edit::detection_id.eq(detection_id)) + .select((edit::decision_key, edit::edit)) + .load::<(String, Json)>(conn) + .await? + .into_iter() + .map(|(key, value)| (key, value.as_value().clone())) + .collect(); + + // Delete the decisions the write omits. + let keys: HashSet<&str> = decisions.iter().map(|d| d.decision_key.as_str()).collect(); + let omitted: Vec<&str> = stored + .keys() + .map(String::as_str) + .filter(|key| !keys.contains(key)) + .collect(); + if !omitted.is_empty() { + diesel::delete( + edits::table + .filter(edit::detection_id.eq(detection_id)) + .filter(edit::decision_key.eq_any(&omitted)), + ) + .execute(conn) + .await?; + } + + // Write the new and changed decisions as the caller; an unchanged one + // is left alone, keeping its author. + for decision in decisions { + if stored.get(&decision.decision_key) == Some(decision.edit.as_value()) { + continue; + } + diesel::insert_into(edits::table) + .values(( + edit::detection_id.eq(detection_id), + edit::decision_key.eq(&decision.decision_key), + edit::account_id.eq(account_id), + edit::edit.eq(&decision.edit), + )) + .on_conflict((edit::detection_id, edit::decision_key)) + .do_update() + .set(( + edit::account_id.eq(account_id), + edit::edit.eq(&decision.edit), + edit::updated_at.eq(now), + )) + .execute(conn) + .await?; + } + + Ok(EditWriteOutcome::Updated(Box::new(detection))) + }) + .await + } + + async fn list_detection_edits( + &mut self, + detection_id: Uuid, + ) -> Result>> { + use schema::accounts; + use schema::workspace_detection_edits::{self as edits, dsl as edit}; + + let rows: Vec<(WorkspaceDetectionEdit, AccountRefRow)> = edits::table + .inner_join(accounts::table.on(edit::account_id.eq(accounts::id))) + .filter(edit::detection_id.eq(detection_id)) + .order((edit::updated_at.asc(), edit::decision_key.asc())) + .select(( + WorkspaceDetectionEdit::as_select(), + AccountRefRow::as_select(), + )) + .load(self) + .await?; + Ok(rows.into_iter().map(WithAccountRef::from).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PgConn; + use crate::model::{NewAccount, NewWorkspaceDetection}; + use crate::query::{AccountRepository, WorkspaceDetectionRepository}; + use crate::test_util::TestDatabase; + + fn decision(key: &str, value: serde_json::Value) -> NewDetectionDecision { + NewDetectionDecision { + decision_key: key.to_owned(), + edit: Json::from_raw(value), + } + } + + /// The stored decisions as `(key, author)`, in key order. + async fn authors(conn: &mut PgConn, detection_id: Uuid) -> anyhow::Result> { + let mut rows: Vec<_> = conn + .list_detection_edits(detection_id) + .await? + .into_iter() + .map(|row| (row.item.decision_key, row.account.id)) + .collect(); + rows.sort(); + Ok(rows) + } + + #[tokio::test] + async fn a_rewrite_keeps_unchanged_authors_and_attributes_the_rest() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let alice = seeded.account_id; + let mut conn = db.client.get_connection().await?; + let bob = conn.create_account(NewAccount::test()).await?.id; + let detection = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + alice, + seeded.document_id, + )) + .await?; + + // Alice sets two decisions. + let outcome = conn + .replace_detection_edits( + seeded.workspace_id, + detection.id, + alice, + 0, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 1 })), + ], + ) + .await?; + let EditWriteOutcome::Updated(updated) = outcome else { + panic!("the first write lands"); + }; + assert_eq!(updated.edit_set_rev, 1); + + // Bob keeps `a`, changes `b`, and adds `c`. + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + bob, + 1, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 2 })), + decision("c", serde_json::json!({ "v": 1 })), + ], + ) + .await?; + assert_eq!( + authors(&mut conn, detection.id).await?, + vec![ + ("a".to_owned(), alice), + ("b".to_owned(), bob), + ("c".to_owned(), bob), + ] + ); + + // Alice drops `c`; the others are unchanged and keep their authors. + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + alice, + 2, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 2 })), + ], + ) + .await?; + assert_eq!( + authors(&mut conn, detection.id).await?, + vec![("a".to_owned(), alice), ("b".to_owned(), bob),] + ); + + // An empty write clears them. + conn.replace_detection_edits(seeded.workspace_id, detection.id, bob, 3, Vec::new()) + .await?; + assert_eq!(authors(&mut conn, detection.id).await?, Vec::new()); + Ok(()) + } + + #[tokio::test] + async fn a_write_is_guarded_by_revision() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + let detection = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + )) + .await?; + assert_eq!(detection.edit_set_rev, 0, "a new detection starts at rev 0"); + let write = || vec![decision("a", serde_json::json!({ "v": 1 }))]; + + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + seeded.account_id, + 0, + write(), + ) + .await?; + + // Reusing the old revision is stale, and changes nothing. + let stale = conn + .replace_detection_edits( + seeded.workspace_id, + detection.id, + seeded.account_id, + 0, + Vec::new(), + ) + .await?; + assert!(matches!(stale, EditWriteOutcome::Stale)); + assert_eq!(authors(&mut conn, detection.id).await?.len(), 1); + + // A detection that does not exist is absent. + let absent = conn + .replace_detection_edits( + seeded.workspace_id, + Uuid::now_v7(), + seeded.account_id, + 0, + write(), + ) + .await?; + assert!(matches!(absent, EditWriteOutcome::Absent)); + Ok(()) + } +} diff --git a/crates/nvisy-postgres/src/query/workspace_detections.rs b/crates/nvisy-postgres/src/query/workspace_detections.rs index 8d617731..16f69987 100644 --- a/crates/nvisy-postgres/src/query/workspace_detections.rs +++ b/crates/nvisy-postgres/src/query/workspace_detections.rs @@ -20,18 +20,6 @@ use crate::types::{ }; use crate::{Error, PgConnection, Result, schema}; -/// The outcome of a guarded `edit_set` write. -#[derive(Debug, Clone)] -pub enum EditWriteOutcome { - /// The write landed; carries the updated detection (with the bumped revision). - Updated(Box), - /// The detection exists but its `edit_set_rev` no longer matches the expected - /// one — a concurrent edit won, so this write was not applied. - Stale, - /// No live detection matches in the workspace. - Absent, -} - /// Resolved display name of a detection's input document. /// /// `None` when the document has been removed (e.g. by retention). Redacted @@ -54,6 +42,13 @@ fn detection_error() -> _ { .nullable() } +#[diesel::dsl::auto_type] +fn detection_tags() -> _ { + schema::workspace_detections::metadata + .retrieve_as_object("tags") + .nullable() +} + #[diesel::dsl::auto_type] fn retained_intermediate() -> _ { diesel::dsl::exists( @@ -111,6 +106,10 @@ pub struct DetectionSummary { #[diesel(select_expression = detection_error())] #[diesel(select_expression_type = detection_error)] pub error: Option, + /// Free-form tags, without loading the rest of the metadata. + #[diesel(select_expression = detection_tags())] + #[diesel(select_expression_type = detection_tags)] + pub tags: Option>>, /// Whether an intermediate artifact is retained. #[diesel(select_expression = retained_intermediate())] #[diesel(select_expression_type = retained_intermediate)] @@ -273,25 +272,6 @@ pub trait WorkspaceDetectionRepository { detection_id: Uuid, updates: UpdateWorkspaceDetection, ) -> impl Future> + Send; - - /// Sets a live detection's accumulated reviewer edits (`edit_set`), scoped to its - /// workspace, under an optimistic-concurrency guard. `expected_rev` is the - /// `edit_set_rev` the caller read; the write proceeds and bumps the revision only - /// if it still matches. Pass `Some` to store the edits, `None` to clear them. - /// - /// Returns [`EditWriteOutcome::Updated`] with the new row, [`Stale`] when the - /// detection exists but its revision has moved on (a concurrent edit won), or - /// [`Absent`] when no live detection matches. - /// - /// [`Stale`]: EditWriteOutcome::Stale - /// [`Absent`]: EditWriteOutcome::Absent - fn set_detection_edits( - &mut self, - workspace_id: Uuid, - detection_id: Uuid, - expected_rev: i32, - edit_set: Option>, - ) -> impl Future> + Send; } impl WorkspaceDetectionRepository for PgConnection { @@ -335,56 +315,6 @@ impl WorkspaceDetectionRepository for PgConnection { .await?) } - async fn set_detection_edits( - &mut self, - workspace_id: Uuid, - detection_id: Uuid, - expected_rev: i32, - edit_set: Option>, - ) -> Result { - use schema::workspace_detections::{self, dsl}; - - // Update only when the revision still matches, bumping it so the next writer's - // stale guard trips. The whole read-decide-write is one statement, so it is - // atomic against a concurrent edit without a separate lock. - let updated: Option = diesel::update( - workspace_detections::table - .filter(dsl::id.eq(detection_id)) - .filter(dsl::workspace_id.eq(workspace_id)) - .filter(dsl::deleted_at.is_null()) - .filter(dsl::edit_set_rev.eq(expected_rev)), - ) - .set(( - dsl::edit_set.eq(edit_set), - dsl::edit_set_rev.eq(dsl::edit_set_rev + 1), - )) - .returning(WorkspaceDetection::as_returning()) - .get_result(self) - .await - .optional()?; - - if let Some(detection) = updated { - return Ok(EditWriteOutcome::Updated(Box::new(detection))); - } - - // No row updated: either the detection is gone (Absent) or its revision moved - // on (Stale). A scoped existence check separates the two. - let exists: bool = diesel::select(diesel::dsl::exists( - workspace_detections::table - .filter(dsl::id.eq(detection_id)) - .filter(dsl::workspace_id.eq(workspace_id)) - .filter(dsl::deleted_at.is_null()), - )) - .get_result(self) - .await?; - - Ok(if exists { - EditWriteOutcome::Stale - } else { - EditWriteOutcome::Absent - }) - } - async fn find_workspace_detection_by_id( &mut self, workspace_id: Uuid, @@ -703,7 +633,7 @@ mod tests { use crate::model::{NewWorkspaceDetection, UpdateWorkspaceDetection}; use crate::query::WorkspaceDetectionRepository; use crate::test_util::TestDatabase; - use crate::types::DetectionStatus; + use crate::types::{DetectionMetadata, DetectionStatus}; #[tokio::test] async fn claim_transitions_pending_and_honors_a_fresh_lease() -> anyhow::Result<()> { @@ -938,6 +868,48 @@ mod tests { Ok(()) } + #[tokio::test] + async fn cursor_list_projects_detection_tags() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + + let mut tagged = + NewWorkspaceDetection::test(seeded.workspace_id, seeded.account_id, seeded.document_id); + tagged.metadata = Some(Json::encode(&DetectionMetadata { + tags: Some(vec!["finance".into(), "q3".into()]), + ..Default::default() + })); + let tagged = conn.create_workspace_detection(tagged).await?; + let untagged = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + )) + .await?; + + let page = conn + .cursor_list_workspace_detections( + seeded.workspace_id, + CursorPagination::new(50), + &DetectionFilter::default(), + ) + .await?; + let tags_of = |id| { + page.items + .iter() + .find(|row| row.detection.id == id) + .and_then(|row| row.detection.tags.as_ref().map(Json::or_default)) + }; + assert_eq!( + tags_of(tagged.id), + Some(vec!["finance".to_owned(), "q3".to_owned()]) + ); + assert_eq!(tags_of(untagged.id), None); + Ok(()) + } + #[tokio::test] async fn cursor_list_filters_by_status_and_names_the_input_document() -> anyhow::Result<()> { let db = TestDatabase::start().await; @@ -1380,57 +1352,4 @@ mod tests { ); Ok(()) } - - #[tokio::test] - async fn set_detection_edits_is_guarded_by_revision() -> anyhow::Result<()> { - use crate::query::EditWriteOutcome; - use crate::types::Json; - - let db = TestDatabase::start().await; - let seeded = db.seed_document().await; - let mut conn = db.client.get_connection().await?; - - let detection = conn - .create_workspace_detection(NewWorkspaceDetection::test( - seeded.workspace_id, - seeded.account_id, - seeded.document_id, - )) - .await?; - assert_eq!(detection.edit_set_rev, 0, "a new detection starts at rev 0"); - - let edits = || Some(Json::from_raw(serde_json::json!({ "v": 1 }))); - - // A write at the current revision lands and bumps the revision. - let first = conn - .set_detection_edits(seeded.workspace_id, detection.id, 0, edits()) - .await?; - let EditWriteOutcome::Updated(updated) = first else { - panic!("expected the write to land"); - }; - assert_eq!(updated.edit_set_rev, 1); - - // A second write at the now-stale revision 0 is rejected, nothing changes. - let stale = conn - .set_detection_edits(seeded.workspace_id, detection.id, 0, edits()) - .await?; - assert!(matches!(stale, EditWriteOutcome::Stale)); - - // A write at the current revision 1 lands again. - let next = conn - .set_detection_edits(seeded.workspace_id, detection.id, 1, None) - .await?; - let EditWriteOutcome::Updated(cleared) = next else { - panic!("expected the write to land"); - }; - assert_eq!(cleared.edit_set_rev, 2); - assert!(cleared.edit_set.is_none(), "None clears the edits"); - - // A write against a detection that does not exist reports Absent. - let absent = conn - .set_detection_edits(seeded.workspace_id, uuid::Uuid::now_v7(), 0, edits()) - .await?; - assert!(matches!(absent, EditWriteOutcome::Absent)); - Ok(()) - } } diff --git a/crates/nvisy-postgres/src/schema.rs b/crates/nvisy-postgres/src/schema.rs index c2ff7d32..f082143b 100644 --- a/crates/nvisy-postgres/src/schema.rs +++ b/crates/nvisy-postgres/src/schema.rs @@ -255,6 +255,19 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + + workspace_detection_edits (detection_id, decision_key) { + detection_id -> Uuid, + decision_key -> Text, + account_id -> Uuid, + edit -> Jsonb, + created_at -> Timestamptz, + updated_at -> Timestamptz, + } +} + diesel::table! { use diesel::sql_types::*; use super::sql_types::OutboxStatus; @@ -297,7 +310,6 @@ diesel::table! { idempotency_key -> Nullable, retention_override -> Nullable, metadata -> Jsonb, - edit_set -> Nullable, edit_set_rev -> Int4, claimed_at -> Nullable, started_at -> Timestamptz, @@ -601,6 +613,8 @@ diesel::joinable!(workspace_connection_syncs -> accounts (account_id)); diesel::joinable!(workspace_connection_syncs -> workspace_connections (connection_id)); diesel::joinable!(workspace_connections -> accounts (account_id)); diesel::joinable!(workspace_connections -> workspaces (workspace_id)); +diesel::joinable!(workspace_detection_edits -> accounts (account_id)); +diesel::joinable!(workspace_detection_edits -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_jobs -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_policy_versions -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_policy_versions -> workspace_policy_versions (policy_version_id)); @@ -653,6 +667,7 @@ diesel::allow_tables_to_appear_in_same_query!( workspace_connection_schedule, workspace_connection_syncs, workspace_connections, + workspace_detection_edits, workspace_detection_jobs, workspace_detection_policy_versions, workspace_detections, diff --git a/crates/nvisy-server/Cargo.toml b/crates/nvisy-server/Cargo.toml index 35bcd9e5..e827e320 100644 --- a/crates/nvisy-server/Cargo.toml +++ b/crates/nvisy-server/Cargo.toml @@ -153,6 +153,9 @@ ipnet = { workspace = true, features = [] } url = { workspace = true, features = [] } [dev-dependencies] +# Elide crates +elide = { workspace = true, features = ["engine"] } + # Internal crates nvisy-nats = { workspace = true, features = [] } nvisy-postgres = { workspace = true, features = ["schema", "test_util"] } diff --git a/crates/nvisy-server/src/domain/detection_decisions.rs b/crates/nvisy-server/src/domain/detection_decisions.rs new file mode 100644 index 00000000..3c569eb0 --- /dev/null +++ b/crates/nvisy-server/src/domain/detection_decisions.rs @@ -0,0 +1,507 @@ +//! A detection's reviewer edits as attributed decisions. +//! +//! An [`EditSet`] is stored one decision per row, each keyed by what it is about, +//! so a rewrite can tell which decisions changed and credit only those to the +//! writer. [`split`] turns a set into keyed decisions, [`merge`] joins decisions +//! back into one set, and [`apply`] lands them on a report under each decision's +//! author, so every audit event names the reviewer who made that decision. +//! +//! Keys follow elide's own channels: a retag is split into its relabel and its +//! relocation, so two reviewers correcting one entity's label and span are each +//! credited with their own correction. An added entity has no id until it is +//! applied, so it is keyed by its content: identical adds redact the same span, +//! so they are one decision. + +use elide_pipeline::Report; +use elide_pipeline::entity::{ + AuditKind, Edit, EditBucket, EditSet, HiddenChoices, HiddenContentEdits, Retag, +}; +use elide_pipeline::modality::{Audio, Image, Modality, Tabular, Text}; +use nvisy_postgres::model::WorkspaceDetectionEdit; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +use crate::response::{ErrorKind, Result}; + +/// One reviewer decision: an [`EditSet`] holding exactly one edit, and the key +/// naming what it is about. +#[derive(Debug, Clone)] +pub(crate) struct Decision { + /// What the decision is about: its modality, channel, and target. + pub key: String, + /// The decision itself. + pub edits: EditSet, +} + +/// Splits `edits` into one [`Decision`] per question it answers. +/// +/// A retag setting both a label and a location becomes two decisions. A +/// decision repeated within the set collapses into one, the last one kept; for +/// an added entity, a repeat is an identical add, which redacts the same span. +/// +/// # Errors +/// +/// - `InternalServerError` if an edit cannot be encoded for its key. +pub(crate) fn split(edits: &EditSet) -> Result> { + let mut decisions = Decisions::default(); + split_bucket::(edits, &mut decisions)?; + split_bucket::(edits, &mut decisions)?; + split_bucket::(edits, &mut decisions)?; + split_bucket::