diff --git a/.env.example b/.env.example index 3ba8bc3c..de333293 100644 --- a/.env.example +++ b/.env.example @@ -127,6 +127,15 @@ ENCRYPTION_KEY_FILEPATH=./encryption.key # Optional path to a TOML file with the deployment engine configuration # ENGINE_CONFIG_FILEPATH= +# Who issues redaction certificates, named at the top of each certificate's PDF, in its +# footer, and in its metadata +CERTIFICATE_ISSUER=nvisy.com + +# Where a reader of a certificate's PDF checks it, drawn as a QR code: {reference} is +# replaced with the certificate's reference, as in +# https://app.nvisy.com/verify/{reference}. Absent means the PDF has no link +# CERTIFICATE_VERIFY_URL= + # ─── Health ─── # How long cached health results remain valid before a fresh check diff --git a/Cargo.lock b/Cargo.lock index 86b14df8..9751669d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,6 +36,7 @@ dependencies = [ "cipher", "cpubits", "cpufeatures 0.3.1", + "zeroize", ] [[package]] @@ -50,6 +51,7 @@ dependencies = [ "ctr", "ctutils", "ghash", + "zeroize", ] [[package]] @@ -239,6 +241,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -915,6 +926,12 @@ dependencies = [ "url", ] +[[package]] +name = "az" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be5eb007b7cacc6c660343e96f650fedf4b5a77512399eb952ca6642cf8d13f7" + [[package]] name = "base16ct" version = "1.0.0" @@ -966,6 +983,20 @@ dependencies = [ "url", ] +[[package]] +name = "biblatex" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "591eba69b7c085632e22ca03606f0bbea68d53bbe26c8962e2d549af20c6a561" +dependencies = [ + "paste", + "roman-numerals-rs", + "strum 0.27.2", + "unic-langid", + "unicode-normalization", + "unscanny", +] + [[package]] name = "bigdecimal" version = "0.4.11" @@ -980,6 +1011,15 @@ dependencies = [ "serde", ] +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -1012,6 +1052,9 @@ name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "bitpacking" @@ -1090,6 +1133,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", + "zeroize", ] [[package]] @@ -1239,6 +1283,12 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + [[package]] name = "bytecheck" version = "0.8.3" @@ -1381,6 +1431,7 @@ dependencies = [ "cipher", "cpufeatures 0.3.1", "rand_core 0.10.1", + "zeroize", ] [[package]] @@ -1393,8 +1444,38 @@ dependencies = [ "chacha20", "cipher", "poly1305", + "zeroize", +] + +[[package]] +name = "chardetng" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53" +dependencies = [ + "cfg-if", + "encoding_rs", + "memchr", +] + +[[package]] +name = "chinese-number" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e964125508474a83c95eb935697abbeb446ff4e9d62c71ce880e3986d1c606b" +dependencies = [ + "chinese-variant", + "enum-ordinalize", + "num-bigint", + "num-traits", ] +[[package]] +name = "chinese-variant" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d1275808335c5583ea45a4141d631dafcb36b79fa8a5e10b00e356b6af3e08a" + [[package]] name = "chrono" version = "0.4.45" @@ -1419,6 +1500,33 @@ dependencies = [ "phf 0.12.1", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "cipher" version = "0.5.2" @@ -1430,6 +1538,17 @@ dependencies = [ "inout", ] +[[package]] +name = "citationberg" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756ff1e3d43a9ecc8183932fb4d9fd3971236f3ce4acb62fe51d1cd43297547d" +dependencies = [ + "quick-xml 0.38.4", + "serde", + "serde_path_to_error", +] + [[package]] name = "clap" version = "4.6.10" @@ -1503,6 +1622,24 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "codex" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0732ab1a27b4ea05e6f9f60a5122c9924dd5123defde0d8e907f58cf643d40e6" +dependencies = [ + "chinese-number", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + [[package]] name = "color_quant" version = "1.1.0" @@ -1525,6 +1662,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "comemo" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c963350b2b08aa4b725d7802593245380ab53dacfedcaa971385fc33306c0d4" +dependencies = [ + "comemo-macros", + "parking_lot", + "rustc-hash", + "siphasher", + "slab", +] + +[[package]] +name = "comemo-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3c400139ba1389ef9e20ad2d87cda68b437a66483aa0da616bdf2cea7413853" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "comfy-table" version = "7.2.2" @@ -1693,6 +1854,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "counter" version = "0.7.1" @@ -2093,6 +2263,12 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "datafusion" version = "53.1.0" @@ -2949,6 +3125,7 @@ dependencies = [ "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", + "zeroize", ] [[package]] @@ -3056,6 +3233,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ecow" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78e4f79b296fbaab6ce2e22d52cb4c7f010fe0ebe7a32e34fa25885fd797bd02" +dependencies = [ + "serde", +] + [[package]] name = "ed25519" version = "2.2.3" @@ -3124,7 +3310,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "elide" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-audio", "elide-backend", @@ -3148,7 +3334,7 @@ dependencies = [ [[package]] name = "elide-audio" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", "elide-codec", @@ -3164,7 +3350,7 @@ dependencies = [ [[package]] name = "elide-backend" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-core", "gloo-timers", @@ -3176,7 +3362,7 @@ dependencies = [ [[package]] name = "elide-bentoml" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "base64 0.23.1", "bentoml", @@ -3193,18 +3379,22 @@ dependencies = [ [[package]] name = "elide-codec" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", + "chardetng", "elide-core", + "encoding_rs", "futures", "hipstr", + "schemars 1.2.3", + "serde", ] [[package]] name = "elide-core" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "blake3", "celes", @@ -3222,7 +3412,7 @@ dependencies = [ [[package]] name = "elide-detection" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-core", "futures", @@ -3235,7 +3425,7 @@ dependencies = [ [[package]] name = "elide-engine" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", "elide-audio", @@ -3258,7 +3448,7 @@ dependencies = [ [[package]] name = "elide-fake" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-core", "fake", @@ -3269,7 +3459,7 @@ dependencies = [ [[package]] name = "elide-format" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-audio", "elide-codec", @@ -3284,7 +3474,7 @@ dependencies = [ [[package]] name = "elide-image" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", "elide-codec", @@ -3301,7 +3491,7 @@ dependencies = [ [[package]] name = "elide-lingua" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-core", "lingua", @@ -3311,7 +3501,7 @@ dependencies = [ [[package]] name = "elide-llm" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "base64 0.23.1", "elide-core", @@ -3329,12 +3519,13 @@ dependencies = [ "tracing", "unicode-normalization", "uuid", + "zeroize", ] [[package]] name = "elide-macros" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -3345,7 +3536,7 @@ dependencies = [ [[package]] name = "elide-markup" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-codec", "elide-core", @@ -3355,7 +3546,7 @@ dependencies = [ [[package]] name = "elide-ner" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "elide-core", "hipstr", @@ -3366,7 +3557,7 @@ dependencies = [ [[package]] name = "elide-office" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", "elide-codec", @@ -3380,7 +3571,7 @@ dependencies = [ [[package]] name = "elide-pattern" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "aho-corasick", "bs58", @@ -3393,14 +3584,14 @@ dependencies = [ "phonenumber", "regex", "serde", - "toml", + "toml 1.2.3+spec-1.1.0", "unicode-segmentation", ] [[package]] name = "elide-pdf" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "bytes", "elide-codec", @@ -3409,7 +3600,7 @@ dependencies = [ "hayro-cmap", "image", "lopdf", - "read-fonts", + "read-fonts 0.47.0", "schemars 1.2.3", "serde", "unicode-normalization", @@ -3418,7 +3609,7 @@ dependencies = [ [[package]] name = "elide-plain" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "anstream", "bytes", @@ -3430,7 +3621,7 @@ dependencies = [ [[package]] name = "elide-redaction" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#985ec3cdeeaa23bcac31d45c3fde6fb1f0198cd1" +source = "git+https://github.com/nvisycom/elide?branch=main#0bafb45094fc6290d34dadd876d553cd82fd4e5f" dependencies = [ "aes-gcm", "base64 0.23.1", @@ -3455,7 +3646,7 @@ dependencies = [ [[package]] name = "elide-runtime" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "bytes", "csv", @@ -3478,25 +3669,31 @@ dependencies = [ [[package]] name = "elide-runtime-certificate" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ + "bytes", "elide", "elide-runtime-core", "elide-runtime-governance", "hipstr", "jiff 1.0.3", + "qrcode", "schemars 1.2.3", "serde", "serde_json", + "typst", + "typst-layout", + "typst-pdf", "uuid", ] [[package]] name = "elide-runtime-core" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", + "getrandom 0.4.3", "schemars 1.2.3", "serde", "sha2 0.11.3", @@ -3505,20 +3702,21 @@ dependencies = [ [[package]] name = "elide-runtime-deployment" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", "elide-runtime-core", "hipstr", "schemars 1.2.3", "serde", - "toml", + "toml 1.2.3+spec-1.1.0", + "zeroize", ] [[package]] name = "elide-runtime-governance" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", "elide-runtime-core", @@ -3532,7 +3730,7 @@ dependencies = [ [[package]] name = "elide-runtime-provider" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", "elide-bentoml", @@ -3545,12 +3743,13 @@ dependencies = [ "schemars 1.2.3", "serde", "uuid", + "zeroize", ] [[package]] name = "elide-runtime-review" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", "elide-runtime-core", @@ -3563,7 +3762,7 @@ dependencies = [ [[package]] name = "elide-runtime-template" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190#4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190" +source = "git+https://github.com/nvisycom/elide-runtime?rev=eaa2922cbff411f5efd5f4b7dcf84fb70f039a70#eaa2922cbff411f5efd5f4b7dcf84fb70f039a70" dependencies = [ "elide", "elide-runtime-core", @@ -3736,6 +3935,15 @@ version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + [[package]] name = "event-listener" version = "5.4.2" @@ -3824,6 +4032,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" +[[package]] +name = "fancy-regex" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax 0.8.12", +] + [[package]] name = "fancy-regex" version = "0.20.2" @@ -3882,6 +4101,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "fearless_simd" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" + [[package]] name = "ferroid" version = "2.0.0" @@ -3948,6 +4179,15 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +dependencies = [ + "num-traits", +] + [[package]] name = "fnv" version = "1.0.7" @@ -3966,6 +4206,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + [[package]] name = "font-types" version = "0.12.7" @@ -3975,6 +4224,29 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + [[package]] name = "form_urlencoded" version = "1.2.3" @@ -4217,6 +4489,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" dependencies = [ "polyval", + "zeroize", ] [[package]] @@ -4253,6 +4526,29 @@ version = "0.33.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4" +[[package]] +name = "glidesort" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2e102e6eb644d3e0b186fc161e4460417880a0a0b87d235f2e5b8fb30f2e9e0" + +[[package]] +name = "glifo" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.2", + "log", + "peniko", + "png", + "skrifa", + "smallvec", + "vello_common 0.0.9", +] + [[package]] name = "glob" version = "0.3.4" @@ -4282,6 +4578,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + [[package]] name = "h2" version = "0.4.21" @@ -4359,46 +4664,177 @@ name = "hashbrown" version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" - -[[package]] -name = "hayro-cmap" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" dependencies = [ - "brotli 8.0.4", - "hayro-postscript", + "foldhash 0.2.0", ] [[package]] -name = "hayro-postscript" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" - -[[package]] -name = "hdrhistogram" -version = "7.6.0" +name = "hayagriva" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d1053f4708f0af3cf9fc5bffc7e68a914a3c45becb231c80068c9c3f78bea" +checksum = "7b6c185c5c72546d50b25b70187f01ab9a1a2fa21c4db8691e2426fa5fce805c" dependencies = [ - "byteorder", - "num-traits", + "biblatex", + "ciborium", + "citationberg", + "icu_collator", + "icu_locale", + "indexmap 2.14.2", + "paste", + "roman-numerals-rs", + "serde", + "serde_yaml", + "thiserror 2.0.21", + "unic-langid", + "unicode-segmentation", + "unscanny", + "url", ] [[package]] -name = "headers" -version = "0.4.2" +name = "hayro" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" +checksum = "c4caa128ab87fd48ffb7490617cf93f77f606820dffbc9fd9ef6ab0ed077f56d" dependencies = [ - "base64 0.22.1", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", + "bytemuck", + "hayro-interpret", + "image", + "kurbo", + "pic-scale", + "vello_cpu", +] + +[[package]] +name = "hayro-ccitt" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" + +[[package]] +name = "hayro-ccitt" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2866f0d976e76497480b853d5e258dab6e4b89ecfe991124e08f15dfa8fd03ad" + +[[package]] +name = "hayro-cmap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" +dependencies = [ + "brotli 8.0.4", + "hayro-postscript", +] + +[[package]] +name = "hayro-interpret" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-syntax", + "kurbo", + "moxcms", + "phf 0.13.1", + "rustc-hash", + "siphasher", + "skrifa", + "smallvec", + "yoke", +] + +[[package]] +name = "hayro-jbig2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000e025850f4592ddcaee85640db70704151f2bafd43b6f431aa5b6a2c6a35a9" +dependencies = [ + "fearless_simd 1.3.0", + "hayro-ccitt 0.4.0", +] + +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd 0.4.1", +] + +[[package]] +name = "hayro-postscript" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" + +[[package]] +name = "hayro-svg" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7434c89e920d84e077214a29e69b462a6518754610f732f1124af3948410cb8c" +dependencies = [ + "base64 0.22.1", + "hayro-interpret", + "image", + "kurbo", + "siphasher", + "xmlwriter", +] + +[[package]] +name = "hayro-syntax" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27" +dependencies = [ + "flate2", + "hayro-ccitt 0.3.0", + "hayro-jbig2", + "hayro-jpeg2000", + "memchr", + "rustc-hash", + "smallvec", + "zune-jpeg", +] + +[[package]] +name = "hayro-write" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0b3db92c4917aad24ff30d61413a9a7509ae88b27aee1ae34eff881e1d2723a" +dependencies = [ + "flate2", + "hayro-syntax", + "pdf-writer", +] + +[[package]] +name = "hdrhistogram" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d1053f4708f0af3cf9fc5bffc7e68a914a3c45becb231c80068c9c3f78bea" +dependencies = [ + "byteorder", + "num-traits", +] + +[[package]] +name = "headers" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" +dependencies = [ + "base64 0.22.1", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", ] [[package]] @@ -4698,6 +5134,12 @@ dependencies = [ "serde", ] +[[package]] +name = "hypher" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45f2b4f6b5da34d400d4c112eadcc14512cc5d04307a8eee182586d9bebd7ce6" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -4731,6 +5173,31 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "icu_collator" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634" + [[package]] name = "icu_collections" version = "2.4.0" @@ -4739,12 +5206,28 @@ checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", + "serde", "utf8_iter", "yoke", "zerofrom", "zerovec", ] +[[package]] +name = "icu_locale" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + [[package]] name = "icu_locale_core" version = "2.4.0" @@ -4753,11 +5236,38 @@ checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9" + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" version = "2.4.0" @@ -4769,6 +5279,9 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] @@ -4789,6 +5302,7 @@ dependencies = [ "icu_locale_core", "icu_properties_data", "icu_provider", + "serde", "zerotrie", "zerovec", ] @@ -4807,6 +5321,9 @@ checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "postcard", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -4814,6 +5331,45 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_provider_blob" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ef59e2bab24a70e7b25d8025861b7c3b2de2982a6e6f64c1ca19e44e554889" +dependencies = [ + "icu_provider", + "postcard", + "serde", + "writeable", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "core_maths", + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "serde", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + [[package]] name = "ident_case" version = "1.0.1" @@ -4892,6 +5448,12 @@ dependencies = [ "rayon", ] +[[package]] +name = "imagesize" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" + [[package]] name = "imgref" version = "1.12.3" @@ -4936,6 +5498,7 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.2", + "rayon", "serde", "serde_core", ] @@ -4953,6 +5516,12 @@ dependencies = [ "web-time", ] +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" + [[package]] name = "inout" version = "0.2.6" @@ -5288,6 +5857,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "kamadak-exif" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8772c92c0f41c4a672cbdee6728253e5ae8fcc1c5eb5c6c676579565684bbf68" +dependencies = [ + "mutate_once", +] + [[package]] name = "kanaria" version = "0.2.0" @@ -5297,6 +5875,65 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "krilla" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33" +dependencies = [ + "base64 0.22.1", + "bumpalo", + "comemo", + "flate2", + "float-cmp", + "gif", + "hayro-write", + "image-webp", + "imagesize", + "indexmap 2.14.2", + "pdf-writer", + "png", + "rayon", + "rustc-hash", + "rustybuzz", + "siphasher", + "skrifa", + "smallvec", + "subsetter", + "tiny-skia-path", + "xmp-writer", + "yoke", + "zune-jpeg", +] + +[[package]] +name = "krilla-svg" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1237d7c37b16ca9fbc2e72dde13a10d321f9a44aceee35c062bc0a43bfc7ce16" +dependencies = [ + "flate2", + "fontdb", + "krilla", + "resvg", + "skrifa", + "smallvec", + "tiny-skia", + "usvg", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + [[package]] name = "lance" version = "7.0.0" @@ -6024,6 +6661,12 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + [[package]] name = "lingua" version = "1.8.0" @@ -6068,11 +6711,24 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "lipsum" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "636860251af8963cc40f6b4baadee105f02e21b28131d76eba8e40ce84ab8064" +dependencies = [ + "rand 0.8.8", + "rand_chacha 0.3.1", +] + [[package]] name = "litemap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +dependencies = [ + "serde_core", +] [[package]] name = "little_exif" @@ -6298,7 +6954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec54a4ea92c533f8ed6b8c80dc4bbd60f5b578b173399d92f19bfb5a34bd99a3" dependencies = [ "serde", - "toml", + "toml 1.2.3+spec-1.1.0", ] [[package]] @@ -6490,8 +7146,14 @@ dependencies = [ ] [[package]] -name = "nalgebra" -version = "0.35.0" +name = "mutate_once" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af" + +[[package]] +name = "nalgebra" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346" dependencies = [ @@ -6959,6 +7621,7 @@ dependencies = [ "url", "uuid", "woothee", + "zeroize", "zxcvbn", ] @@ -7021,6 +7684,15 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.13.2" @@ -7248,6 +7920,39 @@ dependencies = [ "sha2 0.11.3", ] +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + [[package]] name = "parking" version = "2.2.1" @@ -7343,6 +8048,18 @@ dependencies = [ "stfu8", ] +[[package]] +name = "pdf-writer" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753" +dependencies = [ + "bitflags 2.13.2", + "itoa", + "memchr", + "ryu", +] + [[package]] name = "pem" version = "4.0.0" @@ -7371,6 +8088,19 @@ dependencies = [ "base64ct", ] +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -7431,6 +8161,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ + "phf_macros 0.13.1", "phf_shared 0.13.1", "serde", ] @@ -7441,7 +8172,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", + "phf_macros 0.14.0", "phf_shared 0.14.0", ] @@ -7475,6 +8206,19 @@ dependencies = [ "phf_shared 0.14.0", ] +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_macros" version = "0.14.0" @@ -7535,6 +8279,22 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "pic-scale" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d76fd225dc3b8f089eaac369a74f57f557faffbd5da109ddd4e011010ab3ca10" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.2.0" @@ -7557,9 +8317,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pkcs1" @@ -7598,6 +8358,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plist" +version = "1.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7a42747bbcc4374e6922a15040dccacf720e4ce48a77e668f7116b9aa19a0a" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.18.1" @@ -7621,6 +8394,15 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + [[package]] name = "polyval" version = "0.7.3" @@ -7630,6 +8412,7 @@ dependencies = [ "cpubits", "cpufeatures 0.3.1", "universal-hash", + "zeroize", ] [[package]] @@ -7695,6 +8478,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -7777,9 +8562,15 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.21+spec-1.1.0", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -7859,6 +8650,16 @@ dependencies = [ "prost", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "ptr_meta" version = "0.3.2" @@ -7894,6 +8695,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "qrcode" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace1a365f55004297f2cf24acfd96d02966246ca423385273b58a7dc873ee14d" + [[package]] name = "quick-error" version = "2.0.1" @@ -7909,6 +8716,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -8241,6 +9058,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "read-fonts" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +dependencies = [ + "bytemuck", + "font-types 0.11.3", +] + [[package]] name = "read-fonts" version = "0.47.0" @@ -8249,7 +9076,7 @@ checksum = "a39d2f8f681030a7bcbbcf3e8568775ac2393afd51401a2e2133ee89e3953897" dependencies = [ "bytemuck", "foldhash 0.2.0", - "font-types", + "font-types 0.12.7", "once_cell", "smallvec", "yoke", @@ -8508,6 +9335,23 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "resvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be183ad6a216aa96f33e4c8033b0988b8b3ea6fd2359d19af5bac4643fd8e81" +dependencies = [ + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", + "zune-jpeg", +] + [[package]] name = "retry-policies" version = "0.5.2" @@ -8532,6 +9376,9 @@ name = "rgb" version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] [[package]] name = "rig" @@ -8830,6 +9677,27 @@ dependencies = [ "byteorder", ] +[[package]] +name = "roman-numerals-rs" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85cd47a33a4510b1424fe796498e174c6a9cf94e606460ef022a19f3e4ff85e" + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rsa" version = "0.9.10" @@ -8875,6 +9743,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "num-traits", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -8986,6 +9864,24 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + [[package]] name = "ryu" version = "1.0.23" @@ -9276,6 +10172,15 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_spanned" version = "1.1.3" @@ -9331,6 +10236,19 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -9502,18 +10420,46 @@ dependencies = [ "time", ] +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skrifa" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +dependencies = [ + "bytemuck", + "read-fonts 0.39.2", +] + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + [[package]] name = "slug" version = "0.1.6" @@ -9673,6 +10619,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -9691,6 +10650,15 @@ version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51f1e89f093f99e7432c491c382b88a6860a5adbe6bf02574bf0a08efff1978" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "stringprep" version = "0.1.5" @@ -9795,12 +10763,34 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "subsetter" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6" +dependencies = [ + "kurbo", + "rustc-hash", + "skrifa", + "write-fonts", +] + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + [[package]] name = "symphonia" version = "0.6.1" @@ -9928,6 +10918,27 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "syntect" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925" +dependencies = [ + "bincode", + "fancy-regex 0.16.2", + "flate2", + "fnv", + "once_cell", + "plist", + "regex-syntax 0.8.12", + "serde", + "serde_derive", + "serde_json", + "thiserror 2.0.21", + "walkdir", + "yaml-rust", +] + [[package]] name = "system-configuration" version = "0.7.0" @@ -10021,6 +11032,12 @@ dependencies = [ "testcontainers", ] +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + [[package]] name = "thiserror" version = "1.0.69" @@ -10132,6 +11149,32 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -10139,6 +11182,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -10307,6 +11351,18 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + [[package]] name = "toml" version = "1.2.3+spec-1.1.0" @@ -10315,11 +11371,20 @@ checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ "indexmap 2.14.2", "serde_core", - "serde_spanned", - "toml_datetime", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", "toml_writer", - "winnow", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", ] [[package]] @@ -10331,6 +11396,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + [[package]] name = "toml_edit" version = "0.25.21+spec-1.1.0" @@ -10338,9 +11417,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap 2.14.2", - "toml_datetime", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.5", ] [[package]] @@ -10349,9 +11428,15 @@ version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ - "winnow", + "winnow 1.0.5", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "toml_writer" version = "1.2.0+spec-1.1.0" @@ -10588,6 +11673,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + [[package]] name = "tungstenite" version = "0.29.0" @@ -10606,6 +11700,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "two-face" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39e51b6e60e545cfdae5a4639ff423818f52372211a8d9a3e892b4b0761f76b2" +dependencies = [ + "serde", + "serde_derive", + "syntect", +] + [[package]] name = "twox-hash" version = "2.1.5" @@ -10615,6 +11720,12 @@ dependencies = [ "rand 0.10.4", ] +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + [[package]] name = "typed-path" version = "0.13.0" @@ -10657,6 +11768,361 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "typst" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1cb79435d128de5d5443a058a983f6dcc16738760fa55ed703762bc278b1fd3" +dependencies = [ + "arrayvec", + "comemo", + "ecow", + "rustc-hash", + "typst-eval", + "typst-html", + "typst-layout", + "typst-library", + "typst-macros", + "typst-realize", + "typst-syntax", + "typst-timing", + "typst-utils", +] + +[[package]] +name = "typst-assets" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcee505dac6702dd1c5e65aa2e94a6179d19ee09e2e5637d7313db91765dc4e0" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "typst-eval" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8823e1822bd181d8bee47b05632d16bf3a0a8ab042e01d815826350d7ae16c3" +dependencies = [ + "comemo", + "ecow", + "indexmap 2.14.2", + "rustc-hash", + "stacker", + "toml 0.8.23", + "typst-library", + "typst-macros", + "typst-syntax", + "typst-timing", + "typst-utils", + "unicode-segmentation", +] + +[[package]] +name = "typst-html" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f41bcfbe480b640c4447d8bf9bb59020da610f239aa032d53328651a03572c09" +dependencies = [ + "az", + "bumpalo", + "comemo", + "ecow", + "palette", + "rustc-hash", + "time", + "typst-assets", + "typst-library", + "typst-macros", + "typst-svg", + "typst-syntax", + "typst-timing", + "typst-utils", + "unicode-math-class", +] + +[[package]] +name = "typst-layout" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1916c407baf8f8815e5d50030eed6d5ac6a0702d927b3c156e38db7a618499e2" +dependencies = [ + "az", + "bumpalo", + "codex", + "comemo", + "ecow", + "either", + "hypher", + "icu_properties", + "icu_provider", + "icu_provider_blob", + "icu_segmenter", + "kurbo", + "libm", + "memchr", + "rustc-hash", + "rustybuzz", + "smallvec", + "ttf-parser", + "typst-assets", + "typst-library", + "typst-macros", + "typst-syntax", + "typst-timing", + "typst-utils", + "unicode-bidi", + "unicode-math-class", + "unicode-script", + "unicode-segmentation", +] + +[[package]] +name = "typst-library" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12becd02464849f1507f3c4ef3f401a4d28d5938cc74b6acc6f1d703458bf393" +dependencies = [ + "arrayvec", + "az", + "bitflags 2.13.2", + "bumpalo", + "ciborium", + "codex", + "comemo", + "csv", + "ecow", + "either", + "flate2", + "fontdb", + "glidesort", + "hayagriva", + "hayro-syntax", + "icu_properties", + "image", + "indexmap 2.14.2", + "kamadak-exif", + "kurbo", + "libm", + "lipsum", + "memchr", + "moxcms", + "palette", + "percent-encoding", + "phf 0.13.1", + "png", + "rayon", + "regex", + "regex-syntax 0.8.12", + "roxmltree 0.21.2", + "rust_decimal", + "rustc-hash", + "rustybuzz", + "serde", + "serde_json", + "serde_yaml", + "siphasher", + "smallvec", + "syntect", + "time", + "toml 0.8.23", + "ttf-parser", + "two-face", + "typed-arena", + "typst-assets", + "typst-macros", + "typst-syntax", + "typst-timing", + "typst-utils", + "unicode-math-class", + "unicode-normalization", + "unicode-segmentation", + "unscanny", + "usvg", + "utf8_iter", + "wasmi", + "xmlwriter", +] + +[[package]] +name = "typst-macros" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "033626e6fd43dc09170a9237c55a4dd308005fd751456a0c81b5864f822a97df" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "typst-pdf" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aef841ff3e606542f3057ce5dd0ff264d53a439e00ed4a91ec00ec8568b3b7f" +dependencies = [ + "az", + "bytemuck", + "codex", + "comemo", + "ecow", + "flate2", + "image", + "indexmap 2.14.2", + "infer", + "krilla", + "krilla-svg", + "rustc-hash", + "serde", + "smallvec", + "typst-assets", + "typst-layout", + "typst-library", + "typst-macros", + "typst-syntax", + "typst-timing", + "typst-utils", +] + +[[package]] +name = "typst-realize" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f2eb73ab25add88cab03b26effabc657977fe850ff81556b28c6b137ff4bf1" +dependencies = [ + "arrayvec", + "bumpalo", + "comemo", + "ecow", + "regex", + "typst-html", + "typst-library", + "typst-macros", + "typst-syntax", + "typst-timing", + "typst-utils", +] + +[[package]] +name = "typst-svg" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df6dc785695aae085678bd6657aa04a1d26058a76ed042e738658078bca681e" +dependencies = [ + "base64 0.22.1", + "comemo", + "ecow", + "flate2", + "hayro", + "hayro-svg", + "image", + "indexmap 2.14.2", + "itoa", + "rustc-hash", + "ryu", + "ttf-parser", + "typst-assets", + "typst-layout", + "typst-library", + "typst-macros", + "typst-timing", + "typst-utils", + "xmlwriter", +] + +[[package]] +name = "typst-syntax" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92a20d79df5d10c7fb0b4f7c18e4b2671edfc21e5ed9ad9894e18cccefd1c70f" +dependencies = [ + "ecow", + "rustc-hash", + "serde", + "toml 0.8.23", + "typst-timing", + "typst-utils", + "unicode-ident", + "unicode-math-class", + "unicode-script", + "unicode-segmentation", + "unscanny", +] + +[[package]] +name = "typst-timing" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab6ee5110f671a23164c61caa85dbc476043d503103dedd36f16d93f970f3f59" +dependencies = [ + "parking_lot", + "serde", + "serde_json", +] + +[[package]] +name = "typst-utils" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b33ad1675497b45ae9d960a16e95207c35c2c46330d1a6249a9a977670c8c160" +dependencies = [ + "libm", + "once_cell", + "portable-atomic", + "rayon", + "rustc-hash", + "semver", + "siphasher", + "smallvec", + "thin-vec", + "unicode-math-class", +] + +[[package]] +name = "unic-langid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" +dependencies = [ + "unic-langid-impl", + "unic-langid-macros", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" +dependencies = [ + "serde", + "tinystr", +] + +[[package]] +name = "unic-langid-macros" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5957eb82e346d7add14182a3315a7e298f04e1ba4baac36f7f0dbfedba5fc25" +dependencies = [ + "proc-macro-hack", + "tinystr", + "unic-langid-impl", + "unic-langid-macros-impl", +] + +[[package]] +name = "unic-langid-macros-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1249a628de3ad34b821ecb1001355bca3940bcb2f88558f1a8bd82e977f75b5" +dependencies = [ + "proc-macro-hack", + "quote", + "syn 2.0.119", + "unic-langid-impl", +] + [[package]] name = "unicase" version = "2.10.0" @@ -10669,18 +12135,36 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + [[package]] name = "unicode-blocks" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "904aa6a57e7381e4294341de0d9f405161e445f16acfe5469eed3a9becf2a482" +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-math-class" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d246cf599d5fae3c8d56e04b20eb519adb89a8af8d0b0fbcded369aa3647d65" + [[package]] name = "unicode-normalization" version = "0.1.26" @@ -10705,12 +12189,24 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + [[package]] name = "unicode-segmentation" version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + [[package]] name = "unicode-width" version = "0.2.3" @@ -10745,6 +12241,12 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "unscanny" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9df2af067a7953e9c3831320f35c1cc0600c30d44d9f7a12b01db1cd88d6b47" + [[package]] name = "untrusted" version = "0.7.1" @@ -10816,6 +12318,43 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "usvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.21.2", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "ttf-parser", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8-ranges" version = "1.0.5" @@ -10885,6 +12424,53 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "vello_common" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee" +dependencies = [ + "bytemuck", + "fearless_simd 0.4.1", + "guillotiere", + "hashbrown 0.17.2", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_common" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750" +dependencies = [ + "bytemuck", + "fearless_simd 0.4.1", + "guillotiere", + "hashbrown 0.17.2", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.2", + "png", + "vello_common 0.0.8", +] + [[package]] name = "version_check" version = "0.9.5" @@ -11024,6 +12610,52 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wasmi" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2300d0f78cba12f14e29e8dd157ea64050c0a688179aefdb2050105805594a0c" +dependencies = [ + "spin 0.9.9", + "wasmi_collections", + "wasmi_core", + "wasmi_ir", + "wasmparser", +] + +[[package]] +name = "wasmi_collections" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8a8c42a2a76148d43097b1d7cc2a5bf33d5c23bd4dd69015fc887e311767884" + +[[package]] +name = "wasmi_core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9013136083d988725953390bf668b64b7a218fabf26f8b913bbc59546b97ee27" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmi_ir" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba1fa003f79156f406d62ef0e1464dc03e11ace37170e9fa7524299a75ad8f68" +dependencies = [ + "wasmi_core", +] + +[[package]] +name = "wasmparser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9d90bb93e764f6beabf1d02028c70a2156a6583e63ac4218dd07ef733368b0" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "wasmtimer" version = "0.4.5" @@ -11445,6 +13077,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.5" @@ -11482,6 +13123,25 @@ dependencies = [ "regex", ] +[[package]] +name = "write-fonts" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8" +dependencies = [ + "font-types 0.11.3", + "indexmap 2.14.2", + "kurbo", + "log", + "read-fonts 0.39.2", +] + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" @@ -11507,6 +13167,18 @@ dependencies = [ "rustix", ] +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "xmp-writer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" + [[package]] name = "xxhash-rust" version = "0.8.21" @@ -11519,6 +13191,15 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + [[package]] name = "yansi" version = "1.0.1" @@ -11595,6 +13276,7 @@ version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" dependencies = [ + "serde", "zeroize_derive", ] @@ -11616,8 +13298,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", + "litemap", + "serde_core", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -11626,6 +13311,7 @@ version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", @@ -11763,7 +13449,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a4c3078ad169d1dd76ffb4558d0ab04fe8768eccd85e58a4b691103f9950a56" dependencies = [ "derive_builder", - "fancy-regex", + "fancy-regex 0.20.2", "itertools 0.15.0", "lazy_static", "regex", diff --git a/Cargo.toml b/Cargo.toml index be0af97f..1d023d42 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-runtime = { git = "https://github.com/nvisycom/elide-runtime", rev = "4c0f1d8e078157ec7a2ed4ae9a2f86a9670f4190", default-features = false, features = [] } +elide-runtime = { git = "https://github.com/nvisycom/elide-runtime", rev = "eaa2922cbff411f5efd5f4b7dcf84fb70f039a70", default-features = false, features = [] } # Internal crates nvisy-core = { path = "./crates/nvisy-core", version = "0.1.0" } @@ -110,6 +110,7 @@ aead-stream = { version = "0.6", features = ["alloc"] } hkdf = { version = "0.13", features = [] } sha2 = { version = "0.11", features = [] } hmac = { version = "0.13", features = [] } +zeroize = { version = "1.9", features = [] } # Encoding base64 = { version = "0.23", features = [] } diff --git a/crates/nvisy-cli/src/config/server.rs b/crates/nvisy-cli/src/config/server.rs index 6deba7c8..d96e1f1f 100644 --- a/crates/nvisy-cli/src/config/server.rs +++ b/crates/nvisy-cli/src/config/server.rs @@ -109,11 +109,9 @@ impl ServerConfig { self.host.is_unspecified() } - /// Returns whether TLS is configured. - // reason: reads as a config accessor alongside the other `&self` queries. - #[allow(clippy::unused_self)] + /// Returns whether this build serves TLS. #[must_use] - pub const fn is_tls_enabled(&self) -> bool { + pub const fn is_tls_enabled() -> bool { cfg!(feature = "tls") } @@ -123,7 +121,7 @@ impl ServerConfig { target: TRACING_TARGET_CONFIG, host = %self.host, port = self.port, - tls = self.is_tls_enabled(), + tls = Self::is_tls_enabled(), shutdown_timeout = ?self.shutdown_timeout, "Server configuration" ); diff --git a/crates/nvisy-file-service/src/client/service.rs b/crates/nvisy-file-service/src/client/service.rs index feb3cf4a..9c6acfcb 100644 --- a/crates/nvisy-file-service/src/client/service.rs +++ b/crates/nvisy-file-service/src/client/service.rs @@ -94,6 +94,15 @@ impl FileService { self.oauth.contains_key(&provider) } + /// The providers the host has configured an OAuth app for, the only ones + /// that can be connected, in declaration order. + #[must_use] + pub fn configured_providers(&self) -> Vec { + FileServiceProvider::iter() + .filter(|provider| self.is_configured(*provider)) + .collect() + } + /// The [`OAuthClient`] for `provider`: the handle for the authorize URL and /// the code and token exchanges. /// diff --git a/crates/nvisy-postgres/src/model/account_notifications.rs b/crates/nvisy-postgres/src/model/account_notifications.rs index 96a56353..619af3fa 100644 --- a/crates/nvisy-postgres/src/model/account_notifications.rs +++ b/crates/nvisy-postgres/src/model/account_notifications.rs @@ -26,6 +26,8 @@ pub struct AccountNotification { pub created_at: Timestamp, /// Optional expiration timestamp. pub expires_at: Option, + /// Workspace the notification is about. + pub workspace_id: Uuid, } /// Data for creating a new account notification. @@ -36,6 +38,8 @@ pub struct AccountNotification { pub struct NewAccountNotification { /// Account ID. pub account_id: Uuid, + /// Workspace the notification is about. + pub workspace_id: Uuid, /// Notification type; the client-side localization key. pub notify_type: NotificationEvent, /// The self-describing tagged payload (its `type` tag + params). @@ -45,19 +49,19 @@ pub struct NewAccountNotification { } impl NewAccountNotification { - /// A minimal `member.joined` notification for `account_id`, unread and - /// non-expiring, for tests. + /// A minimal `member.joined` notification for `account_id` in + /// `workspace_id`, unread and non-expiring, for tests. #[cfg(any(feature = "test_util", test))] - pub fn test(account_id: Uuid) -> Self { + pub fn test(account_id: Uuid, workspace_id: Uuid) -> Self { use crate::types::{MemberJoinedParams, NotificationPayload}; let payload = NotificationPayload::MemberJoined(MemberJoinedParams { - workspace_id: Uuid::now_v7(), member_id: Uuid::now_v7(), }); let (notify_type, params) = payload.into_stored(); Self { account_id, + workspace_id, notify_type, params, expires_at: None, diff --git a/crates/nvisy-postgres/src/model/mod.rs b/crates/nvisy-postgres/src/model/mod.rs index 9b6c2351..149b5bea 100644 --- a/crates/nvisy-postgres/src/model/mod.rs +++ b/crates/nvisy-postgres/src/model/mod.rs @@ -19,6 +19,7 @@ mod workspace_detection_policy_versions; mod workspace_detections; mod workspace_document_exports; mod workspace_document_imports; +mod workspace_document_states; mod workspace_documents; mod workspace_event_outbox; mod workspace_invites; @@ -58,6 +59,7 @@ pub use workspace_detections::{ }; pub use workspace_document_exports::NewWorkspaceDocumentExport; pub use workspace_document_imports::NewWorkspaceDocumentImport; +pub use workspace_document_states::WorkspaceDocumentState; pub use workspace_documents::{NewWorkspaceDocument, UpdateWorkspaceDocument, WorkspaceDocument}; pub use workspace_event_outbox::{NewWorkspaceEventOutbox, WorkspaceEventOutbox}; pub use workspace_invites::{NewWorkspaceInvite, UpdateWorkspaceInvite, WorkspaceInvite}; diff --git a/crates/nvisy-postgres/src/model/workspace_detections.rs b/crates/nvisy-postgres/src/model/workspace_detections.rs index 135d1d17..cef79723 100644 --- a/crates/nvisy-postgres/src/model/workspace_detections.rs +++ b/crates/nvisy-postgres/src/model/workspace_detections.rs @@ -55,6 +55,12 @@ pub struct WorkspaceDetection { /// /// [`WorkspaceDetectionEdit`]: crate::model::WorkspaceDetectionEdit pub edit_set_rev: i32, + /// How many findings the base analysis left standing: entities it found and + /// did not drop. `None` until the analysis commits. + pub base_finding_count: Option, + /// How many findings stand with the reviewer edits applied: the base count + /// until a reviewer edits. `None` until the analysis commits. + pub finding_count: Option, /// 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 /// that died mid-analysis) can be re-claimed. `None` until first claimed. @@ -130,4 +136,8 @@ pub struct UpdateWorkspaceDetection { pub claimed_at: Option>, /// When the detection completed analysis. pub completed_at: Option>, + /// How many findings the base analysis left standing, set when it commits. + pub base_finding_count: Option>, + /// How many findings stand with the reviewer edits applied. + pub finding_count: Option>, } diff --git a/crates/nvisy-postgres/src/model/workspace_document_states.rs b/crates/nvisy-postgres/src/model/workspace_document_states.rs new file mode 100644 index 00000000..b4e5f06a --- /dev/null +++ b/crates/nvisy-postgres/src/model/workspace_document_states.rs @@ -0,0 +1,35 @@ +//! Document state model: what an original document's detections, redactions, +//! and reviews add up to. + +use diesel::prelude::*; +use jiff_diesel::Timestamp; +use uuid::Uuid; + +use crate::schema::workspace_document_states; +use crate::types::DocumentStage; + +/// What a live original document's detections, redactions, and reviews add up +/// to. Database triggers keep it current; nothing writes it from Rust. A +/// redacted or deleted document has none. +#[derive(Debug, Clone, PartialEq, Queryable, Selectable)] +#[diesel(table_name = workspace_document_states)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct WorkspaceDocumentState { + /// The document. + pub document_id: Uuid, + /// Where it stands in its workflow. + pub stage: DocumentStage, + /// Its latest live detection, by when it started. + pub latest_detection_id: Option, + /// Whether any live detection of it has a live redaction. + pub has_redaction: bool, + /// Whether a review of it awaits a decision: in review, changes requested, + /// or partially approved. + pub has_open_review: bool, + /// The live output of its latest approved review, by when that review + /// reached its quorum. + pub approved_redaction_id: Option, + /// When that review reached its quorum. Every other redaction made before + /// it is superseded. + pub approved_at: Option, +} diff --git a/crates/nvisy-postgres/src/model/workspace_redactions.rs b/crates/nvisy-postgres/src/model/workspace_redactions.rs index 4cc07017..e02bb413 100644 --- a/crates/nvisy-postgres/src/model/workspace_redactions.rs +++ b/crates/nvisy-postgres/src/model/workspace_redactions.rs @@ -11,8 +11,9 @@ use crate::schema::workspace_redactions; /// A detection can be redacted many times — each redact request may carry a /// different set of reviewer edits — so each redaction is its own row. Its review /// audit (the engine's findings after the reviewer edits were applied) is the blob -/// pointed at by `review_audit_blob_id`; the redacted output is a -/// [`WorkspaceDocument`] of kind `redacted`. +/// pointed at by `review_audit_blob_id`, its certificate the blob pointed at by +/// `certificate_blob_id`, and the redacted output is a [`WorkspaceDocument`] of +/// kind `redacted`. /// /// [`WorkspaceDocument`]: crate::model::WorkspaceDocument #[derive(Debug, Clone, PartialEq, Queryable, Selectable)] @@ -33,6 +34,14 @@ pub struct WorkspaceRedaction { pub review_audit_blob_id: Option, /// When the review audit's bytes are released (audit-logs retention). pub review_audit_expires_at: Option, + /// Certificate blob: what the redaction withheld and why. `None` once the + /// bytes are reclaimed on retention (the row is kept). A blob reference. + pub certificate_blob_id: Option, + /// When the certificate's bytes are released (audit-logs retention). + pub certificate_expires_at: Option, + /// The certificate's public number, referenced as `CERT-`: random, + /// eight digits, and unique, drawn by the database on insert. + pub certificate_number: i32, /// When the redaction was created. pub created_at: Timestamp, /// When the redaction was soft-deleted; `None` means live (the row is kept as @@ -56,6 +65,10 @@ pub struct NewWorkspaceRedaction { pub review_audit_blob_id: Option, /// When the review audit's bytes are released. pub review_audit_expires_at: Option, + /// Certificate blob this redaction produced. + pub certificate_blob_id: Option, + /// When the certificate's bytes are released. + pub certificate_expires_at: Option, } impl NewWorkspaceRedaction { @@ -69,6 +82,8 @@ impl NewWorkspaceRedaction { output_document_id: None, review_audit_blob_id: None, review_audit_expires_at: None, + certificate_blob_id: None, + certificate_expires_at: None, } } } diff --git a/crates/nvisy-postgres/src/query/account_notifications.rs b/crates/nvisy-postgres/src/query/account_notifications.rs index 3d42d098..71ed6e9e 100644 --- a/crates/nvisy-postgres/src/query/account_notifications.rs +++ b/crates/nvisy-postgres/src/query/account_notifications.rs @@ -2,15 +2,29 @@ use std::future::Future; +use diesel::dsl::{InnerJoin, IntoBoxed}; +use diesel::pg::Pg; use diesel::prelude::*; use diesel_async::RunQueryDsl; use jiff::Timestamp; use uuid::Uuid; -use crate::model::{AccountNotification, NewAccountNotification, UpdateAccountNotification}; +use crate::model::{ + AccountNotification, NewAccountNotification, UpdateAccountNotification, Workspace, +}; +use crate::schema::{account_notifications, workspace_members, workspaces}; use crate::types::{CursorPage, CursorPagination, TimeCursor, keyset, total}; use crate::{PgConnection, Result, schema}; +/// A notification with the workspace it is about. +#[derive(Debug, Clone, PartialEq)] +pub struct ListedNotification { + /// The notification. + pub notification: AccountNotification, + /// The workspace it is about. + pub workspace: Workspace, +} + /// Repository for account notification database operations. /// /// Handles user notifications including creation, delivery tracking, read status @@ -29,21 +43,27 @@ pub trait AccountNotificationRepository { new_notifications: Vec, ) -> impl Future> + Send; - /// Lists account notifications with cursor pagination. + /// Lists account notifications with cursor pagination, each with its + /// workspace, in `workspace_id` only when given. /// - /// Excludes expired notifications, ordered by creation date descending. + /// Excludes expired notifications and those of deleted workspaces or of + /// workspaces the account is no longer a member of, ordered by creation + /// date descending. fn cursor_list_account_notifications( &mut self, account_id: Uuid, + workspace_id: Option, pagination: CursorPagination, - ) -> impl Future>> + Send; + ) -> impl Future>> + Send; - /// Marks all unread account notifications as read. + /// Marks all unread account notifications the list shows as read, in + /// `workspace_id` only when given. /// /// Returns the count of notifications marked as read. fn mark_all_account_notifications_as_read( &mut self, account_id: Uuid, + workspace_id: Option, ) -> impl Future> + Send; /// Marks a single notification as read, scoped to its owning account. @@ -58,10 +78,14 @@ pub trait AccountNotificationRepository { notification_id: Uuid, ) -> impl Future> + Send; - /// Counts unread account notifications. + /// Counts unread account notifications, in `workspace_id` only when given. + /// + /// Counts what the list shows: expired notifications and those of deleted + /// workspaces or of workspaces the account has left are left out. fn count_unread_account_notifications( &mut self, account_id: Uuid, + workspace_id: Option, ) -> impl Future> + Send; } @@ -97,55 +121,66 @@ impl AccountNotificationRepository for PgConnection { async fn cursor_list_account_notifications( &mut self, - acct_id: Uuid, + account_id: Uuid, + workspace_id: Option, pagination: CursorPagination, - ) -> Result> { - use diesel::dsl::{count_star, now}; - use schema::account_notifications::{self, dsl}; - - let base_filter = dsl::account_id - .eq(acct_id) - .and(dsl::expires_at.is_null().or(dsl::expires_at.gt(now))); + ) -> Result> { + use diesel::dsl::count_star; + use schema::account_notifications::dsl; let total = total!( pagination, self, - account_notifications::table - .filter(base_filter) - .select(count_star()) + listed(account_id, workspace_id).select(count_star()) ); - let query = account_notifications::table - .filter(base_filter) - .into_boxed(); - let after = pagination.after_pair(); - let items = keyset!(query, dsl::created_at, dsl::id, pagination.direction, after) - .limit(pagination.fetch_limit()) - .select(AccountNotification::as_select()) - .load(self) - .await?; - - Ok(CursorPage::new(items, total, pagination.limit, |n| { - TimeCursor::new(n.created_at, n.id) + let rows: Vec<(AccountNotification, Workspace)> = keyset!( + listed(account_id, workspace_id), + dsl::created_at, + dsl::id, + pagination.direction, + after + ) + .limit(pagination.fetch_limit()) + .select((AccountNotification::as_select(), Workspace::as_select())) + .load(self) + .await?; + let items = rows + .into_iter() + .map(|(notification, workspace)| ListedNotification { + notification, + workspace, + }) + .collect(); + + Ok(CursorPage::new(items, total, pagination.limit, |listed| { + TimeCursor::new(listed.notification.created_at, listed.notification.id) })) } - async fn mark_all_account_notifications_as_read(&mut self, account_id: Uuid) -> Result { + async fn mark_all_account_notifications_as_read( + &mut self, + account_id: Uuid, + workspace_id: Option, + ) -> Result { use schema::account_notifications::{self, dsl}; let update_data = UpdateAccountNotification { read_at: Some(Some(jiff_diesel::Timestamp::from(Timestamp::now()))), }; - Ok(diesel::update( - account_notifications::table - .filter(dsl::account_id.eq(account_id)) - .filter(dsl::read_at.is_null()), + // Marks what the list shows unread, so the count it returns is the + // count the unread badge showed. + let unread = listed(account_id, workspace_id) + .filter(dsl::read_at.is_null()) + .select(dsl::id); + Ok( + diesel::update(account_notifications::table.filter(dsl::id.eq_any(unread))) + .set(&update_data) + .execute(self) + .await?, ) - .set(&update_data) - .execute(self) - .await?) } async fn mark_account_notification_as_read( @@ -174,42 +209,70 @@ impl AccountNotificationRepository for PgConnection { Ok(updated > 0) } - async fn count_unread_account_notifications(&mut self, account_id: Uuid) -> Result { - use diesel::dsl::{count_star, now}; - use schema::account_notifications::{self, dsl}; + async fn count_unread_account_notifications( + &mut self, + account_id: Uuid, + workspace_id: Option, + ) -> Result { + use diesel::dsl::count_star; + use schema::account_notifications::dsl; - Ok(account_notifications::table - .filter(dsl::account_id.eq(account_id)) + Ok(listed(account_id, workspace_id) .filter(dsl::read_at.is_null()) - .filter(dsl::expires_at.is_null().or(dsl::expires_at.gt(now))) .select(count_star()) .get_result(self) .await?) } } +/// The notifications a list shows `account_id`, joined to their workspaces: +/// unexpired, of a live workspace it is still a member of, and in +/// `workspace_id` when given. The list, its total, the unread count and +/// mark-all-read all read through it, so they agree. +fn listed( + account_id: Uuid, + workspace_id: Option, +) -> IntoBoxed<'static, InnerJoin, Pg> { + use diesel::dsl::{exists, now}; + use schema::account_notifications::dsl; + + let member = workspace_members::table + .filter(workspace_members::workspace_id.eq(dsl::workspace_id)) + .filter(workspace_members::account_id.eq(account_id)); + let mut query = account_notifications::table + .inner_join(workspaces::table) + .filter(dsl::account_id.eq(account_id)) + .filter(dsl::expires_at.is_null().or(dsl::expires_at.gt(now))) + .filter(workspaces::deleted_at.is_null()) + .filter(exists(member)) + .into_boxed(); + if let Some(workspace_id) = workspace_id { + query = query.filter(dsl::workspace_id.eq(workspace_id)); + } + query +} + #[cfg(test)] mod tests { use jiff::{Span, Timestamp}; - use uuid::Uuid; use crate::PgConn; - use crate::model::{AccountNotification, NewAccountNotification}; - use crate::query::AccountNotificationRepository; - use crate::test_util::{TestDatabase, backdate}; - use crate::types::CursorPagination; + use crate::model::{AccountNotification, NewAccountNotification, NewWorkspace}; + use crate::query::{ + AccountNotificationRepository, WorkspaceMemberRepository, WorkspaceRepository, + }; + use crate::test_util::{SeededWorkspace, TestDatabase, backdate}; + use crate::types::{CursorPagination, WorkspaceRole}; /// Creates a notification already past its expiry: `created_at` two hours ago, /// `expires_at` an hour after that (so it reads as expired against `now()` /// while satisfying the `expires_at > created_at` check). async fn expired_notification( conn: &mut PgConn, - account_id: Uuid, + seeded: SeededWorkspace, ) -> anyhow::Result { let created = Timestamp::now() - Span::new().hours(2); - let notification = conn - .create_account_notification(NewAccountNotification::test(account_id)) - .await?; + let notification = conn.create_account_notification(test(seeded)).await?; // Backdate `created_at` and set `expires_at` an hour later, together, so // the row is expired against `now()` while the `expires_at > created_at` // check still holds. @@ -227,11 +290,9 @@ mod tests { /// test have a strict, deterministic newest-first order. async fn old_notification( conn: &mut PgConn, - account_id: Uuid, + seeded: SeededWorkspace, ) -> anyhow::Result { - let notification = conn - .create_account_notification(NewAccountNotification::test(account_id)) - .await?; + let notification = conn.create_account_notification(test(seeded)).await?; backdate::notification_created_at( conn, notification.id, @@ -241,47 +302,154 @@ mod tests { Ok(notification) } + /// A notification for the seeded account in its seeded workspace. + fn test(seeded: SeededWorkspace) -> NewAccountNotification { + NewAccountNotification::test(seeded.account_id, seeded.workspace_id) + } + #[tokio::test] async fn cursor_list_excludes_expired_and_orders_newest_first() -> anyhow::Result<()> { let db = TestDatabase::start().await; - let account_id = db.seed_account().await; + let seeded = db.seed_owned_workspace().await; let mut conn = db.client.get_connection().await?; // Two live notifications (the first inserted an hour old so the newest-first // order is deterministic) and one already expired. - let first = old_notification(&mut conn, account_id).await?; - let second = conn - .create_account_notification(NewAccountNotification::test(account_id)) - .await?; - let _expired = expired_notification(&mut conn, account_id).await?; + let first = old_notification(&mut conn, seeded).await?; + let second = conn.create_account_notification(test(seeded)).await?; + let _expired = expired_notification(&mut conn, seeded).await?; let page = conn - .cursor_list_account_notifications(account_id, CursorPagination::new(50)) + .cursor_list_account_notifications(seeded.account_id, None, CursorPagination::new(50)) .await?; - // The expired one is filtered out; the newest live one comes first. - let ids: Vec<_> = page.items.iter().map(|n| n.id).collect(); + // The expired one is filtered out; the newest live one comes first, each + // with its workspace. + let ids: Vec<_> = page.items.iter().map(|n| n.notification.id).collect(); assert_eq!(ids, vec![second.id, first.id]); + assert!( + page.items + .iter() + .all(|n| n.workspace.id == seeded.workspace_id) + ); + Ok(()) + } + + #[tokio::test] + async fn a_workspace_scopes_the_list_the_count_and_mark_all() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_owned_workspace().await; + let mut conn = db.client.get_connection().await?; + let other = another_workspace(&db, &mut conn, seeded).await?; + + let here = conn.create_account_notification(test(seeded)).await?; + conn.create_account_notification(test(other)).await?; + + let page = conn + .cursor_list_account_notifications( + seeded.account_id, + Some(seeded.workspace_id), + CursorPagination::new(50), + ) + .await?; + let ids: Vec<_> = page.items.iter().map(|n| n.notification.id).collect(); + assert_eq!(ids, vec![here.id]); + assert_eq!( + conn.count_unread_account_notifications(seeded.account_id, Some(other.workspace_id)) + .await?, + 1 + ); + + // Marking one workspace's read leaves the other's unread. + assert_eq!( + conn.mark_all_account_notifications_as_read( + seeded.account_id, + Some(seeded.workspace_id) + ) + .await?, + 1 + ); + assert_eq!( + conn.count_unread_account_notifications(seeded.account_id, None) + .await?, + 1 + ); + + // A deleted workspace's notifications leave the list and the count. + conn.delete_workspace(other.workspace_id).await?; + assert_eq!( + conn.count_unread_account_notifications(seeded.account_id, None) + .await?, + 0 + ); + let page = conn + .cursor_list_account_notifications(seeded.account_id, None, CursorPagination::new(50)) + .await?; + assert_eq!(page.items.len(), 1); Ok(()) } + #[tokio::test] + async fn a_member_who_left_no_longer_sees_the_workspace_s() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_owned_workspace().await; + let mut conn = db.client.get_connection().await?; + let left = another_workspace(&db, &mut conn, seeded).await?; + conn.create_account_notification(test(seeded)).await?; + conn.create_account_notification(test(left)).await?; + + conn.remove_workspace_member(left.workspace_id, left.account_id) + .await?; + let page = conn + .cursor_list_account_notifications(seeded.account_id, None, CursorPagination::new(50)) + .await?; + assert_eq!(page.items.len(), 1); + assert_eq!( + conn.count_unread_account_notifications(seeded.account_id, None) + .await?, + 1 + ); + + // Mark-all marks what the list showed, as many as the badge counted. + assert_eq!( + conn.mark_all_account_notifications_as_read(seeded.account_id, None) + .await?, + 1 + ); + Ok(()) + } + + /// Another workspace `seeded`'s account owns and is a member of. + async fn another_workspace( + db: &TestDatabase, + conn: &mut PgConn, + seeded: SeededWorkspace, + ) -> anyhow::Result { + let workspace = conn + .create_workspace(NewWorkspace::test(seeded.account_id)) + .await?; + db.seed_workspace_member(workspace.id, seeded.account_id, WorkspaceRole::Owner) + .await; + Ok(SeededWorkspace { + workspace_id: workspace.id, + ..seeded + }) + } + #[tokio::test] async fn create_many_inserts_each_and_counts_them() -> anyhow::Result<()> { let db = TestDatabase::start().await; - let account_id = db.seed_account().await; + let seeded = db.seed_owned_workspace().await; let mut conn = db.client.get_connection().await?; - let batch = vec![ - NewAccountNotification::test(account_id), - NewAccountNotification::test(account_id), - NewAccountNotification::test(account_id), - ]; + let batch = vec![test(seeded), test(seeded), test(seeded)]; assert_eq!(conn.create_account_notifications(batch).await?, 3); // An empty batch is a no-op, not an error. assert_eq!(conn.create_account_notifications(vec![]).await?, 0); assert_eq!( - conn.count_unread_account_notifications(account_id).await?, + conn.count_unread_account_notifications(seeded.account_id, None) + .await?, 3 ); Ok(()) @@ -290,13 +458,12 @@ mod tests { #[tokio::test] async fn mark_as_read_is_scoped_to_the_owning_account() -> anyhow::Result<()> { let db = TestDatabase::start().await; - let owner = db.seed_account().await; + let seeded = db.seed_owned_workspace().await; + let owner = seeded.account_id; let other = db.seed_account().await; let mut conn = db.client.get_connection().await?; - let notification = conn - .create_account_notification(NewAccountNotification::test(owner)) - .await?; + let notification = conn.create_account_notification(test(seeded)).await?; // Another account cannot mark it read; nothing is updated. assert!( @@ -304,42 +471,47 @@ mod tests { .mark_account_notification_as_read(other, notification.id) .await? ); - assert_eq!(conn.count_unread_account_notifications(owner).await?, 1); + assert_eq!( + conn.count_unread_account_notifications(owner, None).await?, + 1 + ); // The owner can, and the unread count drops to zero. assert!( conn.mark_account_notification_as_read(owner, notification.id) .await? ); - assert_eq!(conn.count_unread_account_notifications(owner).await?, 0); + assert_eq!( + conn.count_unread_account_notifications(owner, None).await?, + 0 + ); Ok(()) } #[tokio::test] async fn mark_all_as_read_clears_only_the_accounts_unread() -> anyhow::Result<()> { let db = TestDatabase::start().await; - let account_id = db.seed_account().await; + let seeded = db.seed_owned_workspace().await; + let account_id = seeded.account_id; let mut conn = db.client.get_connection().await?; let _ = conn - .create_account_notifications(vec![ - NewAccountNotification::test(account_id), - NewAccountNotification::test(account_id), - ]) + .create_account_notifications(vec![test(seeded), test(seeded)]) .await?; assert_eq!( - conn.mark_all_account_notifications_as_read(account_id) + conn.mark_all_account_notifications_as_read(account_id, None) .await?, 2 ); assert_eq!( - conn.count_unread_account_notifications(account_id).await?, + conn.count_unread_account_notifications(account_id, None) + .await?, 0 ); // A second call has nothing left to mark. assert_eq!( - conn.mark_all_account_notifications_as_read(account_id) + conn.mark_all_account_notifications_as_read(account_id, None) .await?, 0 ); diff --git a/crates/nvisy-postgres/src/query/accounts.rs b/crates/nvisy-postgres/src/query/accounts.rs index ab6110c0..dd4cc158 100644 --- a/crates/nvisy-postgres/src/query/accounts.rs +++ b/crates/nvisy-postgres/src/query/accounts.rs @@ -40,6 +40,14 @@ pub trait AccountRepository { account_ids: &[Uuid], ) -> impl Future>> + Send; + /// Finds the accounts `account_ids` name. As with [`Self::find_account_refs`], + /// a soft-deleted account still resolves, so a record keeps naming who acted + /// in it; an id matching no account is skipped. In no particular order. + fn find_accounts( + &mut self, + account_ids: &[Uuid], + ) -> impl Future>> + Send; + /// Finds an account by its unique identifier. /// /// Retrieves a specific account using its UUID, automatically excluding @@ -180,6 +188,19 @@ impl AccountRepository for PgConnection { Ok(refs) } + async fn find_accounts(&mut self, account_ids: &[Uuid]) -> Result> { + use schema::accounts::{self, dsl}; + + if account_ids.is_empty() { + return Ok(Vec::new()); + } + Ok(accounts::table + .filter(dsl::id.eq_any(account_ids)) + .select(Account::as_select()) + .load(self) + .await?) + } + 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/blob_pointers.rs b/crates/nvisy-postgres/src/query/blob_pointers.rs index 116b56f1..3cb12d5f 100644 --- a/crates/nvisy-postgres/src/query/blob_pointers.rs +++ b/crates/nvisy-postgres/src/query/blob_pointers.rs @@ -3,9 +3,9 @@ //! Several rows carry a nullable blob pointer, with its own retention expiry, //! whose bytes are released while the row itself is kept: a document's bytes, a //! detection's enrichment intermediate and its base-analysis (audit) findings, and -//! a redaction's review-analysis findings. Each is released the same way — find -//! the rows whose expiry for that pointer has passed, null the pointer, and drop -//! the reference so the blob reaper can purge the bytes. +//! a redaction's review-analysis findings and its certificate. Each is released +//! the same way — find the rows whose expiry for that pointer has passed, null +//! the pointer, and drop the reference so the blob reaper can purge the bytes. //! //! That one shape is generated by [`clear_expired_blob_pointer`] for each //! `(table, column)`, so the concurrency-safe null-then-guarded-decrement is @@ -135,6 +135,12 @@ clear_expired_blob_pointer! { expiring_on crate::schema::workspace_redactions::review_audit_expires_at } +clear_expired_blob_pointer! { + /// Reclaims redactions' expired certificate bytes. + pub fn clear_expired_certificates on workspace_redactions.certificate_blob_id, + expiring_on crate::schema::workspace_redactions::certificate_expires_at +} + #[cfg(test)] mod tests { use jiff::{Span, Timestamp}; @@ -268,6 +274,45 @@ mod tests { Ok(()) } + #[tokio::test] + async fn clearing_a_certificate_keeps_the_row_and_nulls_the_pointer() -> 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?; + let blob = conn + .find_or_create_blob(NewBlob::test(seeded.workspace_id)) + .await?; + let redaction = conn + .create_redaction(NewWorkspaceRedaction { + certificate_blob_id: Some(blob.id), + certificate_expires_at: Some(an_hour_ago().into()), + ..NewWorkspaceRedaction::test(detection.id, seeded.account_id) + }) + .await?; + + let cleared = clear_expired_certificates(&mut conn, 50).await?; + assert_eq!(cleared, 1); + + let kept = conn + .find_redaction_in_workspace(seeded.workspace_id, redaction.id) + .await? + .expect("redaction row survives"); + assert!( + kept.certificate_blob_id.is_none(), + "the certificate pointer is nulled" + ); + assert_eq!(conn.find_blob_by_id(blob.id).await?.unwrap().ref_count, 0); + Ok(()) + } + /// A document uploaded under the default (ephemeral) retention keeps its bytes /// through the processing window, and while a detection on it is in progress, /// then is released so the reaper purges the bytes. diff --git a/crates/nvisy-postgres/src/query/mod.rs b/crates/nvisy-postgres/src/query/mod.rs index e06f5e24..258d31f1 100644 --- a/crates/nvisy-postgres/src/query/mod.rs +++ b/crates/nvisy-postgres/src/query/mod.rs @@ -41,15 +41,16 @@ pub use account_api_tokens::AccountApiTokenRepository; pub use account_identities::{ AccountIdentityRepository, DeleteIdentityOutcome, LinkIdentityOutcome, }; -pub use account_notifications::AccountNotificationRepository; +pub use account_notifications::{AccountNotificationRepository, ListedNotification}; pub use accounts::AccountRepository; pub use analytics::{ AnalyticsSnapshot, DetectionDayPoint, DetectionDurations, DetectionStatusCount, StorageByKind, WorkspaceAnalyticsRepository, }; pub use blob_pointers::{ - clear_expired_detection_audits, clear_expired_detection_intermediates, - clear_expired_document_blobs, clear_expired_review_audits, + clear_expired_certificates, clear_expired_detection_audits, + clear_expired_detection_intermediates, clear_expired_document_blobs, + clear_expired_review_audits, }; pub use outbox::{NewOutboxRow, OutboxRepository, OutboxRow}; pub use workspace_activities::{ActivityFilter, WorkspaceActivityRepository}; @@ -58,12 +59,14 @@ 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_detection_policy_versions::{DetectionPolicy, DetectionPolicyVersionRepository}; pub use workspace_detections::{ DetectionDocuments, DetectionListRow, DetectionSummary, DetectionTreeRow, WorkspaceDetectionRepository, }; -pub use workspace_documents::{DocumentWithBlob, ImportedDocumentRef, WorkspaceDocumentRepository}; +pub use workspace_documents::{ + DocumentWithBlob, ImportedDocumentRef, ListedDocument, WorkspaceDocumentRepository, +}; pub use workspace_invites::{InviteCursor, WorkspaceInviteRepository}; pub use workspace_members::{WorkspaceMemberCursor, WorkspaceMemberRepository}; pub use workspace_policies::{DerivedPolicy, PolicyWithVersion, WorkspacePolicyRepository}; @@ -75,7 +78,8 @@ pub use workspace_review_events::{ TimelineCursor, TimelineEntry, TimelineSource, WorkspaceReviewEventRepository, }; pub use workspace_reviews::{ - ApprovalOutcome, AssignmentOutcome, ReviewDetails, StatusOutcome, WorkspaceReviewRepository, + ApprovalOutcome, AssignmentOutcome, RedactionReviewState, ReviewDetails, StatusOutcome, + WorkspaceReviewRepository, }; pub use workspace_webhooks::WorkspaceWebhookRepository; pub use workspaces::WorkspaceRepository; diff --git a/crates/nvisy-postgres/src/query/workspace_detection_edits.rs b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs index 240300d5..1b527f35 100644 --- a/crates/nvisy-postgres/src/query/workspace_detection_edits.rs +++ b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs @@ -11,6 +11,7 @@ use std::future::Future; use diesel::dsl::now; use diesel::prelude::*; +use diesel::sql_types::{Integer, Nullable}; use diesel_async::{AsyncConnection, RunQueryDsl}; use uuid::Uuid; @@ -18,6 +19,11 @@ use crate::model::{NewDetectionDecision, WorkspaceDetection, WorkspaceDetectionE use crate::types::{AccountRefRow, Json, WithAccountRef}; use crate::{PgConnection, Result, schema}; +diesel::define_sql_function! { + /// `COALESCE(value, fallback)` for nullable integers. + fn coalesce(value: Nullable, fallback: Nullable) -> Nullable; +} + /// The outcome of a guarded write of a detection's edits. #[derive(Debug, Clone)] pub enum EditWriteOutcome { @@ -40,7 +46,9 @@ pub trait DetectionEditRepository { /// 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. + /// `decisions` must be distinct. The detection's finding count becomes + /// `finding_count`, the count standing with `decisions` applied, or its base + /// count when that is `None`. /// /// Returns [`EditWriteOutcome::Updated`] with the detection, [`Stale`] when the /// detection exists but its revision has moved on, or [`Absent`] when no live @@ -55,6 +63,7 @@ pub trait DetectionEditRepository { account_id: Uuid, expected_rev: i32, decisions: Vec, + finding_count: Option, ) -> impl Future> + Send; /// Lists a detection's decisions with their authors, oldest-set first. @@ -72,6 +81,7 @@ impl DetectionEditRepository for PgConnection { account_id: Uuid, expected_rev: i32, decisions: Vec, + finding_count: Option, ) -> Result { use schema::workspace_detection_edits::{self as edits, dsl as edit}; use schema::workspace_detections::{self, dsl}; @@ -80,6 +90,8 @@ impl DetectionEditRepository for PgConnection { // 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. + // The finding count is rewritten with the decisions, or restored to + // the base analysis's when they are cleared. let updated: Option = diesel::update( workspace_detections::table .filter(dsl::id.eq(detection_id)) @@ -87,7 +99,13 @@ impl DetectionEditRepository for PgConnection { .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)) + .set(( + dsl::edit_set_rev.eq(dsl::edit_set_rev + 1), + dsl::finding_count.eq(coalesce( + finding_count.into_sql::>(), + dsl::base_finding_count, + )), + )) .returning(WorkspaceDetection::as_returning()) .get_result(conn) .await @@ -190,6 +208,24 @@ impl DetectionEditRepository for PgConnection { #[cfg(test)] mod tests { use super::*; + + /// Marks the detection's analysis as committed with `findings` standing, as + /// the detection worker does: edits apply only to an analysis. + async fn analyzed( + conn: &mut PgConnection, + detection_id: Uuid, + findings: i32, + ) -> anyhow::Result<()> { + use crate::schema::workspace_detections::{self, dsl}; + diesel::update(workspace_detections::table.filter(dsl::id.eq(detection_id))) + .set(( + dsl::base_finding_count.eq(Some(findings)), + dsl::finding_count.eq(Some(findings)), + )) + .execute(conn) + .await?; + Ok(()) + } use crate::PgConn; use crate::model::{NewAccount, NewWorkspaceDetection}; use crate::query::{AccountRepository, WorkspaceDetectionRepository}; @@ -228,6 +264,7 @@ mod tests { seeded.document_id, )) .await?; + analyzed(&mut conn, detection.id, 3).await?; // Alice sets two decisions. let outcome = conn @@ -240,12 +277,14 @@ mod tests { decision("a", serde_json::json!({ "v": 1 })), decision("b", serde_json::json!({ "v": 1 })), ], + Some(1), ) .await?; let EditWriteOutcome::Updated(updated) = outcome else { panic!("the first write lands"); }; assert_eq!(updated.edit_set_rev, 1); + assert_eq!(updated.finding_count, Some(1)); // Bob keeps `a`, changes `b`, and adds `c`. conn.replace_detection_edits( @@ -258,6 +297,7 @@ mod tests { decision("b", serde_json::json!({ "v": 2 })), decision("c", serde_json::json!({ "v": 1 })), ], + Some(2), ) .await?; assert_eq!( @@ -279,6 +319,7 @@ mod tests { decision("a", serde_json::json!({ "v": 1 })), decision("b", serde_json::json!({ "v": 2 })), ], + Some(1), ) .await?; assert_eq!( @@ -286,9 +327,14 @@ mod tests { 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()) + // An empty write clears them, and restores the base count. + let cleared = conn + .replace_detection_edits(seeded.workspace_id, detection.id, bob, 3, Vec::new(), None) .await?; + let EditWriteOutcome::Updated(cleared) = cleared else { + panic!("the clear lands"); + }; + assert_eq!(cleared.finding_count, Some(3)); assert_eq!(authors(&mut conn, detection.id).await?, Vec::new()); Ok(()) } @@ -306,6 +352,7 @@ mod tests { )) .await?; assert_eq!(detection.edit_set_rev, 0, "a new detection starts at rev 0"); + analyzed(&mut conn, detection.id, 1).await?; let write = || vec![decision("a", serde_json::json!({ "v": 1 }))]; conn.replace_detection_edits( @@ -314,6 +361,7 @@ mod tests { seeded.account_id, 0, write(), + Some(1), ) .await?; @@ -325,6 +373,7 @@ mod tests { seeded.account_id, 0, Vec::new(), + None, ) .await?; assert!(matches!(stale, EditWriteOutcome::Stale)); @@ -338,6 +387,7 @@ mod tests { seeded.account_id, 0, write(), + Some(1), ) .await?; assert!(matches!(absent, EditWriteOutcome::Absent)); diff --git a/crates/nvisy-postgres/src/query/workspace_detection_policy_versions.rs b/crates/nvisy-postgres/src/query/workspace_detection_policy_versions.rs index afcc2b2f..6001107a 100644 --- a/crates/nvisy-postgres/src/query/workspace_detection_policy_versions.rs +++ b/crates/nvisy-postgres/src/query/workspace_detection_policy_versions.rs @@ -11,8 +11,24 @@ use diesel_async::RunQueryDsl; use uuid::Uuid; use crate::model::DetectionPolicyVersion; +use crate::types::PolicyKind; use crate::{PgConnection, Result, schema}; +/// A policy a detection ran under, at the version its analysis pinned. +#[derive(Debug, Clone, PartialEq, Eq, Queryable)] +pub struct DetectionPolicy { + /// The detection that ran under it. + pub detection_id: Uuid, + /// The policy. + pub policy_id: Uuid, + /// The policy's display name now. A derived policy's is its content hash. + pub display_name: String, + /// How the policy came to exist. + pub kind: PolicyKind, + /// The version the analysis ran, as the policy numbers it. + pub version_number: i32, +} + /// Repository for the detection policy-version pin table. pub trait DetectionPolicyVersionRepository { /// Records the policy versions a detection's analysis ran against. @@ -32,6 +48,15 @@ pub trait DetectionPolicyVersionRepository { &mut self, detection_id: Uuid, ) -> impl Future>> + Send; + + /// Lists the policies each of `detection_ids` ran under, at the versions + /// they pinned, ordered by detection, then by display name. A policy since + /// deleted is still listed; a detection whose analysis has not completed + /// pinned none. + fn list_detection_policies( + &mut self, + detection_ids: &[Uuid], + ) -> impl Future>> + Send; } impl DetectionPolicyVersionRepository for PgConnection { @@ -72,6 +97,35 @@ impl DetectionPolicyVersionRepository for PgConnection { .load(self) .await?) } + + async fn list_detection_policies( + &mut self, + detection_ids: &[Uuid], + ) -> Result> { + use schema::{ + workspace_detection_policy_versions as pins, workspace_policies as policies, + workspace_policy_versions as versions, + }; + + if detection_ids.is_empty() { + return Ok(Vec::new()); + } + + Ok(pins::table + .inner_join(versions::table) + .inner_join(policies::table.on(policies::id.eq(versions::policy_id))) + .filter(pins::detection_id.eq_any(detection_ids)) + .order((pins::detection_id, policies::display_name, policies::id)) + .select(( + pins::detection_id, + policies::id, + policies::display_name, + policies::kind, + versions::version_number, + )) + .load(self) + .await?) + } } /// Deduplicates ids, preserving first-seen order. @@ -129,6 +183,20 @@ mod tests { expected.sort(); assert_eq!(pinned, expected); + // Each pinned policy lists with its version, and no other detection's. + let listed = conn.list_detection_policies(&[detection.id]).await?; + let mut policies: Vec<_> = listed.iter().map(|policy| policy.policy_id).collect(); + policies.sort(); + let mut expected = vec![first.policy.id, second.policy.id]; + expected.sort(); + assert_eq!(policies, expected); + assert!( + listed + .iter() + .all(|policy| policy.detection_id == detection.id) + ); + assert!(listed.iter().all(|policy| policy.version_number == 1)); + // Recording again is idempotent (no duplicate-key error). conn.record_detection_policy_versions(detection.id, &[first.version.id]) .await?; diff --git a/crates/nvisy-postgres/src/query/workspace_documents.rs b/crates/nvisy-postgres/src/query/workspace_documents.rs index 30c819a2..93086818 100644 --- a/crates/nvisy-postgres/src/query/workspace_documents.rs +++ b/crates/nvisy-postgres/src/query/workspace_documents.rs @@ -13,6 +13,8 @@ use std::future::Future; +use diesel::dsl::{Eq, InnerJoin, IntoBoxed, LeftJoin, LeftJoinOn, Nullable}; +use diesel::pg::Pg; use diesel::prelude::*; use diesel_async::RunQueryDsl; use pgtrgm::expression_methods::TrgmExpressionMethods; @@ -20,13 +22,16 @@ use uuid::Uuid; use crate::model::{ Blob, NewBlob, NewWorkspaceDocument, NewWorkspaceDocumentExport, NewWorkspaceDocumentImport, - UpdateWorkspaceDocument, WorkspaceDocument, + UpdateWorkspaceDocument, WorkspaceDetection, WorkspaceDocument, WorkspaceDocumentState, }; use crate::query::search::ilike_contains; use crate::query::workspace_blobs::WorkspaceBlobRepository; +use crate::schema::{ + accounts, workspace_blobs, workspace_detections, workspace_document_states, workspace_documents, +}; use crate::types::{ - AccountRefRow, CursorPage, CursorPagination, DocumentFilter, DocumentKind, TimeCursor, - WithAccountRef, keyset, total, + AccountRefRow, CursorPage, CursorPagination, DocumentFilter, DocumentKind, DocumentStage, + TimeCursor, WithAccountRef, keyset, total, }; use crate::{Error, PgConnection, Result, schema}; @@ -44,6 +49,31 @@ pub struct DocumentWithBlob { pub blob: Blob, } +/// A listed document: the document, its backing blob, what its detections, +/// redactions, and reviews add up to, and its latest detection. +#[derive(Debug, Clone)] +pub struct ListedDocument { + /// The document. + pub document: WorkspaceDocument, + /// The document's backing blob. + pub blob: Blob, + /// What its detections, redactions, and reviews add up to; `None` for a + /// redacted document. + pub state: Option, + /// Its latest live detection. + pub latest_detection: Option, +} + +/// A document list row as loaded: the document, its blob, its creator, and its +/// left-joined state and latest detection. +type ListedRow = ( + WorkspaceDocument, + Blob, + AccountRefRow, + Option, + Option, +); + /// A live document imported from a connection, for deletion reconciliation. /// /// A `source_key` no longer present in the remote listing identifies a document @@ -169,15 +199,24 @@ pub trait WorkspaceDocumentRepository { document_id: Uuid, ) -> impl Future> + Send; + /// Counts the originals in a workspace that `filter` keeps, by stage. A + /// stage no document is at is left out. + fn count_workspace_documents_by_stage( + &mut self, + workspace_id: Uuid, + filter: DocumentFilter, + ) -> impl Future>> + Send; + /// Lists all documents in a workspace with cursor pagination and optional - /// filtering, each paired with the handle and avatar of the account that - /// created it. + /// filtering, each with its state and latest detection, and paired with the + /// handle and avatar of + /// the account that created it. fn cursor_list_workspace_documents( &mut self, workspace_id: Uuid, pagination: CursorPagination, filter: DocumentFilter, - ) -> impl Future>>> + Send; + ) -> impl Future>>> + Send; /// Soft-deletes the live documents among `document_ids` that belong to /// `workspace_id`, dropping each one's blob reference, and returns the rows it @@ -508,60 +547,15 @@ impl WorkspaceDocumentRepository for PgConnection { workspace_id: Uuid, pagination: CursorPagination, filter: DocumentFilter, - ) -> Result>> { + ) -> Result>> { use schema::workspace_documents::dsl; - use schema::{accounts, workspace_blobs, workspace_documents}; - - // Precompute filter values - let search_term = filter.search.clone(); - let extensions = filter.extensions.clone(); - let hash = filter.hash.clone(); - - // The scoped builder (filters shared by the count and the page). Content - // identity (extension, hash) lives on the blob, so the builder joins each - // document to its blob; the join must apply to both the count and the page - // or they disagree. - let scoped = || { - let mut query = workspace_documents::table - .inner_join(accounts::table) - .inner_join(workspace_blobs::table) - .filter(dsl::workspace_id.eq(workspace_id)) - .filter(dsl::deleted_at.is_null()) - .into_boxed(); - - if let Some(kind) = filter.kind { - query = query.filter(dsl::kind.eq(kind)); - } - - // Hybrid name search: ILIKE substring (works for short queries) OR - // trigram similarity (typo tolerance); both served by the trgm index. - if let Some(ref term) = search_term { - query = query.filter( - dsl::display_name - .ilike(ilike_contains(term)) - .or(dsl::display_name.trgm_similar_to(term)) - .or(dsl::original_filename.ilike(ilike_contains(term))), - ); - } - - // Apply the extension constraint. A present-but-empty set matches - // nothing (an active facet with no members), so apply whenever `Some`. - if let Some(ref extensions) = extensions { - query = query.filter(dsl::file_extension.eq_any(extensions)); - } - - // Apply the exact content-hash constraint (dedup lookup). - if let Some(ref hash) = hash { - query = query.filter(workspace_blobs::content_hash.eq(hash)); - } - - query - }; + use schema::{workspace_detections, workspace_document_states as states}; + let scoped = || listed(workspace_id, &filter); let total = total!(pagination, self, scoped().count()); let after = pagination.after_pair(); - let rows: Vec<(WorkspaceDocument, Blob, AccountRefRow)> = keyset!( + let rows: Vec = keyset!( scoped(), dsl::created_at, dsl::id, @@ -572,20 +566,28 @@ impl WorkspaceDocumentRepository for PgConnection { WorkspaceDocument::as_select(), Blob::as_select(), AccountRefRow::as_select(), + // A left-joined row loads by position, so each model's fields + // follow its table's column order. + states::all_columns.nullable(), + workspace_detections::all_columns.nullable(), )) .limit(pagination.fetch_limit()) .load(self) .await?; - let items: Vec> = rows + let items = rows .into_iter() - .map(|row| WithAccountRef { - item: DocumentWithBlob { - document: row.0, - blob: row.1, + .map( + |(document, blob, account, state, latest_detection)| WithAccountRef { + item: ListedDocument { + document, + blob, + state, + latest_detection, + }, + account, }, - account: row.2, - }) + ) .collect(); Ok(CursorPage::new(items, total, pagination.limit, |wc| { @@ -593,6 +595,26 @@ impl WorkspaceDocumentRepository for PgConnection { })) } + async fn count_workspace_documents_by_stage( + &mut self, + workspace_id: Uuid, + filter: DocumentFilter, + ) -> Result> { + use diesel::dsl::count_star; + use schema::workspace_document_states as states; + use schema::workspace_documents::dsl; + + // Only originals have a state, so the states of the listed documents + // are the originals the filter keeps. + let listed_ids = listed(workspace_id, &filter).select(dsl::id); + Ok(states::table + .filter(states::document_id.eq_any(listed_ids)) + .group_by(states::stage) + .select((states::stage, count_star())) + .load(self) + .await?) + } + async fn delete_documents_in_workspace( &mut self, workspace_id: Uuid, @@ -642,11 +664,418 @@ impl WorkspaceDocumentRepository for PgConnection { } } +/// What a document list reads from: each document with its creator and blob, +/// and its state and latest detection when it has them. +type ListedSource = LeftJoinOn< + LeftJoin< + InnerJoin, workspace_blobs::table>, + workspace_document_states::table, + >, + workspace_detections::table, + Eq>, +>; + +/// The live documents of `workspace_id` that `filter` keeps, joined to their +/// creators, blobs, states and latest detections. The list, its total and the +/// stage counts all read through it, so they agree. +fn listed(workspace_id: Uuid, filter: &DocumentFilter) -> IntoBoxed<'_, ListedSource, Pg> { + use schema::workspace_document_states as states; + use schema::workspace_documents::dsl; + + // Content identity (extension, hash) lives on the blob, so each document + // joins its blob. + let mut query = workspace_documents::table + .inner_join(accounts::table) + .inner_join(workspace_blobs::table) + .left_join(states::table) + .left_join( + workspace_detections::table + .on(states::latest_detection_id.eq(workspace_detections::id.nullable())), + ) + .filter(dsl::workspace_id.eq(workspace_id)) + .filter(dsl::deleted_at.is_null()) + .into_boxed(); + + if let Some(kinds) = &filter.kinds { + query = query.filter(dsl::kind.eq_any(kinds)); + } + + // A redacted document has no stage, so a stage constraint never matches + // one. + if let Some(stages) = &filter.stages { + query = query.filter(states::stage.nullable().eq_any(stages)); + } + + // Hybrid name search: ILIKE substring (works for short queries) OR trigram + // similarity (typo tolerance); both served by the trgm index. + if let Some(term) = &filter.search { + query = query.filter( + dsl::display_name + .ilike(ilike_contains(term)) + .or(dsl::display_name.trgm_similar_to(term)) + .or(dsl::original_filename.ilike(ilike_contains(term))), + ); + } + + // A present-but-empty extension set matches nothing (an active facet with + // no members), so it applies whenever `Some`. + if let Some(extensions) = &filter.extensions { + query = query.filter(dsl::file_extension.eq_any(extensions)); + } + + // The exact content hash (dedup lookup). + if let Some(hash) = &filter.hash { + query = query.filter(workspace_blobs::content_hash.eq(hash)); + } + + query +} + #[cfg(test)] mod tests { use super::*; use crate::query::{WorkspaceBlobRepository, WorkspaceDocumentRepository}; use crate::test_util::TestDatabase; + use crate::types::DocumentStage; + + /// The stage of the only document a stage filter of `stages` lists, if one. + async fn listed_stage( + conn: &mut PgConnection, + workspace_id: Uuid, + stages: Option>, + ) -> anyhow::Result>> { + let page = conn + .cursor_list_workspace_documents( + workspace_id, + CursorPagination::new(10), + DocumentFilter { + kinds: Some(vec![DocumentKind::Original]), + stages, + ..Default::default() + }, + ) + .await?; + assert!(page.items.len() <= 1); + Ok(page + .items + .first() + .map(|row| row.item.state.as_ref().map(|state| state.stage))) + } + + #[tokio::test] + async fn a_document_s_stage_follows_its_detections_reviews_and_redactions() -> anyhow::Result<()> + { + use crate::model::{NewWorkspaceDetection, NewWorkspaceRedaction, NewWorkspaceReview}; + use crate::query::{ + WorkspaceDetectionRepository, WorkspaceRedactionRepository, WorkspaceReviewRepository, + }; + use crate::schema::workspace_detections::{self, dsl}; + use crate::types::DetectionStatus; + + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let workspace = seeded.workspace_id; + let mut conn = db.client.get_connection().await?; + let stage = async |conn: &mut PgConnection| -> anyhow::Result> { + Ok(listed_stage(conn, workspace, None) + .await? + .expect("the document is listed")) + }; + let settle = async |conn: &mut PgConnection, id: Uuid, status| -> anyhow::Result<()> { + diesel::update(workspace_detections::table.filter(dsl::id.eq(id))) + .set(dsl::status.eq(status)) + .execute(conn) + .await?; + Ok(()) + }; + let detect = async |conn: &mut PgConnection| -> anyhow::Result { + Ok(conn + .create_workspace_detection(NewWorkspaceDetection::test( + workspace, + seeded.account_id, + seeded.document_id, + )) + .await? + .id) + }; + + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Uploaded)); + let first = detect(&mut conn).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Detecting)); + settle(&mut conn, first, DetectionStatus::Failed).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Failed)); + settle(&mut conn, first, DetectionStatus::Complete).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Detected)); + + let redaction = conn + .create_redaction(NewWorkspaceRedaction::test(first, seeded.account_id)) + .await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Redacted)); + + let review = conn + .create_review(NewWorkspaceReview::test( + workspace, + seeded.document_id, + seeded.account_id, + )) + .await?; + assert_eq!( + stage(&mut conn).await?, + Some(DocumentStage::Redacted), + "a draft awaits no decision" + ); + conn.submit_review(review.id, seeded.account_id).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::InReview)); + conn.add_assignee(review.id, seeded.account_id, seeded.account_id) + .await?; + conn.approve_review(review.id, seeded.account_id, 1, redaction.id) + .await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Approved)); + assert_eq!( + listed_stage(&mut conn, workspace, Some(vec![DocumentStage::Approved])).await?, + Some(Some(DocumentStage::Approved)) + ); + assert_eq!( + listed_stage(&mut conn, workspace, Some(vec![DocumentStage::Detected])).await?, + None + ); + + // A newer detection starts the workflow over: the approval was of the + // one before it. + let second = detect(&mut conn).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Detecting)); + settle(&mut conn, second, DetectionStatus::Complete).await?; + assert_eq!(stage(&mut conn).await?, Some(DocumentStage::Detected)); + Ok(()) + } + + #[tokio::test] + async fn a_document_s_stage_is_its_own() -> anyhow::Result<()> { + use crate::model::{NewWorkspaceDetection, NewWorkspaceReview}; + use crate::query::{WorkspaceDetectionRepository, WorkspaceReviewRepository}; + use crate::schema::{workspace_detections, workspace_redactions}; + use crate::types::DetectionStatus; + + let db = TestDatabase::start().await; + let fixture = db.seed_detection_and_redaction().await; + let seeded = fixture.seeded; + let workspace = seeded.workspace_id; + let mut conn = db.client.get_connection().await?; + diesel::update(workspace_detections::table) + .set(workspace_detections::status.eq(DetectionStatus::Complete)) + .execute(&mut conn) + .await?; + + // Another original in the same workspace, detected, with no review. + let other = conn + .create_workspace_document( + NewWorkspaceDocument::test(workspace, seeded.account_id, Uuid::nil()), + NewBlob::test(workspace), + ) + .await?; + let detection = conn + .create_workspace_detection(NewWorkspaceDetection::test( + workspace, + seeded.account_id, + other.id, + )) + .await?; + diesel::update( + workspace_detections::table.filter(workspace_detections::id.eq(detection.id)), + ) + .set(workspace_detections::status.eq(DetectionStatus::Complete)) + .execute(&mut conn) + .await?; + + // The first document's review is approved; the other's stage does not + // follow it. + let review = conn + .create_review(NewWorkspaceReview::test( + workspace, + seeded.document_id, + seeded.account_id, + )) + .await?; + conn.submit_review(review.id, seeded.account_id).await?; + let stages = + async |conn: &mut PgConnection| -> anyhow::Result)>> { + let mut page = conn + .cursor_list_workspace_documents( + workspace, + CursorPagination::new(10), + DocumentFilter::default(), + ) + .await? + .items + .into_iter() + .map(|row| { + ( + row.item.document.id, + row.item.state.as_ref().map(|state| state.stage), + ) + }) + .collect::>(); + page.sort_by_key(|(id, _)| *id == other.id); + Ok(page) + }; + assert_eq!( + stages(&mut conn).await?, + [ + (seeded.document_id, Some(DocumentStage::InReview)), + (other.id, Some(DocumentStage::Detected)), + ] + ); + conn.add_assignee(review.id, seeded.account_id, seeded.account_id) + .await?; + conn.approve_review(review.id, seeded.account_id, 1, fixture.redaction_id) + .await?; + assert_eq!( + stages(&mut conn).await?, + [ + (seeded.document_id, Some(DocumentStage::Approved)), + (other.id, Some(DocumentStage::Detected)), + ] + ); + + // A deleted redaction approves nothing, and leaves nothing redacted. + diesel::update( + workspace_redactions::table.filter(workspace_redactions::id.eq(fixture.redaction_id)), + ) + .set(workspace_redactions::deleted_at.eq(diesel::dsl::now)) + .execute(&mut conn) + .await?; + assert_eq!( + stages(&mut conn).await?[0], + (seeded.document_id, Some(DocumentStage::Detected)) + ); + Ok(()) + } + + #[tokio::test] + async fn deleting_an_account_refreshes_the_documents_it_touched() -> anyhow::Result<()> { + use crate::model::{NewAccount, NewWorkspaceDetection}; + use crate::query::{AccountRepository, WorkspaceDetectionRepository}; + use crate::schema::accounts; + + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + let other = conn.create_account(NewAccount::test()).await?.id; + conn.create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + other, + seeded.document_id, + )) + .await?; + assert_eq!( + listed_stage(&mut conn, seeded.workspace_id, None).await?, + Some(Some(DocumentStage::Detecting)) + ); + + // The account's detection goes with it, by cascade. + diesel::delete(accounts::table.filter(accounts::id.eq(other))) + .execute(&mut conn) + .await?; + assert_eq!( + listed_stage(&mut conn, seeded.workspace_id, None).await?, + Some(Some(DocumentStage::Uploaded)) + ); + Ok(()) + } + + #[tokio::test] + async fn stage_counts_cover_every_original_the_filter_keeps() -> anyhow::Result<()> { + use crate::model::NewWorkspaceDetection; + use crate::query::WorkspaceDetectionRepository; + + let db = TestDatabase::start().await; + let seeded = db.seed_account_and_workspace().await; + let workspace = seeded.workspace_id; + let mut conn = db.client.get_connection().await?; + let mut upload = async |name: &str| -> anyhow::Result { + let mut document = + NewWorkspaceDocument::test(workspace, seeded.account_id, Uuid::nil()); + document.display_name = Some(name.to_owned()); + Ok(conn + .create_workspace_document(document, NewBlob::test(workspace)) + .await?) + }; + + // Two uploaded originals, one detecting, and a redacted output, which + // has no stage. + upload("alpha").await?; + upload("beta").await?; + let detecting = upload("gamma").await?; + let mut output = NewWorkspaceDocument::test(workspace, seeded.account_id, Uuid::nil()); + output.kind = Some(DocumentKind::Redacted); + conn.create_workspace_document(output, NewBlob::test(workspace)) + .await?; + conn.create_workspace_detection(NewWorkspaceDetection::test( + workspace, + seeded.account_id, + detecting.id, + )) + .await?; + + let mut counts = conn + .count_workspace_documents_by_stage(workspace, DocumentFilter::default()) + .await?; + counts.sort_by_key(|&(_, count)| -count); + assert_eq!( + counts, + [(DocumentStage::Uploaded, 2), (DocumentStage::Detecting, 1)] + ); + + // The filter narrows them as it narrows the list. + let counts = conn + .count_workspace_documents_by_stage( + workspace, + DocumentFilter { + search: Some("alpha".to_owned()), + ..Default::default() + }, + ) + .await?; + assert_eq!(counts, [(DocumentStage::Uploaded, 1)]); + Ok(()) + } + + #[tokio::test] + async fn a_redacted_document_has_no_stage() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_account_and_workspace().await; + let workspace = seeded.workspace_id; + let mut conn = db.client.get_connection().await?; + let mut output = NewWorkspaceDocument::test(workspace, seeded.account_id, Uuid::nil()); + output.kind = Some(DocumentKind::Redacted); + conn.create_workspace_document(output, NewBlob::test(workspace)) + .await?; + let redacted = conn + .cursor_list_workspace_documents( + workspace, + CursorPagination::new(10), + DocumentFilter { + kinds: Some(vec![DocumentKind::Redacted]), + ..Default::default() + }, + ) + .await?; + assert_eq!(redacted.items[0].item.state, None); + + // So a stage filter never lists one. + let staged = conn + .cursor_list_workspace_documents( + workspace, + CursorPagination::new(10), + DocumentFilter { + stages: Some(vec![DocumentStage::Uploaded]), + ..Default::default() + }, + ) + .await?; + assert_eq!(staged.items.len(), 0); + Ok(()) + } #[tokio::test] async fn cursor_list_combines_kind_and_original_filename_search() -> anyhow::Result<()> { @@ -668,7 +1097,7 @@ mod tests { .await?; } let filter = DocumentFilter { - kind: Some(DocumentKind::Original), + kinds: Some(vec![DocumentKind::Original]), search: Some("cOnTrAcT_50%".into()), extensions: Some(vec!["pdf".into()]), ..Default::default() @@ -702,7 +1131,7 @@ mod tests { seeded.workspace_id, CursorPagination::new(10), DocumentFilter { - kind: Some(DocumentKind::Redacted), + kinds: Some(vec![DocumentKind::Redacted]), ..Default::default() }, ) diff --git a/crates/nvisy-postgres/src/query/workspace_redactions.rs b/crates/nvisy-postgres/src/query/workspace_redactions.rs index 9452184b..37207b82 100644 --- a/crates/nvisy-postgres/src/query/workspace_redactions.rs +++ b/crates/nvisy-postgres/src/query/workspace_redactions.rs @@ -12,7 +12,13 @@ use crate::types::{ AccountRefRow, CursorPage, CursorPagination, RedactionFilter, TimeCursor, WithAccountRef, keyset, total, }; -use crate::{PgConnection, Result, schema}; +use crate::{AsyncConnection, Error, PgConnection, Result, schema}; + +/// The constraint that keeps certificate numbers unique. +const CERTIFICATE_NUMBER_UNIQUE: &str = "workspace_redactions_certificate_number_unique"; + +/// How many certificate numbers a redaction draws before a collision fails it. +const CERTIFICATE_NUMBER_ATTEMPTS: u32 = 3; /// Redacted output metadata for one detection, used by the artifacts endpoint. #[derive(Debug, Clone)] @@ -63,6 +69,32 @@ pub trait WorkspaceRedactionRepository { redaction_id: Uuid, ) -> impl Future>> + Send; + /// The redacted documents among `document_ids` in a workspace whose live + /// redaction is its input document's approved redaction: the output of the + /// document's latest approved review. + fn list_approved_outputs( + &mut self, + workspace_id: Uuid, + document_ids: &[Uuid], + ) -> impl Future>> + Send; + + /// Finds the live redaction in a workspace that wrote the document + /// `output_document_id`, even when its detection has since been deleted: + /// the file it wrote is still its. + fn find_redaction_by_output( + &mut self, + workspace_id: Uuid, + output_document_id: Uuid, + ) -> impl Future>> + Send; + + /// Finds the live redaction whose certificate has `certificate_number`, with + /// the workspace it belongs to, across every workspace: a certificate's + /// reader holds only its number. + fn find_redaction_by_certificate_number( + &mut self, + certificate_number: i32, + ) -> impl Future>> + Send; + /// Lists a detection's redactions with cursor pagination, newest first. fn cursor_list_detection_redactions( &mut self, @@ -150,11 +182,33 @@ impl WorkspaceRedactionRepository for PgConnection { ) -> Result { use schema::workspace_redactions; - Ok(diesel::insert_into(workspace_redactions::table) - .values(&new_redaction) - .returning(WorkspaceRedaction::as_returning()) - .get_result(self) - .await?) + // The certificate number is drawn at random and checked unlocked, so + // two concurrent inserts can draw the same one; the loser draws again. + // Each attempt runs under its own savepoint, so a losing insert does + // not abort a surrounding transaction. + let mut attempt = 1; + loop { + let inserted = self + .transaction(async |conn| { + Ok::<_, Error>( + diesel::insert_into(workspace_redactions::table) + .values(&new_redaction) + .returning(WorkspaceRedaction::as_returning()) + .get_result(conn) + .await?, + ) + }) + .await; + match inserted { + Err(err) + if attempt < CERTIFICATE_NUMBER_ATTEMPTS + && err.constraint() == Some(CERTIFICATE_NUMBER_UNIQUE) => + { + attempt += 1; + } + inserted => return inserted, + } + } } async fn find_redaction_in_workspace( @@ -180,6 +234,72 @@ impl WorkspaceRedactionRepository for PgConnection { .optional()?) } + async fn list_approved_outputs( + &mut self, + workspace_id: Uuid, + document_ids: &[Uuid], + ) -> Result> { + use schema::workspace_detections::dsl as detections; + use schema::workspace_redactions::dsl as redactions; + use schema::{ + workspace_detections, workspace_document_states as states, workspace_redactions, + }; + + if document_ids.is_empty() { + return Ok(Vec::new()); + } + let outputs: Vec> = workspace_redactions::table + .inner_join(workspace_detections::table) + .inner_join(states::table.on(states::document_id.eq(detections::input_document_id))) + .filter(redactions::output_document_id.eq_any(document_ids)) + .filter(redactions::deleted_at.is_null()) + .filter(detections::workspace_id.eq(workspace_id)) + .filter(states::approved_redaction_id.eq(redactions::id.nullable())) + .select(redactions::output_document_id) + .load(self) + .await?; + Ok(outputs.into_iter().flatten().collect()) + } + + async fn find_redaction_by_output( + &mut self, + workspace_id: Uuid, + output_document_id: Uuid, + ) -> Result> { + use schema::workspace_detections::dsl as detections; + use schema::workspace_redactions::dsl as redactions; + use schema::{workspace_detections, workspace_redactions}; + + Ok(workspace_redactions::table + .inner_join(workspace_detections::table) + .filter(redactions::output_document_id.eq(output_document_id)) + .filter(redactions::deleted_at.is_null()) + .filter(detections::workspace_id.eq(workspace_id)) + .select(WorkspaceRedaction::as_select()) + .first(self) + .await + .optional()?) + } + + async fn find_redaction_by_certificate_number( + &mut self, + certificate_number: i32, + ) -> Result> { + use schema::workspace_detections::dsl as detections; + use schema::workspace_redactions::dsl as redactions; + use schema::{workspace_detections, workspace_redactions}; + + Ok(workspace_redactions::table + .inner_join(workspace_detections::table) + .filter(redactions::certificate_number.eq(certificate_number)) + .filter(redactions::deleted_at.is_null()) + .filter(detections::deleted_at.is_null()) + .select((WorkspaceRedaction::as_select(), detections::workspace_id)) + .first(self) + .await + .optional()?) + } + async fn cursor_list_detection_redactions( &mut self, detection_id: Uuid, @@ -273,6 +393,37 @@ mod tests { use crate::query::{WorkspaceDetectionRepository, WorkspaceRedactionRepository}; use crate::test_util::{TestDatabase, backdate}; + #[tokio::test] + async fn each_certificate_number_is_eight_digits_and_finds_its_redaction() -> anyhow::Result<()> + { + let db = TestDatabase::start().await; + let (account_id, workspace_id, detection_id) = seed_detection(&db).await?; + let mut conn = db.client.get_connection().await?; + let first = conn + .create_redaction(NewWorkspaceRedaction::test(detection_id, account_id)) + .await?; + let second = conn + .create_redaction(NewWorkspaceRedaction::test(detection_id, account_id)) + .await?; + + for redaction in [&first, &second] { + assert!((10_000_000..=99_999_999).contains(&redaction.certificate_number)); + } + assert_ne!(first.certificate_number, second.certificate_number); + + let (found, found_in) = conn + .find_redaction_by_certificate_number(second.certificate_number) + .await? + .expect("the redaction holding the number"); + assert_eq!((found.id, found_in), (second.id, workspace_id)); + assert!( + conn.find_redaction_by_certificate_number(1) + .await? + .is_none() + ); + Ok(()) + } + #[tokio::test] async fn detection_outputs_exclude_other_workspaces_and_deleted_files() -> anyhow::Result<()> { use crate::model::{NewBlob, NewWorkspaceDocument}; diff --git a/crates/nvisy-postgres/src/query/workspace_reviews.rs b/crates/nvisy-postgres/src/query/workspace_reviews.rs index 77ff07f6..c0b627e3 100644 --- a/crates/nvisy-postgres/src/query/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/query/workspace_reviews.rs @@ -17,12 +17,13 @@ use std::future::Future; use diesel::dsl::now; use diesel::prelude::*; use diesel_async::RunQueryDsl; +use jiff_diesel::Timestamp; use uuid::Uuid; use super::workspace_review_events::record_event; use crate::model::{ - NewReviewAssignee, NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceReview, - WorkspaceReviewApproval, WorkspaceReviewEvent, + NewReviewAssignee, NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceRedaction, + WorkspaceReview, WorkspaceReviewApproval, WorkspaceReviewEvent, }; use crate::types::{ AccountRefRow, CursorPage, CursorPagination, DocumentReviewFilter, ReviewEventKind, @@ -45,6 +46,23 @@ pub struct ReviewDetails { pub approvals: Vec, } +/// What a document's live reviews say about one of its redactions. +#[derive(Debug, Clone, PartialEq)] +pub struct RedactionReviewState { + /// Whether it is the output of the document's latest approved review. + pub approved: bool, + /// Whether the document's latest approved review has another live + /// redaction as its output, and reached its quorum after this one was + /// made. + pub superseded: bool, + /// Whether a review of the document awaits a decision: in review, changes + /// requested, or partially approved. + pub open: bool, + /// The approvals of it by the approved reviews that have it as their + /// output, oldest first. A review still short of its quorum adds none. + 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 @@ -145,6 +163,15 @@ pub trait WorkspaceReviewRepository { review: WorkspaceReview, ) -> impl Future> + Send; + /// What the live reviews of a redaction's document say about it, from the + /// document's stored state: whether the latest approved review approved + /// it, or another redaction after it was made, whether one awaits a + /// decision, and the approvals of the reviews that approved it. + fn redaction_review_state( + &mut self, + redaction: &WorkspaceRedaction, + ) -> impl Future> + Send; + /// Submits (or resubmits) a review for review, moving it from `draft` or /// `changes_requested` to `in_review` and recording a `submitted` event. Locks /// the review first and re-checks the status under the lock: a review in any other @@ -409,6 +436,64 @@ impl WorkspaceReviewRepository for PgConnection { .ok_or_else(|| Error::unexpected("review details for one review came back empty")) } + async fn redaction_review_state( + &mut self, + redaction: &WorkspaceRedaction, + ) -> Result { + use schema::{ + workspace_detections as wd, workspace_document_states as states, + workspace_review_approvals as wrap, workspace_reviews as wr, + }; + + // Both reads share one snapshot, so a review reopened between them + // cannot leave the redaction approved with no approvals. + let (state, approvals) = self + .build_transaction() + .read_only() + .repeatable_read() + .run(async |conn| { + // The document's stored state holds its approved redaction. The + // detection is read even when deleted: its document is still the + // redaction's. A document with no state, a deleted one, has no review. + let state: Option<(Option, Option, bool)> = wd::table + .inner_join(states::table.on(states::document_id.eq(wd::input_document_id))) + .filter(wd::id.eq(redaction.detection_id)) + .select(( + states::approved_redaction_id, + states::approved_at, + states::has_open_review, + )) + .first(conn) + .await + .optional()?; + + // Only approvals that count: those of a review that reached its quorum + // with this redaction as its output. + let approvals = wrap::table + .inner_join(wr::table.on(wr::id.eq(wrap::review_id))) + .filter(wrap::redaction_id.eq(redaction.id)) + .filter(wr::deleted_at.is_null()) + .filter(wr::review_status.eq(ReviewStatus::Approved)) + .filter(wr::redaction_id.eq(redaction.id)) + .order((wrap::approved_at.asc(), wrap::account_id.asc())) + .select(WorkspaceReviewApproval::as_select()) + .load(conn) + .await?; + Ok::<_, Error>((state, approvals)) + }) + .await?; + let (approved_redaction_id, approved_at, open) = state.unwrap_or((None, None, false)); + let approved = approved_redaction_id == Some(redaction.id); + let superseded = !approved && approved_at.is_some_and(|at| at > redaction.created_at); + + Ok(RedactionReviewState { + approved, + superseded, + open, + approvals, + }) + } + async fn rename_review( &mut self, review_id: Uuid, @@ -1650,6 +1735,149 @@ mod tests { Ok(()) } + #[tokio::test] + async fn a_later_approval_of_another_redaction_supersedes_one() -> 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 first = conn + .find_redaction_in_workspace(seeded.workspace_id, fixture.redaction_id) + .await? + .expect("the seeded redaction"); + + let untouched = conn.redaction_review_state(&first).await?; + assert!(!untouched.approved && !untouched.superseded && !untouched.open); + assert_eq!(untouched.approvals, Vec::new()); + + let approve = async |conn: &mut PgConn, redaction_id| -> anyhow::Result<()> { + let review = conn + .create_review(NewWorkspaceReview::test( + seeded.workspace_id, + seeded.document_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?; + assert!(conn.redaction_review_state(&first).await?.open); + conn.approve_review(review.id, seeded.account_id, 1, redaction_id) + .await?; + Ok(()) + }; + + approve(&mut conn, first.id).await?; + let approved = conn.redaction_review_state(&first).await?; + assert!(approved.approved && !approved.superseded && !approved.open); + assert_eq!(approved.approvals.len(), 1); + assert_eq!(approved.approvals[0].account_id, seeded.account_id); + + // A redaction made after the approval is not superseded by it. + let second = conn + .create_redaction(NewWorkspaceRedaction::test( + fixture.detection_id, + seeded.account_id, + )) + .await?; + let made_later = conn.redaction_review_state(&second).await?; + assert!(!made_later.approved && !made_later.superseded); + + // Approving it supersedes the first. + approve(&mut conn, second.id).await?; + let replaced = conn.redaction_review_state(&first).await?; + assert!(!replaced.approved && replaced.superseded); + let replacing = conn.redaction_review_state(&second).await?; + assert!(replacing.approved && !replacing.superseded); + + // Once the replacing redaction is deleted, it replaces nothing. + { + use diesel::prelude::*; + use diesel_async::RunQueryDsl; + + use crate::schema::workspace_redactions::{self, dsl}; + diesel::update(workspace_redactions::table.filter(dsl::id.eq(second.id))) + .set(dsl::deleted_at.eq(diesel::dsl::now)) + .execute(&mut conn) + .await?; + } + assert!(!conn.redaction_review_state(&first).await?.superseded); + Ok(()) + } + + #[tokio::test] + async fn the_latest_approval_wins() -> 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 first = conn + .find_redaction_in_workspace(seeded.workspace_id, fixture.redaction_id) + .await? + .expect("the seeded redaction"); + let second = conn + .create_redaction(NewWorkspaceRedaction::test( + fixture.detection_id, + seeded.account_id, + )) + .await?; + let approve = async |conn: &mut PgConn, redaction_id| -> anyhow::Result<()> { + let review = conn + .create_review(NewWorkspaceReview::test( + seeded.workspace_id, + seeded.document_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?; + conn.approve_review(review.id, seeded.account_id, 1, redaction_id) + .await?; + Ok(()) + }; + + // The first, then the second, then the first again: the first stands, + // and only the second is superseded. + approve(&mut conn, first.id).await?; + approve(&mut conn, second.id).await?; + approve(&mut conn, first.id).await?; + let first_state = conn.redaction_review_state(&first).await?; + assert!(first_state.approved && !first_state.superseded); + let second_state = conn.redaction_review_state(&second).await?; + assert!(!second_state.approved && second_state.superseded); + Ok(()) + } + + #[tokio::test] + async fn an_approval_short_of_its_quorum_does_not_count() -> 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 redaction = conn + .find_redaction_in_workspace(seeded.workspace_id, fixture.redaction_id) + .await? + .expect("the seeded redaction"); + let review = conn + .create_review(NewWorkspaceReview::test( + seeded.workspace_id, + seeded.document_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?; + conn.approve_review(review.id, seeded.account_id, 2, redaction.id) + .await?; + + let state = conn.redaction_review_state(&redaction).await?; + assert!(state.open && !state.approved); + assert_eq!(state.approvals, Vec::new()); + Ok(()) + } + #[tokio::test] async fn a_lowered_quorum_promotes_only_the_redaction_approved() -> anyhow::Result<()> { let db = TestDatabase::start().await; diff --git a/crates/nvisy-postgres/src/query/workspaces.rs b/crates/nvisy-postgres/src/query/workspaces.rs index 22cb3b33..6521910e 100644 --- a/crates/nvisy-postgres/src/query/workspaces.rs +++ b/crates/nvisy-postgres/src/query/workspaces.rs @@ -215,9 +215,9 @@ impl WorkspaceRepository for PgConnection { // // Blob references live on documents (`blob_id`), detections // (`intermediate_blob_id` and `audit_blob_id`), and redactions - // (`review_audit_blob_id`). Each `UPDATE ... WHERE deleted_at IS NULL` is - // idempotent (a second pass matches no live row), so a reference is never - // double-dropped. + // (`review_audit_blob_id` and `certificate_blob_id`). Each + // `UPDATE ... WHERE deleted_at IS NULL` is idempotent (a second pass + // matches no live row), so a reference is never double-dropped. self.transaction(async |conn| { let mut refs: Vec = Vec::new(); @@ -252,8 +252,8 @@ impl WorkspaceRepository for PgConnection { } // Redactions scope to the workspace through their detection; each holds - // its review-analysis reference. - let review_blobs: Vec> = diesel::update( + // two references (its review analysis and its certificate). + let redaction_blobs: Vec<(Option, Option)> = diesel::update( workspace_redactions::table .filter(workspace_redactions::deleted_at.is_null()) .filter( @@ -265,10 +265,16 @@ impl WorkspaceRepository for PgConnection { ), ) .set(workspace_redactions::deleted_at.eq(now)) - .returning(workspace_redactions::review_audit_blob_id) + .returning(( + workspace_redactions::review_audit_blob_id, + workspace_redactions::certificate_blob_id, + )) .get_results(conn) .await?; - refs.extend(review_blobs.into_iter().flatten()); + for (review, certificate) in redaction_blobs { + refs.extend(review); + refs.extend(certificate); + } // One decrement per reference: a blob shared by several referrers // appears once for each. diff --git a/crates/nvisy-postgres/src/schema.rs b/crates/nvisy-postgres/src/schema.rs index d14ebfdc..06abf014 100644 --- a/crates/nvisy-postgres/src/schema.rs +++ b/crates/nvisy-postgres/src/schema.rs @@ -26,6 +26,11 @@ pub mod sql_types { #[diesel(enum_type)] pub struct DocumentKind; + #[derive(Clone, diesel::query_builder::QueryId, diesel::sql_types::SqlType)] + #[diesel(postgres_type(name = "document_stage"))] + #[diesel(enum_type)] + pub struct DocumentStage; + #[derive(Clone, diesel::query_builder::QueryId, diesel::sql_types::SqlType)] #[diesel(postgres_type(name = "identity_provider"))] #[diesel(enum_type)] @@ -149,6 +154,7 @@ diesel::table! { params -> Jsonb, created_at -> Timestamptz, expires_at -> Nullable, + workspace_id -> Uuid, } } @@ -331,6 +337,8 @@ diesel::table! { retention_override -> Nullable, metadata -> Jsonb, edit_set_rev -> Int4, + base_finding_count -> Nullable, + finding_count -> Nullable, claimed_at -> Nullable, started_at -> Timestamptz, completed_at -> Nullable, @@ -360,6 +368,21 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use super::sql_types::DocumentStage; + + workspace_document_states (document_id) { + document_id -> Uuid, + stage -> DocumentStage, + latest_detection_id -> Nullable, + has_redaction -> Bool, + has_open_review -> Bool, + approved_redaction_id -> Nullable, + approved_at -> Nullable, + } +} + diesel::table! { use diesel::sql_types::*; use super::sql_types::DocumentKind; @@ -505,6 +528,9 @@ diesel::table! { output_document_id -> Nullable, review_audit_blob_id -> Nullable, review_audit_expires_at -> Nullable, + certificate_blob_id -> Nullable, + certificate_expires_at -> Nullable, + certificate_number -> Int4, created_at -> Timestamptz, deleted_at -> Nullable, } @@ -624,6 +650,7 @@ diesel::table! { diesel::joinable!(account_api_tokens -> accounts (account_id)); diesel::joinable!(account_identities -> accounts (account_id)); diesel::joinable!(account_notifications -> accounts (account_id)); +diesel::joinable!(account_notifications -> workspaces (workspace_id)); diesel::joinable!(workspace_activities -> accounts (account_id)); diesel::joinable!(workspace_activities -> workspaces (workspace_id)); diesel::joinable!(workspace_assistant_jobs -> workspace_review_comments (comment_id)); @@ -645,6 +672,9 @@ diesel::joinable!(workspace_document_exports -> workspace_connections (connectio diesel::joinable!(workspace_document_exports -> workspace_documents (document_id)); diesel::joinable!(workspace_document_imports -> workspace_connections (connection_id)); diesel::joinable!(workspace_document_imports -> workspace_documents (document_id)); +diesel::joinable!(workspace_document_states -> workspace_detections (latest_detection_id)); +diesel::joinable!(workspace_document_states -> workspace_documents (document_id)); +diesel::joinable!(workspace_document_states -> workspace_redactions (approved_redaction_id)); diesel::joinable!(workspace_documents -> accounts (account_id)); diesel::joinable!(workspace_documents -> workspace_blobs (blob_id)); diesel::joinable!(workspace_documents -> workspaces (workspace_id)); @@ -659,7 +689,6 @@ diesel::joinable!(workspace_policy_versions -> workspaces (workspace_id)); diesel::joinable!(workspace_providers -> accounts (account_id)); diesel::joinable!(workspace_providers -> workspaces (workspace_id)); 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)); @@ -693,6 +722,7 @@ diesel::allow_tables_to_appear_in_same_query!( workspace_detections, workspace_document_exports, workspace_document_imports, + workspace_document_states, workspace_documents, workspace_event_outbox, workspace_invites, diff --git a/crates/nvisy-postgres/src/types/enums/document_stage.rs b/crates/nvisy-postgres/src/types/enums/document_stage.rs new file mode 100644 index 00000000..3de8cf7f --- /dev/null +++ b/crates/nvisy-postgres/src/types/enums/document_stage.rs @@ -0,0 +1,31 @@ +//! Document stage enumeration: where an original document stands in its +//! workflow. + +use super::db_enum; + +db_enum! { + /// Where an original document stands in its workflow. + /// + /// Corresponds to the `DOCUMENT_STAGE` `PostgreSQL` enum. Database + /// triggers keep each live original's stage current from its latest live + /// detection, its reviews, and its redactions. A redacted document has + /// none. + pub enum DocumentStage { + /// It has no live detection. + Uploaded = "uploaded", + /// Its latest detection has not finished. + Detecting = "detecting", + /// Its latest detection failed. + Failed = "failed", + /// Its latest detection finished, and nothing below holds. + Detected = "detected", + /// Its latest detection has a live redaction. + Redacted = "redacted", + /// A review of it awaits a decision: in review, changes requested, or + /// partially approved. + InReview = "in_review", + /// Its latest approved review approved a live redaction of its latest + /// detection. + Approved = "approved", + } +} diff --git a/crates/nvisy-postgres/src/types/enums/mod.rs b/crates/nvisy-postgres/src/types/enums/mod.rs index 69d8f9a0..041091a0 100644 --- a/crates/nvisy-postgres/src/types/enums/mod.rs +++ b/crates/nvisy-postgres/src/types/enums/mod.rs @@ -27,6 +27,7 @@ pub mod workspace_role; // Document-related enumerations pub mod document_kind; +pub mod document_stage; // Detection-related enumerations pub mod detection_status; @@ -40,6 +41,7 @@ pub use api_token_type::ApiTokenType; pub use connection_type::ConnectionType; pub use detection_status::DetectionStatus; pub use document_kind::DocumentKind; +pub use document_stage::DocumentStage; pub use identity_provider::IdentityProvider; pub use invite_status::InviteStatus; pub use notification_event::NotificationEvent; diff --git a/crates/nvisy-postgres/src/types/filtering/documents.rs b/crates/nvisy-postgres/src/types/filtering/documents.rs index bce53184..263d478e 100644 --- a/crates/nvisy-postgres/src/types/filtering/documents.rs +++ b/crates/nvisy-postgres/src/types/filtering/documents.rs @@ -1,6 +1,6 @@ //! Filtering options for document queries. -use crate::types::DocumentKind; +use crate::types::{DocumentKind, DocumentStage}; /// Filter options for documents. /// @@ -13,8 +13,12 @@ use crate::types::DocumentKind; /// taxonomy, which lives in the engine's codec registry. #[derive(Debug, Default, Clone)] pub struct DocumentFilter { - /// Document role to include; absent includes both originals and redacted files. - pub kind: Option, + /// Document roles to include. `None` includes every role. + pub kinds: Option>, + /// Workflow stages to include. `None` imposes no constraint; `Some(set)` + /// matches only originals at one of these stages, so never a redacted + /// document, which has none. + pub stages: Option>, /// Search by document name (case-insensitive, partial match). An empty string /// is resolved to `None` by the caller, so a set value is always a real /// search. diff --git a/crates/nvisy-postgres/src/types/json/notification_params.rs b/crates/nvisy-postgres/src/types/json/notification_params.rs index 5e48a40a..e4f12895 100644 --- a/crates/nvisy-postgres/src/types/json/notification_params.rs +++ b/crates/nvisy-postgres/src/types/json/notification_params.rs @@ -16,8 +16,6 @@ use crate::types::{ConnectionId, DetectionId, NotificationEvent, RedactionId}; #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase")] pub struct MemberJoinedParams { - /// Id of the workspace the member joined. - pub workspace_id: Uuid, /// Id of the member's account. pub member_id: Uuid, } diff --git a/crates/nvisy-postgres/src/types/json/workspace_settings.rs b/crates/nvisy-postgres/src/types/json/workspace_settings.rs index 7146446c..992a9d65 100644 --- a/crates/nvisy-postgres/src/types/json/workspace_settings.rs +++ b/crates/nvisy-postgres/src/types/json/workspace_settings.rs @@ -31,12 +31,13 @@ pub enum RasterPolicy { Never, } -/// A workspace's review approval policy: who may approve and how many approvals a -/// review needs before it is signed off. +/// A workspace's review approval policy: who may approve, how many approvals a +/// review needs before it is signed off, whether a redaction needs one, and +/// whether its file waits for one. /// /// The defaults reproduce the minimal behaviour — a single approver, the author -/// allowed — so a workspace that configures nothing behaves as if reviews are a -/// plain single sign-off. +/// allowed, reviews optional, downloads ungated — so a workspace that configures +/// nothing behaves as if reviews are a plain single sign-off. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Serialize, Deserialize)] @@ -49,6 +50,13 @@ pub struct ReviewSettings { /// `1` is a single sign-off; `2` or more is a multi-party rule, which makes the /// `partially_approved` state reachable. Clamped to at least 1 when read. pub min_approvals: u32, + /// Whether every redaction needs an approved review before it is final: one + /// no review has approved yet reads as needing review, even with no review + /// open. + pub required: bool, + /// Whether a redacted file can be downloaded only once a review has + /// approved its redaction, and not once another redaction replaced it. + pub gate_downloads: bool, } impl Default for ReviewSettings { @@ -56,6 +64,8 @@ impl Default for ReviewSettings { Self { author_can_approve: true, min_approvals: 1, + required: false, + gate_downloads: false, } } } diff --git a/crates/nvisy-postgres/src/types/mod.rs b/crates/nvisy-postgres/src/types/mod.rs index dd76268c..ca2171f5 100644 --- a/crates/nvisy-postgres/src/types/mod.rs +++ b/crates/nvisy-postgres/src/types/mod.rs @@ -20,10 +20,10 @@ pub use constraint::{ WorkspaceWebhookConstraints, }; pub use enums::{ - ActivityType, ApiTokenType, ConnectionType, DetectionStatus, DocumentKind, IdentityProvider, - InviteStatus, NotificationEvent, OutboxStatus, PolicyKind, ProviderType, ReviewEventKind, - ReviewStatus, SyncDeletionPolicy, SyncMode, SyncStatus, SyncTriggerType, WebhookEvent, - WebhookStatus, WorkspaceRole, + ActivityType, ApiTokenType, ConnectionType, DetectionStatus, DocumentKind, DocumentStage, + IdentityProvider, InviteStatus, NotificationEvent, OutboxStatus, PolicyKind, ProviderType, + ReviewEventKind, ReviewStatus, SyncDeletionPolicy, SyncMode, SyncStatus, SyncTriggerType, + WebhookEvent, WebhookStatus, WorkspaceRole, }; pub use filtering::{ DetectionFilter, DocumentFilter, DocumentReviewFilter, InviteFilter, MemberFilter, diff --git a/crates/nvisy-server/Cargo.toml b/crates/nvisy-server/Cargo.toml index 139ff1a7..7867ee65 100644 --- a/crates/nvisy-server/Cargo.toml +++ b/crates/nvisy-server/Cargo.toml @@ -55,6 +55,7 @@ elide-runtime = { workspace = true, features = [ "audit-json", "audit-csv", "audit-zip", + "certificate-pdf", ] } # Internal crates @@ -103,9 +104,10 @@ zxcvbn = { workspace = true, features = [] } # Encryption & Cryptography sha2 = { workspace = true, features = [] } -chacha20poly1305 = { workspace = true, features = [] } +chacha20poly1305 = { workspace = true, features = ["zeroize"] } aead-stream = { workspace = true, features = ["alloc"] } hkdf = { workspace = true, features = [] } +zeroize = { workspace = true, features = [] } # Encoding base64 = { workspace = true, features = ["std"] } diff --git a/crates/nvisy-server/src/domain/account_notifications.rs b/crates/nvisy-server/src/domain/account_notifications.rs index 4ff45938..682c678e 100644 --- a/crates/nvisy-server/src/domain/account_notifications.rs +++ b/crates/nvisy-server/src/domain/account_notifications.rs @@ -8,8 +8,7 @@ use nvisy_nats::stream::BroadcastStream; use nvisy_postgres::PgClient; -use nvisy_postgres::model::AccountNotification; -use nvisy_postgres::query::AccountNotificationRepository; +use nvisy_postgres::query::{AccountNotificationRepository, ListedNotification}; use nvisy_postgres::types::{CursorPage, CursorPagination, TimeCursor}; use uuid::Uuid; @@ -39,8 +38,9 @@ impl AccountNotificationService { Self { postgres, emitter } } - /// Lists the account's notifications, most recent first (a pure read; does not - /// change read status). + /// Lists the account's notifications, most recent first, each with its + /// workspace, in `workspace_id` only when given (a pure read; does not change + /// read status). /// /// # Errors /// @@ -48,11 +48,12 @@ impl AccountNotificationService { pub async fn list( &self, account_id: Uuid, + workspace_id: Option, pagination: CursorPagination, - ) -> Result> { + ) -> Result> { let mut conn = self.postgres.get_connection().await?; Ok(conn - .cursor_list_account_notifications(account_id, pagination) + .cursor_list_account_notifications(account_id, workspace_id, pagination) .await?) } @@ -68,31 +69,35 @@ impl AccountNotificationService { self.emitter.subscribe_unread(account_id).await } - /// Returns the account's unread notification count. + /// Returns the account's unread notification count, in `workspace_id` only + /// when given. /// /// # Errors /// /// - A database error if the connection or query fails. - pub async fn unread_count(&self, account_id: Uuid) -> Result { + pub async fn unread_count(&self, account_id: Uuid, workspace_id: Option) -> Result { let mut conn = self.postgres.get_connection().await?; - Ok(conn.count_unread_account_notifications(account_id).await?) + Ok(conn + .count_unread_account_notifications(account_id, workspace_id) + .await?) } - /// Marks every unread notification read, broadcasting the now-zero count when - /// any were marked. Returns how many it marked. + /// Marks every unread notification read, in `workspace_id` only when given, + /// broadcasting the account's new unread count when any were marked. Returns + /// how many it marked. /// /// # Errors /// /// - A database error if the connection or query fails. - pub async fn mark_all_read(&self, account_id: Uuid) -> Result { + pub async fn mark_all_read(&self, account_id: Uuid, workspace_id: Option) -> Result { let mut conn = self.postgres.get_connection().await?; let marked_read = i64::try_from( - conn.mark_all_account_notifications_as_read(account_id) + conn.mark_all_account_notifications_as_read(account_id, workspace_id) .await?, ) .unwrap_or(i64::MAX); - // Push the now-zero unread count so a watching badge clears live. + // Push the new unread count so a watching badge updates live. if marked_read > 0 { self.emitter.broadcast_unread(&mut conn, account_id).await; } diff --git a/crates/nvisy-server/src/domain/detection_decisions.rs b/crates/nvisy-server/src/domain/detection_decisions.rs index 5f1969ab..15006931 100644 --- a/crates/nvisy-server/src/domain/detection_decisions.rs +++ b/crates/nvisy-server/src/domain/detection_decisions.rs @@ -124,6 +124,18 @@ pub(crate) fn apply(report: &mut Report, decisions: &[(Uuid, EditSet)]) -> Resul Ok(()) } +/// How many findings in `report` stand: entities redaction would act on, +/// those neither detection nor a reviewer dropped, or that a reviewer +/// confirmed since. +pub(crate) fn finding_count(report: &Report) -> i32 { + let count = report + .parts() + .entities() + .filter(|part| !part.entity.is_suppressed()) + .count(); + i32::try_from(count).unwrap_or(i32::MAX) +} + /// The accounts the reviewer events in a report's parts name, sorted by id. /// /// Every decision this server lands names its author by account id, so each @@ -302,7 +314,7 @@ mod tests { Edit::Add(Add { label: LabelRef::new("phone_number"), location: TextLocation::inline(at.0..at.1), - part: None, + part: Vec::new(), reason: None, }) } diff --git a/crates/nvisy-server/src/domain/input/workspace_documents.rs b/crates/nvisy-server/src/domain/input/workspace_documents.rs index d690e463..b460fb30 100644 --- a/crates/nvisy-server/src/domain/input/workspace_documents.rs +++ b/crates/nvisy-server/src/domain/input/workspace_documents.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; -use nvisy_postgres::types::{DocumentFilter, DocumentKind}; +use nvisy_postgres::types::{DocumentFilter, DocumentKind, DocumentStage}; use crate::service::{EngineService, UnknownFormatToken}; @@ -12,8 +12,10 @@ use crate::service::{EngineService, UnknownFormatToken}; /// against the engine's codec registry at query time. #[derive(Default)] pub struct ListDocumentsInput { - /// Document role to include. - pub kind: Option, + /// Document roles to include; `None` includes every role. + pub kinds: Option>, + /// Workflow stages to include; `None` imposes no constraint. + pub stages: Option>, /// Search term over document names; an empty term imposes no constraint. pub search: Option, /// File-extension filter tokens (each expands to its format's full set). @@ -51,7 +53,8 @@ impl ListDocumentsInput { .filter(|s| !s.is_empty()); Ok(DocumentFilter { - kind: self.kind, + kinds: self.kinds, + stages: self.stages, search, extensions: intersect_facets(formats, modality), hash: self.hash, diff --git a/crates/nvisy-server/src/domain/mod.rs b/crates/nvisy-server/src/domain/mod.rs index 9edb91c6..eee2d21b 100644 --- a/crates/nvisy-server/src/domain/mod.rs +++ b/crates/nvisy-server/src/domain/mod.rs @@ -21,7 +21,7 @@ mod account_api_tokens; mod account_identities; mod account_notifications; mod config; -mod detection_decisions; +pub(crate) mod detection_decisions; mod json; mod workspace_activities; mod workspace_analytics; @@ -53,6 +53,7 @@ pub use workspace_members::WorkspaceMemberService; pub use workspace_policies::WorkspacePolicyService; pub use workspace_providers::WorkspaceProviderService; pub use workspace_redactions::WorkspaceRedactionService; +pub(crate) use workspace_redactions::review_settings; pub use workspace_reviews::WorkspaceReviewService; pub use workspace_webhooks::WorkspaceWebhookService; pub use workspaces::WorkspaceService; diff --git a/crates/nvisy-server/src/domain/output/workspace_detections.rs b/crates/nvisy-server/src/domain/output/workspace_detections.rs index 925f3828..258eaecd 100644 --- a/crates/nvisy-server/src/domain/output/workspace_detections.rs +++ b/crates/nvisy-server/src/domain/output/workspace_detections.rs @@ -3,7 +3,7 @@ use nvisy_postgres::model::{ WorkspaceDetection as WorkspaceDetectionModel, WorkspaceDetectionEdit, }; -use nvisy_postgres::query::DetectionDocuments; +use nvisy_postgres::query::{DetectionDocuments, DetectionPolicy}; use nvisy_postgres::types::{AccountRefRow, WithAccountRef}; /// A newly created or idempotently replayed detection, with the context a response @@ -29,4 +29,16 @@ pub struct FoundDetection { pub documents: DetectionDocuments, /// The detection's reviewer decisions, each with its author, oldest-set first. pub edits: Vec>, + /// The policies its analysis ran under, at the versions it pinned: none + /// until the analysis completes. + pub policies: Vec, +} + +/// A list row with the policies its detection's analysis ran under. +pub struct WithPolicies { + /// The list row. + pub item: T, + /// The policies its detection's analysis ran under, at the versions it + /// pinned: none until the analysis completes, or with no detection. + pub policies: Vec, } diff --git a/crates/nvisy-server/src/domain/output/workspace_redactions.rs b/crates/nvisy-server/src/domain/output/workspace_redactions.rs index 008b9874..cd93f4d0 100644 --- a/crates/nvisy-server/src/domain/output/workspace_redactions.rs +++ b/crates/nvisy-server/src/domain/output/workspace_redactions.rs @@ -1,7 +1,18 @@ //! Redaction service outputs. +use std::collections::BTreeMap; +use std::fmt; + +use elide_runtime::certificate::{ + CertificateActivity, CertificateApproval, CertificateStatus, DocumentCertificate, +}; use elide_runtime::elide::report::AppliedReport; +use jiff::Timestamp; use nvisy_postgres::types::AccountRefRow; +use schemars::JsonSchema; +use serde::Serialize; + +use crate::service::CertificateReference; /// A redaction's review audit, with the accounts its reviewer events name. pub struct ReviewAudit { @@ -10,3 +21,85 @@ pub struct ReviewAudit { /// The accounts the audit's reviewer events name, sorted by id. pub accounts: Vec, } + +/// A redaction's certificate, with its reference, its status, everything +/// that happened to its file, and the accounts it names. +pub struct RedactionCertificate { + /// The certificate's public reference. + pub reference: CertificateReference, + /// Who issued it. + pub issuer: String, + /// Where it stands now, from its document's reviews and what it left + /// visible. + pub status: CertificateStatus, + /// Where its redaction stands in its document's reviews, which `status` + /// follows. + pub approval: CertificateApproval, + /// What the redaction withheld and why, the files it read and wrote, and + /// the policies it ran under. + pub certificate: DocumentCertificate, + /// Everything that happened to the file, oldest first: the activity the + /// certificate's PDF prints. + pub activity: Vec>, + /// The accounts the activity names, in the order it first names them. + pub accounts: Vec, +} + +/// What an account did to a redaction's file that the certificate itself does +/// not record. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CertificateAction { + /// Uploaded the file. + Uploaded, + /// Ran the detection the redaction was made from. + Detected, + /// Approved the redaction in a review. + Approved, +} + +/// How the certificate's PDF words it, after the account's name. +impl fmt::Display for CertificateAction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Uploaded => "uploaded the file", + Self::Detected => "ran the detection", + Self::Approved => "approved the redaction", + }) + } +} + +/// A redaction's certificate rendered as a PDF. +pub struct CertificatePdf { + /// The PDF/A-2b document. + pub bytes: Vec, + /// The file name to offer it under. + pub file_name: String, +} + +/// What a certificate proves to a reader who holds only its reference: that it +/// was issued, when and by whom, for which redacted file, and how much it +/// withheld. It names no account, reason, policy, or document, and gives no +/// digest of the original: the certificate seals it with a salt the issuer +/// keeps, so it is no use to a reader who holds only the reference. +pub struct CertificateProof { + /// The certificate's public reference. + pub reference: CertificateReference, + /// Who issued it. + pub issuer: String, + /// When it was issued. + pub issued_at: Timestamp, + /// Where it stands now, from its document's reviews and what it left + /// visible. + pub status: CertificateStatus, + /// Where its redaction stands in its document's reviews, which `status` + /// follows. + pub approval: CertificateApproval, + /// The SHA-256 of the redacted file, as 64 lowercase hex digits. + pub output_sha256: String, + /// How many findings were withheld, by label. + pub withheld: BTreeMap, + /// How many findings were left visible, by label. + pub disclosed: BTreeMap, +} diff --git a/crates/nvisy-server/src/domain/workspace_detections.rs b/crates/nvisy-server/src/domain/workspace_detections.rs index fe47760d..36d4f8aa 100644 --- a/crates/nvisy-server/src/domain/workspace_detections.rs +++ b/crates/nvisy-server/src/domain/workspace_detections.rs @@ -24,7 +24,7 @@ use nvisy_postgres::model::{ WorkspaceDetection as WorkspaceDetectionModel, }; use nvisy_postgres::query::{ - DetectionDocuments, DetectionEditRepository, DetectionListRow, + DetectionDocuments, DetectionEditRepository, DetectionListRow, DetectionPolicy, DetectionPolicyVersionRepository, EditWriteOutcome, OutboxRepository, WorkspaceDetectionRepository, WorkspaceDocumentRepository, WorkspacePolicyRepository, WorkspacePolicyVersionRepository, @@ -32,13 +32,13 @@ use nvisy_postgres::query::{ use nvisy_postgres::types::{ AccountRefRow, CursorPage, CursorPagination, DetectionFilter, DetectionStatus, Json, TimeCursor, }; -use nvisy_postgres::{AsyncConnection, PgClient, PgConn}; +use nvisy_postgres::{AsyncConnection, PgClient, PgConn, PgConnection}; use uuid::Uuid; use crate::domain::detection_decisions; use crate::domain::input::{CreateDetectionInput, DerivedPolicyInput, DetectionSourceInput}; use crate::domain::json::{encode, parse_policy_definition}; -use crate::domain::output::{CreatedDetection, FoundDetection}; +use crate::domain::output::{CreatedDetection, FoundDetection, WithPolicies}; use crate::domain::workspace_policies::resolve_derived_policy; use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::event::EventEmitter; @@ -203,6 +203,7 @@ impl WorkspaceDetectionService { input: Some(document.display_name), }, edits: Vec::new(), + policies: Vec::new(), }, created: true, }) @@ -232,10 +233,20 @@ impl WorkspaceDetectionService { workspace_id: Uuid, pagination: CursorPagination, filter: &DetectionFilter, - ) -> Result> { + ) -> Result>> { + // One snapshot, so a detection's policies match the status it lists + // with: none until its analysis has committed. let mut conn = self.postgres.get_connection().await?; Ok(conn - .cursor_list_workspace_detections(workspace_id, pagination, filter) + .build_transaction() + .read_only() + .repeatable_read() + .run(async |conn| { + let page = conn + .cursor_list_workspace_detections(workspace_id, pagination, filter) + .await?; + with_policies(conn, page, |row| Some(row.detection.id)).await + }) .await?) } @@ -346,7 +357,9 @@ impl WorkspaceDetectionService { /// changed one is credited to `account_id`. Before storing, the edits are /// validated against the detection's base analysis and trial-applied exactly /// as a redaction would apply them, so an invalid set is never persisted to - /// wedge a later redaction. Clearing needs no analysis and skips this. + /// wedge a later redaction, and the detection's finding count is taken from + /// the result. Clearing needs no analysis and skips this, restoring the base + /// analysis's count. /// /// # Errors /// @@ -365,11 +378,13 @@ impl WorkspaceDetectionService { expected_rev: i32, edits: Option, ) -> Result { - let decisions = match &edits { - None => Vec::new(), + let (decisions, finding_count) = match &edits { + None => (Vec::new(), None), Some(edits) => { - self.prepare_decisions(workspace_id, detection_id, account_id, edits) - .await? + let (decisions, count) = self + .prepare_decisions(workspace_id, detection_id, account_id, edits) + .await?; + (decisions, Some(count)) } }; @@ -381,6 +396,7 @@ impl WorkspaceDetectionService { account_id, expected_rev, decisions, + finding_count, ) .await? { @@ -395,13 +411,14 @@ impl WorkspaceDetectionService { /// Splits `edits` into the decisions to store, after checking they apply to the /// detection's base analysis as a redaction would apply them: under each /// decision's author, keeping a stored decision's author when it is unchanged. + /// Returns them with how many findings stand once they apply. async fn prepare_decisions( &self, workspace_id: Uuid, detection_id: Uuid, account_id: Uuid, edits: &EditSet, - ) -> Result> { + ) -> Result<(Vec, i32)> { let detection = self.find(workspace_id, detection_id).await?; let stored: HashMap = { let mut conn = self.postgres.get_connection().await?; @@ -443,7 +460,7 @@ impl WorkspaceDetectionService { let mut audit = self.load_base_audit(workspace_id, &detection).await?; edits.validate(&audit.report)?; detection_decisions::apply(&mut audit.report, &attributed)?; - Ok(decisions) + Ok((decisions, detection_decisions::finding_count(&audit.report))) } /// Loads a detection's base analysis (its [`Audit`]), for validating reviewer @@ -616,13 +633,51 @@ async fn found_detection( .detection_document_names(workspace_id, &found.item) .await?; let edits = conn.list_detection_edits(found.item.id).await?; + let policies = conn.list_detection_policies(&[found.item.id]).await?; Ok(Some(FoundDetection { detection: found.item, trigger: found.account, documents, edits, + policies, })) }) .await?; found.ok_or_else(|| Error::not_found(Resource::Detection)) } + +/// Pairs each row of `page` with the policies its detection, named by +/// `detection_of`, ran under, in one query for the whole page. Run it in the +/// transaction that read the page, so the two agree. +/// +/// # Errors +/// +/// - A database error if the query fails. +pub(crate) async fn with_policies( + conn: &mut PgConnection, + page: CursorPage, + detection_of: impl Fn(&T) -> Option, +) -> nvisy_postgres::Result>> { + let ids: Vec = page.items.iter().filter_map(&detection_of).collect(); + let mut policies: HashMap> = HashMap::new(); + for policy in conn.list_detection_policies(&ids).await? { + policies + .entry(policy.detection_id) + .or_default() + .push(policy); + } + Ok(CursorPage { + items: page + .items + .into_iter() + .map(|item| WithPolicies { + policies: detection_of(&item) + .and_then(|id| policies.remove(&id)) + .unwrap_or_default(), + item, + }) + .collect(), + total: page.total, + next_cursor: page.next_cursor, + }) +} diff --git a/crates/nvisy-server/src/domain/workspace_documents.rs b/crates/nvisy-server/src/domain/workspace_documents.rs index 2e4d18fb..5a122cee 100644 --- a/crates/nvisy-server/src/domain/workspace_documents.rs +++ b/crates/nvisy-server/src/domain/workspace_documents.rs @@ -15,14 +15,17 @@ use nvisy_postgres::model::{ UpdateWorkspaceDocument as UpdateDocumentModel, WorkspaceDocument as DocumentModel, }; use nvisy_postgres::query::{ - DocumentWithBlob, WorkspaceBlobRepository, WorkspaceDocumentRepository, + DocumentWithBlob, ListedDocument, WorkspaceBlobRepository, WorkspaceDocumentRepository, +}; +use nvisy_postgres::types::{ + CursorPage, CursorPagination, DocumentFilter, DocumentStage, TimeCursor, WithAccountRef, }; -use nvisy_postgres::types::{CursorPage, CursorPagination, TimeCursor, WithAccountRef}; use nvisy_postgres::{AsyncConnection, PgClient, PgConn}; use uuid::Uuid; use crate::domain::input::ListDocumentsInput; -use crate::domain::output::BulkDeleteOutcome; +use crate::domain::output::{BulkDeleteOutcome, WithPolicies}; +use crate::domain::workspace_detections::with_policies; use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::event::EventEmitter; use crate::service::{DocumentStager, EngineService, StagedDocument, event}; @@ -137,9 +140,39 @@ impl WorkspaceDocumentService { .await } + /// Resolves a list query's format and modality facets against the engine's + /// codec registry into the database filter. + fn filter(&self, query: ListDocumentsInput) -> Result { + query.to_filter(&self.engine).map_err(|err| { + ErrorKind::BadRequest + .with_message("Unknown document format filter") + .with_context(err.to_string()) + }) + } + + /// Counts a workspace's originals by stage, resolving the query's format and + /// modality facets as [`list`](Self::list) does. + /// + /// # Errors + /// + /// - `BadRequest` if a format or modality filter token matches no known + /// extension or modality. + /// - A database error if a connection or the query fails. + pub async fn stage_counts( + &self, + workspace_id: Uuid, + query: ListDocumentsInput, + ) -> Result> { + let filter = self.filter(query)?; + let mut conn = self.postgres.get_connection().await?; + Ok(conn + .count_workspace_documents_by_stage(workspace_id, filter) + .await?) + } + /// Lists a workspace's documents with cursor pagination, each with its backing - /// blob and creator, resolving the query's format and modality facets against - /// the engine's codec registry. + /// blob, creator, state, and latest detection with its policies, resolving the + /// query's format and modality facets against the engine's codec registry. /// /// # Errors /// @@ -151,16 +184,28 @@ impl WorkspaceDocumentService { workspace_id: Uuid, pagination: CursorPagination, query: ListDocumentsInput, - ) -> Result>> { - let filter = query.to_filter(&self.engine).map_err(|err| { - ErrorKind::BadRequest - .with_message("Unknown document format filter") - .with_context(err.to_string()) - })?; + ) -> Result>>> { + let filter = self.filter(query)?; + // One snapshot, so a document's latest detection and its policies + // agree. let mut conn = self.postgres.get_connection().await?; Ok(conn - .cursor_list_workspace_documents(workspace_id, pagination, filter) + .build_transaction() + .read_only() + .repeatable_read() + .run(async |conn| { + let page = conn + .cursor_list_workspace_documents(workspace_id, pagination, filter) + .await?; + with_policies(conn, page, |row| { + row.item + .latest_detection + .as_ref() + .map(|detection| detection.id) + }) + .await + }) .await?) } diff --git a/crates/nvisy-server/src/domain/workspace_redactions.rs b/crates/nvisy-server/src/domain/workspace_redactions.rs index fca38cae..d88f76bb 100644 --- a/crates/nvisy-server/src/domain/workspace_redactions.rs +++ b/crates/nvisy-server/src/domain/workspace_redactions.rs @@ -1,28 +1,41 @@ //! Redaction domain service: redacting a detection, and reading redactions back. +use std::collections::BTreeMap; +use std::fmt::Display; +use std::str::FromStr; + use elide_runtime::AnonymizeRequest; +use elide_runtime::certificate::{CertificateApproval, DocumentCertificate, HistoryEvent}; +use elide_runtime::elide::entity::LabelRef; use elide_runtime::governance::policy::Policy; use elide_runtime::provider::KeyConfig; use elide_runtime::review::EditSet; use nvisy_postgres::model::{ - Blob, NewWorkspaceDocument, NewWorkspaceRedaction, Workspace, + Account, Blob, NewWorkspaceDocument, NewWorkspaceRedaction, Workspace, WorkspaceDetection as WorkspaceDetectionModel, WorkspaceDocument, WorkspaceRedaction, + WorkspaceReviewApproval, }; use nvisy_postgres::query::{ - AccountRepository, DetectionEditRepository, WorkspaceBlobRepository, - WorkspaceDocumentRepository, WorkspaceRedactionRepository, + AccountRepository, DetectionEditRepository, RedactionReviewState, WorkspaceBlobRepository, + WorkspaceDetectionRepository, WorkspaceDocumentRepository, WorkspaceRedactionRepository, + WorkspaceRepository, WorkspaceReviewRepository, }; use nvisy_postgres::types::{ - CursorPage, CursorPagination, DocumentKind, RedactionFilter, TimeCursor, WithAccountRef, + CursorPage, CursorPagination, DocumentKind, RedactionFilter, ReviewSettings, TimeCursor, + WithAccountRef, }; use nvisy_postgres::{AsyncConnection, PgClient, PgConn}; use uuid::Uuid; -use crate::domain::output::ReviewAudit; +use crate::domain::output::{ + CertificateAction, CertificatePdf, CertificateProof, RedactionCertificate, ReviewAudit, +}; use crate::domain::{WorkspaceDetectionService, detection_decisions}; use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::event::EventEmitter; -use crate::service::{ArtifactReader, ArtifactWriter, EngineService, StagedBlob, event}; +use crate::service::{ + ArtifactReader, ArtifactWriter, CertificateReference, EngineService, StagedBlob, event, +}; /// Tracing target for redaction domain operations. const TRACING_TARGET: &str = "nvisy_server::domain::redaction"; @@ -60,6 +73,8 @@ struct Staged { output_name: String, /// The review audit. review: StagedBlob, + /// The certificate. + certificate: StagedBlob, } impl WorkspaceRedactionService { @@ -83,9 +98,9 @@ impl WorkspaceRedactionService { /// Redacts a detection: applies its pinned policies to its stored analysis, /// with the detection's reviewer decisions layered on first, each under the - /// reviewer who set it, and - /// commits the redacted document, the review audit, and the redaction row - /// together. A detection can be redacted more than once. + /// reviewer who set it, and commits the redacted document, the review audit, + /// the certificate, and the redaction row together. A detection can be + /// redacted more than once. /// /// Runs in three phases so a pooled connection is never held across the slow /// work: the pre-flight reads, then the analysis load, inference, and object @@ -149,19 +164,13 @@ impl WorkspaceRedactionService { .await? .ok_or_else(Error::document_content_gone)?; - // The detection's base analysis blob, loaded to seed the working audit. - // A completed detection with a NULL pointer had its bytes reclaimed (404); - // an incomplete one has no analysis yet (409). - let audit_blob_id = detection.audit_blob_id.ok_or_else(|| { - if detection.status.is_complete() { - ErrorKind::NotFound.with_message("The analysis for this detection has been deleted") - } else { - ErrorKind::Conflict.with_message("Detection has no analysis yet") - } - })?; - let audit_blob = conn.find_blob_by_id(audit_blob_id).await?.ok_or_else(|| { - ErrorKind::NotFound.with_message("The analysis for this detection has been deleted") - })?; + // The detection's base analysis blob, loaded to seed the working audit: + // a 404 once reclaimed or past its retention, as the analysis endpoint + // answers. + let audit_blob = self + .reader + .resolve_audit_blob(&mut conn, &detection) + .await?; let edits = detection_decisions::decode( conn.list_detection_edits(detection.id) .await? @@ -223,7 +232,7 @@ impl WorkspaceRedactionService { // context are read back from the audit, recorded at detect time, and the // redacting account is named as who ran it. The applied report it returns, // the record of what was redacted, is persisted as the redaction's review - // audit. + // audit, and the certificate it issues beside it. let redacted_by = redacted_by.to_string(); let request = AnonymizeRequest { policies: &inputs.policies, @@ -232,9 +241,9 @@ impl WorkspaceRedactionService { }; let anonymized = self.engine.anonymize(document, reviewed, &request).await?; - // Stage both produced objects (redacted document + review audit) outside the - // transaction — object writes are not transactional — then commit their blobs, - // document, audit, and redaction rows together. On rollback the staged objects + // Stage the produced objects (redacted document, review audit, certificate) + // outside the transaction — object writes are not transactional — then + // commit their blobs, document, and redaction rows together. On rollback the staged objects // are reclaimed so no orphaned bytes accrue. Retention comes from the // detection's snapshotted override (the run's own retention), so re-redacting // reflects what the detection ran under. @@ -255,34 +264,44 @@ impl WorkspaceRedactionService { anonymized.document.bytes, ) .await?; - // Staging the review audit after the output means a failure here would strand - // the already-written output object (no blob to reclaim it); discard it first. - let staged_review = match self + // Each object staged after the output would strand the ones before it on + // failure (no blob to reclaim them), so a failure discards those first. + let staged_review = self .writer - .stage_review( - inputs.detection.workspace_id, - retention_override.as_ref(), - &retention, - &anonymized.report, + .stage_after( + &[&staged_output], + self.writer.stage_review( + inputs.detection.workspace_id, + retention_override.as_ref(), + &retention, + &anonymized.report, + ), ) - .await - { - Ok(staged) => staged, - Err(err) => { - self.writer.discard_staged(&[&staged_output]).await; - return Err(err); - } - }; + .await?; + let staged_certificate = self + .writer + .stage_after( + &[&staged_output, &staged_review], + self.writer.stage_certificate( + inputs.detection.workspace_id, + retention_override.as_ref(), + &retention, + &anonymized.certificate, + ), + ) + .await?; Ok(Staged { output: staged_output, output_name, review: staged_review, + certificate: staged_certificate, }) } - /// Redaction phase 3: commits the output document, the review audit blob, and - /// the redaction row together, reclaiming the staged objects on failure and - /// any staged object whose content deduplicated onto an existing blob. + /// Redaction phase 3: commits the output document, the review audit and + /// certificate blobs, and the redaction row together, reclaiming the staged + /// objects on failure and any staged object whose content deduplicated onto + /// an existing blob. async fn commit( &self, origin: event::EventOrigin<'_>, @@ -290,14 +309,14 @@ impl WorkspaceRedactionService { inputs: &RedactInputs, staged: Staged, ) -> Result { - // A failure to connect leaves both staged objects with no blob row for the + // A failure to connect leaves the staged objects with no blob row for the // reaper to find, so discard them before returning, as every later // failure path does. let mut conn = match self.postgres.get_connection().await { Ok(conn) => conn, Err(err) => { self.writer - .discard_staged(&[&staged.output, &staged.review]) + .discard_staged(&[&staged.output, &staged.review, &staged.certificate]) .await; return Err(err.into()); } @@ -326,6 +345,9 @@ impl WorkspaceRedactionService { // insert) its blob to record the reference, then point the redaction at // it via `review_audit_blob_id`. let review_resolved = conn.find_or_create_blob(staged.review.blob.clone()).await?; + let certificate_resolved = conn + .find_or_create_blob(staged.certificate.blob.clone()) + .await?; let redaction = conn .create_redaction(NewWorkspaceRedaction { detection_id: inputs.detection.id, @@ -333,6 +355,8 @@ impl WorkspaceRedactionService { output_document_id: Some(output_document.id), review_audit_blob_id: Some(review_resolved.id), review_audit_expires_at: Some(staged.review.expires_at.into()), + certificate_blob_id: Some(certificate_resolved.id), + certificate_expires_at: Some(staged.certificate.expires_at.into()), }) .await?; conn.emit_event( @@ -359,18 +383,20 @@ impl WorkspaceRedactionService { .map(|blob| blob.storage_path), None => None, }; - let review_path = Some(review_resolved.storage_path); - Ok::<_, Error>((redaction, output_path, review_path)) + let review_path = review_resolved.storage_path; + let certificate_path = certificate_resolved.storage_path; + Ok::<_, Error>((redaction, output_path, review_path, certificate_path)) }) .await; - let (redaction, output_path, review_path) = match redaction { + let (redaction, output_path, review_path, certificate_path) = match redaction { Ok(committed) => committed, Err(err) => { // The rows rolled back, so their staged objects are orphans: reclaim - // both (best effort — a failure only leaves them for a later sweep). + // them all (best effort — a failure only leaves them for a later + // sweep). self.writer - .discard_staged(&[&staged.output, &staged.review]) + .discard_staged(&[&staged.output, &staged.review, &staged.certificate]) .await; return Err(err); } @@ -379,12 +405,16 @@ impl WorkspaceRedactionService { // A committed blob whose content deduplicated onto an existing object leaves // the object staged for it orphaned (no row references it). Reclaim each // redundant staged object; best effort, a failure only defers it to a sweep. - if output_path.as_deref() != Some(staged.output.blob.storage_path.as_str()) { - self.writer.discard_staged(&[&staged.output]).await; - } - if review_path.as_deref() != Some(staged.review.blob.storage_path.as_str()) { - self.writer.discard_staged(&[&staged.review]).await; - } + let redundant: Vec<&StagedBlob> = [ + (output_path.as_deref(), &staged.output), + (Some(review_path.as_str()), &staged.review), + (Some(certificate_path.as_str()), &staged.certificate), + ] + .into_iter() + .filter(|(committed, staged)| *committed != Some(staged.blob.storage_path.as_str())) + .map(|(_, staged)| staged) + .collect(); + self.writer.discard_staged(&redundant).await; tracing::info!( target: TRACING_TARGET, @@ -463,6 +493,346 @@ impl WorkspaceRedactionService { }; Ok(ReviewAudit { report, accounts }) } + + /// Loads a redaction's certificate, with its status, its activity, and the + /// accounts the activity names. The connection is released before the + /// object-store load. + /// + /// # Errors + /// + /// - `NotFound` if the redaction does not exist in the workspace, or its + /// certificate has been reclaimed. + /// - A storage or crypto error if loading the certificate fails. + /// - A database error if a connection or a query fails. + pub async fn certificate( + &self, + workspace_id: Uuid, + redaction_id: Uuid, + ) -> Result { + let (redaction, certificate) = self.load_certificate(workspace_id, redaction_id).await?; + let mut conn = self.postgres.get_connection().await?; + let (approval, approvals) = review_of(&mut conn, workspace_id, &redaction).await?; + let history = history(&mut conn, workspace_id, &redaction, &approvals).await?; + let activity = certificate.activity(&history); + let accounts = conn + .find_account_refs(&named_accounts( + activity.iter().map(|entry| entry.by.as_str()), + )) + .await?; + Ok(RedactionCertificate { + reference: CertificateReference::new(redaction.certificate_number), + issuer: self.engine.certificate_issuer().to_owned(), + status: certificate.status(approval), + approval, + certificate, + activity, + accounts, + }) + } + + /// Renders a redaction's certificate as a PDF, with its status and its + /// activity, naming each account by name and email. + /// + /// # Errors + /// + /// - `NotFound` if the redaction does not exist in the workspace, or its + /// certificate has been reclaimed. + /// - A storage or crypto error if loading the certificate fails. + /// - An engine error if the page cannot be typeset. + /// - A database error if a connection or a query fails. + pub async fn certificate_pdf( + &self, + workspace_id: Uuid, + redaction_id: Uuid, + ) -> Result { + let (redaction, certificate) = self.load_certificate(workspace_id, redaction_id).await?; + let (approval, history, names) = { + let mut conn = self.postgres.get_connection().await?; + let (approval, approvals) = review_of(&mut conn, workspace_id, &redaction).await?; + let history = history(&mut conn, workspace_id, &redaction, &approvals).await?; + let activity = certificate.activity(&history); + let names = conn + .find_accounts(&named_accounts( + activity.iter().map(|entry| entry.by.as_str()), + )) + .await? + .iter() + .map(|account| (account.id, contact(account))) + .collect(); + (approval, history, names) + }; + let file_name = format!("{}.certificate.pdf", certificate.document.name); + let bytes = self + .engine + .render_certificate( + certificate, + CertificateReference::new(redaction.certificate_number), + approval, + history, + names, + ) + .await?; + Ok(CertificatePdf { bytes, file_name }) + } + + /// Verifies the certificate `reference` for a reader who holds only that: + /// what it proves, without naming any account, reason, policy, or + /// document. Resolves across every workspace, so it needs no caller. + /// + /// # Errors + /// + /// - `NotFound` if no live redaction has that reference, or its + /// certificate has been reclaimed. + /// - A storage or crypto error if loading the certificate fails. + /// - A database error if a connection or a query fails. + pub async fn verify_certificate( + &self, + reference: CertificateReference, + ) -> Result { + let not_found = || ErrorKind::NotFound.with_message("No certificate has this reference"); + // A reclaimed certificate, whether its pointer was cleared or its bytes + // purged mid-read, is the same answer as none: a reader learns nothing + // about a redaction it cannot verify. + let reclaimed = |err: Error| match err.kind() { + ErrorKind::NotFound => not_found(), + _ => err, + }; + let (workspace_id, blob, approval) = { + let mut conn = self.postgres.get_connection().await?; + let (redaction, workspace_id) = conn + .find_redaction_by_certificate_number(reference.number()) + .await? + .ok_or_else(not_found)?; + let blob = self + .reader + .resolve_certificate_blob(&mut conn, &redaction) + .await + .map_err(reclaimed)?; + let (approval, _) = review_of(&mut conn, workspace_id, &redaction).await?; + (workspace_id, blob, approval) + }; + let certificate = self + .reader + .load_certificate(workspace_id, &blob) + .await + .map_err(reclaimed)?; + + Ok(CertificateProof { + reference, + issuer: self.engine.certificate_issuer().to_owned(), + issued_at: convert_timestamp(certificate.issued_at)?, + status: certificate.status(approval), + approval, + output_sha256: certificate.document.output.to_string(), + withheld: label_counts(certificate.withheld_by_label()), + disclosed: label_counts(certificate.disclosed_by_label()), + }) + } + + /// Checks that the redacted document `document_id` may be downloaded: where + /// the workspace gates downloads, only once a review has approved the + /// redaction that wrote it, and not once another redaction replaced it. + /// + /// # Errors + /// + /// - `Forbidden` if the workspace gates downloads and no review has + /// approved the redaction, another redaction replaced it, or the + /// redaction was deleted. + /// - A database error if a connection or a query fails. + pub async fn check_download(&self, workspace_id: Uuid, document_id: Uuid) -> Result<()> { + let mut conn = self.postgres.get_connection().await?; + let settings = review_settings(&mut conn, workspace_id).await?; + match release_hold(&mut conn, workspace_id, settings, document_id).await? { + None => Ok(()), + Some(hold) => Err(ErrorKind::Forbidden.with_message(hold)), + } + } + + /// Loads a redaction scoped to the workspace and its certificate, releasing + /// the connection before the object-store load. + async fn load_certificate( + &self, + workspace_id: Uuid, + redaction_id: Uuid, + ) -> Result<(WorkspaceRedaction, DocumentCertificate)> { + let (redaction, blob) = { + let mut conn = self.postgres.get_connection().await?; + let redaction = find_redaction(&mut conn, workspace_id, redaction_id).await?; + let blob = self + .reader + .resolve_certificate_blob(&mut conn, &redaction) + .await?; + (redaction, blob) + }; + let certificate = self.reader.load_certificate(workspace_id, &blob).await?; + Ok((redaction, certificate)) + } +} + +/// Where `redaction` stands in its document's reviews under the workspace's +/// review settings, with the approvals that put it there. +async fn review_of( + conn: &mut PgConn, + workspace_id: Uuid, + redaction: &WorkspaceRedaction, +) -> Result<(CertificateApproval, Vec)> { + let settings = review_settings(conn, workspace_id).await?; + let state = conn.redaction_review_state(redaction).await?; + Ok((approval(&state, settings), state.approvals)) +} + +/// What the server saw happen to `redaction`'s file that the certificate does +/// not record, oldest first: the document's upload, the detection's run, and +/// each of `approvals`. A document or detection since deleted leaves its event +/// out. +async fn history( + conn: &mut PgConn, + workspace_id: Uuid, + redaction: &WorkspaceRedaction, + approvals: &[WorkspaceReviewApproval], +) -> Result>> { + let event = |at: jiff::Timestamp, by: Uuid, action| -> Result<_> { + Ok(HistoryEvent::new( + convert_timestamp(at)?, + by.to_string(), + action, + )) + }; + let mut history = Vec::new(); + if let Some(detection) = conn + .find_workspace_detection_by_id(workspace_id, redaction.detection_id) + .await? + { + if let Some(document) = conn + .find_document_in_workspace(workspace_id, detection.input_document_id) + .await? + { + history.push(event( + document.created_at.into(), + document.account_id, + CertificateAction::Uploaded, + )?); + } + history.push(event( + detection.started_at.into(), + detection.account_id, + CertificateAction::Detected, + )?); + } + for approved in approvals { + history.push(event( + approved.approved_at.into(), + approved.account_id, + CertificateAction::Approved, + )?); + } + Ok(history) +} + +/// Why the redacted document `document_id` may not be downloaded yet, or +/// `None` when it may: under `settings` that gate downloads, only once a +/// review has approved the redaction that wrote it, and not once another +/// redaction replaced it. +async fn release_hold( + conn: &mut PgConn, + workspace_id: Uuid, + settings: ReviewSettings, + document_id: Uuid, +) -> Result> { + if !settings.gate_downloads { + return Ok(None); + } + let Some(redaction) = conn + .find_redaction_by_output(workspace_id, document_id) + .await? + else { + return Ok(Some( + "This redacted file's redaction was deleted, so no review can release it", + )); + }; + let state = conn.redaction_review_state(&redaction).await?; + Ok(match approval(&state, settings) { + CertificateApproval::Approved => None, + CertificateApproval::Superseded => { + Some("A review approved another redaction of this document in this file's place") + } + CertificateApproval::Pending | CertificateApproval::Untracked => { + Some("This workspace releases a redacted file only once a review approves it") + } + }) +} + +/// A workspace's review settings. +pub(crate) async fn review_settings( + conn: &mut PgConn, + workspace_id: Uuid, +) -> Result { + Ok(conn + .find_workspace_by_id(workspace_id) + .await? + .ok_or_else(|| Error::not_found(Resource::Workspace))? + .settings + .or_default() + .review) +} + +/// Where a redaction stands in the review its workspace's `settings` ask +/// for, from what its document's reviews say about it: replaced by a later +/// approval of another redaction, approved, awaiting a decision (or one the +/// workspace requires), or untracked. +fn approval(state: &RedactionReviewState, settings: ReviewSettings) -> CertificateApproval { + if state.superseded { + CertificateApproval::Superseded + } else if state.approved { + CertificateApproval::Approved + } else if state.open || settings.required { + CertificateApproval::Pending + } else { + CertificateApproval::Untracked + } +} + +/// The accounts named in `by`, each once, in the order first named. A name +/// that is not an account id is skipped. +fn named_accounts<'a>(by: impl Iterator) -> Vec { + let mut accounts = Vec::new(); + for account in by.filter_map(|name| name.parse::().ok()) { + if !accounts.contains(&account) { + accounts.push(account); + } + } + accounts +} + +/// A certificate's counts by label, keyed by each label's id. +fn label_counts(counts: BTreeMap<&LabelRef, usize>) -> BTreeMap { + counts + .into_iter() + .map(|(label, count)| (label.to_string(), count)) + .collect() +} + +/// Carries a timestamp across jiff's major versions: the engine's are jiff 1's, +/// the server's jiff 0.2's. RFC 3339 carries one into the other losslessly. +fn convert_timestamp(at: impl Display) -> Result +where + T::Err: Display, +{ + at.to_string().parse().map_err(|err: T::Err| { + ErrorKind::InternalServerError + .with_message("Failed to convert a timestamp") + .with_context(err.to_string()) + }) +} + +/// An account as a certificate's reader sees it: its display name and email +/// (`Jane Doe `), or its email alone when it has no display +/// name. +fn contact(account: &Account) -> String { + match &account.display_name { + Some(display_name) => format!("{display_name} <{}>", account.email_address), + None => account.email_address.clone(), + } } /// Loads a redaction scoped to the workspace, or a `NotFound`. A redaction id is @@ -476,3 +846,54 @@ async fn find_redaction( .await? .ok_or_else(|| Error::not_found(Resource::Redaction)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn state(approved: bool, superseded: bool, open: bool) -> RedactionReviewState { + RedactionReviewState { + approved, + superseded, + open, + approvals: Vec::new(), + } + } + + #[test] + fn a_later_approval_outranks_this_one_and_this_one_an_open_review() { + let optional = ReviewSettings::default(); + assert_eq!( + approval(&state(true, true, true), optional), + CertificateApproval::Superseded + ); + assert_eq!( + approval(&state(true, false, true), optional), + CertificateApproval::Approved + ); + assert_eq!( + approval(&state(false, false, true), optional), + CertificateApproval::Pending + ); + assert_eq!( + approval(&state(false, false, false), optional), + CertificateApproval::Untracked + ); + } + + #[test] + fn a_required_review_holds_a_redaction_none_has_approved() { + let required = ReviewSettings { + required: true, + ..ReviewSettings::default() + }; + assert_eq!( + approval(&state(false, false, false), required), + CertificateApproval::Pending + ); + assert_eq!( + approval(&state(true, false, false), required), + CertificateApproval::Approved + ); + } +} diff --git a/crates/nvisy-server/src/extract/idempotency_key.rs b/crates/nvisy-server/src/extract/idempotency_key.rs index 8b64a14c..082a3335 100644 --- a/crates/nvisy-server/src/extract/idempotency_key.rs +++ b/crates/nvisy-server/src/extract/idempotency_key.rs @@ -4,6 +4,8 @@ //! client can safely retry a mutating request: a repeat with the same key //! returns the original outcome instead of performing the action again. +use std::future::{Future, ready}; + use aide::OperationInput; use aide::generate::GenContext; use aide::openapi::{ @@ -12,12 +14,12 @@ use aide::openapi::{ }; use aide::operation::add_parameters; use axum::extract::FromRequestParts; -use axum::http::HeaderName; use axum::http::request::Parts; +use axum::http::{HeaderMap, HeaderName}; use indexmap::IndexMap; use schemars::json_schema; -use crate::response::{Error, ErrorKind, error_responses}; +use crate::response::{Error, ErrorKind, Result, error_responses}; /// The idempotency header name, lowercased to match `HeaderMap` lookup. const IDEMPOTENCY_HEADER: HeaderName = HeaderName::from_static("idempotency-key"); @@ -40,12 +42,19 @@ where { type Rejection = Error; - // reason: `FromRequestParts::from_request_parts` is an `async fn` in the trait; this - // extractor reads a header with no await, but the sibling extractors all keep the - // `async fn` form, so match them rather than diverge to a bare `impl Future`. - #[allow(clippy::unused_async_trait_impl)] - async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { - let Some(value) = parts.headers.get(&IDEMPOTENCY_HEADER) else { + /// Reads the header with no await, so the future is already resolved. + fn from_request_parts( + parts: &mut Parts, + _state: &S, + ) -> impl Future> + Send { + ready(Self::from_headers(&parts.headers)) + } +} + +impl IdempotencyKey { + /// Reads the key from `headers`: absent, or a valid key. + fn from_headers(headers: &HeaderMap) -> Result { + let Some(value) = headers.get(&IDEMPOTENCY_HEADER) else { return Ok(Self(None)); }; let key = value.to_str().map_err(|_| { diff --git a/crates/nvisy-server/src/handler/account_notifications.rs b/crates/nvisy-server/src/handler/account_notifications.rs index 4e1a32fd..471ec429 100644 --- a/crates/nvisy-server/src/handler/account_notifications.rs +++ b/crates/nvisy-server/src/handler/account_notifications.rs @@ -16,7 +16,9 @@ use uuid::Uuid; use crate::domain::AccountNotificationService; use crate::extract::{AuthState, Json, Path, Query}; -use crate::handler::request::{AccountNotificationPathParams, CursorPagination}; +use crate::handler::request::{ + AccountNotificationPathParams, AccountNotificationsQuery, CursorPagination, +}; use crate::handler::response::{ AccountMarkedReadStatus, AccountNotification, AccountNotificationsPage, AccountUnreadStatus, }; @@ -26,7 +28,8 @@ use crate::service::{ServiceState, UnreadCountEvent}; /// Tracing target for notification operations. const TRACING_TARGET: &str = "nvisy_server::handler::account_notifications"; -/// Lists notifications for the authenticated account. +/// Lists notifications for the authenticated account, each naming its +/// workspace, optionally only those about one workspace. /// /// A pure read: it does not change read status. The client marks notifications /// read explicitly via `POST /notifications/read/` (all) or @@ -35,16 +38,22 @@ const TRACING_TARGET: &str = "nvisy_server::handler::account_notifications"; async fn list_notifications( State(notifications): State, auth_state: AuthState, + Query(query): Query, Query(pagination): Query, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Listing notifications"); let page = notifications - .list(auth_state.account_id, pagination.into_cursor()) + .list( + auth_state.account_id, + query.workspace, + pagination.into_cursor(), + ) .await?; - let response = - AccountNotificationsPage::from_cursor_page(page, |n| AccountNotification::from_model(&n)); + let response = AccountNotificationsPage::from_cursor_page(page, |listed| { + AccountNotification::from_model(&listed) + }); tracing::debug!( target: TRACING_TARGET, @@ -59,21 +68,26 @@ fn list_notifications_docs(op: TransformOperation) -> TransformOperation { op.summary("List notifications") .description( "Returns the authenticated account's notifications, most recent \ - first. Read-only — use POST /notifications/read/ or \ + first, each naming the workspace it is about; `workspace` keeps \ + only one workspace's. Read-only — use POST /notifications/read/ or \ POST /notifications/{notificationId}/read/ to mark them read.", ) .response::<200, Json>() } -/// Returns the count of unread notifications for the authenticated account. +/// Returns the count of unread notifications for the authenticated account, +/// optionally only those about one workspace. #[tracing::instrument(skip_all)] async fn get_unread_status( State(notifications): State, auth_state: AuthState, + Query(query): Query, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Checking unread notifications count"); - let unread_count = notifications.unread_count(auth_state.account_id).await?; + let unread_count = notifications + .unread_count(auth_state.account_id, query.workspace) + .await?; tracing::debug!( target: TRACING_TARGET, @@ -86,7 +100,10 @@ async fn get_unread_status( fn get_unread_status_docs(op: TransformOperation) -> TransformOperation { op.summary("Get unread notifications count") - .description("Returns the number of unread notifications for the authenticated account.") + .description( + "Returns the number of unread notifications for the authenticated \ + account; `workspace` counts only one workspace's.", + ) .response::<200, Json>() } @@ -124,7 +141,7 @@ async fn stream_unread_status( // live would otherwise be missed until the next change. let mut updates = notifications.subscribe_unread(account_id).await?; - let current = notifications.unread_count(account_id).await?; + let current = notifications.unread_count(account_id, None).await?; let stream = stream! { // Emit the current count first so a client that connects between changes @@ -156,7 +173,7 @@ async fn reread_unread_count( notifications: &AccountNotificationService, account_id: Uuid, ) -> Option { - match notifications.unread_count(account_id).await { + match notifications.unread_count(account_id, None).await { Ok(count) => Some(count), Err(err) => { tracing::debug!(target: TRACING_TARGET, error = %err, %account_id, "Failed to re-read unread count"); @@ -183,15 +200,19 @@ fn stream_unread_status_docs(op: TransformOperation) -> TransformOperation { ) } -/// Marks all of the authenticated account's unread notifications as read. +/// Marks all of the authenticated account's unread notifications as read, +/// optionally only those about one workspace. #[tracing::instrument(skip_all)] async fn mark_all_notifications_read( State(notifications): State, auth_state: AuthState, + Query(query): Query, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Marking all notifications as read"); - let marked_read = notifications.mark_all_read(auth_state.account_id).await?; + let marked_read = notifications + .mark_all_read(auth_state.account_id, query.workspace) + .await?; Ok(Json(AccountMarkedReadStatus { marked_read })) } @@ -200,7 +221,8 @@ fn mark_all_notifications_read_docs(op: TransformOperation) -> TransformOperatio op.summary("Mark all notifications as read") .description( "Marks every unread notification for the authenticated account as \ - read and returns how many it marked.", + read (only one workspace's with `workspace`) and returns how many \ + it marked.", ) .response::<200, Json>() .response::<401, Json>() diff --git a/crates/nvisy-server/src/handler/capabilities.rs b/crates/nvisy-server/src/handler/capabilities.rs index fdaf1123..d1c8f5e7 100644 --- a/crates/nvisy-server/src/handler/capabilities.rs +++ b/crates/nvisy-server/src/handler/capabilities.rs @@ -21,8 +21,8 @@ use nvisy_postgres::types::IdentityProvider; use crate::extract::{AuthState, Json}; use crate::handler::response::{ - AuthCapabilities, ConnectorCapabilities, FileProviders, FormatCapabilities, - InferenceCapabilities, RecognizerCatalog, SupportedFormat, + AuthCapabilities, ConnectorCapabilities, FormatCapabilities, InferenceCapabilities, + RecognizerCatalog, SupportedFormat, }; use crate::service::{EngineService, OidcService, ServiceState, SignupConfig, format_modality}; @@ -69,7 +69,7 @@ async fn list_connectors( _: AuthState, ) -> Json { Json(ConnectorCapabilities { - file_services: FileProviders::from_service(&file_service), + file_services: file_service.configured_providers(), object_stores: true, inference: InferenceCapabilities::from_policy(endpoint_policy), }) @@ -78,10 +78,10 @@ async fn list_connectors( fn list_connectors_docs(op: TransformOperation) -> TransformOperation { op.summary("List connectors") .description( - "Returns which connector families and providers this deployment can create: each \ - OAuth file-service provider is available only when its app is configured on the \ - server, while object-store and inference connections carry their own credentials \ - and are always available. The inference section also reports whether a local Ollama \ + "Returns which connector families and providers this deployment can create: \ + `fileServices` lists the OAuth file-service providers whose app is configured on \ + the server, each a `provider` the connect request takes, while object-store and \ + inference connections carry their own credentials and are always available. The inference section also reports whether a local Ollama \ backend can be used (self-hosted deployments only). Use it to render the connect UI \ without probing.", ) @@ -202,6 +202,7 @@ mod tests { use nvisy_core::Secret; use nvisy_file_service::OAuthApps; use nvisy_file_service::oauth::OAuthApp; + use nvisy_file_service::provider::FileServiceProvider; use super::*; use crate::service::DocumentModality; @@ -239,19 +240,17 @@ mod tests { }; let file_service = FileService::new(&apps).unwrap(); - let providers = FileProviders::from_service(&file_service); - - assert!(providers.google_drive); - assert!(!providers.dropbox); - assert!(!providers.one_drive); - assert!(!providers.box_provider); + assert_eq!( + file_service.configured_providers(), + [FileServiceProvider::GoogleDrive] + ); } #[tokio::test] async fn formats_report_what_the_engine_decodes() { use crate::service::{EngineConfig, EngineService}; - let engine = EngineService::from_config(EngineConfig { config_path: None }) + let engine = EngineService::from_config(EngineConfig::default()) .await .expect("default engine builds"); let capabilities = super::format_capabilities(&engine); diff --git a/crates/nvisy-server/src/handler/mod.rs b/crates/nvisy-server/src/handler/mod.rs index c0a808e4..40acafa0 100644 --- a/crates/nvisy-server/src/handler/mod.rs +++ b/crates/nvisy-server/src/handler/mod.rs @@ -122,6 +122,9 @@ fn public_routes() -> ApiRouter { // Authorization header, so it is public; its single-use CSRF state guards // it. .merge(connection_oauth::public_routes()) + // A certificate is verified by whoever it was handed to, who has no + // account: the reference printed on it is all they hold. + .merge(workspace_redactions::public_routes()) } /// Returns an [`ApiRouter`] with all routes, over any application state `S` from diff --git a/crates/nvisy-server/src/handler/request/account_notifications.rs b/crates/nvisy-server/src/handler/request/account_notifications.rs new file mode 100644 index 00000000..0cc93495 --- /dev/null +++ b/crates/nvisy-server/src/handler/request/account_notifications.rs @@ -0,0 +1,14 @@ +//! Notification request types: scope the inbox to one workspace. + +use schemars::JsonSchema; +use serde::Deserialize; +use uuid::Uuid; + +/// Query parameters scoping an account's notifications to one workspace. +#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct AccountNotificationsQuery { + /// Keep only the notifications about this workspace (workspace id). Omit + /// for every workspace. + pub workspace: Option, +} diff --git a/crates/nvisy-server/src/handler/request/mod.rs b/crates/nvisy-server/src/handler/request/mod.rs index 71940549..f083360a 100644 --- a/crates/nvisy-server/src/handler/request/mod.rs +++ b/crates/nvisy-server/src/handler/request/mod.rs @@ -2,6 +2,7 @@ mod account_api_tokens; mod account_identities; +mod account_notifications; mod accounts; mod authentications; mod exports; @@ -24,6 +25,7 @@ mod workspaces; pub use account_api_tokens::*; pub use account_identities::*; +pub use account_notifications::*; pub use accounts::*; pub use authentications::*; pub use exports::*; diff --git a/crates/nvisy-server/src/handler/request/paths.rs b/crates/nvisy-server/src/handler/request/paths.rs index 67600a72..241ffc50 100644 --- a/crates/nvisy-server/src/handler/request/paths.rs +++ b/crates/nvisy-server/src/handler/request/paths.rs @@ -5,6 +5,8 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; +use crate::service::CertificateReference; + /// Path parameters for workspace member operations. #[must_use] #[derive(Debug, Serialize, Deserialize, JsonSchema)] @@ -95,6 +97,16 @@ pub struct WorkspaceRedactionPathParams { pub redaction_id: RedactionId, } +/// Path parameters for verifying a certificate by its public reference. +#[must_use] +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct CertificatePathParams { + /// The certificate's reference, as printed on it (`CERT-48210375`) or as + /// its bare eight digits. + pub reference: CertificateReference, +} + /// Path parameters for notification operations. /// /// The notification id is globally unique; account ownership is enforced in the diff --git a/crates/nvisy-server/src/handler/request/workspace_documents.rs b/crates/nvisy-server/src/handler/request/workspace_documents.rs index b9a096fa..acbc1921 100644 --- a/crates/nvisy-server/src/handler/request/workspace_documents.rs +++ b/crates/nvisy-server/src/handler/request/workspace_documents.rs @@ -7,7 +7,7 @@ use derive_more::{AsRef, Into}; use elide_runtime::elide::codec::FormatRegistry; use garde::Validate; use nvisy_postgres::model; -use nvisy_postgres::types::DocumentKind; +use nvisy_postgres::types::{DocumentKind, DocumentStage}; use schemars::{JsonSchema, Schema, SchemaGenerator}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -111,9 +111,14 @@ registry_token!( #[derive(Debug, Default, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct ListWorkspaceDocuments { - /// Filter by document role (`original` or `redacted`). Omit to include both. + /// Filter by document role (`original`, `redacted`), one or more. Omit to + /// list originals only: a redacted file is reached through its redaction. #[serde(skip_serializing_if = "Option::is_none")] - pub kind: Option, + pub kind: Option>, + /// Filter by workflow stage, one or more. Matches originals only: a + /// redacted document has no stage. + #[serde(skip_serializing_if = "Option::is_none")] + pub stage: Option>, /// Search the display name or original filename (case-insensitive). #[serde(skip_serializing_if = "Option::is_none")] pub search: Option, @@ -134,7 +139,8 @@ pub struct ListWorkspaceDocuments { impl From for ListDocumentsInput { fn from(query: ListWorkspaceDocuments) -> Self { ListDocumentsInput { - kind: query.kind, + kinds: Some(query.kind.unwrap_or_else(|| vec![DocumentKind::Original])), + stages: query.stage, search: query.search, formats: query .formats @@ -147,6 +153,41 @@ impl From for ListDocumentsInput { } } +/// Query parameters for counting a workspace's originals by stage: the list's +/// filters that narrow which documents are counted. +#[must_use] +#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct CountWorkspaceDocumentStages { + /// Search the display name or original filename (case-insensitive). + #[serde(skip_serializing_if = "Option::is_none")] + pub search: Option, + /// Filter by file extension. Each entry expands to its format's full + /// extension set (so `jpg` also matches `jpeg`). + #[serde(skip_serializing_if = "Option::is_none")] + pub formats: Option>, + /// Filter by modality (`text`, `tabular`, `image`, `audio`). + #[serde(skip_serializing_if = "Option::is_none")] + pub modality: Option>, +} + +impl From for ListDocumentsInput { + fn from(query: CountWorkspaceDocumentStages) -> Self { + ListDocumentsInput { + kinds: Some(vec![DocumentKind::Original]), + stages: None, + search: query.search, + formats: query + .formats + .map(|t| t.into_iter().map(Into::into).collect()), + modality: query + .modality + .map(|t| t.into_iter().map(Into::into).collect()), + hash: None, + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/nvisy-server/src/handler/response/account_notifications.rs b/crates/nvisy-server/src/handler/response/account_notifications.rs index 80df7ed4..bd05b59b 100644 --- a/crates/nvisy-server/src/handler/response/account_notifications.rs +++ b/crates/nvisy-server/src/handler/response/account_notifications.rs @@ -1,23 +1,27 @@ //! Account notification response types. use jiff::Timestamp; -use nvisy_postgres::model::AccountNotification as AccountNotificationModel; +use nvisy_postgres::query::ListedNotification; use nvisy_postgres::types::NotificationPayload; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::Page; +use super::{Page, WorkspaceRef}; /// Response type for an account notification. /// /// The typed payload is nested under `payload`, so a notification is -/// `{ id, payload: { notifyType, }, readAt, ... }`. +/// `{ id, workspaceId, workspaceHandle, payload: { notifyType, }, +/// readAt, ... }`. #[derive(Debug, Clone, Serialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct AccountNotification { /// Unique notification identifier. pub id: Uuid, + /// The workspace the notification is about. + #[serde(flatten)] + pub workspace: WorkspaceRef, /// The notification type and its typed params, absent when the stored params /// do not decode into their `notifyType`. #[serde(skip_serializing_if = "Option::is_none")] @@ -52,16 +56,18 @@ pub struct AccountMarkedReadStatus { } impl AccountNotification { - /// Builds the response from a stored notification, reconstructing the typed + /// Builds the response from a listed notification, reconstructing the typed /// payload from `notify_type` and the stored params. /// /// Total by design: a row whose stored params do not decode into their /// `notify_type` still appears, with `payload` absent rather than the row /// dropped. Dropping it would let the list silently disagree with the unread /// count. - pub fn from_model(notification: &AccountNotificationModel) -> Self { + pub fn from_model(listed: &ListedNotification) -> Self { + let notification = &listed.notification; Self { id: notification.id, + workspace: WorkspaceRef::from(&listed.workspace), payload: notification.params.optional(), read_at: notification.read_at.map(Into::into), created_at: notification.created_at.into(), diff --git a/crates/nvisy-server/src/handler/response/capabilities.rs b/crates/nvisy-server/src/handler/response/capabilities.rs index 683f7210..95be36f0 100644 --- a/crates/nvisy-server/src/handler/response/capabilities.rs +++ b/crates/nvisy-server/src/handler/response/capabilities.rs @@ -2,7 +2,6 @@ use elide_runtime::RegisteredComponent; use nvisy_core::net::EndpointPolicy; -use nvisy_file_service::FileService; use nvisy_file_service::provider::FileServiceProvider; use nvisy_postgres::types::IdentityProvider; use schemars::JsonSchema; @@ -20,41 +19,6 @@ pub struct RecognizerCatalog { pub llm: Vec, } -/// Per-provider availability for the OAuth file services. Each field is `true` -/// only when that provider's OAuth app is configured on the server. -#[derive(Debug, Serialize, JsonSchema)] -#[serde(rename_all = "camelCase")] -// reason: one serialized availability flag per provider; a struct-per-bool would -// not read better and would change the wire shape. -#[allow(clippy::struct_excessive_bools)] -pub struct FileProviders { - /// Whether Google Drive can be connected. - pub google_drive: bool, - /// Whether Dropbox can be connected. - pub dropbox: bool, - /// Whether `OneDrive` can be connected. - pub one_drive: bool, - /// Whether Box can be connected. (`box` is a Rust keyword, hence the field - /// name; the wire name is `box`.) - #[serde(rename = "box")] - pub box_provider: bool, -} - -impl FileProviders { - /// Builds the availability report from the deployment's file service. - pub(crate) fn from_service(file_service: &FileService) -> Self { - // Matched exhaustively so adding a `FileServiceProvider` variant fails to compile - // until it is represented here. - let is = |provider| file_service.is_configured(provider); - Self { - google_drive: is(FileServiceProvider::GoogleDrive), - dropbox: is(FileServiceProvider::Dropbox), - one_drive: is(FileServiceProvider::OneDrive), - box_provider: is(FileServiceProvider::Box), - } - } -} - /// What inference providers this deployment can connect to. /// /// Inference providers carry their own credentials, so creating one is always @@ -96,8 +60,10 @@ impl InferenceCapabilities { #[derive(Debug, Serialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct ConnectorCapabilities { - /// Availability of each OAuth file-service provider. - pub file_services: FileProviders, + /// The OAuth file-service providers whose app the host configured, the + /// only ones a client can connect: each is a `provider` the connect request + /// takes. + pub file_services: Vec, /// Whether object-store connections can be created. Currently always `true` — /// they carry their own credentials, so nothing gates them server-side — but /// clients should read the field rather than assume it. diff --git a/crates/nvisy-server/src/handler/response/workspace_detections.rs b/crates/nvisy-server/src/handler/response/workspace_detections.rs index 2e1b0b29..7548fb40 100644 --- a/crates/nvisy-server/src/handler/response/workspace_detections.rs +++ b/crates/nvisy-server/src/handler/response/workspace_detections.rs @@ -5,13 +5,16 @@ use jiff::Timestamp; use nvisy_postgres::model::{ WorkspaceDetection as DetectionModel, WorkspaceDetectionEdit as EditModel, }; -use nvisy_postgres::query::DetectionDocuments; -use nvisy_postgres::types::{DetectionId, DetectionMetadata, DetectionStatus, WithAccountRef}; +use nvisy_postgres::query::{DetectionDocuments, DetectionListRow, DetectionPolicy}; +use nvisy_postgres::types::{ + DetectionId, DetectionMetadata, DetectionStatus, PolicyKind, WithAccountRef, +}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; use super::{AccountRef, Page, WorkspaceRef}; +use crate::domain::output::WithPolicies; /// Response type for a detection. /// @@ -44,6 +47,9 @@ pub struct WorkspaceDetection { pub error: Option, /// Non-encrypted metadata for filtering/display. pub metadata: DetectionMetadata, + /// The policies the analysis ran under, at the versions it ran, by display + /// name. Empty until the analysis completes. + pub policies: Vec, /// The reviewer decisions applied over the base analysis at redact time, one /// per entry, each with the reviewer who last set it, oldest first. Together /// they are the detection's edits: join every entry's `edit` into one set to @@ -60,6 +66,33 @@ pub struct WorkspaceDetection { pub completed_at: Option, } +/// A policy a detection ran under, at the version it ran. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceDetectionPolicy { + /// The policy's id. + pub id: Uuid, + /// The policy's display name now. A derived policy's is a content hash, + /// not a name to show. + pub display_name: String, + /// How the policy came to exist: `derived` when minted from the label list + /// the detection was started with, `authored` otherwise. + pub kind: PolicyKind, + /// The version the analysis ran. + pub version_number: i32, +} + +impl From for WorkspaceDetectionPolicy { + fn from(policy: DetectionPolicy) -> Self { + Self { + id: policy.policy_id, + display_name: policy.display_name, + kind: policy.kind, + version_number: policy.version_number, + } + } +} + /// One reviewer decision on a detection, with the reviewer who last set it. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] @@ -96,6 +129,9 @@ pub struct WorkspaceDetectionSummary { pub error: Option, /// Free-form tags attached to the detection (empty when none). pub tags: Vec, + /// The policies the analysis ran under, at the versions it ran, by display + /// name. Empty until the analysis completes. + pub policies: Vec, /// When the detection started. pub started_at: Timestamp, /// When analysis finished. @@ -108,8 +144,12 @@ pub struct WorkspaceDetectionSummary { } impl WorkspaceDetectionSummary { - /// Builds a compact response from a list query's projection. - pub fn from_row(row: nvisy_postgres::query::DetectionListRow, workspace: WorkspaceRef) -> Self { + /// Builds a compact response from a listed detection and its policies. + pub fn from_listed(listed: WithPolicies, workspace: WorkspaceRef) -> Self { + let WithPolicies { + item: row, + policies, + } = listed; Self { id: DetectionId::from_uuid(row.detection.id), workspace, @@ -123,6 +163,7 @@ impl WorkspaceDetectionSummary { .tags .map(|tags| tags.or_default()) .unwrap_or_default(), + policies: policies.into_iter().map(Into::into).collect(), started_at: row.detection.started_at.into(), completed_at: row.detection.completed_at.map(Into::into), has_intermediate: row.detection.has_intermediate, @@ -136,14 +177,15 @@ pub type WorkspaceDetectionsPage = Page; impl WorkspaceDetection { /// Creates a detection response from the database model, the owning workspace - /// id and handle, the triggering account, and the resolved input file display - /// name. + /// id and handle, the triggering account, the resolved input file display + /// name, the reviewer decisions, and the policies the analysis ran under. pub fn from_model( detection: &DetectionModel, workspace: WorkspaceRef, triggered_by: AccountRef, files: DetectionDocuments, edits: Vec>, + policies: Vec, ) -> Self { // Surface the failure reason (written to metadata.error by the worker / // enqueue-failure path) as a dedicated field for a failed detection. @@ -173,6 +215,7 @@ impl WorkspaceDetection { status: detection.status, error, metadata, + policies: policies.into_iter().map(Into::into).collect(), edits, edit_set_rev: detection.edit_set_rev, started_at: detection.started_at.into(), diff --git a/crates/nvisy-server/src/handler/response/workspace_documents.rs b/crates/nvisy-server/src/handler/response/workspace_documents.rs index 43e98488..25485c5e 100644 --- a/crates/nvisy-server/src/handler/response/workspace_documents.rs +++ b/crates/nvisy-server/src/handler/response/workspace_documents.rs @@ -2,12 +2,66 @@ use jiff::Timestamp; use nvisy_postgres::model::{Blob, WorkspaceDocument as DocumentModel}; -use nvisy_postgres::types::DocumentKind; +use nvisy_postgres::query::ListedDocument; +use nvisy_postgres::types::{DetectionId, DocumentKind, DocumentStage, WithAccountRef}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::{AccountRef, Page, WorkspaceRef}; +use super::{AccountRef, Page, WorkspaceDetectionPolicy, WorkspaceRef}; +use crate::domain::output::WithPolicies; + +/// How many of a workspace's originals stand at each stage. +#[must_use] +#[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + Serialize, + Deserialize, + JsonSchema +)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceDocumentStageCounts { + /// Originals with no live detection. + pub uploaded: i64, + /// Originals whose latest detection has not finished. + pub detecting: i64, + /// Originals whose latest detection failed. + pub failed: i64, + /// Originals detected, with nothing further. + pub detected: i64, + /// Originals whose latest detection has a live redaction. + pub redacted: i64, + /// Originals with a review awaiting a decision. + pub in_review: i64, + /// Originals whose latest approved review approved a live redaction. + pub approved: i64, +} + +impl WorkspaceDocumentStageCounts { + /// Builds the counts from each stage's count; a stage left out counts + /// none. + pub fn from_counts(counts: impl IntoIterator) -> Self { + let mut stages = Self::default(); + for (stage, count) in counts { + let slot = match stage { + DocumentStage::Uploaded => &mut stages.uploaded, + DocumentStage::Detecting => &mut stages.detecting, + DocumentStage::Failed => &mut stages.failed, + DocumentStage::Detected => &mut stages.detected, + DocumentStage::Redacted => &mut stages.redacted, + DocumentStage::InReview => &mut stages.in_review, + DocumentStage::Approved => &mut stages.approved, + }; + *slot = count; + } + stages + } +} /// Represents a document in responses. #[must_use] @@ -113,8 +167,81 @@ pub struct WorkspaceDeletedDocuments { /// Response for document uploads (simple list without pagination). pub type WorkspaceDocuments = Vec; +/// A document in a list, with where it stands in its workflow. +#[must_use] +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceDocumentSummary { + /// The document. + #[serde(flatten)] + pub document: WorkspaceDocument, + /// Where an original stands in its workflow, the first that holds: + /// `failed` or `detecting` while its latest detection failed or has not + /// finished, `in_review` while a review of it awaits a decision, + /// `approved` once its latest approved review approved a redaction of its + /// latest detection, `redacted` once its latest detection has a redaction, + /// `detected` once that detection finished, and `uploaded` with no + /// detection. A redacted document has none, and omits it. + #[serde(skip_serializing_if = "Option::is_none")] + pub stage: Option, + /// Whether any of its detections has a redaction. + pub has_redaction: bool, + /// Its latest detection, which its stage follows; omitted with none. + #[serde(skip_serializing_if = "Option::is_none")] + pub latest_detection: Option, +} + +/// A document's latest detection, as its list entry shows it. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceDocumentDetection { + /// The detection's id. + pub id: DetectionId, + /// When its analysis finished; absent until it does. + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + /// How many findings stand with its reviewer edits applied: entities the + /// analysis found that neither it nor a reviewer dropped. Absent until the + /// analysis finishes. + #[serde(skip_serializing_if = "Option::is_none")] + pub finding_count: Option, + /// The policies its analysis ran under, at the versions it ran: none until + /// it finishes. + pub policies: Vec, +} + +impl WorkspaceDocumentSummary { + /// Builds the list entry from the document's list row, in `workspace`. + pub fn from_listed( + listed: WithPolicies>, + workspace: WorkspaceRef, + ) -> Self { + let WithPolicies { + item: row, + policies, + } = listed; + let ListedDocument { + document, + blob, + state, + latest_detection, + } = row.item; + Self { + document: WorkspaceDocument::from_model(document, &blob, workspace, row.account.into()), + stage: state.as_ref().map(|state| state.stage), + has_redaction: state.is_some_and(|state| state.has_redaction), + latest_detection: latest_detection.map(|detection| WorkspaceDocumentDetection { + id: detection.id.into(), + completed_at: detection.completed_at.map(Into::into), + finding_count: detection.finding_count, + policies: policies.into_iter().map(Into::into).collect(), + }), + } + } +} + /// Paginated response for document listing. -pub type WorkspaceDocumentsPage = Page; +pub type WorkspaceDocumentsPage = Page; #[cfg(test)] mod tests { diff --git a/crates/nvisy-server/src/handler/response/workspace_redactions.rs b/crates/nvisy-server/src/handler/response/workspace_redactions.rs index 31022dff..c616adaf 100644 --- a/crates/nvisy-server/src/handler/response/workspace_redactions.rs +++ b/crates/nvisy-server/src/handler/response/workspace_redactions.rs @@ -1,5 +1,10 @@ //! Redaction response types. +use std::collections::BTreeMap; + +use elide_runtime::certificate::{ + CertificateActivity, CertificateApproval, CertificateStatus, DocumentCertificate, +}; use elide_runtime::elide::report::AppliedReport; use jiff::Timestamp; use nvisy_postgres::model::WorkspaceRedaction as RedactionModel; @@ -9,7 +14,10 @@ use serde::{Deserialize, Serialize}; use uuid::Uuid; use super::{AccountRef, Page, WorkspaceRef}; -use crate::domain::output::ReviewAudit; +use crate::domain::output::{ + CertificateAction, CertificateProof, RedactionCertificate, ReviewAudit, +}; +use crate::service::CertificateReference; /// Response type for a redaction. /// @@ -89,3 +97,103 @@ impl WorkspaceRedactionReview { } } } + +/// Response type for a redaction's certificate. +#[derive(Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceRedactionCertificate { + /// The certificate's public reference, printed on its PDF, by which anyone + /// holding it can verify it. + pub reference: CertificateReference, + /// Who issued it, as its PDF prints it. + pub issuer: String, + /// Where it stands now, as its PDF and its verification show it. + pub status: CertificateStatus, + /// Where its redaction stands in its document's reviews, which `status` + /// follows: it tells an approved release from one nothing was left to + /// check, both `complete`. + pub approval: CertificateApproval, + /// What the redaction withheld and why: the files it read and wrote by + /// digest, the policies it ran under, and each reviewer decision behind + /// it. `redacted_by` and each decision's `by` are account ids. + /// `document.name` and each decision's `reason` are carried as written, + /// so can hold a withheld value. + pub certificate: DocumentCertificate, + /// Everything that happened to the file, oldest first, as the PDF's + /// activity prints it: its upload, the detection, each reviewer's + /// decisions, the redaction, and each approval of it by a review that + /// reached its quorum with it. A document or + /// detection since deleted leaves its entry out. + pub activity: Vec>, + /// The accounts the activity names, resolved so a client can show who did + /// each without a lookup, in the order the activity first names them. An + /// account since deleted still resolves. + pub accounts: Vec, +} + +impl WorkspaceRedactionCertificate { + /// Creates the response from the certificate and its resolved accounts. + #[must_use] + pub fn from_output(certificate: RedactionCertificate) -> Self { + Self { + reference: certificate.reference, + issuer: certificate.issuer, + status: certificate.status, + approval: certificate.approval, + certificate: certificate.certificate, + activity: certificate.activity, + accounts: certificate + .accounts + .into_iter() + .map(AccountRef::from) + .collect(), + } + } +} + +/// Response type for verifying a certificate by its reference. +/// +/// What anyone holding a certificate can check without an account: that it was +/// issued, when and by whom, where it stands now, for which redacted file, and +/// how much it withheld. It names no account, reason, policy, or document, and +/// gives no digest of the original. +#[derive(Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct CertificateVerification { + /// The certificate's reference. + pub reference: CertificateReference, + /// Who issued it. + pub issuer: String, + /// When it was issued. + pub issued_at: Timestamp, + /// Where it stands now, as its PDF shows it. + pub status: CertificateStatus, + /// Where its redaction stands in its document's reviews, which `status` + /// follows: it tells an approved release from one nothing was left to + /// check, both `complete`. It names no reviewer. + pub approval: CertificateApproval, + /// The SHA-256 of the redacted file, as 64 lowercase hex digits: what + /// `sha256sum` prints for the file handed over. + pub output_sha256: String, + /// How many findings were withheld, by label. + pub withheld: BTreeMap, + /// How many findings were left visible, by label. + pub disclosed: BTreeMap, +} + +impl CertificateVerification { + /// Creates the response from what the certificate proves. + #[must_use] + pub fn from_output(proof: CertificateProof) -> Self { + Self { + reference: proof.reference, + issuer: proof.issuer, + issued_at: proof.issued_at, + status: proof.status, + approval: proof.approval, + output_sha256: proof.output_sha256, + withheld: proof.withheld, + disclosed: proof.disclosed, + } + } +} diff --git a/crates/nvisy-server/src/handler/response/workspace_webhooks.rs b/crates/nvisy-server/src/handler/response/workspace_webhooks.rs index 5267cbd9..8070e042 100644 --- a/crates/nvisy-server/src/handler/response/workspace_webhooks.rs +++ b/crates/nvisy-server/src/handler/response/workspace_webhooks.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use jiff::Timestamp; use nvisy_postgres::model; use nvisy_postgres::types::{WebhookEvent, WebhookId, WebhookStatus}; +use nvisy_webhook::provider::WebhookResponse; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -125,18 +126,10 @@ pub struct WorkspaceWebhookResult { impl WorkspaceWebhookResult { /// Creates a `WebhookResult` from the core webhook response. - // reason: jiff reports the total as f64 milliseconds and there is no fallible - // f64->i64 conversion; the duration is small and positive, so truncation is fine. - #[allow(clippy::cast_possible_truncation)] - pub fn from_response(response: &nvisy_webhook::provider::WebhookResponse) -> Self { - let duration_ms = response - .duration() - .total(jiff::Unit::Millisecond) - .unwrap_or(0.0) as i64; - + pub fn from_response(response: &WebhookResponse) -> Self { Self { status_code: response.status_code, - response_time_ms: duration_ms, + response_time_ms: i64::try_from(response.duration().as_millis()).unwrap_or(i64::MAX), } } } diff --git a/crates/nvisy-server/src/handler/utility/redaction_key.rs b/crates/nvisy-server/src/handler/utility/redaction_key.rs index 58d875d4..18e14949 100644 --- a/crates/nvisy-server/src/handler/utility/redaction_key.rs +++ b/crates/nvisy-server/src/handler/utility/redaction_key.rs @@ -8,6 +8,7 @@ use elide_runtime::provider::KeyConfig; use nvisy_core::Secret; use schemars::{JsonSchema, Schema, SchemaGenerator}; use serde::Deserialize; +use zeroize::Zeroizing; /// The length of a [`RedactionKey`] in bytes: what AES-256 requires, and a /// sound length for HMAC. @@ -27,7 +28,7 @@ impl RedactionKey { #[must_use] pub fn into_key_config(self) -> KeyConfig { KeyConfig::Static { - key: self.0.into_inner(), + key: Zeroizing::new(self.0.into_inner()), } } } diff --git a/crates/nvisy-server/src/handler/workspace_detections.rs b/crates/nvisy-server/src/handler/workspace_detections.rs index c7eaef3b..cb19643a 100644 --- a/crates/nvisy-server/src/handler/workspace_detections.rs +++ b/crates/nvisy-server/src/handler/workspace_detections.rs @@ -7,11 +7,6 @@ //! many times. The streaming (SSE) and redaction actions stay here, loading a //! detection through the service. -// Axum handlers take their dependencies as typed extractor arguments, so a -// dependency-heavy handler exceeds the arg limit by construction; the signature -// is fixed by the framework and cannot be bundled into a struct. -#![allow(clippy::too_many_arguments)] - use aide::axum::ApiRouter; use aide::transform::TransformOperation; use async_stream::stream; @@ -53,6 +48,7 @@ fn detection_response( found.trigger.into(), found.documents, found.edits, + found.policies, ) } @@ -131,7 +127,7 @@ async fn list_workspace_detections( Ok(Json(WorkspaceDetectionsPage::from_cursor_page( page, - |row| WorkspaceDetectionSummary::from_row(row, WorkspaceRef::from(workspace)), + |listed| WorkspaceDetectionSummary::from_listed(listed, WorkspaceRef::from(workspace)), ))) } @@ -335,8 +331,6 @@ fn status_event(event: &DetectionStatusEvent) -> Event { detection_id = %path_params.detection_id, ) )] -// reason: long but cohesive; splitting adds no clarity. -#[allow(clippy::too_many_lines)] async fn redact_detection( State(redactions): State, authz: Authorized, diff --git a/crates/nvisy-server/src/handler/workspace_documents.rs b/crates/nvisy-server/src/handler/workspace_documents.rs index fe51af97..51ea1df6 100644 --- a/crates/nvisy-server/src/handler/workspace_documents.rs +++ b/crates/nvisy-server/src/handler/workspace_documents.rs @@ -6,11 +6,6 @@ //! here, loading a document through the service. All operations are secured with //! workspace-level authorization. -// Axum handlers take their dependencies as typed extractor arguments, so a -// dependency-heavy handler exceeds the arg limit by construction; the signature -// is fixed by the framework and cannot be bundled into a struct. -#![allow(clippy::too_many_arguments)] - use std::io; use std::str::FromStr; @@ -27,12 +22,13 @@ use tokio_util::io::ReaderStream; use crate::domain; use crate::extract::{Authorized, Json, Multipart, Path, Permission, Query, ValidateJson, markers}; use crate::handler::request::{ - CursorPagination, DeleteWorkspaceDocuments as DeleteDocumentsRequest, ListWorkspaceDocuments, + CountWorkspaceDocumentStages, CursorPagination, + DeleteWorkspaceDocuments as DeleteDocumentsRequest, ListWorkspaceDocuments, UpdateWorkspaceDocument, WorkspaceDocumentPathParams, }; use crate::handler::response::{ - self, WorkspaceDocument, WorkspaceDocumentDetails, WorkspaceDocuments, WorkspaceDocumentsPage, - WorkspaceRef, + self, WorkspaceDocumentDetails, WorkspaceDocumentStageCounts, WorkspaceDocumentSummary, + WorkspaceDocuments, WorkspaceDocumentsPage, WorkspaceRef, }; use crate::handler::utility::DownloadDocs; use crate::middleware::UploadConfig; @@ -61,13 +57,8 @@ async fn list_documents( ) .await?; - let response = WorkspaceDocumentsPage::from_cursor_page(page, |wc| { - WorkspaceDocument::from_model( - wc.item.document, - &wc.item.blob, - WorkspaceRef::from(workspace), - wc.account.into(), - ) + let response = WorkspaceDocumentsPage::from_cursor_page(page, |listed| { + WorkspaceDocumentSummary::from_listed(listed, WorkspaceRef::from(workspace)) }); tracing::debug!( @@ -83,11 +74,35 @@ async fn list_documents( fn list_documents_docs(op: TransformOperation) -> TransformOperation { op.summary("List documents") .description( - "Lists documents in a workspace with cursor-based pagination. Use the `after` parameter with the `nextCursor` value from the response to fetch subsequent pages. Use `kind=original` or `kind=redacted` to filter by role, and `search` to find a display name or original filename. Pass `hash` (a hex SHA-256) to find documents with identical content — a non-empty result means the document already exists, so an upload can be skipped.", + "Lists documents in a workspace with cursor-based pagination. Use the `after` parameter with the `nextCursor` value from the response to fetch subsequent pages. Originals only unless `kind` says otherwise (`kind=redacted`, or both by repeating it); `search` finds a display name or original filename. Each original carries its `stage` in the workflow, whether it has a redaction, and its latest detection with its finding count and policies; repeat `stage` to list the originals at any of several stages. Pass `hash` (a hex SHA-256) to find documents with identical content — a non-empty result means the document already exists, so an upload can be skipped.", ) .response::<200, Json>() } +/// Counts a workspace's originals by stage. +#[tracing::instrument(skip_all)] +async fn count_document_stages( + State(documents): State, + authz: Authorized, + Query(query): Query, +) -> Result> { + tracing::debug!(target: TRACING_TARGET, "Counting document stages"); + + let counts = documents + .stage_counts(authz.workspace.id, query.into()) + .await?; + + Ok(Json(WorkspaceDocumentStageCounts::from_counts(counts))) +} + +fn count_document_stages_docs(op: TransformOperation) -> TransformOperation { + op.summary("Count documents by stage") + .description( + "Counts the workspace's originals at each stage of the workflow, every stage present (zero when none is there). `search`, `formats`, and `modality` narrow what is counted as they narrow the documents list, so each stage's count is the total that listing it with the same filters pages through.", + ) + .response::<200, Json>() +} + /// Streams every document field of the multipart body to storage. Non-document /// fields are skipped. On any error the objects staged so far are reclaimed, so a /// failed batch never leaves an object with no row to reclaim it. @@ -251,6 +266,7 @@ fn update_document_docs(op: TransformOperation) -> TransformOperation { )] async fn download_document( State(documents): State, + State(redactions): State, State(blobs): State, State(crypto): State, // Gate on document access before resolving the document, so a caller who @@ -279,6 +295,9 @@ async fn download_document( }; authz.require(permission)?; + if document.kind == DocumentKind::Redacted { + redactions.check_download(workspace.id, document.id).await?; + } let document_key = DocumentKey::from_str(&blob.storage_path).map_err(|err| { tracing::error!( @@ -347,7 +366,11 @@ fn download_document_docs(op: TransformOperation) -> TransformOperation { .description( "Downloads a document by ID. Returns the document content as a binary stream. The required \ permission depends on the document's kind: an original document needs \ - DownloadOriginalDocuments, and a redacted output needs DownloadRedactedDocuments.", + DownloadOriginalDocuments, and a redacted output needs DownloadRedactedDocuments. \ + Where the workspace gates downloads (`review.gateDownloads`), a redacted output \ + downloads only once a review has approved the redaction that wrote it, and not once \ + a review approved another redaction of the same document in its place: until then \ + it is a 403.", ) .download_response("The document content.", &["application/octet-stream"]) .response::<403, Json>() @@ -437,6 +460,10 @@ pub fn routes(max_file_body_bytes: usize) -> ApiRouter { .layer(DefaultBodyLimit::max(max_file_body_bytes)) .get_with(list_documents, list_documents_docs), ) + .api_route( + "/workspaces/{workspaceId}/documents/stages", + get_with(count_document_stages, count_document_stages_docs), + ) .api_route( "/workspaces/{workspaceId}/documents/delete", post_with(bulk_delete_documents, bulk_delete_documents_docs), diff --git a/crates/nvisy-server/src/handler/workspace_redactions.rs b/crates/nvisy-server/src/handler/workspace_redactions.rs index dd861362..8b40b19f 100644 --- a/crates/nvisy-server/src/handler/workspace_redactions.rs +++ b/crates/nvisy-server/src/handler/workspace_redactions.rs @@ -1,5 +1,5 @@ -//! Redaction handlers: list a detection's redactions and read a redaction's -//! review audit. +//! Redaction handlers: list a detection's redactions, read a redaction's review +//! audit and its certificate, and verify a certificate by its reference. //! //! A redaction is produced by `POST /detections/{detectionId}/redactions/` (in //! [`detections`]); these endpoints read them back. @@ -9,7 +9,9 @@ use aide::axum::ApiRouter; use aide::axum::routing::get_with; use aide::transform::TransformOperation; +use axum::body::Body; use axum::extract::State; +use axum::http::{HeaderMap, HeaderValue}; use nvisy_postgres::model::{Workspace, WorkspaceRedaction}; use nvisy_postgres::types::{CursorPage, WithAccountRef}; @@ -17,13 +19,15 @@ use crate::domain; use crate::extract::{Authorized, Json, Path, Query, markers}; use crate::handler::ServiceState; use crate::handler::request::{ - CursorPagination, WorkspaceDetectionPathParams, WorkspaceRedactionPathParams, - WorkspaceRedactionsQuery, + CertificatePathParams, CursorPagination, WorkspaceDetectionPathParams, + WorkspaceRedactionPathParams, WorkspaceRedactionsQuery, }; use crate::handler::response::{ - WorkspaceRedactionResult, WorkspaceRedactionReview, WorkspaceRedactionsPage, WorkspaceRef, + CertificateVerification, WorkspaceRedactionCertificate, WorkspaceRedactionResult, + WorkspaceRedactionReview, WorkspaceRedactionsPage, WorkspaceRef, }; -use crate::response::{ErrorResponse, Result}; +use crate::handler::utility::DownloadDocs; +use crate::response::{ErrorResponse, Result, attachment_headers}; /// Tracing target for redaction operations. const TRACING_TARGET: &str = "nvisy_server::handler::workspace_redactions"; @@ -131,6 +135,131 @@ fn get_redaction_review_docs(op: TransformOperation) -> TransformOperation { .response::<409, Json>() } +/// Returns a redaction's certificate: what it withheld and why, with the +/// accounts it names. +#[tracing::instrument( + skip_all, + fields( + redaction_id = %path_params.redaction_id, + ) +)] +async fn get_redaction_certificate( + State(redactions): State, + authz: Authorized, + Path(path_params): Path, +) -> Result> { + tracing::debug!(target: TRACING_TARGET, "Getting redaction certificate"); + + let certificate = redactions + .certificate(authz.workspace.id, path_params.redaction_id.as_uuid()) + .await?; + Ok(Json(WorkspaceRedactionCertificate::from_output( + certificate, + ))) +} + +fn get_redaction_certificate_docs(op: TransformOperation) -> TransformOperation { + op.summary("Get redaction certificate") + .description( + "Returns the certificate the redaction was issued with: what it withheld and what it \ + left visible, and why; the files it read and wrote by digest; the policies it ran \ + under; and each reviewer decision behind it. Its `redaction.digest` matches the \ + redaction's review audit. `status` is where it stands now, as its PDF and its \ + verification show it: `superseded` once a review approved another redaction of the \ + document after this one was made, `complete` once a review approved this one, \ + `needs_review` while a review of the document is open or the workspace requires one, \ + and otherwise `needs_review` only if a finding was left visible because no rule \ + matched it. `approval` is the review state `status` follows (`approved`, `pending`, \ + `untracked`, or `superseded`), which tells an approved release from one nothing was \ + left to check. `activity` is everything that happened to the file, as the PDF prints \ + it: the upload and the detection, which the certificate does not record, each \ + reviewer's decisions, the redaction, and each approval of it by a review that reached \ + its quorum with it. `redacted_by`, each \ + decision's `by`, and each activity's `by` are account ids, which `accounts` \ + resolves. Text callers wrote, such as \ + `document.name` and each decision's `reason`, is carried as written and can hold a \ + withheld value: check it before handing the certificate over.", + ) + .response::<200, Json>() +} + +/// Downloads a redaction's certificate as a PDF/A-2b document, naming each +/// account by name and email. +#[tracing::instrument( + skip_all, + fields( + redaction_id = %path_params.redaction_id, + ) +)] +async fn download_redaction_certificate( + State(redactions): State, + authz: Authorized, + Path(path_params): Path, +) -> Result<(HeaderMap, Body)> { + tracing::debug!(target: TRACING_TARGET, "Downloading redaction certificate"); + + let pdf = redactions + .certificate_pdf(authz.workspace.id, path_params.redaction_id.as_uuid()) + .await?; + let headers = attachment_headers( + &pdf.file_name, + HeaderValue::from_static("application/pdf"), + u64::try_from(pdf.bytes.len()).unwrap_or(u64::MAX), + ); + Ok((headers, Body::from(pdf.bytes))) +} + +fn download_redaction_certificate_docs(op: TransformOperation) -> TransformOperation { + op.summary("Download redaction certificate") + .description( + "Downloads the redaction's certificate as a PDF/A-2b document to hand over with the \ + redacted file. It shows the certificate's status, summarizes what was withheld by \ + label, and names who uploaded the file, ran the detection, reviewed, redacted, and \ + approved it by name and email. The file name \ + and reviewers' reasons are printed as written and can hold a withheld value: check \ + them before handing it over.", + ) + .download_response("The redaction's certificate.", &["application/pdf"]) +} + +/// Verifies a certificate by the reference printed on it, for anyone holding +/// it: no account is needed. +#[tracing::instrument( + skip_all, + fields( + reference = %path_params.reference, + ) +)] +async fn verify_certificate( + State(redactions): State, + Path(path_params): Path, +) -> Result> { + tracing::debug!(target: TRACING_TARGET, "Verifying certificate"); + + let proof = redactions.verify_certificate(path_params.reference).await?; + Ok(Json(CertificateVerification::from_output(proof))) +} + +fn verify_certificate_docs(op: TransformOperation) -> TransformOperation { + op.summary("Verify certificate") + .description( + "Verifies a redaction certificate by the reference printed on it (`CERT-48210375`, \ + or its bare eight digits), with no account: when and by whom it was issued, where \ + it stands now (`status`, as its PDF shows it, and the review state it follows, \ + `approval`, which names no reviewer), the SHA-256 of the redacted file, and how \ + many findings were withheld and left visible, by label. A reader checks the file they were handed by comparing its `sha256sum` \ + against `outputSha256`. It names no account, reason, policy, or document, and gives \ + no digest of the original, which the certificate seals with a salt only the issuer \ + holds. A reference that is not eight digits, optionally after \ + `CERT-`, is a 400; one no certificate has, or one whose certificate has passed its \ + retention, is a 404. It needs no account, so a deployment \ + should rate limit it in front of the server.", + ) + .response::<200, Json>() + .response::<400, Json>() + .response::<404, Json>() +} + /// Maps a page of redactions, each with its requester, to the response. fn redactions_page( workspace: &Workspace, @@ -160,5 +289,27 @@ pub fn routes() -> ApiRouter { "/workspaces/{workspaceId}/redactions/{redactionId}/review", get_with(get_redaction_review, get_redaction_review_docs), ) + .api_route( + "/workspaces/{workspaceId}/redactions/{redactionId}/certificate", + get_with(get_redaction_certificate, get_redaction_certificate_docs), + ) + .api_route( + "/workspaces/{workspaceId}/redactions/{redactionId}/certificate/pdf", + get_with( + download_redaction_certificate, + download_redaction_certificate_docs, + ), + ) .with_path_items(|item| item.tag("Redactions")) } + +/// Builds the public certificate routes: verification needs no account, only +/// the certificate's reference. +pub fn public_routes() -> ApiRouter { + ApiRouter::new() + .api_route( + "/certificates/{reference}", + get_with(verify_certificate, verify_certificate_docs), + ) + .with_path_items(|item| item.tag("Certificates")) +} diff --git a/crates/nvisy-server/src/lib.rs b/crates/nvisy-server/src/lib.rs index 8b0f21b7..2f2b19f4 100644 --- a/crates/nvisy-server/src/lib.rs +++ b/crates/nvisy-server/src/lib.rs @@ -1,6 +1,11 @@ #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc = include_str!("../README.md")] +// Axum handlers take their dependencies as typed extractor arguments, a +// signature the framework fixes, so a dependency-heavy one exceeds the argument +// limit by construction. A long function that does one thing reads better whole +// than split to satisfy a line count. +#![allow(clippy::too_many_arguments, clippy::too_many_lines)] mod args; mod error; diff --git a/crates/nvisy-server/src/middleware/specification.rs b/crates/nvisy-server/src/middleware/specification.rs index 15146815..f2de270a 100644 --- a/crates/nvisy-server/src/middleware/specification.rs +++ b/crates/nvisy-server/src/middleware/specification.rs @@ -244,8 +244,6 @@ fn collapse_in_object(map: &mut serde_json::Map) { /// /// This function configures the `OpenAPI` documentation with API info and /// organized tags for different API sections. -// reason: long but cohesive; splitting adds no clarity. -#[allow(clippy::too_many_lines)] fn api_docs(api: TransformOpenApi) -> TransformOpenApi { api.title("Nvisy API") .summary("Document detection and redaction platform") diff --git a/crates/nvisy-server/src/service/blob/reader.rs b/crates/nvisy-server/src/service/blob/reader.rs index 7185a4dd..9af1e41a 100644 --- a/crates/nvisy-server/src/service/blob/reader.rs +++ b/crates/nvisy-server/src/service/blob/reader.rs @@ -1,13 +1,15 @@ //! Read side of the pipeline-run blob store: loading a run's staged outputs. use elide_runtime::Audit; +use elide_runtime::certificate::DocumentCertificate; use elide_runtime::elide::audit::AuditHash; use elide_runtime::elide::report::{AppliedReport, Artifacts}; use elide_runtime::elide::schema::{Schema, Stored}; use elide_runtime::file::Document; -use nvisy_postgres::PgConn; +use jiff::Timestamp; use nvisy_postgres::model::{Blob, WorkspaceDetection, WorkspaceDocument, WorkspaceRedaction}; use nvisy_postgres::query::WorkspaceBlobRepository; +use nvisy_postgres::{JiffTimestamp, PgConn}; use nvisy_s3::{AuditKey, DocumentKey, IntermediateKey, ObjectKey}; use uuid::Uuid; @@ -15,9 +17,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 analyses, review audits and enrichment intermediates, decodes -/// them, and checks them against their recorded digests. Its write counterpart is -/// [`ArtifactWriter`]. +/// and decrypts analyses, review audits, certificates and enrichment +/// intermediates, decodes them, and checks each that records a digest against +/// it. 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 @@ -63,9 +65,10 @@ impl ArtifactReader { if detection.audit_blob_id.is_none() && !detection.status.is_complete() { return Err(ErrorKind::Conflict.with_message("Detection has no analysis yet")); } - self.blob_or_gone( + blob_or_gone( conn, detection.audit_blob_id, + detection.audit_expires_at, "The analysis for this detection has been deleted", ) .await @@ -110,9 +113,10 @@ impl ArtifactReader { conn: &mut PgConn, detection: &WorkspaceDetection, ) -> Result { - self.blob_or_gone( + blob_or_gone( conn, detection.intermediate_blob_id, + detection.intermediate_expires_at, "The intermediates for this detection are not available", ) .await @@ -185,14 +189,71 @@ impl ArtifactReader { conn: &mut PgConn, redaction: &WorkspaceRedaction, ) -> Result { - self.blob_or_gone( + blob_or_gone( conn, redaction.review_audit_blob_id, + redaction.review_audit_expires_at, "The review audit for this redaction has been deleted", ) .await } + /// Resolves the blob holding a redaction's certificate. + /// + /// The connection-bound step of loading a certificate; pair with + /// [`load_certificate`] to release the connection before the object-store + /// round-trip. A redaction always issues a certificate, so a NULL pointer + /// means its blob has since been reclaimed (404). + /// + /// [`load_certificate`]: Self::load_certificate + /// + /// # Errors + /// + /// - `NotFound` if the certificate's blob has been reclaimed. + /// - A database error if the lookup fails. + pub async fn resolve_certificate_blob( + &self, + conn: &mut PgConn, + redaction: &WorkspaceRedaction, + ) -> Result { + blob_or_gone( + conn, + redaction.certificate_blob_id, + redaction.certificate_expires_at, + "The certificate for this redaction has been deleted", + ) + .await + } + + /// Loads and decodes a redaction's [`DocumentCertificate`] from its already-resolved + /// blob. Holds no database connection: only object-store I/O and decryption. + /// + /// # Errors + /// + /// - `NotFound` if the object is missing from storage (its bytes were purged + /// after the blob was looked up). + /// - `InternalServerError` if the blob's storage path is not a valid audit + /// key, if reading its bytes fails, if decrypting them fails, or if the + /// certificate cannot be decoded. + /// - A storage error if the object store rejects the read. + pub async fn load_certificate( + &self, + workspace_id: Uuid, + certificate_blob: &Blob, + ) -> Result { + let plaintext = self + .read_decrypted::(workspace_id, &certificate_blob.storage_path, "certificate") + .await? + .ok_or_else(|| { + ErrorKind::NotFound.with_message("The certificate is missing from storage") + })?; + serde_json::from_slice(&plaintext).map_err(|err| { + ErrorKind::InternalServerError + .with_message("Failed to decode certificate") + .with_context(err.to_string()) + }) + } + /// Reads a document's bytes from its blob and builds an engine [`Document`], /// stamping the run's id as the correlation id. /// @@ -285,23 +346,27 @@ impl ArtifactReader { })?; Ok(Some(plaintext)) } +} - /// Fetches a blob by its optional id, mapping a reclaimed blob to a 404 with - /// `gone_message`. A `None` id is the reclaimed case too: once the bytes pass - /// retention the referrer's pointer is nulled (the row is kept), so an absent - /// pointer and an absent blob row are the same "gone" outcome. Shared by the - /// audit/intermediate/review resolvers, which differ only in that message. - async fn blob_or_gone( - &self, - conn: &mut PgConn, - blob_id: Option, - gone_message: &'static str, - ) -> Result { - let blob_id = blob_id.ok_or_else(|| ErrorKind::NotFound.with_message(gone_message))?; - conn.find_blob_by_id(blob_id) - .await? - .ok_or_else(|| ErrorKind::NotFound.with_message(gone_message)) +/// Fetches a blob by its optional id, mapping a reclaimed or expired blob to a +/// 404 with `gone_message`. A `None` id is the reclaimed case too: once the +/// bytes pass retention the referrer's pointer is nulled (the row is kept), so +/// an absent pointer and an absent blob row are the same "gone" outcome. A +/// referrer past `expires_at` is gone already, before the reaper clears its +/// pointer. Shared by the audit, intermediate, review and certificate +/// resolvers, which differ only in their columns and message. +async fn blob_or_gone( + conn: &mut PgConn, + blob_id: Option, + expires_at: Option, + gone_message: &'static str, +) -> Result { + let gone = || ErrorKind::NotFound.with_message(gone_message); + if expires_at.is_some_and(|at| Timestamp::from(at) <= Timestamp::now()) { + return Err(gone()); } + let blob_id = blob_id.ok_or_else(gone)?; + conn.find_blob_by_id(blob_id).await?.ok_or_else(gone) } /// The engine digest recorded on an audit, review or intermediates blob when it @@ -321,3 +386,36 @@ fn recorded_digest(blob: &Blob) -> Result { })?; Ok(AuditHash::from_bytes(bytes)) } + +#[cfg(test)] +mod tests { + use nvisy_postgres::model::NewBlob; + use nvisy_postgres::test_util::TestDatabase; + + use super::*; + + #[tokio::test] + async fn a_referrer_past_its_expiry_is_gone_before_the_reaper_runs() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_account_and_workspace().await; + let mut conn = db.client.get_connection().await?; + let blob = conn + .find_or_create_blob(NewBlob::test(seeded.workspace_id)) + .await?; + let hour = jiff::SignedDuration::from_hours(1); + let later = JiffTimestamp::from(Timestamp::now() + hour); + let earlier = JiffTimestamp::from(Timestamp::now() - hour); + + let live = blob_or_gone(&mut conn, Some(blob.id), Some(later), "gone").await?; + assert_eq!(live.id, blob.id); + let kept = blob_or_gone(&mut conn, Some(blob.id), None, "gone").await?; + assert_eq!(kept.id, blob.id); + + // Its pointer and blob are still there, but it has expired. + let expired = blob_or_gone(&mut conn, Some(blob.id), Some(earlier), "gone") + .await + .expect_err("an expired referrer is gone"); + assert_eq!(expired.kind(), ErrorKind::NotFound); + Ok(()) + } +} diff --git a/crates/nvisy-server/src/service/blob/writer.rs b/crates/nvisy-server/src/service/blob/writer.rs index 5e059fc3..c7962be4 100644 --- a/crates/nvisy-server/src/service/blob/writer.rs +++ b/crates/nvisy-server/src/service/blob/writer.rs @@ -4,6 +4,7 @@ use std::io::Cursor; use bytes::Bytes; use elide_runtime::Audit; +use elide_runtime::certificate::DocumentCertificate; use elide_runtime::elide::report::{AppliedReport, Artifacts}; use nvisy_postgres::model::{NewBlob, WorkspaceDocument}; use nvisy_postgres::types::{Retention, RetentionOverride, RetentionScope, RetentionSettings}; @@ -113,18 +114,67 @@ impl ArtifactWriter { workspace_settings: &RetentionSettings, report: &AppliedReport, ) -> Result { - let plaintext = to_json(report)?; - let retention = workspace_settings.resolve(RetentionScope::AuditLogs, retention_override); - self.stage_encrypted( - AuditKey::generate(workspace_id), + let digest = Some(report.digest().as_bytes().to_vec()); + self.stage_audit_log( workspace_id, - &plaintext, - retention, - Some(report.digest().as_bytes().to_vec()), + retention_override, + workspace_settings, + report, + digest, + ) + .await + } + + /// Encrypts a redaction's [`DocumentCertificate`], writes it to the audit bucket, + /// and builds the [`StagedBlob`] that will hold it, under the audit-logs + /// retention scope it shares with the review audit it vouches for. + /// + /// The certificate holds no redacted value, but it names the document and + /// carries the reviewers' free-text reasons, so it is encrypted with the + /// workspace key like the audit. A redaction points at it through + /// `certificate_blob_id`. + /// + /// # Errors + /// + /// - `InternalServerError` if serializing or encrypting the certificate + /// fails. + /// - A storage error if the object write fails. + pub async fn stage_certificate( + &self, + workspace_id: Uuid, + retention_override: Option<&RetentionOverride>, + workspace_settings: &RetentionSettings, + certificate: &DocumentCertificate, + ) -> Result { + self.stage_audit_log( + workspace_id, + retention_override, + workspace_settings, + certificate, + None, ) .await } + /// Awaits `stage`, staging an object after `earlier`. Those have no blob row + /// yet to reclaim them by, so if `stage` fails they are discarded before its + /// error is returned. + /// + /// # Errors + /// + /// - Whatever `stage` fails with. + pub async fn stage_after( + &self, + earlier: &[&StagedBlob], + stage: impl Future>, + ) -> Result { + let staged = stage.await; + if staged.is_err() { + self.discard_staged(earlier).await; + } + staged + } + /// Encrypts a detection's enrichment intermediates (OCR layout, transcript), /// writes them to the intermediates store, and builds the [`StagedBlob`] that /// will hold them, under their own retention scope. @@ -212,6 +262,28 @@ impl ArtifactWriter { } } + /// Serializes `value` and stages it in the audit bucket under the audit-logs + /// retention scope, recording `audit_digest` when it has one. + async fn stage_audit_log( + &self, + workspace_id: Uuid, + retention_override: Option<&RetentionOverride>, + workspace_settings: &RetentionSettings, + value: &impl Serialize, + audit_digest: Option>, + ) -> Result { + let plaintext = to_json(value)?; + let retention = workspace_settings.resolve(RetentionScope::AuditLogs, retention_override); + self.stage_encrypted( + AuditKey::generate(workspace_id), + workspace_id, + &plaintext, + retention, + audit_digest, + ) + .await + } + /// Encrypts `plaintext` with the workspace key, writes it at `key`, and builds /// the [`StagedBlob`] describing it (hashed and sized over the plaintext, so /// identical content shares a blob). @@ -263,7 +335,7 @@ impl ArtifactWriter { fn to_json(value: &impl Serialize) -> Result> { serde_json::to_vec(value).map_err(|err| -> Error { ErrorKind::InternalServerError - .with_message("Failed to serialize analysis") + .with_message("Failed to serialize a run output") .with_context(err.to_string()) }) } diff --git a/crates/nvisy-server/src/service/crypto/key.rs b/crates/nvisy-server/src/service/crypto/key.rs index 195bf132..a96d3cc4 100644 --- a/crates/nvisy-server/src/service/crypto/key.rs +++ b/crates/nvisy-server/src/service/crypto/key.rs @@ -1,11 +1,14 @@ //! Encryption key management. +use std::fmt; + use hkdf::Hkdf; -use nvisy_core::Secret; +use nvisy_core::REDACTED; #[cfg(test)] use rand::Rng; use sha2::Sha256; use uuid::Uuid; +use zeroize::Zeroizing; use super::error::{CryptoError, CryptoResult}; @@ -17,11 +20,11 @@ const WORKSPACE_KEY_INFO: &[u8] = b"nvisy-workspace-encryption-key-v1"; /// A 256-bit encryption key for XChaCha20-Poly1305. /// -/// This type wraps the raw key bytes and provides safe construction methods. -/// The key is stored in memory and should be handled carefully to avoid leaks. -#[derive(Debug, Clone)] +/// Its bytes are wiped when it, or any clone of it, is dropped, and its +/// `Debug` output is [`REDACTED`]. +#[derive(Clone)] pub struct EncryptionKey { - bytes: Secret<[u8; KEY_SIZE]>, + bytes: Zeroizing<[u8; KEY_SIZE]>, } impl EncryptionKey { @@ -31,30 +34,30 @@ impl EncryptionKey { /// /// Returns [`CryptoError::InvalidKeyLength`] if the slice is not exactly 32 bytes. pub fn from_bytes(bytes: &[u8]) -> CryptoResult { - let bytes: [u8; KEY_SIZE] = bytes - .try_into() - .map_err(|_| CryptoError::InvalidKeyLength)?; - Ok(Self { - bytes: Secret::new(bytes), - }) + if bytes.len() != KEY_SIZE { + return Err(CryptoError::InvalidKeyLength); + } + // Copied straight into the wiped buffer, so no unwiped array of the + // key is left on the stack. + let mut key = Zeroizing::new([0u8; KEY_SIZE]); + key.copy_from_slice(bytes); + Ok(Self { bytes: key }) } /// Generates a new random encryption key using a cryptographically secure RNG. #[cfg(test)] #[must_use] pub fn generate() -> Self { - let mut bytes = [0u8; KEY_SIZE]; - rand::rng().fill_bytes(&mut bytes); - Self { - bytes: Secret::new(bytes), - } + let mut bytes = Zeroizing::new([0u8; KEY_SIZE]); + rand::rng().fill_bytes(bytes.as_mut()); + Self { bytes } } /// Returns the raw key bytes. #[inline] #[must_use] pub fn as_bytes(&self) -> &[u8; KEY_SIZE] { - self.bytes.expose() + &self.bytes } /// Derives a workspace-specific encryption key using HKDF-SHA256. @@ -63,15 +66,21 @@ impl EncryptionKey { /// the master key with the workspace ID. #[must_use] pub fn derive_workspace_key(&self, workspace_id: Uuid) -> Self { - let hkdf = Hkdf::::new(Some(workspace_id.as_bytes()), self.bytes.expose()); + let hkdf = Hkdf::::new(Some(workspace_id.as_bytes()), self.bytes.as_ref()); - let mut derived_key = [0u8; KEY_SIZE]; - hkdf.expand(WORKSPACE_KEY_INFO, &mut derived_key) + let mut bytes = Zeroizing::new([0u8; KEY_SIZE]); + hkdf.expand(WORKSPACE_KEY_INFO, bytes.as_mut()) .expect("HKDF expand should not fail for 32-byte output"); - Self { - bytes: Secret::new(derived_key), - } + Self { bytes } + } +} + +impl fmt::Debug for EncryptionKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EncryptionKey") + .field("bytes", &REDACTED) + .finish() } } @@ -86,21 +95,20 @@ impl TryFrom<&[u8]> for EncryptionKey { impl TryFrom> for EncryptionKey { type Error = CryptoError; + /// Reads the key from `bytes`, then wipes them. fn try_from(bytes: Vec) -> Result { - Self::from_bytes(&bytes) + Self::from_bytes(&Zeroizing::new(bytes)) } } impl AsRef<[u8]> for EncryptionKey { fn as_ref(&self) -> &[u8] { - self.bytes.expose() + self.bytes.as_ref() } } #[cfg(test)] mod tests { - use nvisy_core::REDACTED; - use super::*; #[test] diff --git a/crates/nvisy-server/src/service/crypto/service.rs b/crates/nvisy-server/src/service/crypto/service.rs index bf5f8969..3f0f914b 100644 --- a/crates/nvisy-server/src/service/crypto/service.rs +++ b/crates/nvisy-server/src/service/crypto/service.rs @@ -12,6 +12,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use tokio::io::AsyncRead; use uuid::Uuid; +use zeroize::Zeroizing; use super::{ CryptoResult, EncryptionKey, decrypt, decrypt_json, decrypt_reader, encrypt, encrypt_json, @@ -212,10 +213,11 @@ impl CryptoConfig { } tracing::debug!(target: TRACING_TARGET, path = %path.display(), "Loading master encryption key"); - let bytes = tokio::fs::read(path).await.map_err(|e| { + // The file's bytes are the master key: wiped once it is read from them. + let bytes = Zeroizing::new(tokio::fs::read(path).await.map_err(|e| { tracing::error!(target: TRACING_TARGET, path = %path.display(), error = %e, "Failed to read encryption key file"); Error::file_system("Failed to read encryption key file").with_source(e) - })?; + })?); let service = CryptoService::from_key_bytes(&bytes)?; tracing::info!(target: TRACING_TARGET, "Master encryption key loaded"); diff --git a/crates/nvisy-server/src/service/emitter/notification.rs b/crates/nvisy-server/src/service/emitter/notification.rs index 48dfd5d9..d751e6c5 100644 --- a/crates/nvisy-server/src/service/emitter/notification.rs +++ b/crates/nvisy-server/src/service/emitter/notification.rs @@ -86,7 +86,10 @@ impl NotificationEmitter { /// Takes the caller's open connection so the count read shares the same /// connection as the insert or update that triggered it. pub async fn broadcast_unread(&self, conn: &mut PgConn, account_id: Uuid) { - let unread_count = match conn.count_unread_account_notifications(account_id).await { + let unread_count = match conn + .count_unread_account_notifications(account_id, None) + .await + { Ok(count) => count, Err(err) => { tracing::debug!( @@ -153,6 +156,7 @@ impl NotificationEmitter { conn.create_account_notification(NewAccountNotification { account_id, + workspace_id, notify_type: event, params, expires_at: None, @@ -200,6 +204,7 @@ impl NotificationEmitter { .iter() .map(|&account_id| NewAccountNotification { account_id, + workspace_id, notify_type: event, params: params.clone(), expires_at: None, @@ -241,7 +246,6 @@ mod tests { }); let payload = || { NotificationPayload::MemberJoined(MemberJoinedParams { - workspace_id: seeded.workspace_id, member_id: seeded.account_id, }) }; @@ -271,7 +275,7 @@ mod tests { .unwrap() ); assert_eq!( - conn.count_unread_account_notifications(seeded.account_id) + conn.count_unread_account_notifications(seeded.account_id, None) .await .unwrap(), 1 @@ -294,7 +298,7 @@ mod tests { .unwrap() ); assert_eq!( - conn.count_unread_account_notifications(seeded.account_id) + conn.count_unread_account_notifications(seeded.account_id, None) .await .unwrap(), 2 diff --git a/crates/nvisy-server/src/service/engine/certificate.rs b/crates/nvisy-server/src/service/engine/certificate.rs new file mode 100644 index 00000000..a984bfda --- /dev/null +++ b/crates/nvisy-server/src/service/engine/certificate.rs @@ -0,0 +1,187 @@ +//! Redaction certificates: their public reference, and their PDF on the +//! deployment's letterhead. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::str::FromStr; + +use elide_runtime::certificate::Letterhead; +use schemars::{JsonSchema, Schema, SchemaGenerator}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use uuid::Uuid; + +/// What a certificate's reference starts with. +const PREFIX: &str = "CERT-"; + +/// A certificate's public reference, `CERT-48210375`: its redaction's +/// certificate number, which a reader holding only the PDF looks it up by. +/// +/// It is always written with `CERT-`, and read with or without it, so a +/// reference typed as its bare eight digits still resolves. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CertificateReference(i32); + +impl CertificateReference { + /// The reference of certificate number `number`. + #[must_use] + pub const fn new(number: i32) -> Self { + Self(number) + } + + /// The certificate number it names. + #[must_use] + pub const fn number(self) -> i32 { + self.0 + } +} + +impl fmt::Display for CertificateReference { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{PREFIX}{}", self.0) + } +} + +/// The error reading a [`CertificateReference`] from text that is not eight +/// digits, optionally after `CERT-`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InvalidCertificateReference; + +impl fmt::Display for InvalidCertificateReference { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a certificate reference is eight digits, optionally after `CERT-`") + } +} + +impl std::error::Error for InvalidCertificateReference {} + +impl FromStr for CertificateReference { + type Err = InvalidCertificateReference; + + fn from_str(text: &str) -> Result { + let digits = text.strip_prefix(PREFIX).unwrap_or(text); + if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) { + return Err(InvalidCertificateReference); + } + digits + .parse() + .map(Self) + .map_err(|_| InvalidCertificateReference) + } +} + +impl Serialize for CertificateReference { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for CertificateReference { + fn deserialize>(deserializer: D) -> Result { + let text = Cow::::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } +} + +impl JsonSchema for CertificateReference { + fn schema_name() -> Cow<'static, str> { + "CertificateReference".into() + } + + fn json_schema(_generator: &mut SchemaGenerator) -> Schema { + schemars::json_schema!({ + "type": "string", + "pattern": "^(CERT-)?[0-9]{8}$", + "description": "A certificate's public reference: `CERT-` and its eight-digit number. Read with or without `CERT-`; always written with it.", + "examples": ["CERT-48210375"], + }) + } +} + +/// The deployment's side of every certificate it renders: who issues it, and +/// where a reader checks it. +#[derive(Debug, Clone)] +pub(super) struct CertificateIssuer { + /// Who issues the certificates. + pub(super) issuer: String, + /// The verification link, with `{reference}` to fill in. + pub(super) verify_url: Option, +} + +impl CertificateIssuer { + /// The letterhead of the certificate `reference`: the issuer, the + /// reference, its verification link, and the name each account in + /// `names` prints as. + pub(super) fn letterhead( + &self, + reference: CertificateReference, + names: HashMap, + ) -> Letterhead { + let reference = reference.to_string(); + let mut letterhead = names.into_iter().fold( + Letterhead::new(self.issuer.clone()), + |letterhead, (account, name)| letterhead.with_name(account.to_string(), name), + ); + if let Some(template) = &self.verify_url { + letterhead = letterhead.with_verify_url(template.replace("{reference}", &reference)); + } + letterhead.reference = Some(reference); + letterhead + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_reference_reads_back_as_written() { + let reference = CertificateReference::new(48_210_375); + assert_eq!(reference.to_string(), "CERT-48210375"); + assert_eq!("CERT-48210375".parse(), Ok(reference)); + assert_eq!("48210375".parse(), Ok(reference)); + } + + #[test] + fn a_reference_is_eight_digits_after_an_optional_prefix() { + for text in [ + "cert-48210375", + "CERT-", + "4821037", + "CERT-4821037", + "CERT-482103750", + "CERT-+4821037", + "CERT-4821037a", + ] { + assert_eq!( + text.parse::(), + Err(InvalidCertificateReference), + "{text}" + ); + } + } + + #[test] + fn the_verify_link_names_the_reference() { + let issuer = CertificateIssuer { + issuer: "nvisy.com".to_owned(), + verify_url: Some("https://app.nvisy.com/verify/{reference}".to_owned()), + }; + let letterhead = issuer.letterhead(CertificateReference::new(48_210_375), HashMap::new()); + assert_eq!( + letterhead.verify_url.as_deref(), + Some("https://app.nvisy.com/verify/CERT-48210375") + ); + assert_eq!(letterhead.reference.as_deref(), Some("CERT-48210375")); + } + + #[test] + fn no_template_means_no_link() { + let issuer = CertificateIssuer { + issuer: "nvisy.com".to_owned(), + verify_url: None, + }; + let letterhead = issuer.letterhead(CertificateReference::new(48_210_375), HashMap::new()); + assert!(letterhead.verify_url.is_none()); + } +} diff --git a/crates/nvisy-server/src/service/engine/config.rs b/crates/nvisy-server/src/service/engine/config.rs index 9338b097..eab314a6 100644 --- a/crates/nvisy-server/src/service/engine/config.rs +++ b/crates/nvisy-server/src/service/engine/config.rs @@ -2,7 +2,8 @@ //! //! The operator-owned TOML file (pointed at by `ENGINE_CONFIG_FILEPATH`) that //! configures the engine at startup: the NER/LLM recognizer lineups and the -//! OCR/STT enricher backends. These are uniform across the deployment; a +//! OCR/STT enricher backends. Beside it, the letterhead redaction certificates +//! are issued on. These are uniform across the deployment; a //! pipeline's definition carries detection intent, not this infrastructure //! config. //! @@ -12,13 +13,16 @@ use std::path::{Path, PathBuf}; -use elide_runtime::provider::Deployment; +use elide_runtime::provider::deployment::Deployment; use crate::{Error, Result}; +/// Who issues redaction certificates when no issuer is configured. +const DEFAULT_CERTIFICATE_ISSUER: &str = "nvisy.com"; + /// Deployment configuration for the redaction engine. #[must_use] -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] #[cfg_attr(feature = "cli", derive(clap::Args))] pub struct EngineConfig { /// Optional path to a TOML file with the deployment engine configuration. @@ -28,6 +32,31 @@ pub struct EngineConfig { /// still run). #[cfg_attr(feature = "cli", arg(long, env = "ENGINE_CONFIG_FILEPATH"))] pub config_path: Option, + + /// Who issues redaction certificates, named at the top of each + /// certificate's PDF, in its footer, and in its metadata. + #[cfg_attr( + feature = "cli", + arg(long, env = "CERTIFICATE_ISSUER", default_value = DEFAULT_CERTIFICATE_ISSUER) + )] + pub certificate_issuer: String, + + /// Where a reader of a certificate's PDF checks it, drawn as a QR code: + /// `{reference}` is replaced with the certificate's reference, as in + /// `https://app.nvisy.com/verify/{reference}`. Absent means the PDF has no + /// link. + #[cfg_attr(feature = "cli", arg(long, env = "CERTIFICATE_VERIFY_URL"))] + pub certificate_verify_url: Option, +} + +impl Default for EngineConfig { + fn default() -> Self { + Self { + config_path: None, + certificate_issuer: DEFAULT_CERTIFICATE_ISSUER.to_owned(), + certificate_verify_url: None, + } + } } /// Reads and parses the engine [`Deployment`] from a TOML file. diff --git a/crates/nvisy-server/src/service/engine/mod.rs b/crates/nvisy-server/src/service/engine/mod.rs index b5fba506..3a866ba5 100644 --- a/crates/nvisy-server/src/service/engine/mod.rs +++ b/crates/nvisy-server/src/service/engine/mod.rs @@ -8,11 +8,13 @@ //! //! [`Engine`]: elide_runtime::Engine +mod certificate; mod config; mod error; mod modality; mod service; +pub use certificate::CertificateReference; pub use config::EngineConfig; pub use error::UnknownFormatToken; pub use modality::{DocumentModality, format_modality}; diff --git a/crates/nvisy-server/src/service/engine/service.rs b/crates/nvisy-server/src/service/engine/service.rs index a8af5015..33150978 100644 --- a/crates/nvisy-server/src/service/engine/service.rs +++ b/crates/nvisy-server/src/service/engine/service.rs @@ -1,16 +1,21 @@ //! The injectable redaction-engine service. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; +use std::fmt::Display; use derive_more::Deref; +use elide_runtime::certificate::{CertificateApproval, DocumentCertificate, HistoryEvent}; use elide_runtime::elide::{ Error as EngineError, ErrorKind as EngineErrorKind, Result as EngineResult, }; use elide_runtime::file::Document; use elide_runtime::governance::policy::Policy; -use elide_runtime::provider::{Deployment, Provider, RequestContext}; +use elide_runtime::provider::deployment::Deployment; +use elide_runtime::provider::{Provider, RequestContext}; use elide_runtime::{Analyzed, Engine}; +use uuid::Uuid; +use super::certificate::{CertificateIssuer, CertificateReference}; use super::config::{self, EngineConfig}; use super::error::UnknownFormatToken; use super::modality::{DocumentModality, format_modality}; @@ -28,6 +33,7 @@ use crate::Result; pub struct EngineService { #[deref] engine: Engine, + certificates: CertificateIssuer, } impl EngineService { @@ -48,7 +54,20 @@ impl EngineService { }; let engine = Engine::new(Provider::new(deployment)); - Ok(Self { engine }) + let certificates = CertificateIssuer { + issuer: config.certificate_issuer, + verify_url: config.certificate_verify_url, + }; + Ok(Self { + engine, + certificates, + }) + } + + /// Who issues the deployment's certificates. + #[must_use] + pub fn certificate_issuer(&self) -> &str { + &self.certificates.issuer } /// Borrows the underlying [`Engine`]. @@ -96,6 +115,37 @@ impl EngineService { .map_err(|err| EngineError::new(EngineErrorKind::Processing, err))? } + /// Renders the certificate `reference` as a PDF on a blocking thread, on the + /// deployment's letterhead: its status under the host's `approval`, + /// `history` as the events only the server saw, and each account in + /// `names` printed by its name. + /// + /// Typesetting is CPU-bound, so it runs off the async workers, as + /// [`analyze_blocking`](Self::analyze_blocking) does. + /// + /// # Errors + /// + /// - A `Processing` engine error if the blocking task panics or is + /// cancelled, or if the page cannot be typeset. + /// - A `MalformedInput` engine error if the verification link is too long + /// for a QR code. + pub async fn render_certificate( + &self, + certificate: DocumentCertificate, + reference: CertificateReference, + approval: CertificateApproval, + history: Vec>, + names: HashMap, + ) -> EngineResult> { + let letterhead = self + .certificates + .letterhead(reference, names) + .with_approval(approval); + tokio::task::spawn_blocking(move || certificate.to_pdf(&letterhead, &history)) + .await + .map_err(|err| EngineError::new(EngineErrorKind::Processing, err))? + } + /// Resolves file-extension filter tokens to the set of extensions to match. /// /// Each token is a file extension (`pdf`, `jpg`); it expands to its format's diff --git a/crates/nvisy-server/src/service/event/workspace_event.rs b/crates/nvisy-server/src/service/event/workspace_event.rs index d423bfb9..9158d92f 100644 --- a/crates/nvisy-server/src/service/event/workspace_event.rs +++ b/crates/nvisy-server/src/service/event/workspace_event.rs @@ -169,7 +169,6 @@ impl EventKind for MemberAdded { exclude: Some(self.member_id), }, payload: NotificationPayload::MemberJoined(MemberJoinedParams { - workspace_id: self.workspace_id, member_id: self.member_id, }), }] diff --git a/crates/nvisy-server/src/service/mod.rs b/crates/nvisy-server/src/service/mod.rs index 203b704a..647bd873 100644 --- a/crates/nvisy-server/src/service/mod.rs +++ b/crates/nvisy-server/src/service/mod.rs @@ -44,7 +44,8 @@ pub use crate::service::crypto::{CryptoConfig, CryptoService}; pub(crate) use crate::service::crypto::{CryptoError, HashingReader, LimitedReader, Measurements}; pub use crate::service::emitter::{NotificationEmitter, UnreadCountEvent, WebhookEmitter}; pub use crate::service::engine::{ - DocumentModality, EngineConfig, EngineService, UnknownFormatToken, format_modality, + CertificateReference, DocumentModality, EngineConfig, EngineService, UnknownFormatToken, + format_modality, }; pub use crate::service::health::{HealthConfig, HealthReading, HealthService}; pub use crate::service::infra::Infra; diff --git a/crates/nvisy-server/src/worker/detection/worker.rs b/crates/nvisy-server/src/worker/detection/worker.rs index 37ae8750..0cb5ba32 100644 --- a/crates/nvisy-server/src/worker/detection/worker.rs +++ b/crates/nvisy-server/src/worker/detection/worker.rs @@ -27,6 +27,7 @@ use uuid::Uuid; use super::job::{DetectionJob, DetectionStream, broadcast_status}; use super::support::{FailDetection, FailOutcome, fail_detection, resolve_policies_by_ids}; +use crate::domain::detection_decisions; use crate::extract::SecurityContext; use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::{ArtifactReader, ArtifactWriter, EngineService, Infra, StagedBlob, event}; @@ -84,12 +85,9 @@ impl Worker for DetectionWorker { .event_subscriber::() .consume(self.concurrency, &cancel, move |job, _delivery| { let worker = worker.clone(); - async move { - // reason: detection job future is inherently large; boxing would only move the allocation - #[allow(clippy::large_futures)] - let settle = worker.run_job(job).await; - settle - } + // The job's future is large; on the heap it keeps each consumer + // task's stack small. + async move { Box::pin(worker.run_job(job)).await } }) .await?; Ok(()) @@ -266,8 +264,6 @@ impl DetectionWorker { /// inputs under a connection and releases it, phase 2 runs the (slow) document /// build, analysis, and audit staging with no connection held, and phase 3 /// re-acquires a connection only for the finalize transaction. - // reason: long but cohesive; splitting adds no clarity - #[allow(clippy::too_many_lines)] async fn detect( &self, job: &DetectionJob, @@ -341,6 +337,7 @@ impl DetectionWorker { .analyze_blocking(engine_document, policies, request) .await?; let audit = &analyzed.audit; + let finding_count = detection_decisions::finding_count(&audit.report); // Write the (non-transactional) audit object first, then commit its blob // and base-audit row together with the detection's status in one @@ -455,6 +452,8 @@ impl DetectionWorker { intermediate_expires_at: Some(intermediate_expires_at), audit_blob_id: Some(Some(audit_resolved.id)), audit_expires_at: Some(Some(audit_blob.expires_at.into())), + base_finding_count: Some(Some(finding_count)), + finding_count: Some(Some(finding_count)), ..Default::default() }, ) diff --git a/crates/nvisy-server/src/worker/integration/export.rs b/crates/nvisy-server/src/worker/integration/export.rs index 7a45a502..8299a6d2 100644 --- a/crates/nvisy-server/src/worker/integration/export.rs +++ b/crates/nvisy-server/src/worker/integration/export.rs @@ -5,14 +5,19 @@ //! export so a later run does not push it again. Stateless beyond its [`Infra`] //! and connector, so it is cheap to clone. +use std::collections::HashSet; use std::io; use std::str::FromStr; use bytes::Bytes; use futures::{Stream, TryStreamExt}; use nvisy_core::{ByteStream, Error as CoreError, FileUpload}; +use nvisy_postgres::PgConn; use nvisy_postgres::model::{Blob, WorkspaceConnection, WorkspaceDocument}; -use nvisy_postgres::query::{DocumentWithBlob, WorkspaceDocumentRepository}; +use nvisy_postgres::query::{ + DocumentWithBlob, WorkspaceDocumentRepository, WorkspaceRedactionRepository, +}; +use nvisy_postgres::types::DocumentKind; use nvisy_s3::DocumentKey; use tokio::io::AsyncRead; use tokio_util::io::ReaderStream; @@ -22,6 +27,7 @@ use super::connector::Connector; use super::count_transferred; use super::file_source::FileSource; use super::naming::{export_key, mime_from_extension}; +use crate::domain::review_settings; use crate::response::{ErrorKind, Result}; use crate::service::{ConnectionConfig, CryptoService, Infra}; @@ -35,6 +41,46 @@ const EXPORT_PREFIX_REDACTED: &str = "redacted/"; /// Object-store key prefix for manually exported files. const EXPORT_PREFIX_SELECTED: &str = "exports/"; +/// Keeps the files among `files` that may leave the workspace as the batch is +/// selected: every original, and, where the workspace gates downloads, only the +/// redacted files whose redaction a review approved and no later approval +/// replaced. Each one held back is logged and dropped. Each upload checks its +/// file again as it starts. +async fn released( + conn: &mut PgConn, + workspace_id: Uuid, + files: Vec, +) -> Result> { + if !review_settings(conn, workspace_id).await?.gate_downloads { + return Ok(files); + } + let redacted: Vec = files + .iter() + .filter(|file| file.document.kind == DocumentKind::Redacted) + .map(|file| file.document.id) + .collect(); + let approved: HashSet = conn + .list_approved_outputs(workspace_id, &redacted) + .await? + .into_iter() + .collect(); + Ok(files + .into_iter() + .filter(|file| { + let held = file.document.kind == DocumentKind::Redacted + && !approved.contains(&file.document.id); + if held { + tracing::debug!( + target: TRACING_TARGET, + file_id = %file.document.id, + "Holding back a redacted file no review has released", + ); + } + !held + }) + .collect()) +} + /// Exports workspace files out to a connection. #[derive(Clone)] pub(super) struct Exporter { @@ -62,7 +108,8 @@ impl Exporter { } /// Exports a caller-selected set of workspace files to the connection, each - /// as a new provider file. Ids not found in the workspace are skipped. + /// as a new provider file. Ids not found in the workspace, and redacted + /// files held back until a review approves them, are skipped. /// Returns the number exported. Backs the manual export endpoint. #[tracing::instrument( name = "sync.export_selected", @@ -90,7 +137,7 @@ impl Exporter { "Skipping export of files not found in the workspace or with reclaimed content", ); } - files + released(&mut conn, connection.workspace_id, files).await? }; let exported = self .export_files(connection, config, files, EXPORT_PREFIX_SELECTED) @@ -101,7 +148,9 @@ impl Exporter { } /// Exports every redacted output in the connection's workspace that has not - /// yet been exported to this connection. Backs scheduled export syncs. + /// yet been exported to this connection and may leave the workspace. Backs + /// scheduled export syncs. One held back until a review approves it is not + /// recorded, so a later run exports it once one does. /// /// Each redacted file is streamed out and its export recorded so a later run /// does not push it again. A single file failing is logged and skipped rather @@ -120,8 +169,10 @@ impl Exporter { let pending = { let mut conn = self.infra.postgres.get_connection().await?; - conn.redacted_documents_not_exported(connection.workspace_id, connection.id) - .await? + let pending = conn + .redacted_documents_not_exported(connection.workspace_id, connection.id) + .await?; + released(&mut conn, connection.workspace_id, pending).await? }; let exported = self .export_files(connection, config, pending, EXPORT_PREFIX_REDACTED) @@ -164,12 +215,20 @@ impl Exporter { let exported = self .export_one(source, connection, &file.document, &file.blob, &remote_key) .await; - if let Err(err) = &exported { - tracing::warn!( + match &exported { + // A redacted file a review stopped releasing is held back, + // not failed. + Err(err) if err.kind() == ErrorKind::Forbidden => tracing::debug!( + target: TRACING_TARGET, + file_id = %file.document.id, + "Holding back a redacted file no review has released", + ), + Err(err) => tracing::warn!( target: TRACING_TARGET, file_id = %file.document.id, error = %err, "Skipping file that failed to export", - ); + ), + Ok(()) => {} } exported.is_ok() }) @@ -183,6 +242,8 @@ impl Exporter { /// Streams the file's bytes from the files store, decrypts them, and uploads /// them to the external store. On success the export is recorded so a /// scheduled redacted export never re-pushes a file already exported here. + /// A redacted file the workspace's review gate no longer releases is + /// refused before any bytes move, and left unrecorded for a later run. #[tracing::instrument( name = "sync.export_one", skip_all, @@ -198,6 +259,23 @@ impl Exporter { ) -> Result<()> { tracing::debug!(target: TRACING_TARGET, "Exporting file to connection"); + // The batch was filtered when it was selected; an approval since then + // may have replaced this file, so it is checked again as it leaves. + if document.kind == DocumentKind::Redacted { + let mut conn = self.infra.postgres.get_connection().await?; + if review_settings(&mut conn, connection.workspace_id) + .await? + .gate_downloads + && conn + .list_approved_outputs(connection.workspace_id, &[document.id]) + .await? + .is_empty() + { + return Err(ErrorKind::Forbidden + .with_message("No review releases this redacted file any longer")); + } + } + let file_key = DocumentKey::from_str(&blob.storage_path).map_err(|err| { ErrorKind::InternalServerError .with_message("Invalid file storage path") diff --git a/crates/nvisy-server/src/worker/reaper/worker.rs b/crates/nvisy-server/src/worker/reaper/worker.rs index 2ed96bb8..2cce578d 100644 --- a/crates/nvisy-server/src/worker/reaper/worker.rs +++ b/crates/nvisy-server/src/worker/reaper/worker.rs @@ -69,14 +69,15 @@ impl BlobReaper { /// nulls the blob pointer on expired documents (originals and redacted /// outputs, except while a detection on them is in progress), detection /// intermediates, detection base-analysis (audit) blobs, and redaction - /// review-analysis blobs, keeping the rows and each dropping one blob - /// reference. Pages through all four until a pass clears nothing, so the following Purge sweep sees the - /// now-unreferenced blobs. Stops early on cancellation so shutdown is not held - /// up by a backlog. + /// review-analysis and certificate blobs, keeping the rows and each dropping + /// one blob reference. Pages through all five until a pass clears nothing, so + /// the following Purge sweep sees the now-unreferenced blobs. Stops early on + /// cancellation so shutdown is not held up by a backlog. async fn release_expired_referrers(&self, cancel: &CancellationToken) -> Result<()> { use nvisy_postgres::query::{ - clear_expired_detection_audits, clear_expired_detection_intermediates, - clear_expired_document_blobs, clear_expired_review_audits, + clear_expired_certificates, clear_expired_detection_audits, + clear_expired_detection_intermediates, clear_expired_document_blobs, + clear_expired_review_audits, }; loop { @@ -89,7 +90,8 @@ impl BlobReaper { clear_expired_detection_intermediates(&mut conn, SWEEP_BATCH).await?; let detection_audits = clear_expired_detection_audits(&mut conn, SWEEP_BATCH).await?; let review_audits = clear_expired_review_audits(&mut conn, SWEEP_BATCH).await?; - if documents == 0 && intermediates == 0 && detection_audits == 0 && review_audits == 0 { + let certificates = clear_expired_certificates(&mut conn, SWEEP_BATCH).await?; + if documents + intermediates + detection_audits + review_audits + certificates == 0 { break; } } diff --git a/crates/nvisy-server/tests/workspace_redactions.rs b/crates/nvisy-server/tests/workspace_redactions.rs index 3247f612..b377df90 100644 --- a/crates/nvisy-server/tests/workspace_redactions.rs +++ b/crates/nvisy-server/tests/workspace_redactions.rs @@ -1,9 +1,11 @@ -//! A redaction's review audit, end to end: detect, decide, redact, review. +//! A redaction's review audit and certificate, end to end: detect, decide, +//! redact, then read them back. #![cfg(feature = "test_util")] use std::collections::HashSet; use std::time::Duration; +use axum::http::StatusCode; use axum_test::multipart::{MultipartForm, Part}; use elide_runtime::elide::entity::LabelRef; use elide_runtime::elide::modality::text::Text; @@ -13,11 +15,14 @@ use nvisy_server::test_util::{Actor, TestApp}; use serde_json::{Value, json}; use uuid::Uuid; +/// The document every test uploads. +const CONTENT: &[u8] = b"Contact jane@example.com today."; + /// Uploads a text document holding one email address and returns its id. async fn upload(app: &TestApp, workspace: Uuid, actor: &Actor) -> String { let form = MultipartForm::new().add_part( "file", - Part::bytes(b"Contact jane@example.com today.".to_vec()) + Part::bytes(CONTENT.to_vec()) .file_name("contact.txt") .mime_type("text/plain"), ); @@ -82,22 +87,22 @@ async fn set_edits(app: &TestApp, path: &str, actor: &Actor, rev: i32, edits: &[ .assert_status_ok(); } -#[tokio::test] -async fn the_review_audit_credits_every_reviewer_decision() { - let app = TestApp::spawn().await; - let _workers = app.spawn_workers(); - let (owner, workspace) = app.workspace_owner().await; - let editor = app.member_of(workspace, WorkspaceRole::Editor).await; - - let document = upload(&app, workspace, &owner).await; - let path = detect(&app, workspace, &owner, &document).await; +/// Redacts `document` after the owner relabels its email address and the editor +/// suppresses it, returning the detection's analysis and the redaction's id. +async fn redact_with_two_reviewers( + app: &TestApp, + workspace: Uuid, + owner: &Actor, + editor: &Actor, +) -> (Value, String) { + let document = upload(app, workspace, owner).await; + let path = detect(app, workspace, owner, &document).await; let analysis: Value = app .server() .get(&format!("{path}/analysis")) .authorization_bearer(&owner.jwt) .await .json(); - let report_id = &analysis["report"]["id"]; let entity: Uuid = analysis["report"]["parts"][0]["entities"][0]["id"] .as_str() .and_then(|id| id.parse().ok()) @@ -115,17 +120,127 @@ async fn the_review_audit_credits_every_reviewer_decision() { id: entity, reason: None, }); - set_edits(&app, &path, &owner, 0, std::slice::from_ref(&relabel)).await; - set_edits(&app, &path, &editor, 1, &[relabel, suppress]).await; + set_edits(app, &path, owner, 0, std::slice::from_ref(&relabel)).await; + set_edits(app, &path, editor, 1, &[relabel, suppress]).await; let response = app .server() .post(&format!("{path}/redactions")) .authorization_bearer(&owner.jwt) .await; - response.assert_status(axum::http::StatusCode::CREATED); + response.assert_status(StatusCode::CREATED); let redaction: Value = response.json(); - let redaction = redaction["id"].as_str().expect("the redaction id"); + let redaction = redaction["id"] + .as_str() + .expect("the redaction id") + .to_owned(); + (analysis, redaction) +} + +/// Each entry of a certificate's activity, as its kind and who did it. +fn kinds(certificate: &Value) -> Vec<(String, String)> { + certificate["activity"] + .as_array() + .expect("the activity") + .iter() + .map(|entry| { + ( + entry["kind"].as_str().expect("the kind").to_owned(), + entry["by"].as_str().expect("the account").to_owned(), + ) + }) + .collect() +} + +/// Redacts the detection at `path` with no edits, returning the redaction's +/// id and its redacted document's. +async fn redact(app: &TestApp, path: &str, actor: &Actor) -> (String, String) { + let response = app + .server() + .post(&format!("{path}/redactions")) + .authorization_bearer(&actor.jwt) + .await; + response.assert_status(StatusCode::CREATED); + let redaction: Value = response.json(); + let field = |name: &str| { + redaction[name] + .as_str() + .unwrap_or_else(|| panic!("the redaction's {name}")) + .to_owned() + }; + (field("id"), field("outputDocumentId")) +} + +/// Opens a review of `document`, submits it, assigns `actor`, and returns its +/// path. +async fn open_review(app: &TestApp, workspace: Uuid, document: &str, actor: &Actor) -> String { + let response = app + .server() + .post(&format!( + "/workspaces/{workspace}/documents/{document}/reviews" + )) + .authorization_bearer(&actor.jwt) + .json(&json!({ "displayName": "Release" })) + .await; + response.assert_status_success(); + let review: Value = response.json(); + let path = format!( + "/workspaces/{workspace}/reviews/{}", + review["id"].as_str().expect("the review id") + ); + for step in [ + format!("{path}/submit"), + format!("{path}/assignees/{}", actor.account_id), + ] { + app.server() + .post(&step) + .authorization_bearer(&actor.jwt) + .await + .assert_status_success(); + } + path +} + +/// Approves `redaction` in the review at `path`, as `actor`. +async fn approve(app: &TestApp, path: &str, actor: &Actor, redaction: &str) { + app.server() + .post(&format!("{path}/approve")) + .authorization_bearer(&actor.jwt) + .json(&json!({ "redactionId": redaction })) + .await + .assert_status_success(); +} + +/// The certificate of `redaction`, as `actor` reads it. +async fn certificate(app: &TestApp, workspace: Uuid, redaction: &str, actor: &Actor) -> Value { + app.server() + .get(&format!( + "/workspaces/{workspace}/redactions/{redaction}/certificate" + )) + .authorization_bearer(&actor.jwt) + .await + .json() +} + +/// The ids of the accounts in a response's `accounts`. +fn account_ids(response: &Value) -> HashSet { + response["accounts"] + .as_array() + .expect("the resolved accounts") + .iter() + .filter_map(|account| account["id"].as_str()) + .map(ToOwned::to_owned) + .collect() +} + +#[tokio::test] +async fn the_review_audit_credits_every_reviewer_decision() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let editor = app.member_of(workspace, WorkspaceRole::Editor).await; + + let (analysis, redaction) = redact_with_two_reviewers(&app, workspace, &owner, &editor).await; let review_path = format!("/workspaces/{workspace}/redactions/{redaction}/review"); let review: Value = app @@ -136,7 +251,7 @@ async fn the_review_audit_credits_every_reviewer_decision() { .json(); // The review is the report the detection's analysis was applied from. - assert_eq!(&review["report"]["id"], report_id); + assert_eq!(review["report"]["id"], analysis["report"]["id"]); // Each reviewer's decision is on the entity's trail under their account id, // and every account the trail names is resolved. @@ -154,19 +269,392 @@ async fn the_review_audit_credits_every_reviewer_decision() { .map(ToOwned::to_owned) .collect(); assert_eq!(named, both, "{trail:#?}"); - let accounts: HashSet = review["accounts"] + assert_eq!(account_ids(&review), both); + + let outsider = app.actor().await; + app.server() + .get(&review_path) + .authorization_bearer(&outsider.jwt) + .await + .assert_status_forbidden(); +} + +#[tokio::test] +async fn the_certificate_names_its_accounts_and_verifies_by_reference() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let editor = app.member_of(workspace, WorkspaceRole::Editor).await; + let (analysis, redaction) = redact_with_two_reviewers(&app, workspace, &owner, &editor).await; + + let path = format!("/workspaces/{workspace}/redactions/{redaction}/certificate"); + let response: Value = app + .server() + .get(&path) + .authorization_bearer(&editor.jwt) + .await + .json(); + let certificate = &response["certificate"]; + + // It vouches for the report the redaction applied, under the account that + // redacted, and resolves that account and each reviewer. + assert_eq!(certificate["redaction"]["report"], analysis["report"]["id"]); + assert_eq!(certificate["redacted_by"], owner.account_id.to_string()); + let deciders: HashSet = certificate["redaction"]["decisions"] .as_array() - .expect("the resolved accounts") + .expect("the reviewer decisions") .iter() - .filter_map(|account| account["id"].as_str()) + .filter_map(|decision| decision["by"].as_str()) .map(ToOwned::to_owned) .collect(); - assert_eq!(accounts, both); + let both: HashSet = [owner.account_id, editor.account_id] + .iter() + .map(Uuid::to_string) + .collect(); + assert_eq!(deciders, both, "{certificate:#?}"); + assert_eq!(account_ids(&response), both); + + // Its activity runs from the upload and the detection, which the + // certificate does not record, through each reviewer's decisions to the + // redaction, each by the account that did it. + let owner_id = owner.account_id.to_string(); + let activity = kinds(&response); + assert_eq!(activity.len(), 5, "{activity:?}"); + assert_eq!( + activity[..2], + [ + ("uploaded".to_owned(), owner_id.clone()), + ("detected".to_owned(), owner_id.clone()) + ] + ); + let reviewed: HashSet = activity[2..4] + .iter() + .map(|(kind, by)| { + assert_eq!(kind, "reviewed"); + by.clone() + }) + .collect(); + assert_eq!(reviewed, both); + assert_eq!(activity[4], ("redacted".to_owned(), owner_id)); + assert!(response["issuer"].is_string()); + + let pdf = app + .server() + .get(&format!("{path}/pdf")) + .authorization_bearer(&editor.jwt) + .await; + pdf.assert_status_ok(); + assert_eq!(pdf.header("content-type"), "application/pdf"); + assert!(pdf.as_bytes().starts_with(b"%PDF-")); + + // Anyone holding the reference verifies it without an account, and learns + // only the redacted file's digest and the findings counted by label: the suppressed + // email address, relabeled, was left visible. + let reference = response["reference"].as_str().expect("the reference"); + assert!( + reference.starts_with("CERT-") && reference.len() == 13, + "{reference}" + ); + let verification: Value = app + .server() + .get(&format!("/certificates/{reference}")) + .await + .json(); + assert_eq!(verification["reference"], reference); + assert_eq!(verification["status"], response["status"]); + assert_eq!( + verification["outputSha256"], + certificate["document"]["output"] + ); + assert!(verification.get("sourceSha256").is_none()); + assert_eq!(verification["withheld"], json!({})); + assert_eq!(verification["disclosed"], json!({ "person_name": 1 })); + app.server() + .get("/certificates/CERT-00000001") + .await + .assert_status_not_found(); + let bare: Value = app + .server() + .get(&format!("/certificates/{}", &reference[5..])) + .await + .json(); + assert_eq!(bare["reference"], reference); + app.server() + .get("/certificates/cert-48210375") + .await + .assert_status_bad_request(); let outsider = app.actor().await; + for path in [path.clone(), format!("{path}/pdf")] { + app.server() + .get(&path) + .authorization_bearer(&outsider.jwt) + .await + .assert_status_forbidden(); + } +} + +#[tokio::test] +async fn a_certificate_follows_its_document_s_reviews() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let document = upload(&app, workspace, &owner).await; + let path = detect(&app, workspace, &owner, &document).await; + let (first, _) = redact(&app, &path, &owner).await; + let status = async |redaction: &str| { + certificate(&app, workspace, redaction, &owner).await["status"] + .as_str() + .expect("the status") + .to_owned() + }; + + // With no review, nothing withheld by a rule is left for a person to check. + assert_eq!(status(&first).await, "complete"); + assert_eq!( + certificate(&app, workspace, &first, &owner).await["approval"], + "untracked" + ); + + // An open review holds it until someone approves it. + let review = open_review(&app, workspace, &document, &owner).await; + assert_eq!(status(&first).await, "needs_review"); + approve(&app, &review, &owner, &first).await; + let approved = certificate(&app, workspace, &first, &owner).await; + assert_eq!(approved["status"], "complete"); + assert_eq!(approved["approval"], "approved"); + assert_eq!( + kinds(&approved).last(), + Some(&("approved".to_owned(), owner.account_id.to_string())) + ); + + // A later redaction approved in its place supersedes it, which a reader + // holding only its reference sees too. + let (second, _) = redact(&app, &path, &owner).await; + assert_eq!(status(&second).await, "complete"); + let review = open_review(&app, workspace, &document, &owner).await; + approve(&app, &review, &owner, &second).await; + assert_eq!(status(&first).await, "superseded"); + assert_eq!(status(&second).await, "complete"); + let reference = certificate(&app, workspace, &first, &owner).await["reference"].clone(); + let verification: Value = app + .server() + .get(&format!( + "/certificates/{}", + reference.as_str().expect("the reference") + )) + .await + .json(); + assert_eq!(verification["status"], "superseded"); + assert_eq!(verification["approval"], "superseded"); +} + +#[tokio::test] +async fn a_gated_workspace_releases_only_the_approved_redaction() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; app.server() - .get(&review_path) - .authorization_bearer(&outsider.jwt) + .patch(&format!("/workspaces/{workspace}")) + .authorization_bearer(&owner.jwt) + .json(&json!({ "settings": { "review": { "gateDownloads": true } } })) .await - .assert_status_forbidden(); + .assert_status_ok(); + let document = upload(&app, workspace, &owner).await; + let path = detect(&app, workspace, &owner, &document).await; + let (first, first_output) = redact(&app, &path, &owner).await; + let download = async |output: &str| { + app.server() + .get(&format!( + "/workspaces/{workspace}/documents/{output}/content" + )) + .authorization_bearer(&owner.jwt) + .await + .status_code() + }; + + assert_eq!(download(&first_output).await, StatusCode::FORBIDDEN); + let review = open_review(&app, workspace, &document, &owner).await; + approve(&app, &review, &owner, &first).await; + assert_eq!(download(&first_output).await, StatusCode::OK); + + // Another redaction approved in its place takes over the release. + let (second, second_output) = redact(&app, &path, &owner).await; + assert_eq!(download(&second_output).await, StatusCode::FORBIDDEN); + let review = open_review(&app, workspace, &document, &owner).await; + approve(&app, &review, &owner, &second).await; + assert_eq!(download(&first_output).await, StatusCode::FORBIDDEN); + assert_eq!(download(&second_output).await, StatusCode::OK); + + // The original is not gated. + assert_eq!(download(&document).await, StatusCode::OK); +} + +#[tokio::test] +async fn the_document_list_shows_where_each_original_stands() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let document = upload(&app, workspace, &owner).await; + let path = detect(&app, workspace, &owner, &document).await; + let list = async |query: &str| -> Vec { + let page: Value = app + .server() + .get(&format!("/workspaces/{workspace}/documents{query}")) + .authorization_bearer(&owner.jwt) + .await + .json(); + page["items"].as_array().expect("the documents").clone() + }; + + let listed = list("").await; + assert_eq!(listed.len(), 1); + assert_eq!(listed[0]["stage"], "detected"); + assert_eq!(listed[0]["hasRedaction"], false); + let latest = &listed[0]["latestDetection"]; + assert_eq!(latest["id"], path.rsplit('/').next().expect("the id")); + assert_eq!(latest["findingCount"], 1); + assert_eq!(latest["policies"].as_array().map(Vec::len), Some(1)); + assert!(latest["completedAt"].is_string()); + + // The finding count follows the reviewer edits, and returns once they are + // cleared. + let analysis: Value = app + .server() + .get(&format!("{path}/analysis")) + .authorization_bearer(&owner.jwt) + .await + .json(); + let entity: Uuid = analysis["report"]["parts"][0]["entities"][0]["id"] + .as_str() + .and_then(|id| id.parse().ok()) + .expect("the detected email address"); + let suppress = Edit::Suppress(Suppress { + id: entity, + reason: None, + }); + set_edits(&app, &path, &owner, 0, &[suppress]).await; + assert_eq!(list("").await[0]["latestDetection"]["findingCount"], 0); + app.server() + .patch(&path) + .authorization_bearer(&owner.jwt) + .json(&json!({ "editSetRev": 1 })) + .await + .assert_status_ok(); + assert_eq!(list("").await[0]["latestDetection"]["findingCount"], 1); + + // Redacting moves it on, and its redacted file is listed only when asked + // for. + redact(&app, &path, &owner).await; + let listed = list("").await; + assert_eq!(listed.len(), 1); + assert_eq!(listed[0]["stage"], "redacted"); + assert_eq!(listed[0]["hasRedaction"], true); + let both = list("?kind=original&kind=redacted").await; + assert_eq!(both.len(), 2); + assert!(both.iter().any(|document| document["stage"].is_null())); + assert_eq!(list("?stage=redacted&stage=approved").await.len(), 1); + assert_eq!(list("?stage=detected").await.len(), 0); + + // The stage counts cover every original, each stage present. + let counts = async |query: &str| -> Value { + app.server() + .get(&format!("/workspaces/{workspace}/documents/stages{query}")) + .authorization_bearer(&owner.jwt) + .await + .json() + }; + assert_eq!( + counts("").await, + json!({ + "uploaded": 0, + "detecting": 0, + "failed": 0, + "detected": 0, + "redacted": 1, + "inReview": 0, + "approved": 0, + }) + ); + assert_eq!(counts("?search=no-such-file").await["redacted"], 0); +} + +#[tokio::test] +async fn a_detection_names_the_policies_it_ran_under() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let document = upload(&app, workspace, &owner).await; + let path = detect(&app, workspace, &owner, &document).await; + + // A label list runs as its derived policy, at its first version, both on + // the detection and on its row in the workspace's list. + let detection: Value = app + .server() + .get(&path) + .authorization_bearer(&owner.jwt) + .await + .json(); + let policies = detection["policies"].as_array().expect("the policies"); + assert_eq!(policies.len(), 1, "{detection:#?}"); + assert_eq!(policies[0]["kind"], "derived"); + assert_eq!(policies[0]["versionNumber"], 1); + + let page: Value = app + .server() + .get(&format!("/workspaces/{workspace}/detections")) + .authorization_bearer(&owner.jwt) + .await + .json(); + let listed = page["items"] + .as_array() + .expect("the detections") + .iter() + .find(|item| item["id"] == detection["id"]) + .expect("the detection in the list"); + assert_eq!(listed["policies"], detection["policies"]); +} + +#[tokio::test] +async fn a_notification_names_its_workspace() { + let app = TestApp::spawn().await; + let _workers = app.spawn_workers(); + let (owner, workspace) = app.workspace_owner().await; + let document = upload(&app, workspace, &owner).await; + detect(&app, workspace, &owner, &document).await; + let get = async |path: &str| -> Value { + app.server() + .get(path) + .authorization_bearer(&owner.jwt) + .await + .json() + }; + + // The detection's completion is told to whoever ran it, once its event is + // delivered. + let mut items = Vec::new(); + for _ in 0..40 { + items = get("/notifications").await["items"] + .as_array() + .expect("the notifications") + .clone(); + if !items.is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + let notification = items.first().expect("the detection's notification"); + assert_eq!(notification["workspaceId"], workspace.to_string()); + assert!(notification["workspaceHandle"].is_string()); + + // A workspace scopes the list and the unread count. + let here = get(&format!("/notifications?workspace={workspace}")).await; + assert_eq!(here["items"].as_array().map(Vec::len), Some(items.len())); + let elsewhere = Uuid::now_v7(); + let there = get(&format!("/notifications?workspace={elsewhere}")).await; + assert_eq!(there["items"].as_array().map(Vec::len), Some(0)); + assert_eq!( + get(&format!("/notifications/unread?workspace={elsewhere}")).await["unreadCount"], + 0 + ); } diff --git a/crates/nvisy-webhook/src/provider/response.rs b/crates/nvisy-webhook/src/provider/response.rs index 0ff9c6a9..06ee5f00 100644 --- a/crates/nvisy-webhook/src/provider/response.rs +++ b/crates/nvisy-webhook/src/provider/response.rs @@ -1,6 +1,6 @@ //! Webhook delivery response types. -use jiff::{Span, Timestamp}; +use jiff::{SignedDuration, Timestamp}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -38,10 +38,10 @@ impl WebhookResponse { (200..300).contains(&self.status_code) } - /// Calculates the response time as a duration. + /// How long the endpoint took to respond. #[must_use] - pub fn duration(&self) -> Span { - self.started_at.until(self.finished_at).unwrap_or_default() + pub fn duration(&self) -> SignedDuration { + self.finished_at.duration_since(self.started_at) } } diff --git a/deny.toml b/deny.toml index f95fd79e..0749919e 100644 --- a/deny.toml +++ b/deny.toml @@ -68,6 +68,21 @@ ignore = [ # transitive dep of `testcontainers`, used to build test containers, and # never ships in the server binary. Remove once `testcontainers` replaces it. "RUSTSEC-2026-0440", + # Five unmaintained crates (no vulnerability), all pulled by Typst, which + # typesets redaction certificates as PDFs (`elide-runtime`'s + # `certificate-pdf`): `rustybuzz` and `ttf-parser` shape and read the fonts + # compiled into the certificate, through `typst-pdf`; `bincode`, `yaml-rust`, + # and `unsafe-libyaml` load syntax-highlighting and bibliography data, through + # `typst-library`'s `syntect` and `hayagriva`. The certificate's template and + # fonts are compiled in, and its values are passed as data, never as markup: + # `rustybuzz` shapes caller text (a file name, an account's name) only in + # those fonts, and the other four never see caller input. Remove each once + # Typst moves off it. + "RUSTSEC-2026-0206", + "RUSTSEC-2026-0192", + "RUSTSEC-2025-0141", + "RUSTSEC-2024-0320", + "RUSTSEC-2024-0449", ] [licenses] diff --git a/migrations/2025-05-21-222840_workspaces/down.sql b/migrations/2025-05-21-222840_workspaces/down.sql index 71a0ca92..2ffa5022 100644 --- a/migrations/2025-05-21-222840_workspaces/down.sql +++ b/migrations/2025-05-21-222840_workspaces/down.sql @@ -3,6 +3,9 @@ DROP TABLE IF EXISTS workspace_invites; DROP TABLE IF EXISTS workspace_members; + +ALTER TABLE account_notifications DROP COLUMN IF EXISTS workspace_id; + DROP TABLE IF EXISTS workspaces; DROP TYPE IF EXISTS INVITE_STATUS; diff --git a/migrations/2025-05-21-222840_workspaces/up.sql b/migrations/2025-05-21-222840_workspaces/up.sql index c7d14612..e9795f67 100644 --- a/migrations/2025-05-21-222840_workspaces/up.sql +++ b/migrations/2025-05-21-222840_workspaces/up.sql @@ -104,6 +104,19 @@ COMMENT ON TYPE WORKSPACE_ROLE IS 'Access role of a workspace member: owner, adm -- notifications migration). ALTER TYPE NOTIFICATION_EVENT ADD VALUE IF NOT EXISTS 'member.joined'; +-- Every notification tells of something in one workspace, so it names that +-- workspace (added here, as the notifications migration runs before workspaces +-- exist) and goes with it. +ALTER TABLE account_notifications + ADD COLUMN workspace_id UUID NOT NULL REFERENCES workspaces (id) ON DELETE CASCADE; + +-- An account's notifications in one workspace, newest first (the workspace +-- inbox); also serves the cascade from a deleted workspace. +CREATE INDEX account_notifications_workspace_idx + ON account_notifications (workspace_id, account_id, created_at DESC); + +COMMENT ON COLUMN account_notifications.workspace_id IS 'Workspace the notification is about'; + -- Workspace members table: an account's membership in a workspace. CREATE TABLE workspace_members ( -- Primary key (composite) diff --git a/migrations/2026-01-19-045016_detections/up.sql b/migrations/2026-01-19-045016_detections/up.sql index cba1dced..f4272c32 100644 --- a/migrations/2026-01-19-045016_detections/up.sql +++ b/migrations/2026-01-19-045016_detections/up.sql @@ -69,6 +69,17 @@ CREATE TABLE workspace_detections ( -- other (a stale PATCH is rejected as a conflict). edit_set_rev INTEGER NOT NULL DEFAULT 0, + -- How many findings stand: entities the analysis found that neither it nor + -- a reviewer dropped. The base count is the analysis's own, set when it + -- commits; the count is with the reviewer edits applied, rewritten with + -- them, and the base count again once they are cleared. Null until the + -- analysis commits. + base_finding_count INTEGER DEFAULT NULL, + finding_count INTEGER DEFAULT NULL, + CONSTRAINT workspace_detections_base_finding_count_min CHECK (base_finding_count >= 0), + CONSTRAINT workspace_detections_finding_count_min CHECK (finding_count >= 0), + CONSTRAINT workspace_detections_finding_counts_pair CHECK ((base_finding_count IS NULL) = (finding_count IS NULL)), + -- Detection lease: when a worker last claimed this detection. A redelivered -- job whose claim is still fresh is skipped (no double-analyze); a stale claim -- (a worker that died mid-analysis) can be re-claimed. Null until claimed. diff --git a/migrations/2026-01-19-045017_redactions/down.sql b/migrations/2026-01-19-045017_redactions/down.sql index d9cca567..1f06c48a 100644 --- a/migrations/2026-01-19-045017_redactions/down.sql +++ b/migrations/2026-01-19-045017_redactions/down.sql @@ -2,3 +2,4 @@ -- Objects are dropped in reverse order of creation. DROP TABLE IF EXISTS workspace_redactions; +DROP FUNCTION IF EXISTS generate_certificate_number(); diff --git a/migrations/2026-01-19-045017_redactions/up.sql b/migrations/2026-01-19-045017_redactions/up.sql index 21fd2891..d8773f0b 100644 --- a/migrations/2026-01-19-045017_redactions/up.sql +++ b/migrations/2026-01-19-045017_redactions/up.sql @@ -2,6 +2,28 @@ -- redacted many times, so each redaction is its own row owning the review audit -- it applied and the redacted document it produced. +-- A random certificate number no redaction holds yet: eight digits, so a +-- certificate's public reference (`CERT-48210375`) reveals neither how many +-- redactions there are nor which came before it. The digits come from +-- `gen_random_uuid`, which draws on a cryptographic source, unlike `random()`; +-- the unique constraint still guards two inserts that draw the same number at +-- once. +CREATE FUNCTION generate_certificate_number() RETURNS INTEGER AS $$ +DECLARE + candidate INTEGER; +BEGIN + LOOP + candidate := 10000000 + + (('x' || substr(replace(gen_random_uuid()::TEXT, '-', ''), 1, 8))::BIT(32)::BIGINT + % 90000000)::INTEGER; + EXIT WHEN NOT EXISTS ( + SELECT 1 FROM workspace_redactions WHERE certificate_number = candidate + ); + END LOOP; + RETURN candidate; +END; +$$ LANGUAGE plpgsql VOLATILE; + CREATE TABLE workspace_redactions ( -- Primary identifier id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -29,6 +51,19 @@ CREATE TABLE workspace_redactions ( -- referrers with different retention. review_audit_expires_at TIMESTAMPTZ DEFAULT NULL, + -- The certificate: what the redaction withheld and why, the files it read and + -- wrote, and the policies it ran under, stored as bytes in a blob. NULL once + -- the bytes are reclaimed on retention, like the review audit it vouches for. + certificate_blob_id UUID DEFAULT NULL REFERENCES workspace_blobs (id) ON DELETE SET NULL, + -- When the certificate's bytes are released, from the audit-logs retention. + certificate_expires_at TIMESTAMPTZ DEFAULT NULL, + -- The certificate's public number, its reference read as `CERT-`: + -- what a reader who holds only the PDF looks the certificate up by. + certificate_number INTEGER NOT NULL DEFAULT generate_certificate_number(), + CONSTRAINT workspace_redactions_certificate_number_unique UNIQUE (certificate_number), + CONSTRAINT workspace_redactions_certificate_number_digits + CHECK (certificate_number BETWEEN 10000000 AND 99999999), + -- Timing created_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp, @@ -60,13 +95,27 @@ CREATE INDEX workspace_redactions_review_audit_expiry_idx ON workspace_redactions (review_audit_expires_at) WHERE review_audit_blob_id IS NOT NULL; -COMMENT ON TABLE workspace_redactions IS 'Redactions: one redact pass over a detection, with its own reviewer edits, review audit, and output.'; +-- Back the certificate blob reference, walked by the retention sweep that +-- reclaims the certificate bytes and nulls this pointer. +CREATE INDEX workspace_redactions_certificate_blob_idx + ON workspace_redactions (certificate_blob_id) + WHERE certificate_blob_id IS NOT NULL; + +-- The reaper's walk for redactions whose certificate retention has passed. +CREATE INDEX workspace_redactions_certificate_expiry_idx + ON workspace_redactions (certificate_expires_at) + WHERE certificate_blob_id IS NOT NULL; + +COMMENT ON TABLE workspace_redactions IS 'Redactions: one redact pass over a detection, with its own reviewer edits, review audit, certificate, and output.'; COMMENT ON COLUMN workspace_redactions.id IS 'Unique redaction identifier'; COMMENT ON COLUMN workspace_redactions.detection_id IS 'Detection this redaction was produced from'; COMMENT ON COLUMN workspace_redactions.account_id IS 'Account that requested the redaction'; COMMENT ON COLUMN workspace_redactions.output_document_id IS 'Redacted document this redaction produced'; COMMENT ON COLUMN workspace_redactions.review_audit_blob_id IS 'Review analysis (findings after reviewer edits) blob; NULL once the bytes are reclaimed on retention (the row is kept)'; COMMENT ON COLUMN workspace_redactions.review_audit_expires_at IS 'When the review analysis bytes are released (audit-logs retention)'; +COMMENT ON COLUMN workspace_redactions.certificate_blob_id IS 'Redaction certificate blob; NULL once the bytes are reclaimed on retention (the row is kept)'; +COMMENT ON COLUMN workspace_redactions.certificate_expires_at IS 'When the certificate bytes are released (audit-logs retention)'; +COMMENT ON COLUMN workspace_redactions.certificate_number IS 'Public certificate number, referenced as CERT-; random, eight digits, unique'; COMMENT ON COLUMN workspace_redactions.created_at IS 'When the redaction was created'; COMMENT ON COLUMN workspace_redactions.deleted_at IS 'Soft-deletion timestamp; NULL means live. The row is kept as a ledger record; only its blob bytes are reclaimed'; diff --git a/migrations/2026-09-11-040235_reviews/down.sql b/migrations/2026-09-11-040235_reviews/down.sql index 556d6e3a..39e908d8 100644 --- a/migrations/2026-09-11-040235_reviews/down.sql +++ b/migrations/2026-09-11-040235_reviews/down.sql @@ -1,6 +1,20 @@ -- Revert the review tables and their enum types. -- Objects are dropped in reverse order of creation (children reference reviews). +DROP TRIGGER IF EXISTS workspace_review_approvals_document_state ON workspace_review_approvals; +DROP TRIGGER IF EXISTS workspace_reviews_document_state ON workspace_reviews; +DROP TRIGGER IF EXISTS workspace_redactions_document_state ON workspace_redactions; +DROP TRIGGER IF EXISTS workspace_detections_document_state ON workspace_detections; +DROP TRIGGER IF EXISTS workspace_documents_state ON workspace_documents; +DROP FUNCTION IF EXISTS trigger_workspace_review_approval_document_state(); +DROP FUNCTION IF EXISTS trigger_workspace_review_document_state(); +DROP FUNCTION IF EXISTS trigger_workspace_redaction_document_state(); +DROP FUNCTION IF EXISTS trigger_workspace_detection_document_state(); +DROP FUNCTION IF EXISTS trigger_workspace_document_state(); +DROP FUNCTION IF EXISTS refresh_workspace_document_state(UUID); +DROP TABLE IF EXISTS workspace_document_states; +DROP TYPE IF EXISTS DOCUMENT_STAGE; + DROP TABLE IF EXISTS workspace_review_events; DROP TABLE IF EXISTS workspace_review_approvals; DROP TABLE IF EXISTS workspace_review_assignees; diff --git a/migrations/2026-09-11-040235_reviews/up.sql b/migrations/2026-09-11-040235_reviews/up.sql index 765dcc7e..01314c02 100644 --- a/migrations/2026-09-11-040235_reviews/up.sql +++ b/migrations/2026-09-11-040235_reviews/up.sql @@ -272,6 +272,283 @@ COMMENT ON COLUMN workspace_review_events.actor_account_id IS 'Account that perf 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'; +-- Where an original document stands in its workflow. +CREATE TYPE DOCUMENT_STAGE AS ENUM ( + 'uploaded', -- It has no live detection + 'detecting', -- Its latest detection has not finished + 'failed', -- Its latest detection failed + 'detected', -- Its latest detection finished, and nothing below holds + 'redacted', -- Its latest detection has a live redaction + 'in_review', -- A review of it awaits a decision + 'approved' -- Its latest approved review approved a redaction of its latest detection +); + +COMMENT ON TYPE DOCUMENT_STAGE IS 'Where an original document stands in its workflow.'; + +-- What each live original document's detections, redactions, and reviews add +-- up to, kept current by the triggers below: the document list reads, filters, +-- and pages by it in one join, and a redaction's certificate and download gate +-- read its approval from it. Kept apart from workspace_documents so a change +-- here is not an edit of the document (its updated_at stays put). A redacted or +-- deleted document has no row. +CREATE TABLE workspace_document_states ( + document_id UUID PRIMARY KEY REFERENCES workspace_documents (id) ON DELETE CASCADE, + + -- Where it stands in its workflow, the first that holds: + -- failed / detecting the latest detection failed, or has not finished + -- in_review a review of it awaits a decision + -- approved the approved redaction is of the latest detection + -- redacted the latest detection has a live redaction + -- detected the latest detection finished + -- uploaded it has no live detection + stage DOCUMENT_STAGE NOT NULL, + + -- Its latest live detection, by when it started; NULL with none. + latest_detection_id UUID DEFAULT NULL REFERENCES workspace_detections (id) ON DELETE SET NULL, + + -- Whether any live detection of it has a live redaction. + has_redaction BOOLEAN NOT NULL, + + -- Whether a review of it awaits a decision: in review, changes + -- requested, or partially approved. + has_open_review BOOLEAN NOT NULL, + + -- The live output of its latest approved review, by when that review + -- reached its quorum, and that time. Every other redaction made before it + -- is superseded. NULL with no such review. The refresh writes the two + -- together; the reference only keeps a deleted redaction's id from + -- dangling until it runs. + approved_redaction_id UUID DEFAULT NULL REFERENCES workspace_redactions (id) ON DELETE SET NULL, + approved_at TIMESTAMPTZ DEFAULT NULL +); + +-- The documents at a stage (backs the document list's stage filter). +CREATE INDEX workspace_document_states_stage_idx + ON workspace_document_states (stage, document_id); + +-- Works out a document's state from its detections, redactions, and reviews, +-- and stores it, or removes it when the document is not a live original. +CREATE FUNCTION refresh_workspace_document_state(p_document_id UUID) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + latest_id UUID; + latest_status DETECTION_STATUS; + approved_id UUID; + approved_detection UUID; + approved_time TIMESTAMPTZ; + open_review BOOLEAN; + redacted BOOLEAN; + current_stage DOCUMENT_STAGE; +BEGIN + -- Refreshes of one document run one at a time, each after the last has + -- committed: every statement below takes a fresh snapshot, so it sees the + -- reviews, detections, and redactions another transaction just wrote + -- instead of overwriting its result with an older one. NO KEY UPDATE, not + -- UPDATE: it does not conflict with the KEY SHARE lock a new detection or + -- review takes on the document through its foreign key, so two of those + -- inserted at once do not deadlock here. + PERFORM 1 + FROM workspace_documents d + WHERE d.id = p_document_id + FOR NO KEY UPDATE; + + IF NOT EXISTS ( + SELECT 1 + FROM workspace_documents d + WHERE d.id = p_document_id + AND d.kind = 'original' + AND d.deleted_at IS NULL + ) THEN + DELETE FROM workspace_document_states WHERE document_id = p_document_id; + RETURN; + END IF; + + SELECT t.id, t.status + INTO latest_id, latest_status + FROM workspace_detections t + WHERE t.input_document_id = p_document_id + AND t.deleted_at IS NULL + ORDER BY t.started_at DESC, t.id DESC + LIMIT 1; + + -- A review reaches its quorum at the last approval of its output. + SELECT r.id, r.detection_id, quorum.at + INTO approved_id, approved_detection, approved_time + FROM workspace_reviews v + JOIN workspace_redactions r ON r.id = v.redaction_id AND r.deleted_at IS NULL + CROSS JOIN LATERAL ( + SELECT max(a.approved_at) AS at + FROM workspace_review_approvals a + WHERE a.review_id = v.id + AND a.redaction_id = v.redaction_id + ) quorum + WHERE v.document_id = p_document_id + AND v.deleted_at IS NULL + AND v.review_status = 'approved' + ORDER BY quorum.at DESC NULLS LAST, v.id DESC + LIMIT 1; + + open_review := EXISTS ( + SELECT 1 + FROM workspace_reviews v + WHERE v.document_id = p_document_id + AND v.deleted_at IS NULL + AND v.review_status IN ('in_review', 'changes_requested', 'partially_approved') + ); + + redacted := EXISTS ( + SELECT 1 + FROM workspace_redactions r + JOIN workspace_detections t ON t.id = r.detection_id + WHERE t.input_document_id = p_document_id + AND t.deleted_at IS NULL + AND r.deleted_at IS NULL + ); + + current_stage := CASE + WHEN latest_id IS NULL THEN 'uploaded' + WHEN latest_status = 'failed' THEN 'failed' + WHEN latest_status <> 'complete' THEN 'detecting' + WHEN open_review THEN 'in_review' + WHEN approved_detection = latest_id THEN 'approved' + WHEN EXISTS ( + SELECT 1 + FROM workspace_redactions r + WHERE r.detection_id = latest_id + AND r.deleted_at IS NULL + ) THEN 'redacted' + ELSE 'detected' + END; + + INSERT INTO workspace_document_states AS s ( + document_id, stage, latest_detection_id, has_redaction, has_open_review, + approved_redaction_id, approved_at + ) + VALUES ( + p_document_id, current_stage, latest_id, redacted, open_review, + approved_id, approved_time + ) + ON CONFLICT (document_id) DO UPDATE SET + stage = EXCLUDED.stage, + latest_detection_id = EXCLUDED.latest_detection_id, + has_redaction = EXCLUDED.has_redaction, + has_open_review = EXCLUDED.has_open_review, + approved_redaction_id = EXCLUDED.approved_redaction_id, + approved_at = EXCLUDED.approved_at + WHERE (s.stage, s.latest_detection_id, s.has_redaction, s.has_open_review, + s.approved_redaction_id, s.approved_at) + IS DISTINCT FROM + (EXCLUDED.stage, EXCLUDED.latest_detection_id, EXCLUDED.has_redaction, + EXCLUDED.has_open_review, EXCLUDED.approved_redaction_id, EXCLUDED.approved_at); +END; +$$; + +COMMENT ON FUNCTION refresh_workspace_document_state(UUID) IS 'Stores what a document''s detections, redactions, and reviews add up to, or removes it when the document is not a live original.'; + +-- Each trigger refreshes the state of the document a write touches. Deletes +-- are included: an account's deletion cascades to its detections, redactions, +-- reviews, and approvals on other accounts' documents. +CREATE FUNCTION trigger_workspace_document_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM refresh_workspace_document_state(NEW.id); + RETURN NULL; +END; +$$; + +CREATE FUNCTION trigger_workspace_detection_document_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + PERFORM refresh_workspace_document_state(OLD.input_document_id); + ELSE + PERFORM refresh_workspace_document_state(NEW.input_document_id); + END IF; + RETURN NULL; +END; +$$; + +-- A redaction deleted along with its detection finds no detection here; the +-- detection's own trigger refreshes its document. +CREATE FUNCTION trigger_workspace_redaction_document_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + v_detection_id UUID; +BEGIN + IF TG_OP = 'DELETE' THEN + v_detection_id := OLD.detection_id; + ELSE + v_detection_id := NEW.detection_id; + END IF; + PERFORM refresh_workspace_document_state(t.input_document_id) + FROM workspace_detections t + WHERE t.id = v_detection_id; + RETURN NULL; +END; +$$; + +CREATE FUNCTION trigger_workspace_review_document_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + PERFORM refresh_workspace_document_state(OLD.document_id); + ELSE + PERFORM refresh_workspace_document_state(NEW.document_id); + END IF; + RETURN NULL; +END; +$$; + +-- An approval deleted along with its review finds no review here; the +-- review's own trigger refreshes its document. +CREATE FUNCTION trigger_workspace_review_approval_document_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + v_review_id UUID; +BEGIN + IF TG_OP = 'DELETE' THEN + v_review_id := OLD.review_id; + ELSE + v_review_id := NEW.review_id; + END IF; + PERFORM refresh_workspace_document_state(v.document_id) + FROM workspace_reviews v + WHERE v.id = v_review_id; + RETURN NULL; +END; +$$; + +CREATE TRIGGER workspace_documents_state + AFTER INSERT OR UPDATE OF kind, deleted_at ON workspace_documents + FOR EACH ROW EXECUTE FUNCTION trigger_workspace_document_state(); +CREATE TRIGGER workspace_detections_document_state + AFTER INSERT OR UPDATE OF status, deleted_at OR DELETE ON workspace_detections + FOR EACH ROW EXECUTE FUNCTION trigger_workspace_detection_document_state(); +CREATE TRIGGER workspace_redactions_document_state + AFTER INSERT OR UPDATE OF deleted_at OR DELETE ON workspace_redactions + FOR EACH ROW EXECUTE FUNCTION trigger_workspace_redaction_document_state(); +CREATE TRIGGER workspace_reviews_document_state + AFTER INSERT OR UPDATE OF review_status, redaction_id, deleted_at OR DELETE ON workspace_reviews + FOR EACH ROW EXECUTE FUNCTION trigger_workspace_review_document_state(); +CREATE TRIGGER workspace_review_approvals_document_state + AFTER INSERT OR UPDATE OR DELETE ON workspace_review_approvals + FOR EACH ROW EXECUTE FUNCTION trigger_workspace_review_approval_document_state(); + +-- Documents that existed before these triggers get their state now. +SELECT refresh_workspace_document_state(id) FROM workspace_documents; + -- Review lifecycle events feed the event sinks; each value is added by this -- migration (the one that introduces reviews). ALTER TYPE only adds labels here -- (no rows use them yet), so it stays transactional.