From 9cae04d33ac656e0f744d03be8f83c00dc24c7fb Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:06:52 +1300 Subject: [PATCH 1/7] app/: blob storage (S3: presigned uploads and downloads, checked by hash) and page texts stored once by hash --- app/Cargo.lock | 394 ++++++++++++++++++++++++++++++++++++- app/Cargo.toml | 6 + app/src/config.rs | 22 +++ app/src/lib.rs | 2 + app/src/storage/blobs.rs | 210 ++++++++++++++++++++ app/src/storage/mod.rs | 6 + app/src/storage/texts.rs | 55 ++++++ app/src/testing.rs | 1 + app/tests/storage_blobs.rs | 34 ++++ 9 files changed, 729 insertions(+), 1 deletion(-) create mode 100644 app/src/config.rs create mode 100644 app/src/storage/blobs.rs create mode 100644 app/src/storage/mod.rs create mode 100644 app/src/storage/texts.rs create mode 100644 app/tests/storage_blobs.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index 0435d0d0..a1b8589d 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -61,6 +61,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.22" @@ -253,7 +268,7 @@ dependencies = [ "addr2line", "cfg-if", "libc", - "miniz_oxide", + "miniz_oxide 0.9.1", "object", "rustc-demangle", "windows-link 0.2.1", @@ -344,18 +359,50 @@ dependencies = [ "cipher", ] +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bstr" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.2" @@ -646,6 +693,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + [[package]] name = "cronexpr" version = "1.7.2" @@ -801,6 +857,21 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", +] + [[package]] name = "either" version = "1.19.0" @@ -899,12 +970,32 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "find-msvc-tools" version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "flume" version = "0.12.0" @@ -1095,6 +1186,19 @@ version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" +[[package]] +name = "globset" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71217a07f20b48b4938c14203b77b610f8a7fa6762c3f75394a10c5f31e5aee0" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1445,6 +1549,32 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c8d2831f3eb9706eeac62164959a288f12c047a3c53b353c6c00d5d60eb5c7f" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1521,6 +1651,27 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "instant-xml" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0201956651e8e4b5a78978dd2840bbb3797227a262a74f47b3576ef053b53bb" +dependencies = [ + "instant-xml-macros", + "xmlparser", +] + +[[package]] +name = "instant-xml-macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f38f6d268cc5e23813c7b2b5bae70317626bf4a95c6de1136b96a221c45148f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "inventory" version = "0.3.25" @@ -2393,6 +2544,33 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "lopdf" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6ad532ff9262dd4bfd6e085400cbb39959d48cb8d08518b01b68f77bdf6feca" +dependencies = [ + "aes", + "bitflags", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom 0.4.3", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand 0.10.4", + "rangemap", + "sha2 0.11.3", + "stringprep", + "thiserror", + "weezl", +] + [[package]] name = "lru-slab" version = "0.1.3" @@ -2481,6 +2659,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -2488,6 +2676,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -2501,6 +2690,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -2524,6 +2723,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2750,6 +2958,19 @@ dependencies = [ "regex", ] +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polyval" version = "0.7.3" @@ -2811,6 +3032,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quinn" version = "0.11.12" @@ -2943,6 +3176,12 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rangemap" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2d43a8c8c74056248124068fde0df374d1ddf9039e747d190f01c36faeaab08" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2952,6 +3191,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "regex" version = "1.13.2" @@ -3197,6 +3456,25 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-s3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c091b4ca9c4d51c1a959fa746cc74f5a612a2242070a4ae7b14e22b04c71f8c" +dependencies = [ + "base64 0.23.1", + "hmac", + "instant-xml", + "jiff 1.1.0", + "md-5", + "percent-encoding", + "serde", + "serde_json", + "sha2 0.11.3", + "url", + "zeroize", +] + [[package]] name = "ryu" version = "1.0.23" @@ -3221,6 +3499,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -3286,6 +3589,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -3392,6 +3706,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3408,6 +3728,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "slab" version = "0.4.12" @@ -3429,6 +3755,17 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" +[[package]] +name = "snapshot-diff" +version = "0.1.0" +dependencies = [ + "regex", + "schemars", + "serde", + "serde_json", + "similar", +] + [[package]] name = "socket2" version = "0.6.5" @@ -4198,12 +4535,34 @@ version = "0.0.0" dependencies = [ "axum", "hex", + "image", "laravel-rust", "oauth-provider-laravel", + "reqwest 0.12.28", + "rusty-s3", "serde", "serde_json", "sha2 0.10.9", + "snapshot-diff", "tokio", + "visualci-core", +] + +[[package]] +name = "visualci-core" +version = "0.2.16" +dependencies = [ + "globset", + "hex", + "image", + "lopdf", + "schemars", + "serde", + "serde_json", + "sha2 0.10.9", + "similar", + "snapshot-diff", + "thiserror", ] [[package]] @@ -4346,6 +4705,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "whoami" version = "2.1.3" @@ -4567,6 +4932,12 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "yoke" version = "0.8.4" @@ -4686,8 +5057,29 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/app/Cargo.toml b/app/Cargo.toml index 550ccded..67d58e3d 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -32,6 +32,12 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +rusty-s3 = "0.12" +# VisualCI's own crates, shared with the CLI. +visualci-core = { path = "../crates/visualci-core" } +snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] diff --git a/app/src/config.rs b/app/src/config.rs new file mode 100644 index 00000000..46e4b1d0 --- /dev/null +++ b/app/src/config.rs @@ -0,0 +1,22 @@ +//! The app's own configuration sections, read from the environment. + +use laravel::config::Section; + +/// S3-compatible blob storage: R2 in production, RustFS or MinIO in development and CI. +#[derive(Clone, Debug, Section)] +pub struct Storage { + /// Such as `https://.r2.cloudflarestorage.com`, or `http://127.0.0.1:59000`. + #[env("S3_ENDPOINT", default = "http://127.0.0.1:59000")] + pub endpoint: String, + /// The endpoint clients upload to, when it differs from the one the server uses (a cluster-internal store). + #[env("S3_PUBLIC_ENDPOINT")] + pub public_endpoint: Option, + #[env("S3_BUCKET", default = "visualci")] + pub bucket: String, + #[env("S3_REGION", default = "auto")] + pub region: String, + #[env("S3_ACCESS_KEY_ID", default = "visualci")] + pub access_key_id: String, + #[env("S3_SECRET_ACCESS_KEY", default = "visualci-dev-secret")] + pub secret_access_key: String, +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 331bfb5e..a9cd9a1f 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,12 +1,14 @@ //! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900. pub mod auth; +pub mod config; pub mod forge; pub mod http; pub mod listeners; pub mod models; #[path = "../database/seeders/mod.rs"] pub mod seeders; +pub mod storage; pub mod testing; use laravel::Application; diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs new file mode 100644 index 00000000..ee678c80 --- /dev/null +++ b/app/src/storage/blobs.rs @@ -0,0 +1,210 @@ +//! Content-addressed blob storage on S3 (R2 in production, MinIO in development). Blobs live at `blobs/`. +//! Clients and renderers upload and download through presigned URLs, so bytes never pass through the app; the server +//! itself reads blobs (images to diff) the same way. + +use std::time::Duration; + +use rusty_s3::{Bucket, Credentials, S3Action, UrlStyle}; + +use crate::config::Storage; + +/// A storage error, as a message. +fn error(message: impl Into) -> laravel::Error { + laravel::Error::msg(message) +} + +type Result = laravel::Result; + +const URL_TTL: Duration = Duration::from_secs(3600); +/// An upload link lasts minutes, not an hour: the client uploads right after registering, and someone who got the link +/// for a hash before its real owner uploaded can't hold it long enough to overwrite the object later. Bytes are checked +/// against their hash whenever the server reads them, but a browser fetches blobs straight from the bucket. +const UPLOAD_TTL: Duration = Duration::from_secs(900); +/// The largest blob the server reads (and a client may declare): a PDF, screenshot or text file. +pub const MAX_BLOB_BYTES: u64 = 64 * 1024 * 1024; +/// Images embedded where VisualCI can't refresh the URL (a pull request comment, an agent's own comment): a week, the +/// longest a presigned URL can last. +const EMBED_TTL: Duration = Duration::from_secs(7 * 24 * 3600); + +#[derive(Clone)] +pub struct BlobStore { + bucket: Bucket, + public_bucket: Bucket, + credentials: Credentials, + http: reqwest::Client, +} + +pub fn key(sha256: &str) -> String { + format!("blobs/{sha256}") +} + +impl BlobStore { + /// # Errors + /// When an endpoint isn't a URL. + pub fn new(settings: &Storage) -> Result { + let bucket = |endpoint: &str| -> Result { + let url = endpoint.parse().map_err(|e| error(format!("storage endpoint {endpoint}: {e}")))?; + Bucket::new(url, UrlStyle::Path, settings.bucket.clone(), settings.region.clone()) + .map_err(|e| error(format!("storage bucket: {e}"))) + }; + Ok(Self { + bucket: bucket(&settings.endpoint)?, + public_bucket: bucket(settings.public_endpoint.as_deref().unwrap_or(&settings.endpoint))?, + credentials: Credentials::new(settings.access_key_id.clone(), settings.secret_access_key.clone()), + http: reqwest::Client::builder() + .timeout(Duration::from_secs(120)) + .build() + .map_err(|e| error(e.to_string()))?, + }) + } + + /// A URL a client can PUT the blob's bytes to. The client sends `Content-Type: content_type`. + pub fn upload_url(&self, sha256: &str) -> String { + self.public_bucket.put_object(Some(&self.credentials), &key(sha256)).sign(UPLOAD_TTL).to_string() + } + + /// A URL a browser or renderer can GET the blob from. + pub fn download_url(&self, sha256: &str) -> String { + self.public_bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL).to_string() + } + + /// A URL that keeps working for a week, for images embedded in a pull request comment or anywhere else VisualCI + /// can't hand out a fresh one. + pub fn embed_url(&self, sha256: &str) -> String { + self.public_bucket.get_object(Some(&self.credentials), &key(sha256)).sign(EMBED_TTL).to_string() + } + + /// Whether the blob is in the bucket. + /// + /// # Errors + /// When the store can't be reached. + pub async fn exists(&self, sha256: &str) -> Result { + let url = self.bucket.head_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let response = self.http.head(url).send().await.map_err(|e| error(e.to_string()))?; + Ok(response.status().is_success()) + } + + /// The blob's bytes, checked against its SHA-256: a client uploads under the hash it declares, so bytes that don't + /// match (another account's file put under someone else's hash) are never used. + /// + /// # Errors + /// When the blob is missing, doesn't match its hash, or the store can't be reached. + pub async fn get(&self, sha256: &str) -> Result> { + let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("blob {sha256}: HTTP {}", response.status()))); + } + if response.content_length().is_some_and(|n| n > MAX_BLOB_BYTES) { + return Err(error(format!("blob {sha256}: larger than {MAX_BLOB_BYTES} bytes"))); + } + let mut response = response; + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| error(e.to_string()))? { + if bytes.len() + chunk.len() > MAX_BLOB_BYTES as usize { + return Err(error(format!("blob {sha256}: larger than {MAX_BLOB_BYTES} bytes"))); + } + bytes.extend_from_slice(&chunk); + } + if visualci_core::sha256_hex(&bytes) != sha256 { + return Err(error(format!("blob {sha256}: its bytes don't match its SHA-256"))); + } + Ok(bytes) + } + + /// The stored object's size when it's there, no larger than [`MAX_BLOB_BYTES`], and its bytes hash to `sha256`, + /// read in chunks so a large PDF is never held whole; else `None`. An object that doesn't match is deleted, so the + /// hash can be uploaded again. (Not the size a client declared: whoever registers a hash first declares it.) + /// + /// # Errors + /// When the store can't be reached. + pub async fn verify(&self, sha256: &str) -> Result> { + use sha2::Digest; + let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let mut response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; + if response.status().as_u16() == 404 { + return Ok(None); + } + if !response.status().is_success() { + return Err(error(format!("blob {sha256}: HTTP {}", response.status()))); + } + let limit = MAX_BLOB_BYTES; + let mut hasher = sha2::Sha256::new(); + let mut read: u64 = 0; + let mut too_big = response.content_length().is_some_and(|n| n > limit); + while !too_big && let Some(chunk) = response.chunk().await.map_err(|e| error(e.to_string()))? { + read += chunk.len() as u64; + too_big = read > limit; + hasher.update(&chunk); + } + if !too_big && hex::encode(hasher.finalize()) == sha256 { + return Ok(Some(read)); + } + self.delete(sha256).await?; + Ok(None) + } + + /// Store bytes under their SHA-256 and return it. + /// + /// # Errors + /// When the store can't be reached. + pub async fn put(&self, bytes: Vec, content_type: &str) -> Result { + let sha256 = visualci_core::sha256_hex(&bytes); + let url = self.bucket.put_object(Some(&self.credentials), &key(&sha256)).sign(URL_TTL); + let response = self + .http + .put(url) + .header("content-type", content_type) + .body(bytes) + .send() + .await + .map_err(|e| error(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("storing blob {sha256}: HTTP {}", response.status()))); + } + Ok(sha256) + } + + /// Delete the blob from the store. Deleting one that isn't there succeeds. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn delete(&self, sha256: &str) -> Result<()> { + let url = self.bucket.delete_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let response = self.http.delete(url).send().await.map_err(|e| error(e.to_string()))?; + let status = response.status(); + if status.is_success() || status.as_u16() == 404 { + Ok(()) + } else { + Err(error(format!("deleting blob {sha256}: HTTP {status}"))) + } + } + + /// Create the bucket if it doesn't exist (development and tests; production buckets are made by Terraform). + /// + /// # Errors + /// When the store can't be reached. + pub async fn ensure_bucket(&self) -> Result<()> { + let url = self.bucket.create_bucket(&self.credentials).sign(URL_TTL); + let response = self.http.put(url).send().await.map_err(|e| error(e.to_string()))?; + let status = response.status(); + if status.is_success() || status.as_u16() == 409 { + Ok(()) + } else { + Err(error(format!("creating bucket: HTTP {status}"))) + } + } + + /// The store the configuration names (`S3_*`), built once per process. + /// + /// # Errors + /// When the endpoint or bucket can't be read. + pub fn current() -> Result { + static STORE: std::sync::OnceLock = std::sync::OnceLock::new(); + if let Some(store) = STORE.get() { + return Ok(store.clone()); + } + let store = Self::new(laravel::config().section::())?; + Ok(STORE.get_or_init(|| store).clone()) + } +} diff --git a/app/src/storage/mod.rs b/app/src/storage/mod.rs new file mode 100644 index 00000000..b0c6910e --- /dev/null +++ b/app/src/storage/mod.rs @@ -0,0 +1,6 @@ +//! Storage: content-addressed blobs and page texts. + +pub mod blobs; +pub mod texts; + +pub use blobs::BlobStore; diff --git a/app/src/storage/texts.rs b/app/src/storage/texts.rs new file mode 100644 index 00000000..897b0377 --- /dev/null +++ b/app/src/storage/texts.rs @@ -0,0 +1,55 @@ +//! Page text, stored once by its SHA-256 in `texts` (lz4-compressed). Page rows and render pages hold the hash. + +use std::collections::HashMap; + +use laravel::db; + +use crate::models::Text; + +/// The hash a text is stored under. +#[must_use] +pub fn sha(body: &str) -> String { + visualci_core::sha256_hex(body.as_bytes()) +} + +struct Row { + sha256: String, + body: String, +} + +/// Store texts, once each, and return their hashes in order. +/// +/// # Errors +/// On a database error. +pub async fn store(bodies: &[&str]) -> laravel::Result> { + let shas: Vec = bodies.iter().map(|b| sha(b)).collect(); + let mut unique: HashMap<&str, &str> = HashMap::new(); + for (s, b) in shas.iter().zip(bodies) { + unique.insert(s.as_str(), b); + } + let rows: Vec = unique.into_iter().map(|(s, b)| Row { sha256: s.to_string(), body: b.to_string() }).collect(); + // Two parameters a row, well under PostgreSQL's 65,535. + for chunk in rows.chunks(10_000) { + db::query!("INSERT INTO texts (sha256, body) VALUES {...chunk(sha256, body)} ON CONFLICT DO NOTHING") + .insert() + .await?; + } + Ok(shas) +} + +/// The texts stored under these hashes. +/// +/// # Errors +/// On a database error. +pub async fn load(shas: &[String]) -> laravel::Result> { + let mut wanted: Vec<&str> = shas.iter().filter(|s| !s.is_empty()).map(String::as_str).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let mut out = HashMap::new(); + for chunk in wanted.chunks(10_000) { + for t in Text::query().filter(Text::sha256.is_in(chunk.to_vec())).get().await? { + out.insert(t.sha256, t.body); + } + } + Ok(out) +} diff --git a/app/src/testing.rs b/app/src/testing.rs index 66a1fa38..bac13b31 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -30,6 +30,7 @@ pub fn configure() -> ApplicationBuilder { ("SESSION_DRIVER", "memory"), ("WORKFLOW_STORE", "memory"), ("DB_CONNECTION", "pgsql"), + ("S3_BUCKET", "visualci-test"), ]) .with_env("DATABASE_URL", url) .refresh_database() diff --git a/app/tests/storage_blobs.rs b/app/tests/storage_blobs.rs new file mode 100644 index 00000000..7dd4b19d --- /dev/null +++ b/app/tests/storage_blobs.rs @@ -0,0 +1,34 @@ +//! Blob storage (S3: RustFS or MinIO in tests) and page texts. + +use app::storage::{BlobStore, texts}; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn texts_are_stored_once_by_hash(_app: Application) -> laravel::Result<()> { + let shas = texts::store(&["page one", "page two", "page one"]).await?; + assert_eq!(shas[0], shas[2]); + assert_eq!(shas[0], texts::sha("page one")); + let count: Option = laravel::db::query!("SELECT COUNT(*) FROM texts").scalar().await?; + assert_eq!(count, Some(2)); + let loaded = texts::load(&shas).await?; + assert_eq!(loaded[&shas[1]], "page two"); + // Storing them again changes nothing. + texts::store(&["page two"]).await?; + let count: Option = laravel::db::query!("SELECT COUNT(*) FROM texts").scalar().await?; + assert_eq!(count, Some(2)); + Ok(()) +} + +#[laravel::test] +async fn blobs_round_trip_and_are_checked_by_hash(_app: Application) -> laravel::Result<()> { + let store = BlobStore::current()?; + store.ensure_bucket().await?; + let sha = store.put(b"hello blob".to_vec(), "text/plain").await?; + assert_eq!(store.get(&sha).await?, b"hello blob"); + assert!(store.exists(&sha).await?); + assert_eq!(store.verify(&sha).await?, Some(10)); + assert!(store.upload_url(&sha).contains(&format!("blobs/{sha}"))); + store.delete(&sha).await?; + assert!(!store.exists(&sha).await?); + Ok(()) +} From 10f42c303b31a8dba4d41c20c6a2614270e225bf Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:08:18 +1300 Subject: [PATCH 2/7] CI: the app job runs RustFS, so the storage tests run --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d487609..710ef512 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,6 +51,11 @@ jobs: working-directory: app steps: - uses: actions/checkout@v4 + # S3 storage for the blob tests: RustFS, as the visual job uses. + - run: | + docker run -d --name s3 -p 59000:9000 \ + -e RUSTFS_ACCESS_KEY=visualci -e RUSTFS_SECRET_KEY=visualci-dev-secret rustfs/rustfs:1.0.6 + for _ in $(seq 1 30); do curl -s -o /dev/null http://127.0.0.1:59000/ && break; sleep 1; done - uses: Swatinem/rust-cache@v2 with: workspaces: app From 8043070896c6bc1570bbc7d2fff1b2c4f2016370 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:09:25 +1300 Subject: [PATCH 3/7] AGENTS.md: a test never skips quietly; it fails naming the missing service --- AGENTS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index ea0db5a3..763d4ba3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,9 @@ design is in `docs/design.md`; read it before changing the architecture, and upd reached VisualCI instead). Production listens on 5150 inside its cluster, which is separate. - Any UI design (the landing page, the review UI, emails): load the `hallmark` skill and the frontend design skills before writing markup or CSS. +- A test never skips quietly. When a service it needs (the blob store, Postgres, a forge stub) is missing, it fails + with a message naming the service: a test that returns early passes in CI. (3 Dec 2026: the server tests that need + blobs returned early in CI's `test` job, which runs no S3, and passed without checking anything.) - Every background process (workers, renderers, scheduled jobs) ships with a health check or heartbeat that checks the work is done, not just that the process is up, in the same change. - Production reads its secrets from 1Password through the cluster's ExternalSecrets (talira-ai/infra, From a5badaf25c0650a72c0a421159c55688645e8220 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:10:56 +1300 Subject: [PATCH 4/7] app/: tests get the blob store through fixtures::blob_store, which fails naming the store when it isn't running --- app/src/testing.rs | 14 ++++++++++++++ app/tests/storage_blobs.rs | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/app/src/testing.rs b/app/src/testing.rs index bac13b31..4020d1ca 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -54,6 +54,20 @@ pub mod fixtures { create!(Project { pid: laravel::str::uuid7(), organization_id: organization.id, slug: slug, name: slug }).await } + /// The blob store, with its bucket made. Fails, naming the store, when it isn't running: a test never skips. + /// + /// # Errors + /// When the store (`S3_ENDPOINT`, RustFS or MinIO on port 59000 in development and CI) isn't reachable. + pub async fn blob_store() -> laravel::Result { + let store = crate::storage::BlobStore::current()?; + store.ensure_bucket().await.map_err(|e| { + laravel::Error::msg(format!( + "the blob store isn't reachable (S3_ENDPOINT, RustFS or MinIO on 127.0.0.1:59000 in CI): {e}" + )) + })?; + Ok(store) + } + /// `role` is `admin`, `member` or `read`. /// /// # Errors diff --git a/app/tests/storage_blobs.rs b/app/tests/storage_blobs.rs index 7dd4b19d..34e9a117 100644 --- a/app/tests/storage_blobs.rs +++ b/app/tests/storage_blobs.rs @@ -1,6 +1,7 @@ //! Blob storage (S3: RustFS or MinIO in tests) and page texts. -use app::storage::{BlobStore, texts}; +use app::storage::texts; +use app::testing::fixtures; use laravel::testing::prelude::*; #[laravel::test] @@ -21,8 +22,7 @@ async fn texts_are_stored_once_by_hash(_app: Application) -> laravel::Result<()> #[laravel::test] async fn blobs_round_trip_and_are_checked_by_hash(_app: Application) -> laravel::Result<()> { - let store = BlobStore::current()?; - store.ensure_bucket().await?; + let store = fixtures::blob_store().await?; let sha = store.put(b"hello blob".to_vec(), "text/plain").await?; assert_eq!(store.get(&sha).await?, b"hello blob"); assert!(store.exists(&sha).await?); From 6dc66431e9e2be1482451d0cc070df33a6c7115e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:30:13 +1300 Subject: [PATCH 5/7] app/: Cargo.lock for the storage dependencies --- app/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Cargo.lock b/app/Cargo.lock index a1b8589d..6ed23918 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4550,7 +4550,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.16" +version = "0.2.17" dependencies = [ "globset", "hex", From 68a31abb087f852fb54699c4a7883563db97a71c Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:53:16 +1300 Subject: [PATCH 6/7] app/: a blob's key is only ever a SHA-256 (64 lowercase hex characters), so no crafted hash names another key or presigned URL; the storage settings are required, with no development fallback --- app/src/config.rs | 11 ++++++----- app/src/storage/blobs.rs | 36 +++++++++++++++++++++++------------- app/src/testing.rs | 4 ++++ app/tests/storage_blobs.rs | 17 ++++++++++++++++- 4 files changed, 49 insertions(+), 19 deletions(-) diff --git a/app/src/config.rs b/app/src/config.rs index 46e4b1d0..635ffca6 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -2,21 +2,22 @@ use laravel::config::Section; -/// S3-compatible blob storage: R2 in production, RustFS or MinIO in development and CI. +/// S3-compatible blob storage: R2 in production, RustFS or MinIO in development and CI. Every setting is required: +/// the app doesn't start without them, so production never falls back to a development store or its credentials. #[derive(Clone, Debug, Section)] pub struct Storage { /// Such as `https://.r2.cloudflarestorage.com`, or `http://127.0.0.1:59000`. - #[env("S3_ENDPOINT", default = "http://127.0.0.1:59000")] + #[env("S3_ENDPOINT", required)] pub endpoint: String, /// The endpoint clients upload to, when it differs from the one the server uses (a cluster-internal store). #[env("S3_PUBLIC_ENDPOINT")] pub public_endpoint: Option, - #[env("S3_BUCKET", default = "visualci")] + #[env("S3_BUCKET", required)] pub bucket: String, #[env("S3_REGION", default = "auto")] pub region: String, - #[env("S3_ACCESS_KEY_ID", default = "visualci")] + #[env("S3_ACCESS_KEY_ID", required)] pub access_key_id: String, - #[env("S3_SECRET_ACCESS_KEY", default = "visualci-dev-secret")] + #[env("S3_SECRET_ACCESS_KEY", required)] pub secret_access_key: String, } diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs index ee678c80..4769e558 100644 --- a/app/src/storage/blobs.rs +++ b/app/src/storage/blobs.rs @@ -34,8 +34,18 @@ pub struct BlobStore { http: reqwest::Client, } -pub fn key(sha256: &str) -> String { - format!("blobs/{sha256}") +pub fn key(sha256: &str) -> Result { + if !valid_sha256(sha256) { + return Err(error(format!("not a SHA-256 (64 lowercase hex characters): {sha256:?}"))); + } + Ok(format!("blobs/{sha256}")) +} + +/// Whether a string is a SHA-256 as blobs are named: exactly 64 lowercase hex characters. Anything else (`../x`, `a?b`) +/// would name another key, or change a presigned URL. +#[must_use] +pub fn valid_sha256(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } impl BlobStore { @@ -59,19 +69,19 @@ impl BlobStore { } /// A URL a client can PUT the blob's bytes to. The client sends `Content-Type: content_type`. - pub fn upload_url(&self, sha256: &str) -> String { - self.public_bucket.put_object(Some(&self.credentials), &key(sha256)).sign(UPLOAD_TTL).to_string() + pub fn upload_url(&self, sha256: &str) -> Result { + Ok(self.public_bucket.put_object(Some(&self.credentials), &key(sha256)?).sign(UPLOAD_TTL).to_string()) } /// A URL a browser or renderer can GET the blob from. - pub fn download_url(&self, sha256: &str) -> String { - self.public_bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL).to_string() + pub fn download_url(&self, sha256: &str) -> Result { + Ok(self.public_bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL).to_string()) } /// A URL that keeps working for a week, for images embedded in a pull request comment or anywhere else VisualCI /// can't hand out a fresh one. - pub fn embed_url(&self, sha256: &str) -> String { - self.public_bucket.get_object(Some(&self.credentials), &key(sha256)).sign(EMBED_TTL).to_string() + pub fn embed_url(&self, sha256: &str) -> Result { + Ok(self.public_bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(EMBED_TTL).to_string()) } /// Whether the blob is in the bucket. @@ -79,7 +89,7 @@ impl BlobStore { /// # Errors /// When the store can't be reached. pub async fn exists(&self, sha256: &str) -> Result { - let url = self.bucket.head_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let url = self.bucket.head_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); let response = self.http.head(url).send().await.map_err(|e| error(e.to_string()))?; Ok(response.status().is_success()) } @@ -90,7 +100,7 @@ impl BlobStore { /// # Errors /// When the blob is missing, doesn't match its hash, or the store can't be reached. pub async fn get(&self, sha256: &str) -> Result> { - let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); let response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; if !response.status().is_success() { return Err(error(format!("blob {sha256}: HTTP {}", response.status()))); @@ -120,7 +130,7 @@ impl BlobStore { /// When the store can't be reached. pub async fn verify(&self, sha256: &str) -> Result> { use sha2::Digest; - let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); let mut response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; if response.status().as_u16() == 404 { return Ok(None); @@ -150,7 +160,7 @@ impl BlobStore { /// When the store can't be reached. pub async fn put(&self, bytes: Vec, content_type: &str) -> Result { let sha256 = visualci_core::sha256_hex(&bytes); - let url = self.bucket.put_object(Some(&self.credentials), &key(&sha256)).sign(URL_TTL); + let url = self.bucket.put_object(Some(&self.credentials), &key(&sha256)?).sign(URL_TTL); let response = self .http .put(url) @@ -170,7 +180,7 @@ impl BlobStore { /// # Errors /// When the store can't be reached or refuses. pub async fn delete(&self, sha256: &str) -> Result<()> { - let url = self.bucket.delete_object(Some(&self.credentials), &key(sha256)).sign(URL_TTL); + let url = self.bucket.delete_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); let response = self.http.delete(url).send().await.map_err(|e| error(e.to_string()))?; let status = response.status(); if status.is_success() || status.as_u16() == 404 { diff --git a/app/src/testing.rs b/app/src/testing.rs index 4020d1ca..1474fca0 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -30,7 +30,11 @@ pub fn configure() -> ApplicationBuilder { ("SESSION_DRIVER", "memory"), ("WORKFLOW_STORE", "memory"), ("DB_CONNECTION", "pgsql"), + // The test blob store: RustFS in CI, MinIO on a development machine, both on port 59000. + ("S3_ENDPOINT", "http://127.0.0.1:59000"), ("S3_BUCKET", "visualci-test"), + ("S3_ACCESS_KEY_ID", "visualci"), + ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), ]) .with_env("DATABASE_URL", url) .refresh_database() diff --git a/app/tests/storage_blobs.rs b/app/tests/storage_blobs.rs index 34e9a117..45d1f939 100644 --- a/app/tests/storage_blobs.rs +++ b/app/tests/storage_blobs.rs @@ -27,8 +27,23 @@ async fn blobs_round_trip_and_are_checked_by_hash(_app: Application) -> laravel: assert_eq!(store.get(&sha).await?, b"hello blob"); assert!(store.exists(&sha).await?); assert_eq!(store.verify(&sha).await?, Some(10)); - assert!(store.upload_url(&sha).contains(&format!("blobs/{sha}"))); + assert!(store.upload_url(&sha)?.contains(&format!("blobs/{sha}"))); store.delete(&sha).await?; assert!(!store.exists(&sha).await?); Ok(()) } + +#[laravel::test] +async fn only_a_sha256_names_a_blob(_app: Application) -> laravel::Result<()> { + use app::storage::blobs::{key, valid_sha256}; + let good = "a".repeat(64); + assert_eq!(key(&good)?, format!("blobs/{good}")); + for bad in ["../x", "a?b", &"A".repeat(64), &"a".repeat(63), &format!("{}/", "a".repeat(63)), ""] { + assert!(!valid_sha256(bad), "{bad:?}"); + assert!(key(bad).is_err(), "{bad:?}"); + } + let store = fixtures::blob_store().await?; + assert!(store.upload_url("../x").is_err(), "no presigned URL for another key"); + assert!(store.get("a?b").await.is_err()); + Ok(()) +} From 163eb5185d68a6a5f083d5f23a816e5172ea4c4f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:14:57 +1300 Subject: [PATCH 7/7] app/: the blob store is one per application, from the container, so its HTTP connections belong to that application's runtime (a process-wide client failed with 'error sending request' once a test's runtime ended) --- app/src/storage/blobs.rs | 18 ++++++++++-------- app/src/testing.rs | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs index 4769e558..35db6c83 100644 --- a/app/src/storage/blobs.rs +++ b/app/src/storage/blobs.rs @@ -205,16 +205,18 @@ impl BlobStore { } } - /// The store the configuration names (`S3_*`), built once per process. + /// The application's store (`S3_*`): one per application, from the container, so its HTTP connections belong to + /// the application's runtime (each test has its own). /// /// # Errors /// When the endpoint or bucket can't be read. - pub fn current() -> Result { - static STORE: std::sync::OnceLock = std::sync::OnceLock::new(); - if let Some(store) = STORE.get() { - return Ok(store.clone()); - } - let store = Self::new(laravel::config().section::())?; - Ok(STORE.get_or_init(|| store).clone()) + pub async fn current() -> Result { + Ok(BlobStore::clone(&*laravel::resolve::().await?)) } } + +/// The store's factory: the container builds it once per application. +#[laravel::container::singleton] +async fn blob_store(config: laravel::config::Section) -> laravel::Result { + BlobStore::new(&config) +} diff --git a/app/src/testing.rs b/app/src/testing.rs index 1474fca0..d629b476 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -63,7 +63,7 @@ pub mod fixtures { /// # Errors /// When the store (`S3_ENDPOINT`, RustFS or MinIO on port 59000 in development and CI) isn't reachable. pub async fn blob_store() -> laravel::Result { - let store = crate::storage::BlobStore::current()?; + let store = crate::storage::BlobStore::current().await?; store.ensure_bucket().await.map_err(|e| { laravel::Error::msg(format!( "the blob store isn't reachable (S3_ENDPOINT, RustFS or MinIO on 127.0.0.1:59000 in CI): {e}"