From 7fd2614a53295cad1bbd2a62cc8fab6c39a7ff50 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 17:36:27 +0100 Subject: [PATCH 1/3] Move to Rust 1.100.0 and sqlx 0.9 sqlx 0.9 needs Rust 1.94 or later. Statements built from constant fragments are asserted safe in one helper; values stay bound. The rsa advisory no longer applies. libsqlite3-sys moves to 0.37, the newest sqlx 0.9 allows; the SQLite advisory stays ignored until sqlx allows 0.39. --- .cargo/audit.toml | 15 +- Cargo.lock | 449 ++++++------------------ Cargo.toml | 4 +- Dockerfile | 2 +- crates/fleet-server/src/db.rs | 20 +- crates/fleet-server/tests/migrations.rs | 23 +- rust-toolchain.toml | 2 +- 7 files changed, 146 insertions(+), 369 deletions(-) diff --git a/.cargo/audit.toml b/.cargo/audit.toml index 9acdb3a..f622eb5 100644 --- a/.cargo/audit.toml +++ b/.cargo/audit.toml @@ -2,14 +2,11 @@ # condition; revisit them whenever dependencies or the toolchain change. [advisories] ignore = [ - # rsa (Marvin attack). Listed in Cargo.lock only because sqlx-macros-core - # declares optional MySQL support; it is never compiled - # (`cargo tree -i rsa` prints nothing). Remove with the sqlx 0.9 upgrade. - "RUSTSEC-2023-0071", - # libsqlite3-sys bundles SQLite < 3.54 (stale page-cache bytes when an - # attacker-written database and -wal file are opened together). SQLite is - # only used for local development and tests, on files the service creates - # itself. The fix needs sqlx 0.9, which requires Rust 1.94; this workspace - # is pinned to Rust 1.93.1 to match SendBox. Remove when the toolchain moves. + # libsqlite3-sys bundles SQLite older than the fix (stale page-cache bytes + # when an attacker-written database and -wal file are opened together). + # The fix is libsqlite3-sys 0.39, but sqlx-sqlite 0.9.0 requires < 0.38, so + # 0.37 is the newest usable release. SQLite is only used for local + # development and tests, on files the service creates itself; production + # uses PostgreSQL. Remove when an sqlx release allows libsqlite3-sys 0.39. "RUSTSEC-2026-0459", ] diff --git a/Cargo.lock b/Cargo.lock index c0c368d..5a0a424 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -33,7 +33,7 @@ dependencies = [ "bytestring", "derive_more", "encoding_rs", - "foldhash 0.2.0", + "foldhash", "futures-core", "http", "httparse", @@ -140,7 +140,7 @@ dependencies = [ "cfg-if", "derive_more", "encoding_rs", - "foldhash 0.2.0", + "foldhash", "futures-core", "futures-util", "impl-more", @@ -330,6 +330,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "clap" version = "4.6.7" @@ -370,6 +381,12 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -479,6 +496,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -513,7 +539,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", "zeroize", ] @@ -556,9 +581,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid 0.9.6", "crypto-common 0.1.7", - "subtle", ] [[package]] @@ -570,6 +593,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid 0.10.3", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -649,18 +673,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "etcetera" -version = "0.8.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" dependencies = [ "cfg-if", - "home", - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -719,9 +742,9 @@ dependencies = [ [[package]] name = "flume" -version = "0.11.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" dependencies = [ "futures-core", "futures-sink", @@ -734,12 +757,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" @@ -856,17 +873,18 @@ dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core 0.10.1", ] [[package]] name = "hashbrown" -version = "0.15.5" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash 0.1.5", + "foldhash", ] [[package]] @@ -877,11 +895,11 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "hashlink" -version = "0.10.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" dependencies = [ - "hashbrown 0.15.5", + "hashbrown 0.16.1", ] [[package]] @@ -898,29 +916,20 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hkdf" -version = "0.12.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ "hmac", ] [[package]] name = "hmac" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "home" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" -dependencies = [ - "windows-sys 0.61.2", + "digest 0.11.3", ] [[package]] @@ -1098,9 +1107,6 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" -dependencies = [ - "spin", -] [[package]] name = "libc" @@ -1108,29 +1114,11 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "libredox" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" -dependencies = [ - "bitflags", - "libc", - "plain", - "redox_syscall 0.9.5", -] - [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" dependencies = [ "cc", "pkg-config", @@ -1187,12 +1175,12 @@ dependencies = [ [[package]] name = "md-5" -version = "0.10.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -1234,47 +1222,12 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "num-bigint-dig" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" -dependencies = [ - "lazy_static", - "libm", - "num-integer", - "num-iter", - "num-traits", - "rand", - "smallvec", - "zeroize", -] - [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-iter" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" -dependencies = [ - "num-integer", - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -1282,7 +1235,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", - "libm", ] [[package]] @@ -1321,20 +1273,11 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.18", + "redox_syscall", "smallvec", "windows-link", ] -[[package]] -name = "pem-rfc7468" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" -dependencies = [ - "base64ct", -] - [[package]] name = "percent-encoding" version = "2.3.2" @@ -1347,17 +1290,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pkcs1" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" -dependencies = [ - "der", - "pkcs8", - "spki", -] - [[package]] name = "pkcs8" version = "0.10.2" @@ -1374,12 +1306,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[package]] -name = "plain" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" - [[package]] name = "potential_utf" version = "0.1.6" @@ -1395,15 +1321,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -1430,23 +1347,13 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ - "ppv-lite86", - "rand_core", + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1459,19 +1366,16 @@ dependencies = [ ] [[package]] -name = "redox_syscall" -version = "0.5.18" +name = "rand_core" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "redox_syscall" -version = "0.9.5" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ "bitflags", ] @@ -1513,26 +1417,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rsa" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" -dependencies = [ - "const-oid 0.9.6", - "digest 0.10.7", - "num-bigint-dig", - "num-integer", - "num-traits", - "pkcs1", - "pkcs8", - "rand_core", - "signature", - "spki", - "subtle", - "zeroize", -] - [[package]] name = "rustc_version" version = "0.4.1" @@ -1552,7 +1436,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1622,7 +1506,6 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" dependencies = [ "serde", ] @@ -1630,7 +1513,6 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" dependencies = [ "sendbox-core", "serde", @@ -1644,7 +1526,6 @@ dependencies = [ [[package]] name = "sendbox-security" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" dependencies = [ "base64", "ed25519-dalek", @@ -1726,13 +1607,13 @@ dependencies = [ [[package]] name = "sha1" -version = "0.10.7" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1788,8 +1669,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "digest 0.10.7", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1844,9 +1724,9 @@ dependencies = [ [[package]] name = "sqlx" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" dependencies = [ "sqlx-core", "sqlx-macros", @@ -1857,12 +1737,13 @@ dependencies = [ [[package]] name = "sqlx-core" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" dependencies = [ "base64", "bytes", + "cfg-if", "crc", "crossbeam-queue", "either", @@ -1871,12 +1752,11 @@ dependencies = [ "futures-intrusive", "futures-io", "futures-util", - "hashbrown 0.15.5", + "hashbrown 0.16.1", "hashlink", "indexmap", "log", "memchr", - "once_cell", "percent-encoding", "rustls", "serde", @@ -1888,14 +1768,14 @@ dependencies = [ "tokio-stream", "tracing", "url", - "webpki-roots 0.26.11", + "webpki-roots", ] [[package]] name = "sqlx-macros" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" dependencies = [ "proc-macro2", "quote", @@ -1906,15 +1786,15 @@ dependencies = [ [[package]] name = "sqlx-macros-core" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3" dependencies = [ + "cfg-if", "dotenvy", "either", "heck", "hex", - "once_cell", "proc-macro2", "quote", "serde", @@ -1924,56 +1804,42 @@ dependencies = [ "sqlx-postgres", "sqlx-sqlite", "syn 2.0.119", + "thiserror", "tokio", "url", ] [[package]] name = "sqlx-mysql" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27" dependencies = [ - "atoi", - "base64", "bitflags", "byteorder", "bytes", "crc", - "digest 0.10.7", + "digest 0.11.3", "dotenvy", "either", - "futures-channel", "futures-core", - "futures-io", "futures-util", "generic-array", - "hex", - "hkdf", - "hmac", - "itoa", "log", - "md-5", - "memchr", - "once_cell", "percent-encoding", - "rand", - "rsa", + "serde", "sha1", - "sha2 0.10.9", - "smallvec", + "sha2 0.11.1", "sqlx-core", - "stringprep", "thiserror", "tracing", - "whoami", ] [[package]] name = "sqlx-postgres" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" dependencies = [ "atoi", "base64", @@ -1988,16 +1854,14 @@ dependencies = [ "hex", "hkdf", "hmac", - "home", "itoa", "log", "md-5", "memchr", - "once_cell", "rand", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.1", "smallvec", "sqlx-core", "stringprep", @@ -2008,12 +1872,13 @@ dependencies = [ [[package]] name = "sqlx-sqlite" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" dependencies = [ "atoi", "flume", + "form_urlencoded", "futures-channel", "futures-core", "futures-executor", @@ -2023,7 +1888,6 @@ dependencies = [ "log", "percent-encoding", "serde", - "serde_urlencoded", "sqlx-core", "thiserror", "tracing", @@ -2108,7 +1972,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2435,21 +2299,6 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" -[[package]] -name = "wasite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" - -[[package]] -name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.12", -] - [[package]] name = "webpki-roots" version = "1.0.12" @@ -2461,13 +2310,9 @@ dependencies = [ [[package]] name = "whoami" -version = "1.6.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" -dependencies = [ - "libredox", - "wasite", -] +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" [[package]] name = "windows-link" @@ -2475,22 +2320,13 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -2502,67 +2338,34 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -2575,48 +2378,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -2665,26 +2444,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "zerocopy" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "zerofrom" version = "0.1.8" diff --git a/Cargo.toml b/Cargo.toml index a780504..99a5daa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "3" [workspace.package] version = "0.1.0" edition = "2024" -rust-version = "1.93.1" +rust-version = "1.100.0" license = "Apache-2.0" repository = "https://github.com/mbianchidev/sendbox-fleet" publish = false @@ -23,7 +23,7 @@ serde_yaml_ng = { package = "yaml_serde", version = "0.10.7" } sha2 = "0.11.0" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" -sqlx = { version = "0.8.6", default-features = false, features = ["macros", "migrate", "postgres", "runtime-tokio", "sqlite", "tls-rustls"] } +sqlx = { version = "0.9.0", default-features = false, features = ["macros", "migrate", "postgres", "runtime-tokio", "sqlite-bundled", "tls-rustls"] } tempfile = "3.27.0" thiserror = "2.0.21" time = "0.3.47" diff --git a/Dockerfile b/Dockerfile index 5931bcd..7a5be6b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ # Multi-stage build for the sendbox-fleet server. # Base images are pinned by digest; update tag and digest together. -FROM rust:1.93.1-slim-trixie@sha256:c0a38f5662afdb298898da1d70b909af4bda4e0acff2dc52aea6360a9b9c6956 AS build +FROM rust:1.100.0-slim-trixie@sha256:e9d95b74296f7126a83ae3d041aeaba1ff4c478f13abc5cc034fcf7c131c3d4a AS build WORKDIR /src # rust-toolchain.toml is intentionally not copied: the image already provides # the pinned toolchain and the build does not need clippy or rustfmt. diff --git a/crates/fleet-server/src/db.rs b/crates/fleet-server/src/db.rs index fe61893..aacdcd7 100644 --- a/crates/fleet-server/src/db.rs +++ b/crates/fleet-server/src/db.rs @@ -161,13 +161,13 @@ impl Database { /// Runs a read-only query outside a transaction. pub async fn fetch_all(&self, sql: &str, args: &[Arg]) -> Result, DbError> { match self { - Self::Postgres(pool) => Ok(bind_pg(sqlx::query(sql), args) + Self::Postgres(pool) => Ok(bind_pg(sqlx::query(statement(sql)), args) .fetch_all(pool) .await? .into_iter() .map(Row::Postgres) .collect()), - Self::Sqlite(pool) => Ok(bind_sqlite(sqlx::query(sql), args) + Self::Sqlite(pool) => Ok(bind_sqlite(sqlx::query(statement(sql)), args) .fetch_all(pool) .await? .into_iter() @@ -246,8 +246,14 @@ impl From> for Arg { } } +/// Statements are assembled only from constant SQL fragments and generated +/// placeholders; every value is bound as a parameter, never interpolated. +fn statement(sql: &str) -> sqlx::AssertSqlSafe { + sqlx::AssertSqlSafe(sql.to_owned()) +} + type PgQuery<'q> = sqlx::query::Query<'q, Postgres, sqlx::postgres::PgArguments>; -type SqliteQuery<'q> = sqlx::query::Query<'q, Sqlite, sqlx::sqlite::SqliteArguments<'q>>; +type SqliteQuery<'q> = sqlx::query::Query<'q, Sqlite, sqlx::sqlite::SqliteArguments>; fn bind_pg<'q>(mut query: PgQuery<'q>, args: &'q [Arg]) -> PgQuery<'q> { for arg in args { @@ -296,11 +302,11 @@ impl Tx { /// Executes a statement and returns the number of affected rows. pub async fn execute(&mut self, sql: &str, args: &[Arg]) -> Result { Ok(match self { - Self::Postgres(transaction) => bind_pg(sqlx::query(sql), args) + Self::Postgres(transaction) => bind_pg(sqlx::query(statement(sql)), args) .execute(&mut **transaction) .await? .rows_affected(), - Self::Sqlite(transaction) => bind_sqlite(sqlx::query(sql), args) + Self::Sqlite(transaction) => bind_sqlite(sqlx::query(statement(sql)), args) .execute(&mut **transaction) .await? .rows_affected(), @@ -309,13 +315,13 @@ impl Tx { pub async fn fetch_all(&mut self, sql: &str, args: &[Arg]) -> Result, DbError> { Ok(match self { - Self::Postgres(transaction) => bind_pg(sqlx::query(sql), args) + Self::Postgres(transaction) => bind_pg(sqlx::query(statement(sql)), args) .fetch_all(&mut **transaction) .await? .into_iter() .map(Row::Postgres) .collect(), - Self::Sqlite(transaction) => bind_sqlite(sqlx::query(sql), args) + Self::Sqlite(transaction) => bind_sqlite(sqlx::query(statement(sql)), args) .fetch_all(&mut **transaction) .await? .into_iter() diff --git a/crates/fleet-server/tests/migrations.rs b/crates/fleet-server/tests/migrations.rs index b65d48a..3c97b37 100644 --- a/crates/fleet-server/tests/migrations.rs +++ b/crates/fleet-server/tests/migrations.rs @@ -7,6 +7,7 @@ use fleet_server::config::{DatabaseKind, DatabaseUrl}; use fleet_server::db::Database; +use sqlx::AssertSqlSafe; const TABLES: [&str; 12] = [ "api_tokens", @@ -53,16 +54,30 @@ async fn database() -> Database { async fn exec(database: &Database, sql: &str) -> Result<(), sqlx::Error> { match database { - Database::Postgres(pool) => sqlx::raw_sql(sql).execute(pool).await.map(drop), - Database::Sqlite(pool) => sqlx::raw_sql(sql).execute(pool).await.map(drop), + Database::Postgres(pool) => sqlx::raw_sql(AssertSqlSafe(sql.to_owned())) + .execute(pool) + .await + .map(drop), + Database::Sqlite(pool) => sqlx::raw_sql(AssertSqlSafe(sql.to_owned())) + .execute(pool) + .await + .map(drop), } } async fn count(database: &Database, table: &str) -> i64 { let sql = format!("SELECT COUNT(*) FROM {table}"); match database { - Database::Postgres(pool) => sqlx::query_scalar::<_, i64>(&sql).fetch_one(pool).await, - Database::Sqlite(pool) => sqlx::query_scalar::<_, i64>(&sql).fetch_one(pool).await, + Database::Postgres(pool) => { + sqlx::query_scalar::<_, i64>(AssertSqlSafe(sql.clone())) + .fetch_one(pool) + .await + } + Database::Sqlite(pool) => { + sqlx::query_scalar::<_, i64>(AssertSqlSafe(sql.clone())) + .fetch_one(pool) + .await + } } .unwrap() } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f8800ea..b17b266 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.93.1" +channel = "1.100.0" components = ["clippy", "rustfmt"] profile = "minimal" From 94cee06a16134448e916c292f01248733a32b976 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 18:02:27 +0100 Subject: [PATCH 2/3] Complete the fleet: identity providers, token exchange, outcomes, anchoring, operations - Sign in with any OpenID Connect issuer (people and CI such as GitHub Actions). JWTs are verified with ring against the issuer's JWKS, with exact issuer and audience, required claims, verified email, and optional auto-provisioning without roles. Rejection reasons are logged. - POST/GET/DELETE /v1/tokens: exchange a sign-in for a short-lived service token, list and revoke tokens. Service tokens cannot mint more. - POST /v1/grants/{id}:outcome records host-reported stream outcomes. - Signed audit heads (GET /v1/audit/head), periodic anchoring outside the database, and admin audit keygen/anchor/verify. - Per-principal and per-peer rate limits with Retry-After, Prometheus metrics on a separate listener, size plus daily log rotation. - FLEET_MIGRATE=false with admin migrate, least-privilege PostgreSQL roles (deploy/postgres/roles.sql), CA certificates in the image. - Pin the contract to the sendbox PR branch with the new api types. - Docs: README status, deployment guide, roadmap, architecture, contract, threat model, development. --- .env.example | 20 + Cargo.lock | 523 +++++++++- Cargo.toml | 11 +- Dockerfile | 9 +- README.md | 16 +- crates/fleet-server/Cargo.toml | 5 + crates/fleet-server/src/admin.rs | 163 ++- crates/fleet-server/src/anchor.rs | 364 +++++++ crates/fleet-server/src/audit.rs | 1 + crates/fleet-server/src/auth.rs | 205 +++- crates/fleet-server/src/config.rs | 183 ++++ crates/fleet-server/src/db.rs | 44 + crates/fleet-server/src/lib.rs | 4 + crates/fleet-server/src/logging.rs | 31 +- crates/fleet-server/src/logging/retention.rs | 25 +- crates/fleet-server/src/logging/rotation.rs | 174 ++++ crates/fleet-server/src/main.rs | 34 +- crates/fleet-server/src/metrics.rs | 168 +++ crates/fleet-server/src/oidc.rs | 712 +++++++++++++ crates/fleet-server/src/problem.rs | 18 + crates/fleet-server/src/ratelimit.rs | 123 +++ crates/fleet-server/src/routes/v1/audit.rs | 23 +- .../fleet-server/src/routes/v1/authorize.rs | 10 +- crates/fleet-server/src/routes/v1/grants.rs | 65 +- crates/fleet-server/src/routes/v1/mod.rs | 2 + crates/fleet-server/src/routes/v1/tokens.rs | 220 ++++ crates/fleet-server/src/server.rs | 95 +- crates/fleet-server/src/state.rs | 5 + crates/fleet-server/tests/http.rs | 969 +++++++++++++++++- crates/fleet-server/tests/migrations.rs | 89 +- deploy/postgres/roles.sql | 56 + docker-compose.yml | 15 + docs/architecture.md | 84 +- docs/contract.md | 6 +- docs/deployment.md | 254 +++++ docs/development.md | 53 +- docs/roadmap.md | 40 +- docs/threat-model.md | 37 +- 38 files changed, 4725 insertions(+), 131 deletions(-) create mode 100644 crates/fleet-server/src/anchor.rs create mode 100644 crates/fleet-server/src/logging/rotation.rs create mode 100644 crates/fleet-server/src/metrics.rs create mode 100644 crates/fleet-server/src/oidc.rs create mode 100644 crates/fleet-server/src/ratelimit.rs create mode 100644 crates/fleet-server/src/routes/v1/tokens.rs create mode 100644 deploy/postgres/roles.sql create mode 100644 docs/deployment.md diff --git a/.env.example b/.env.example index 7e4d8c8..625a305 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,26 @@ FLEET_AUTHORITY_ID=sendbox-fleet # Path inside the container to the profile signer file; mount it with a # compose override. Publication is refused while this is empty. FLEET_PROFILE_TRUST= +# Path inside the container to the OIDC issuer file (docs/deployment.md). +# Empty: only service tokens from `sendbox-fleet admin token create` work. +FLEET_OIDC_CONFIG= +# Lifetime of tokens issued by POST /v1/tokens (default 12 h, max 7 d). +FLEET_TOKEN_TTL_SECONDS=43200 +FLEET_TOKEN_MAX_TTL_SECONDS=604800 +# Ed25519 key from `sendbox-fleet admin audit keygen` (file mode 0600). +FLEET_AUDIT_SIGNING_KEY= +# Directory for periodic signed audit heads; needs the signing key. +# Use /var/lib/sendbox-fleet/anchors to write to the compose volume. +FLEET_AUDIT_ANCHOR_DIR= +FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS=3600 +# Per-principal /v1 requests and per-peer failed sign-ins per minute (0 disables). +FLEET_RATE_LIMIT_PER_MINUTE=1200 +FLEET_AUTH_FAILURES_PER_MINUTE=60 +# Separate unauthenticated Prometheus listener, e.g. 0.0.0.0:9090. Empty disables. +FLEET_METRICS_BIND= +# false: refuse to start until `sendbox-fleet admin migrate` has run. +FLEET_MIGRATE=true +FLEET_LOG_MAX_BYTES=104857600 # Running the binary directly with SQLite (export these in your shell) # FLEET_DATABASE_URL=sqlite://sendbox-fleet.db?mode=rwc diff --git a/Cargo.lock b/Cargo.lock index 5a0a424..e9e4faf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,7 +35,7 @@ dependencies = [ "encoding_rs", "foldhash", "futures-core", - "http", + "http 0.2.12", "httparse", "httpdate", "itoa", @@ -68,7 +68,7 @@ checksum = "125f4331c1f10734a96c038bc7503dff22d8ccd5f82b214e6696728561ef1149" dependencies = [ "bytestring", "cfg-if", - "http", + "http 0.2.12", "regex-lite", "serde", "tracing", @@ -248,6 +248,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" @@ -260,6 +266,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -293,6 +305,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "byteorder" version = "1.5.0" @@ -393,6 +411,16 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -414,6 +442,22 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "core_detect" version = "1.0.0" @@ -720,9 +764,12 @@ version = "0.1.0" dependencies = [ "actix-http", "actix-web", - "base64", + "base64 0.22.1", "clap", "getrandom 0.4.3", + "reqwest", + "ring", + "rustls", "sendbox-governance", "sendbox-security", "serde", @@ -737,7 +784,9 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "url", "yaml_serde", + "zeroize", ] [[package]] @@ -943,6 +992,39 @@ dependencies = [ "itoa", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http 1.5.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "pin-project-lite", +] + [[package]] name = "httparse" version = "1.10.1" @@ -964,6 +1046,64 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http 1.5.0", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http 1.5.0", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -1084,6 +1224,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -1096,6 +1242,66 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "language-tags" version = "0.3.2" @@ -1249,6 +1455,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "parking" version = "2.2.1" @@ -1403,6 +1615,40 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "ring" version = "0.17.14" @@ -1453,6 +1699,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -1462,6 +1720,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.17" @@ -1491,12 +1776,53 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "1.0.28" @@ -1506,6 +1832,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" dependencies = [ "serde", ] @@ -1513,6 +1840,7 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" dependencies = [ "sendbox-core", "serde", @@ -1526,8 +1854,9 @@ dependencies = [ [[package]] name = "sendbox-security" version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" dependencies = [ - "base64", + "base64 0.22.1", "ed25519-dalek", "getrandom 0.4.3", "rustix", @@ -1672,6 +2001,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -1741,7 +2080,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "cfg-if", "crc", @@ -1842,7 +2181,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" dependencies = [ "atoi", - "base64", + "base64 0.22.1", "bitflags", "byteorder", "crc", @@ -1951,6 +2290,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -2078,6 +2426,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -2103,6 +2461,51 @@ dependencies = [ "tokio", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http 1.5.0", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -2191,6 +2594,12 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -2293,12 +2702,105 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "1.0.12" @@ -2314,6 +2816,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 99a5daa..8edfff5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,8 +16,11 @@ actix-web = { version = "4.19.0", default-features = false, features = ["macros" base64 = "0.22.1" clap = { version = "4.6.2", features = ["derive"] } getrandom = "0.4.3" -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } -sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider"] } +ring = "0.17.14" +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std"] } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "cp-desktop-fleet-project-roles-exceptions" } +sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "cp-desktop-fleet-project-roles-exceptions" } serde_json_canonicalizer = "0.3.2" serde_yaml_ng = { package = "yaml_serde", version = "0.10.7" } sha2 = "0.11.0" @@ -27,10 +30,12 @@ sqlx = { version = "0.9.0", default-features = false, features = ["macros", "mig tempfile = "3.27.0" thiserror = "2.0.21" time = "0.3.47" -tokio = { version = "1.54.1", features = ["rt", "time"] } +tokio = { version = "1.54.1", features = ["rt", "sync", "time"] } tracing = "0.1.44" tracing-appender = "0.2.5" tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } +url = "2.5.8" +zeroize = "1.8.2" [workspace.lints.rust] unsafe_code = "forbid" diff --git a/Dockerfile b/Dockerfile index 7a5be6b..497988b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,10 +12,15 @@ RUN cargo build --locked --release --bin sendbox-fleet \ && install -D -m 0755 target/release/sendbox-fleet /out/sendbox-fleet FROM debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS runtime -RUN groupadd --system --gid 10001 fleet \ +# CA certificates verify identity-provider discovery and JWKS over HTTPS. +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --system --gid 10001 fleet \ && useradd --system --uid 10001 --gid fleet --no-create-home \ --home-dir /var/lib/sendbox-fleet --shell /usr/sbin/nologin fleet \ - && install -d -o fleet -g fleet -m 0700 /var/lib/sendbox-fleet /var/log/sendbox-fleet + && install -d -o fleet -g fleet -m 0700 /var/lib/sendbox-fleet /var/log/sendbox-fleet \ + /var/lib/sendbox-fleet/anchors COPY --from=build /out/sendbox-fleet /usr/local/bin/sendbox-fleet USER 10001:10001 WORKDIR /var/lib/sendbox-fleet diff --git a/README.md b/README.md index a6c319a..27bbbe5 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,17 @@ Shared governance service for [SendBox](https://github.com/mbianchidev/sendbox) Provider credentials never reach this service; they stay in the SendBox host broker. +## Status + +Feature-complete for increment 2 and usable for team deployments: + +- Signed profiles, project roles, session admission, grants, per-request authorization, revocation, and exceptions with a different approver. +- Sign-in with any OpenID Connect provider (people and CI such as GitHub Actions), exchanged for short-lived service tokens; admin-issued tokens for bootstrap. +- Hash-chained audit with host-reported request outcomes, signed chain heads, and anchoring outside the database. +- Operations: PostgreSQL least-privilege roles, rate limits, Prometheus metrics, size and daily log rotation, deployment and backup guidance. + +Not yet done: a governed session on Apple or Kata against real model providers through a deployed fleet. That run is host-side work tracked in [mbianchidev/sendbox#96](https://github.com/mbianchidev/sendbox/issues/96). See the [roadmap](docs/roadmap.md). + ## Quick start ```sh @@ -14,11 +25,12 @@ cargo run --bin sendbox-fleet curl -H "Authorization: Bearer $(cat you.token)" http://127.0.0.1:8080/v1/whoami ``` -Set `FLEET_PROFILE_TRUST` to publish signed profiles; see [development](docs/development.md#bootstrap-principals-tokens-and-projects). With PostgreSQL: `cp .env.example .env`, set `POSTGRES_PASSWORD`, then `docker compose build --no-cache && docker compose up`. +Set `FLEET_PROFILE_TRUST` to publish signed profiles; see [development](docs/development.md#bootstrap-principals-tokens-and-projects). With PostgreSQL: `cp .env.example .env`, set `POSTGRES_PASSWORD`, then `docker compose build --no-cache && docker compose up`. For a shared setup, follow [deployment](docs/deployment.md). ## Documentation -- [Architecture](docs/architecture.md): relationship to SendBox, trust boundaries, roles, API surface, schema, audit +- [Architecture](docs/architecture.md): relationship to SendBox, trust boundaries, authentication, roles, API surface, schema, audit +- [Deployment](docs/deployment.md): TLS, database roles, identity providers, audit anchoring, metrics, backups - [Shared contract](docs/contract.md): how `sendbox-governance` is pinned and versioned - [Threat model](docs/threat-model.md) - [Roadmap](docs/roadmap.md): delivered and remaining work mapped to the issue's acceptance criteria diff --git a/crates/fleet-server/Cargo.toml b/crates/fleet-server/Cargo.toml index d004e28..c715949 100644 --- a/crates/fleet-server/Cargo.toml +++ b/crates/fleet-server/Cargo.toml @@ -17,6 +17,9 @@ actix-web.workspace = true base64.workspace = true clap.workspace = true getrandom.workspace = true +reqwest.workspace = true +ring.workspace = true +rustls.workspace = true sendbox-governance.workspace = true sendbox-security.workspace = true serde_json_canonicalizer.workspace = true @@ -31,6 +34,8 @@ tokio.workspace = true tracing.workspace = true tracing-appender.workspace = true tracing-subscriber.workspace = true +url.workspace = true +zeroize.workspace = true [dev-dependencies] actix-http.workspace = true diff --git a/crates/fleet-server/src/admin.rs b/crates/fleet-server/src/admin.rs index 077791f..bc21093 100644 --- a/crates/fleet-server/src/admin.rs +++ b/crates/fleet-server/src/admin.rs @@ -3,6 +3,10 @@ //! meant for whoever operates the service host. Every change is audited with //! the actor `cli:admin`. +use std::io::Write as _; +use std::os::unix::fs::OpenOptionsExt as _; +use std::path::PathBuf; + use clap::{Args, Subcommand, ValueEnum}; use sendbox_governance::{Clock, PrincipalId, ProjectId, SystemClock}; @@ -28,6 +32,35 @@ pub enum AdminCommand { /// Create projects with their first owner. #[command(subcommand)] Project(ProjectCommand), + /// Sign, anchor, and verify the audit chain. + #[command(subcommand)] + Audit(AuditCommand), + /// Apply pending database migrations, for deployments that run the + /// service with `FLEET_MIGRATE=false` and a least-privilege role. + Migrate, +} + +#[derive(Debug, Subcommand)] +pub enum AuditCommand { + /// Create an audit signing key (mode 0600) and print its public identity. + Keygen { + #[arg(long, value_name = "PATH")] + output: PathBuf, + }, + /// Write the current chain head, signed with FLEET_AUDIT_SIGNING_KEY, into + /// DIR (for example a write-once bucket mount). + Anchor { + #[arg(long, value_name = "DIR")] + output: PathBuf, + }, + /// Recompute the whole chain and check every given anchor against it. + Verify { + /// Public identity printed by `audit keygen` (JSON). + #[arg(long, value_name = "PATH")] + identity: Option, + #[arg(long = "anchor", value_name = "FILE")] + anchors: Vec, + }, } #[derive(Debug, Subcommand)] @@ -91,6 +124,10 @@ pub enum AdminError { #[error("{0}")] Invalid(String), #[error(transparent)] + Anchor(#[from] crate::anchor::AnchorError), + #[error("audit verification failed")] + Unverified, + #[error(transparent)] Database(#[from] DbError), #[error("{}", .0.detail)] Refused(Problem), @@ -138,15 +175,128 @@ fn display_name(value: Option) -> Result, AdminError> { } /// Runs one admin command. Results go to stdout; a new token is the only -/// thing printed for `token issue`. -pub async fn run(url: &DatabaseUrl, command: AdminCommand) -> Result<(), AdminError> { +/// thing printed for `token issue`. Pending migrations are applied first +/// unless `migrate` is false (`FLEET_MIGRATE=false`), in which case only +/// `admin migrate` changes the schema. +pub async fn run( + url: &DatabaseUrl, + migrate: bool, + command: AdminCommand, +) -> Result<(), AdminError> { + if let AdminCommand::Audit(AuditCommand::Keygen { output }) = &command { + return keygen(output); + } let database = Database::connect(url).await?; - database.migrate().await?; - let result = execute(&database, command, SystemClock.now_unix()).await; + if migrate || matches!(command, AdminCommand::Migrate) { + database.migrate().await?; + } else { + database.check_migrated().await?; + } + let result = match command { + AdminCommand::Migrate => { + println!("migrations applied"); + Ok(()) + } + AdminCommand::Audit(audit) => run_audit(&database, audit).await, + command => execute(&database, command, SystemClock.now_unix()).await, + }; database.close().await; result } +/// Creates an audit signing key; needs no database. +pub fn keygen(output: &std::path::Path) -> Result<(), AdminError> { + let key = sendbox_security::provenance::SigningKeyMaterial::generate() + .map_err(|error| AdminError::Invalid(format!("generate key: {error}")))?; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(output) + .map_err(|error| AdminError::Invalid(format!("create {}: {error}", output.display())))?; + file.write_all(key.export().as_bytes()) + .and_then(|()| file.write_all(b"\n")) + .map_err(|error| AdminError::Invalid(format!("write {}: {error}", output.display())))?; + let identity = crate::anchor::AuditSigner::from_key(key).identity; + eprintln!( + "audit signing key written to {}; keep it out of the database host's backups. Public identity:", + output.display() + ); + println!( + "{}", + serde_json::to_string_pretty(&identity) + .map_err(|error| AdminError::Invalid(error.to_string()))? + ); + Ok(()) +} + +async fn run_audit(database: &Database, command: AuditCommand) -> Result<(), AdminError> { + match command { + AuditCommand::Keygen { .. } => Err(AdminError::Invalid("unreachable".to_owned())), + AuditCommand::Anchor { output } => { + let key = std::env::var_os(crate::config::AUDIT_SIGNING_KEY_VAR).ok_or_else(|| { + AdminError::Invalid(format!( + "{} is required", + crate::config::AUDIT_SIGNING_KEY_VAR + )) + })?; + let signer = crate::anchor::AuditSigner::load(std::path::Path::new(&key))?; + let authority = std::env::var(crate::config::AUTHORITY_ID_VAR) + .unwrap_or_else(|_| "sendbox-fleet".to_owned()); + let head = crate::anchor::current_head(database, &authority, SystemClock.now_unix()) + .await + .map_err(AdminError::Refused)?; + let signed = signer.sign(head)?; + match crate::anchor::write_anchor(&output, &signed)? { + Some(path) => println!( + "anchored sequence {} in {}", + signed.head.sequence, + path.display() + ), + None => println!("sequence {} is already anchored", signed.head.sequence), + } + Ok(()) + } + AuditCommand::Verify { identity, anchors } => { + let chain = crate::audit::verify_chain(database) + .await + .map_err(AdminError::Refused)?; + println!( + "{}", + serde_json::to_string(&chain) + .map_err(|error| AdminError::Invalid(error.to_string()))? + ); + let mut valid = chain.valid; + if !anchors.is_empty() { + let path = identity.ok_or_else(|| { + AdminError::Invalid("--identity is required to check anchors".to_owned()) + })?; + let bytes = std::fs::read(&path).map_err(|error| { + AdminError::Invalid(format!("read {}: {error}", path.display())) + })?; + let identity: sendbox_security::provenance::Identity = + serde_json::from_slice(&bytes).map_err(|error| { + AdminError::Invalid(format!("{}: {error}", path.display())) + })?; + for anchor in anchors { + let check = crate::anchor::check_anchor(database, &identity, &anchor).await?; + valid &= check.valid; + println!( + "{}", + serde_json::to_string(&check) + .map_err(|error| AdminError::Invalid(error.to_string()))? + ); + } + } + if valid { + Ok(()) + } else { + Err(AdminError::Unverified) + } + } + } +} + async fn execute(database: &Database, command: AdminCommand, now: u64) -> Result<(), AdminError> { let mut tx = database.begin_write().await?; let record = |event_type| AuditRecord { @@ -325,6 +475,11 @@ async fn execute(database: &Database, command: AdminCommand, now: u64) -> Result .await?; println!("revoked token {token_id}"); } + AdminCommand::Audit(_) | AdminCommand::Migrate => { + return Err(AdminError::Invalid( + "handled before the transaction".to_owned(), + )); + } AdminCommand::Project(ProjectCommand::Create { project, owner, diff --git a/crates/fleet-server/src/anchor.rs b/crates/fleet-server/src/anchor.rs new file mode 100644 index 0000000..94e4209 --- /dev/null +++ b/crates/fleet-server/src/anchor.rs @@ -0,0 +1,364 @@ +//! Anchoring the audit chain outside the database. +//! +//! The service signs its chain head (sequence and event hash) with an +//! Ed25519 key that is kept out of the database. Signed heads are written +//! periodically to `FLEET_AUDIT_ANCHOR_DIR` (meant to be storage the database +//! administrator cannot rewrite, such as a write-once bucket mount) and served +//! to operators at `GET /v1/audit/head`. `sendbox-fleet admin audit verify +//! --anchor FILE` later proves the database still contains the anchored +//! events: a rewritten or truncated chain no longer reproduces the anchored +//! hash. + +use std::collections::BTreeMap; +use std::io::Write as _; +use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use sendbox_governance::Sha256Digest; +use sendbox_security::provenance::{ + DetachedSignature, Identity, SignedSubject, SigningKeyMaterial, SubjectKind, TrustPolicy, + TrustStore, +}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::audit::GENESIS_HASH; +use crate::db::{Arg, Database}; +use crate::problem::Problem; +use crate::state::from_db; + +pub const HEAD_FORMAT: &str = "sendbox-fleet-audit-head"; +const HEAD_VERSION: u32 = 1; +const SUBJECT_NAME: &str = "audit-head"; +const MAX_KEY_BYTES: u64 = 4 * 1024; + +#[derive(Debug, Error)] +pub enum AnchorError { + #[error("{0}")] + Invalid(String), + #[error("{context} {path}: {source}")] + Io { + context: &'static str, + path: PathBuf, + source: std::io::Error, + }, +} + +/// The chain head at one point in time. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditHead { + pub format: String, + pub version: u32, + pub authority_id: String, + /// Number of events; `0` with the genesis hash for an empty log. + pub sequence: u64, + pub event_hash: Sha256Digest, + pub signed_at_unix: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignedAuditHead { + pub head: AuditHead, + pub signature: DetachedSignature, +} + +/// The service's audit signing key. +pub struct AuditSigner { + key: SigningKeyMaterial, + pub identity: Identity, +} + +impl std::fmt::Debug for AuditSigner { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("AuditSigner") + .field("fingerprint", &self.identity.fingerprint) + .finish_non_exhaustive() + } +} + +impl AuditSigner { + /// Loads a key file written by `sendbox-fleet admin audit keygen` (or + /// `sendbox governance keygen`). The file must not be readable by group + /// or others. + pub fn load(path: &Path) -> Result { + let io = |source| AnchorError::Io { + context: "read audit signing key", + path: path.to_path_buf(), + source, + }; + let metadata = std::fs::metadata(path).map_err(io)?; + if !metadata.is_file() || metadata.len() > MAX_KEY_BYTES { + return Err(AnchorError::Invalid(format!( + "{} is not a small regular file", + path.display() + ))); + } + if metadata.permissions().mode() & 0o077 != 0 { + return Err(AnchorError::Invalid(format!( + "{} must not be accessible by group or others (chmod 600)", + path.display() + ))); + } + let text = zeroize::Zeroizing::new(std::fs::read_to_string(path).map_err(io)?); + let key = SigningKeyMaterial::import(text.trim()) + .map_err(|error| AnchorError::Invalid(format!("audit signing key: {error}")))?; + Ok(Self::from_key(key)) + } + + #[must_use] + pub fn from_key(key: SigningKeyMaterial) -> Self { + let identity = key.identity("SendBox fleet audit", None, 0, None); + Self { key, identity } + } + + pub fn sign(&self, head: AuditHead) -> Result { + let bytes = serde_json_canonicalizer::to_vec(&head) + .map_err(|error| AnchorError::Invalid(error.to_string()))?; + let signature = DetachedSignature::sign( + SignedSubject::from_bytes(SubjectKind::Artifact, Some(SUBJECT_NAME.to_owned()), &bytes), + &self.key, + head.signed_at_unix, + None, + BTreeMap::from([("sequence".to_owned(), head.sequence.to_string())]), + ) + .map_err(|error| AnchorError::Invalid(format!("sign audit head: {error}")))?; + Ok(SignedAuditHead { head, signature }) + } +} + +/// Reads the current chain head. +pub async fn current_head( + database: &Database, + authority_id: &str, + now_unix: u64, +) -> Result { + let row = database + .fetch_optional( + "SELECT sequence, event_hash FROM audit_events ORDER BY sequence DESC LIMIT 1", + &[], + ) + .await?; + let (sequence, hash) = match row { + Some(row) => (from_db(row.int("sequence")?)?, row.text("event_hash")?), + None => (0, GENESIS_HASH.to_owned()), + }; + Ok(AuditHead { + format: HEAD_FORMAT.to_owned(), + version: HEAD_VERSION, + authority_id: authority_id.to_owned(), + sequence, + event_hash: Sha256Digest::parse_hex(&hash).map_err(|_| Problem::internal())?, + signed_at_unix: now_unix, + }) +} + +/// Writes `audit-head-.json` once; an existing anchor for the same +/// sequence is never overwritten. +pub fn write_anchor( + directory: &Path, + signed: &SignedAuditHead, +) -> Result, AnchorError> { + let path = directory.join(format!("audit-head-{:020}.json", signed.head.sequence)); + let bytes = serde_json::to_vec_pretty(signed) + .map_err(|error| AnchorError::Invalid(error.to_string()))?; + let mut file = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(&path) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Ok(None), + Err(source) => { + return Err(AnchorError::Io { + context: "create audit anchor", + path, + source, + }); + } + }; + file.write_all(&bytes) + .and_then(|()| file.write_all(b"\n")) + .and_then(|()| file.sync_all()) + .map_err(|source| AnchorError::Io { + context: "write audit anchor", + path: path.clone(), + source, + })?; + Ok(Some(path)) +} + +/// Result of checking one anchor against the database. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AnchorCheck { + pub file: String, + pub sequence: u64, + pub valid: bool, + pub reason: Option, +} + +/// Verifies an anchor's signature against `identity` and that the database +/// still holds the same event hash at the anchored sequence. +pub async fn check_anchor( + database: &Database, + identity: &Identity, + file: &Path, +) -> Result { + let bytes = std::fs::read(file).map_err(|source| AnchorError::Io { + context: "read audit anchor", + path: file.to_path_buf(), + source, + })?; + let fail = |sequence, reason: String| AnchorCheck { + file: file.display().to_string(), + sequence, + valid: false, + reason: Some(reason), + }; + let signed: SignedAuditHead = match serde_json::from_slice(&bytes) { + Ok(signed) => signed, + Err(error) => return Ok(fail(0, format!("not a signed audit head: {error}"))), + }; + let head = &signed.head; + if head.format != HEAD_FORMAT || head.version != HEAD_VERSION { + return Ok(fail(head.sequence, "unsupported anchor format".to_owned())); + } + let mut trust = TrustStore::new(TrustPolicy { + allow_unsigned: false, + threshold: 1, + required_signers: std::collections::BTreeSet::new(), + }); + trust + .add_identity(identity.clone()) + .map_err(|error| AnchorError::Invalid(format!("audit identity: {error}")))?; + let canonical = serde_json_canonicalizer::to_vec(head) + .map_err(|error| AnchorError::Invalid(error.to_string()))?; + if let Err(error) = trust.verify( + &canonical, + SubjectKind::Artifact, + std::slice::from_ref(&signed.signature), + head.signed_at_unix, + ) { + return Ok(fail(head.sequence, format!("signature: {error}"))); + } + if signed.signature.subject.name.as_deref() != Some(SUBJECT_NAME) { + return Ok(fail( + head.sequence, + "signature names another subject".to_owned(), + )); + } + let stored = if head.sequence == 0 { + Some(GENESIS_HASH.to_owned()) + } else { + database + .fetch_optional( + "SELECT event_hash FROM audit_events WHERE sequence = $1", + &[Arg::from(i64::try_from(head.sequence).unwrap_or(i64::MAX))], + ) + .await + .map_err(|error| AnchorError::Invalid(error.to_string()))? + .map(|row| row.text("event_hash")) + .transpose() + .map_err(|error| AnchorError::Invalid(error.to_string()))? + }; + Ok(match stored { + None => fail( + head.sequence, + "the database no longer holds this sequence".to_owned(), + ), + Some(hash) if hash != head.event_hash.to_string() => fail( + head.sequence, + "the database holds a different event at this sequence".to_owned(), + ), + Some(_) => AnchorCheck { + file: file.display().to_string(), + sequence: head.sequence, + valid: true, + reason: None, + }, + }) +} + +/// Writes a signed head to `directory` whenever the chain advanced. +pub fn spawn_anchoring( + database: Database, + signer: Arc, + authority_id: String, + directory: PathBuf, + interval: Duration, + clock: Arc, +) -> tokio::task::JoinHandle<()> { + actix_web::rt::spawn(async move { + let mut ticker = tokio::time::interval(interval); + let mut last = None; + loop { + ticker.tick().await; + let head = match current_head(&database, &authority_id, clock.now_unix()).await { + Ok(head) => head, + Err(_) => { + tracing::warn!("cannot read the audit chain head for anchoring"); + continue; + } + }; + if last == Some(head.sequence) { + continue; + } + match signer + .sign(head) + .map(|signed| (signed.head.sequence, write_anchor(&directory, &signed))) + { + Ok((sequence, Ok(written))) => { + if let Some(path) = written { + tracing::info!(sequence, path = %path.display(), "audit chain head anchored"); + } + last = Some(sequence); + } + Ok((_, Err(error))) | Err(error) => { + tracing::error!(%error, "audit chain head anchoring failed"); + } + } + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn head(sequence: u64) -> AuditHead { + AuditHead { + format: HEAD_FORMAT.to_owned(), + version: HEAD_VERSION, + authority_id: "fleet.example.com".to_owned(), + sequence, + event_hash: Sha256Digest::of(b"event"), + signed_at_unix: 1_800_000_000, + } + } + + #[test] + fn anchors_are_written_once_and_keys_must_be_private() { + let directory = tempfile::tempdir().unwrap(); + let signer = AuditSigner::from_key(SigningKeyMaterial::generate().unwrap()); + let signed = signer.sign(head(7)).unwrap(); + let path = write_anchor(directory.path(), &signed).unwrap().unwrap(); + assert!(path.ends_with("audit-head-00000000000000000007.json")); + assert!(write_anchor(directory.path(), &signed).unwrap().is_none()); + + let key = directory.path().join("audit.key"); + std::fs::write( + &key, + SigningKeyMaterial::generate().unwrap().export().as_bytes(), + ) + .unwrap(); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(AuditSigner::load(&key).is_err()); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert!(AuditSigner::load(&key).is_ok()); + } +} diff --git a/crates/fleet-server/src/audit.rs b/crates/fleet-server/src/audit.rs index a9b52f3..6b60f7b 100644 --- a/crates/fleet-server/src/audit.rs +++ b/crates/fleet-server/src/audit.rs @@ -192,6 +192,7 @@ pub async fn append(tx: &mut Tx, now_unix: u64, record: AuditRecord) -> Result = Pin> + Send + 'a>>; @@ -110,6 +129,7 @@ impl Authenticator for DatabaseAuthenticator { principal, kind, operator: row.flag("operator").ok()?, + method: AuthMethod::ServiceToken, }) })(); caller.ok_or_else(|| { @@ -120,6 +140,145 @@ impl Authenticator for DatabaseAuthenticator { } } +/// Service tokens and, when configured, identity-provider JWTs. +pub struct FleetAuthenticator { + tokens: DatabaseAuthenticator, + oidc: Option, + database: Database, + clock: Arc, +} + +impl FleetAuthenticator { + #[must_use] + pub fn new(database: Database, clock: Arc, oidc: Option) -> Self { + Self { + tokens: DatabaseAuthenticator::new(database.clone(), Arc::clone(&clock)), + oidc, + database, + clock, + } + } + + async fn resolve(&self, identity: OidcIdentity) -> Result { + let unavailable = |error: crate::db::DbError| { + tracing::error!(%error, "principal lookup failed"); + AuthError::Unavailable + }; + let lookup = "SELECT kind, is_operator AS operator, disabled_at_unix FROM principals \ + WHERE id = $1"; + let row = self + .database + .fetch_optional(lookup, &[identity.principal.as_str().into()]) + .await + .map_err(unavailable)?; + let expected = match identity.kind { + CallerKind::User => "user", + CallerKind::Worker => "worker", + }; + if let Some(row) = row { + let active = row + .opt_int("disabled_at_unix") + .map_err(unavailable)? + .is_none(); + let kind = row.text("kind").map_err(unavailable)?; + if !active || kind != expected { + tracing::info!( + principal = %identity.principal, + issuer = %identity.issuer, + reason = if active { "kind_mismatch" } else { "principal_disabled" }, + "identity-provider sign-in refused" + ); + return Err(AuthError::InvalidToken); + } + return Ok(Caller { + principal: identity.principal, + kind: identity.kind, + operator: row.flag("operator").map_err(unavailable)?, + method: AuthMethod::IdentityProvider, + }); + } + if !identity.auto_provision { + tracing::info!( + principal = %identity.principal, + issuer = %identity.issuer, + reason = "not_registered", + "identity-provider sign-in refused" + ); + return Err(AuthError::NotRegistered); + } + let now = self.clock.now_unix(); + let mut tx = self.database.begin_write().await.map_err(unavailable)?; + let exists = tx + .fetch_optional( + "SELECT id FROM principals WHERE id = $1", + &[identity.principal.as_str().into()], + ) + .await + .map_err(unavailable)? + .is_some(); + if !exists { + let created = i64::try_from(now).map_err(|_| AuthError::Unavailable)?; + tx.execute( + "INSERT INTO principals (id, kind, created_at_unix) VALUES ($1, $2, $3)", + &[ + identity.principal.as_str().into(), + expected.into(), + created.into(), + ], + ) + .await + .map_err(unavailable)?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "principal.provisioned", + actor: Some(identity.principal.to_string()), + principal: Some(identity.principal.to_string()), + detail: Some(format!("kind={expected} issuer={}", identity.issuer)), + ..AuditRecord::default() + }, + ) + .await + .map_err(|_| AuthError::Unavailable)?; + tx.commit().await.map_err(unavailable)?; + } + Box::pin(self.resolve(OidcIdentity { + auto_provision: false, + ..identity + })) + .await + } +} + +impl Authenticator for FleetAuthenticator { + fn authenticate<'a>(&'a self, bearer_token: &'a str) -> AuthFuture<'a> { + Box::pin(async move { + if bearer_token.starts_with(TOKEN_PREFIX) { + return self.tokens.authenticate(bearer_token).await; + } + let Some(oidc) = self + .oidc + .as_ref() + .filter(|_| OidcVerifier::handles(bearer_token)) + else { + return Err(AuthError::InvalidToken); + }; + let identity = oidc + .verify(bearer_token) + .await + .map_err(|error| match error { + OidcError::Rejected(reason) => { + tracing::info!(reason, "identity-provider token rejected"); + AuthError::InvalidToken + } + OidcError::Unavailable => AuthError::Unavailable, + })?; + self.resolve(identity).await + }) + } +} + /// A new token and the SHA-256 digest that is stored in its place. #[must_use] pub fn token_from_bytes(bytes: &[u8; 32]) -> (String, String) { @@ -167,12 +326,44 @@ pub async fn require_bearer( } async fn authenticate(request: &ServiceRequest) -> Result { - let token = bearer_token(request.request())?; + let limits = request + .app_data::>() + .map(|state| std::sync::Arc::clone(&state.limits)); + let peer = request + .peer_addr() + .map_or_else(|| "unknown".to_owned(), |address| address.ip().to_string()); + let now = std::time::Instant::now(); + if let Some(wait) = limits + .as_ref() + .and_then(|limits| limits.auth_failures.exhausted(&peer, now)) + { + crate::metrics::METRICS.rate_limited(); + return Err(Problem::too_many_requests(wait)); + } + let failed = |problem: Problem| { + crate::metrics::METRICS.auth_failure(); + if let Some(limits) = &limits { + let _ = limits.auth_failures.spend(&peer, now); + } + problem + }; + let token = bearer_token(request.request()).map_err(failed)?; let authenticator = request .app_data::() .cloned() .ok_or_else(|| rejection(AuthError::NotConfigured))?; - authenticator.authenticate(&token).await.map_err(rejection) + let caller = match authenticator.authenticate(&token).await { + Ok(caller) => caller, + Err(AuthError::Unavailable) => return Err(rejection(AuthError::Unavailable)), + Err(error) => return Err(failed(rejection(error))), + }; + if let Some(limits) = &limits + && let Err(wait) = limits.requests.spend(caller.principal.as_str(), now) + { + crate::metrics::METRICS.rate_limited(); + return Err(Problem::too_many_requests(wait)); + } + Ok(caller) } fn bearer_token(request: &HttpRequest) -> Result { @@ -213,7 +404,7 @@ fn valid_token(token: &str) -> bool { fn rejection(error: AuthError) -> Problem { match error { AuthError::Unavailable => Problem::service_unavailable(error.to_string()), - AuthError::NotConfigured | AuthError::InvalidToken => { + AuthError::NotConfigured | AuthError::InvalidToken | AuthError::NotRegistered => { Problem::unauthorized(error.to_string(), CHALLENGE_INVALID_TOKEN) } } diff --git a/crates/fleet-server/src/config.rs b/crates/fleet-server/src/config.rs index 4c5f609..2c0d9a3 100644 --- a/crates/fleet-server/src/config.rs +++ b/crates/fleet-server/src/config.rs @@ -13,15 +13,33 @@ pub const DATABASE_URL_VAR: &str = "FLEET_DATABASE_URL"; pub const LOG_DIR_VAR: &str = "FLEET_LOG_DIR"; pub const LOG_LEVEL_VAR: &str = "FLEET_LOG_LEVEL"; pub const LOG_RETENTION_DAYS_VAR: &str = "FLEET_LOG_RETENTION_DAYS"; +pub const LOG_MAX_BYTES_VAR: &str = "FLEET_LOG_MAX_BYTES"; pub const AUTHORITY_ID_VAR: &str = "FLEET_AUTHORITY_ID"; pub const PROFILE_TRUST_VAR: &str = "FLEET_PROFILE_TRUST"; +pub const OIDC_CONFIG_VAR: &str = "FLEET_OIDC_CONFIG"; +pub const TOKEN_TTL_VAR: &str = "FLEET_TOKEN_TTL_SECONDS"; +pub const TOKEN_MAX_TTL_VAR: &str = "FLEET_TOKEN_MAX_TTL_SECONDS"; +pub const AUDIT_SIGNING_KEY_VAR: &str = "FLEET_AUDIT_SIGNING_KEY"; +pub const RATE_LIMIT_VAR: &str = "FLEET_RATE_LIMIT_PER_MINUTE"; +pub const AUTH_FAILURES_VAR: &str = "FLEET_AUTH_FAILURES_PER_MINUTE"; +pub const METRICS_BIND_VAR: &str = "FLEET_METRICS_BIND"; +pub const MIGRATE_VAR: &str = "FLEET_MIGRATE"; +pub const AUDIT_ANCHOR_DIR_VAR: &str = "FLEET_AUDIT_ANCHOR_DIR"; +pub const AUDIT_ANCHOR_INTERVAL_VAR: &str = "FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS"; const DEFAULT_BIND: &str = "127.0.0.1:8080"; const DEFAULT_LOG_DIR: &str = "./logs"; const DEFAULT_LOG_LEVEL: &str = "info,sqlx=warn"; const DEFAULT_LOG_RETENTION_DAYS: u32 = 30; const MAX_LOG_RETENTION_DAYS: u32 = 3650; +const DEFAULT_LOG_MAX_BYTES: u64 = 100 * 1024 * 1024; +const LOG_MAX_BYTES_RANGE: std::ops::RangeInclusive = + (1024 * 1024)..=(10 * 1024 * 1024 * 1024); const DEFAULT_AUTHORITY_ID: &str = "sendbox-fleet"; +const DEFAULT_TOKEN_TTL_SECONDS: u64 = 12 * 60 * 60; +const DEFAULT_TOKEN_MAX_TTL_SECONDS: u64 = 7 * 24 * 60 * 60; +/// Matches the `api_tokens` lifetime bound in the schema. +pub const HARD_MAX_TOKEN_TTL_SECONDS: u64 = 90 * 24 * 60 * 60; const MAX_TRUST_BYTES: u64 = 256 * 1024; const MAX_TRUSTED_SIGNERS: usize = 32; @@ -35,6 +53,43 @@ pub struct Config { pub authority_id: String, /// File listing the operator signers that published profiles must satisfy. pub profile_trust: Option, + /// File listing trusted OIDC issuers. + pub oidc: Option, + pub tokens: TokenLimits, + pub audit: AuditAnchoring, + /// `/v1` requests per principal per minute; `0` disables. + pub rate_limit_per_minute: u32, + /// Failed authentications per peer address per minute; `0` disables. + pub auth_failures_per_minute: u32, + /// Separate listener for `/metrics`; `None` disables metrics. + pub metrics_bind: Option, + /// Apply migrations at startup. When false, startup fails unless every + /// migration was already applied (`sendbox-fleet admin migrate`). + pub migrate: bool, +} + +/// Signing and external anchoring of the audit chain head. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct AuditAnchoring { + pub signing_key: Option, + pub directory: Option, + pub interval_seconds: u64, +} + +/// Lifetimes of service tokens exchanged at `POST /v1/tokens`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TokenLimits { + pub default_seconds: u64, + pub max_seconds: u64, +} + +impl Default for TokenLimits { + fn default() -> Self { + Self { + default_seconds: DEFAULT_TOKEN_TTL_SECONDS, + max_seconds: DEFAULT_TOKEN_MAX_TTL_SECONDS, + } + } } /// The signer set and threshold for profile publication. Same shape as the @@ -113,6 +168,8 @@ pub struct LogConfig { /// `fleet_server=debug,actix_web=info`. pub filter: String, pub retention_days: u32, + /// Size at which the current day's file continues in a new part. + pub max_file_bytes: u64, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -206,6 +263,18 @@ pub enum ConfigError { Invalid { name: &'static str, reason: String }, } +/// `FLEET_MIGRATE`: unset or `true` applies migrations at startup. +pub fn parse_migrate(value: Option<&str>) -> Result { + match value { + None | Some("true") => Ok(true), + Some("false") => Ok(false), + Some(_) => Err(ConfigError::Invalid { + name: MIGRATE_VAR, + reason: "must be `true` or `false`".to_owned(), + }), + } +} + impl Config { pub fn from_env() -> Result { Self::from_lookup(|name| std::env::var_os(name)) @@ -281,6 +350,106 @@ impl Config { let profile_trust = lookup(PROFILE_TRUST_VAR) .filter(|value| !value.is_empty()) .map(PathBuf::from); + let oidc = lookup(OIDC_CONFIG_VAR) + .filter(|value| !value.is_empty()) + .map(PathBuf::from); + let seconds = |name: &'static str, default: u64| -> Result { + match text(name)? { + None => Ok(default), + Some(value) => value + .parse::() + .ok() + .filter(|seconds| (60..=HARD_MAX_TOKEN_TTL_SECONDS).contains(seconds)) + .ok_or_else(|| ConfigError::Invalid { + name, + reason: format!( + "must be a whole number of seconds in 60..={HARD_MAX_TOKEN_TTL_SECONDS}" + ), + }), + } + }; + let audit = AuditAnchoring { + signing_key: lookup(AUDIT_SIGNING_KEY_VAR) + .filter(|value| !value.is_empty()) + .map(PathBuf::from), + directory: lookup(AUDIT_ANCHOR_DIR_VAR) + .filter(|value| !value.is_empty()) + .map(PathBuf::from), + interval_seconds: match text(AUDIT_ANCHOR_INTERVAL_VAR)? { + None => 3600, + Some(value) => value + .parse::() + .ok() + .filter(|seconds| (60..=86_400).contains(seconds)) + .ok_or_else(|| ConfigError::Invalid { + name: AUDIT_ANCHOR_INTERVAL_VAR, + reason: "must be a whole number of seconds in 60..=86400".to_owned(), + })?, + }, + }; + if audit.directory.is_some() && audit.signing_key.is_none() { + return Err(ConfigError::Invalid { + name: AUDIT_ANCHOR_DIR_VAR, + reason: format!("needs {AUDIT_SIGNING_KEY_VAR}"), + }); + } + let per_minute = |name: &'static str, default: u32| -> Result { + match text(name)? { + None => Ok(default), + Some(value) => value + .parse::() + .ok() + .filter(|value| *value <= 1_000_000) + .ok_or_else(|| ConfigError::Invalid { + name, + reason: "must be a whole number in 0..=1000000 (0 disables)".to_owned(), + }), + } + }; + let rate_limit_per_minute = per_minute(RATE_LIMIT_VAR, 1200)?; + let auth_failures_per_minute = per_minute(AUTH_FAILURES_VAR, 60)?; + let metrics_bind = text(METRICS_BIND_VAR)? + .filter(|value| !value.is_empty()) + .map(|value| { + value.parse().map_err(|_| ConfigError::Invalid { + name: METRICS_BIND_VAR, + reason: format!("`{value}` is not a socket address such as `127.0.0.1:9090`"), + }) + }) + .transpose()?; + if metrics_bind.is_some_and(|address| address == bind) { + return Err(ConfigError::Invalid { + name: METRICS_BIND_VAR, + reason: format!("must differ from {BIND_VAR}"), + }); + } + let migrate = parse_migrate(text(MIGRATE_VAR)?.as_deref())?; + let tokens = TokenLimits { + default_seconds: seconds(TOKEN_TTL_VAR, DEFAULT_TOKEN_TTL_SECONDS)?, + max_seconds: seconds(TOKEN_MAX_TTL_VAR, DEFAULT_TOKEN_MAX_TTL_SECONDS)?, + }; + if tokens.default_seconds > tokens.max_seconds { + return Err(ConfigError::Invalid { + name: TOKEN_TTL_VAR, + reason: format!("must not exceed {TOKEN_MAX_TTL_VAR}"), + }); + } + + let max_file_bytes = match text(LOG_MAX_BYTES_VAR)? { + None => DEFAULT_LOG_MAX_BYTES, + Some(value) => value + .parse::() + .ok() + .filter(|bytes| LOG_MAX_BYTES_RANGE.contains(bytes)) + .ok_or_else(|| ConfigError::Invalid { + name: LOG_MAX_BYTES_VAR, + reason: format!( + "must be a whole number of bytes in {}..={}", + LOG_MAX_BYTES_RANGE.start(), + LOG_MAX_BYTES_RANGE.end() + ), + })?, + }; Ok(Self { bind, @@ -289,9 +458,17 @@ impl Config { dir, filter, retention_days, + max_file_bytes, }, authority_id, profile_trust, + oidc, + tokens, + audit, + rate_limit_per_minute, + auth_failures_per_minute, + metrics_bind, + migrate, }) } } @@ -349,6 +526,12 @@ mod tests { (LOG_RETENTION_DAYS_VAR, "thirty"), (AUTHORITY_ID_VAR, "local"), (AUTHORITY_ID_VAR, "has space"), + (TOKEN_TTL_VAR, "59"), + (TOKEN_MAX_TTL_VAR, "7776001"), + (TOKEN_TTL_VAR, "700000"), + (RATE_LIMIT_VAR, "-1"), + (METRICS_BIND_VAR, "127.0.0.1:8080"), + (MIGRATE_VAR, "yes"), ] { match config(&[base, (name, value)]) { Err(ConfigError::Invalid { name: reported, .. }) => assert_eq!(reported, name), diff --git a/crates/fleet-server/src/db.rs b/crates/fleet-server/src/db.rs index aacdcd7..a33be12 100644 --- a/crates/fleet-server/src/db.rs +++ b/crates/fleet-server/src/db.rs @@ -34,6 +34,10 @@ pub enum DbError { Migrate(#[from] MigrateError), #[error("database query failed: {0}")] Query(#[from] sqlx::Error), + #[error( + "migrations {0} are not applied; run `sendbox-fleet admin migrate` with a schema-owner role" + )] + Pending(String), } #[derive(Debug, Clone)] @@ -121,6 +125,46 @@ impl Database { Ok(()) } + /// Fails unless every embedded migration has been applied successfully, + /// for deployments whose runtime role cannot change the schema. + pub async fn check_migrated(&self) -> Result<(), DbError> { + let migrator = match self { + Self::Postgres(_) => &POSTGRES_MIGRATIONS, + Self::Sqlite(_) => &SQLITE_MIGRATIONS, + }; + let ledger = match self { + Self::Postgres(_) => { + "SELECT 1 AS present WHERE to_regclass('_sqlx_migrations') IS NOT NULL" + } + Self::Sqlite(_) => { + "SELECT 1 AS present FROM sqlite_master \ + WHERE type = 'table' AND name = '_sqlx_migrations'" + } + }; + let applied = if self.fetch_optional(ledger, &[]).await?.is_some() { + self.fetch_all( + "SELECT version FROM _sqlx_migrations WHERE success = TRUE", + &[], + ) + .await? + .iter() + .map(|row| row.int("version")) + .collect::, _>>()? + } else { + std::collections::BTreeSet::new() + }; + let missing = migrator + .iter() + .filter(|migration| !applied.contains(&migration.version)) + .map(|migration| migration.version.to_string()) + .collect::>(); + if missing.is_empty() { + Ok(()) + } else { + Err(DbError::Pending(missing.join(", "))) + } + } + /// Round-trips a trivial query; used by the readiness probe. pub async fn ping(&self) -> Result<(), DbError> { match self { diff --git a/crates/fleet-server/src/lib.rs b/crates/fleet-server/src/lib.rs index e2a3228..1bfe74e 100644 --- a/crates/fleet-server/src/lib.rs +++ b/crates/fleet-server/src/lib.rs @@ -8,13 +8,17 @@ //! hash-chained central audit log. It never holds provider credentials. pub mod admin; +pub mod anchor; pub mod audit; pub mod auth; pub mod config; pub mod db; pub mod governance; pub mod logging; +pub mod metrics; +pub mod oidc; pub mod problem; +pub mod ratelimit; pub mod routes; pub mod server; pub mod state; diff --git a/crates/fleet-server/src/logging.rs b/crates/fleet-server/src/logging.rs index 09ee34c..b9b9bef 100644 --- a/crates/fleet-server/src/logging.rs +++ b/crates/fleet-server/src/logging.rs @@ -1,12 +1,14 @@ -//! Structured logging to stdout and a daily-rotated `.log` file. +//! Structured logging to stdout and a rotated `.log` file. //! //! Both sinks receive the same JSON-lines events. The file sink rotates at -//! each UTC calendar day (`sendbox-fleet.YYYY-MM-DD.log`) and +//! each UTC calendar day (`sendbox-fleet.YYYY-MM-DD.log`) and whenever a file +//! reaches the configured size (`sendbox-fleet.YYYY-MM-DD.N.log`); //! [`retention`] removes inactive files once they are older than the //! configured retention window. Request bodies, headers, and query strings are //! never logged. pub mod retention; +pub mod rotation; use std::io; use std::path::{Component, Path, PathBuf}; @@ -19,7 +21,6 @@ use actix_web::dev::{ServiceRequest, ServiceResponse}; use actix_web::middleware::Next; use thiserror::Error; use tracing_appender::non_blocking::{NonBlockingBuilder, WorkerGuard}; -use tracing_appender::rolling::{RollingFileAppender, Rotation}; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, fmt}; @@ -40,10 +41,7 @@ pub enum LoggingError { #[error("cannot create log directory {path}: {source}")] CreateDir { path: PathBuf, source: io::Error }, #[error("cannot open log file in {path}: {source}")] - Appender { - path: PathBuf, - source: tracing_appender::rolling::InitError, - }, + Appender { path: PathBuf, source: io::Error }, #[error("invalid log filter: {0}")] Filter(String), #[error("a global tracing subscriber is already installed: {0}")] @@ -61,15 +59,12 @@ pub struct LoggingGuard { pub fn init(config: &LogConfig) -> Result { let dir = resolve_dir(&config.dir)?; create_private_dir(&dir)?; - let appender = RollingFileAppender::builder() - .rotation(Rotation::DAILY) - .filename_prefix(LOG_FILE_PREFIX) - .filename_suffix(LOG_FILE_SUFFIX) - .build(&dir) - .map_err(|source| LoggingError::Appender { + let appender = rotation::RotatingFile::new(&dir, config.max_file_bytes).map_err(|source| { + LoggingError::Appender { path: dir.clone(), source, - })?; + } + })?; let (file_writer, guard) = NonBlockingBuilder::default() .lossy(false) .buffered_lines_limit(FILE_QUEUE_LINES) @@ -143,6 +138,14 @@ pub async fn request_log( let started = Instant::now(); let response = next.call(request).await; let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let micros = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX); + crate::metrics::METRICS.request( + match &response { + Ok(response) => response.status().as_u16(), + Err(error) => error.as_response_error().status_code().as_u16(), + }, + micros, + ); match &response { Ok(response) => tracing::info!( request_id, diff --git a/crates/fleet-server/src/logging/retention.rs b/crates/fleet-server/src/logging/retention.rs index 95876f6..d9df471 100644 --- a/crates/fleet-server/src/logging/retention.rs +++ b/crates/fleet-server/src/logging/retention.rs @@ -1,7 +1,8 @@ //! Deletes inactive log files older than the retention window. //! -//! Only regular files named `sendbox-fleet.YYYY-MM-DD.log` directly inside the -//! log directory are candidates; symlinks, directories, and every other file +//! Only regular files named `sendbox-fleet.YYYY-MM-DD.log` (or a size-rotated +//! part `sendbox-fleet.YYYY-MM-DD.N.log`) directly inside the log directory are +//! candidates; symlinks, directories, and every other file //! are left untouched. A file's age comes from the UTC date in its name, not //! its modification time, so copying or touching a file does not extend its //! retention. A file is deleted when its last possible record (the end of its @@ -62,13 +63,25 @@ pub fn enforce( Ok(report) } -/// The UTC day encoded in a file name produced by the daily appender. +/// The UTC day encoded in a file name produced by the log writer. fn log_file_day(name: &str) -> Option { - let date = name + let stem = name .strip_prefix(LOG_FILE_PREFIX)? .strip_prefix('.')? .strip_suffix(LOG_FILE_SUFFIX)? .strip_suffix('.')?; + let date = match stem.split_once('.') { + None => stem, + Some((date, part)) + if !part.is_empty() + && part.len() <= 4 + && !part.starts_with('0') + && part.bytes().all(|byte| byte.is_ascii_digit()) => + { + date + } + Some(_) => return None, + }; let bytes = date.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { return None; @@ -114,6 +127,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); for name in [ "sendbox-fleet.2026-09-01.log", + "sendbox-fleet.2026-09-01.12.log", "sendbox-fleet.2026-10-15.log", "sendbox-fleet.2026-10-16.log", "sendbox-fleet.2026-11-15.log", @@ -124,6 +138,7 @@ mod tests { assert_eq!( deleted_names(&report), [ + "sendbox-fleet.2026-09-01.12.log", "sendbox-fleet.2026-09-01.log", "sendbox-fleet.2026-10-15.log" ] @@ -149,6 +164,8 @@ mod tests { "sendbox-fleet.2020-01-01.txt", "sendbox-fleet.2020-13-01.log", "sendbox-fleet.2020-1-01.log", + "sendbox-fleet.2020-01-01.01.log", + "sendbox-fleet.2020-01-01.x.log", "sendbox-fleet.log", ]; for name in keep { diff --git a/crates/fleet-server/src/logging/rotation.rs b/crates/fleet-server/src/logging/rotation.rs new file mode 100644 index 0000000..848f7e6 --- /dev/null +++ b/crates/fleet-server/src/logging/rotation.rs @@ -0,0 +1,174 @@ +//! Log file writer that rotates at each UTC day and when a file reaches a +//! size limit. +//! +//! The first file of a day is `sendbox-fleet.YYYY-MM-DD.log`; when it reaches +//! the limit, writing continues in `sendbox-fleet.YYYY-MM-DD.1.log`, `.2.log`, +//! and so on. Files are created with mode `0600`. A single background thread +//! owns the writer, so no locking is needed. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Write}; +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt as _; +use std::path::{Path, PathBuf}; + +use time::{Date, OffsetDateTime}; + +use super::{LOG_FILE_PREFIX, LOG_FILE_SUFFIX}; + +/// Highest part number tried for one day before writing to the last one. +const MAX_PARTS: u32 = 9_999; + +pub type Today = Box Date + Send>; + +struct Current { + day: Date, + part: u32, + file: File, + size: u64, +} + +pub struct RotatingFile { + dir: PathBuf, + max_bytes: u64, + today: Today, + current: Option, +} + +/// The file name of one part of a day's log. +#[must_use] +pub fn file_name(day: Date, part: u32) -> String { + if part == 0 { + format!("{LOG_FILE_PREFIX}.{day}.{LOG_FILE_SUFFIX}") + } else { + format!("{LOG_FILE_PREFIX}.{day}.{part}.{LOG_FILE_SUFFIX}") + } +} + +impl RotatingFile { + pub fn new(dir: &Path, max_bytes: u64) -> io::Result { + Self::with_clock( + dir, + max_bytes, + Box::new(|| OffsetDateTime::now_utc().date()), + ) + } + + pub fn with_clock(dir: &Path, max_bytes: u64, today: Today) -> io::Result { + let mut writer = Self { + dir: dir.to_path_buf(), + max_bytes: max_bytes.max(1), + today, + current: None, + }; + writer.ensure(0)?; + Ok(writer) + } + + fn open(&self, day: Date, part: u32) -> io::Result { + let mut options = OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + options.mode(0o600); + let file = options.open(self.dir.join(file_name(day, part)))?; + let size = file.metadata()?.len(); + Ok(Current { + day, + part, + file, + size, + }) + } + + /// Makes sure the current file is today's and has room for `incoming` + /// bytes, starting a new part when it is full. + fn ensure(&mut self, incoming: u64) -> io::Result<()> { + let day = (self.today)(); + let mut part = match &self.current { + Some(current) if current.day == day => { + if current.size == 0 || current.size + incoming <= self.max_bytes { + return Ok(()); + } + current.part + 1 + } + _ => 0, + }; + loop { + let opened = self.open(day, part)?; + if opened.size == 0 || opened.size + incoming <= self.max_bytes || part >= MAX_PARTS { + if let Some(previous) = self.current.as_mut() { + previous.file.flush()?; + } + self.current = Some(opened); + return Ok(()); + } + part += 1; + } + } +} + +impl Write for RotatingFile { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.ensure(buffer.len() as u64)?; + let current = self + .current + .as_mut() + .ok_or_else(|| io::Error::other("no log file is open"))?; + let written = current.file.write(buffer)?; + current.size += written as u64; + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + match self.current.as_mut() { + Some(current) => current.file.flush(), + None => Ok(()), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicU8, Ordering}; + + use time::macros::date; + + use super::*; + + #[test] + fn rotates_by_size_within_a_day_and_at_each_day() { + let dir = tempfile::tempdir().unwrap(); + let day = Arc::new(AtomicU8::new(15)); + let clock = Arc::clone(&day); + let mut writer = RotatingFile::with_clock( + dir.path(), + 10, + Box::new(move || { + date!(2026 - 11 - 01) + .replace_day(clock.load(Ordering::SeqCst)) + .unwrap() + }), + ) + .unwrap(); + for line in ["12345678\n", "abcdefgh\n", "ABCDEFGH\n"] { + writer.write_all(line.as_bytes()).unwrap(); + } + day.store(16, Ordering::SeqCst); + writer.write_all(b"next day\n").unwrap(); + writer.flush().unwrap(); + let read = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap(); + assert_eq!(read("sendbox-fleet.2026-11-15.log"), "12345678\n"); + assert_eq!(read("sendbox-fleet.2026-11-15.1.log"), "abcdefgh\n"); + assert_eq!(read("sendbox-fleet.2026-11-15.2.log"), "ABCDEFGH\n"); + assert_eq!(read("sendbox-fleet.2026-11-16.log"), "next day\n"); + + drop(writer); + day.store(15, Ordering::SeqCst); + let mut reopened = + RotatingFile::with_clock(dir.path(), 10, Box::new(|| date!(2026 - 11 - 15))).unwrap(); + reopened.write_all(b"restart\n").unwrap(); + reopened.flush().unwrap(); + assert_eq!(read("sendbox-fleet.2026-11-15.3.log"), "restart\n"); + } +} diff --git a/crates/fleet-server/src/main.rs b/crates/fleet-server/src/main.rs index b33f4c3..17d2661 100644 --- a/crates/fleet-server/src/main.rs +++ b/crates/fleet-server/src/main.rs @@ -3,8 +3,8 @@ use std::process::ExitCode; use clap::{Parser, Subcommand}; -use fleet_server::admin::{self, AdminCommand}; -use fleet_server::config::{Config, DATABASE_URL_VAR, DatabaseUrl}; +use fleet_server::admin::{self, AdminCommand, AuditCommand}; +use fleet_server::config::{Config, DATABASE_URL_VAR, DatabaseUrl, MIGRATE_VAR, parse_migrate}; use fleet_server::{logging, server}; /// SendBox shared governance service. @@ -32,23 +32,33 @@ fn main() -> ExitCode { } fn run_admin(command: AdminCommand) -> ExitCode { - let url = match std::env::var(DATABASE_URL_VAR) + let report = |result: Result<(), admin::AdminError>| match result { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("sendbox-fleet admin: {error}"); + ExitCode::FAILURE + } + }; + if let AdminCommand::Audit(AuditCommand::Keygen { output }) = &command { + return report(admin::keygen(output)); + } + let settings = std::env::var(DATABASE_URL_VAR) .map_err(|_| format!("{DATABASE_URL_VAR} is required")) .and_then(|url| DatabaseUrl::parse(&url).map_err(|error| error.to_string())) - { - Ok(url) => url, + .and_then(|url| { + let migrate = std::env::var(MIGRATE_VAR).ok(); + parse_migrate(migrate.as_deref()) + .map(|migrate| (url, migrate)) + .map_err(|error| error.to_string()) + }); + let (url, migrate) = match settings { + Ok(settings) => settings, Err(error) => { eprintln!("sendbox-fleet: configuration error: {error}"); return ExitCode::from(2); } }; - match actix_web::rt::System::new().block_on(admin::run(&url, command)) { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("sendbox-fleet admin: {error}"); - ExitCode::FAILURE - } - } + report(actix_web::rt::System::new().block_on(admin::run(&url, migrate, command))) } fn serve() -> ExitCode { diff --git a/crates/fleet-server/src/metrics.rs b/crates/fleet-server/src/metrics.rs new file mode 100644 index 0000000..04b7188 --- /dev/null +++ b/crates/fleet-server/src/metrics.rs @@ -0,0 +1,168 @@ +//! Process metrics in the Prometheus text format, served on the separate, +//! unauthenticated `FLEET_METRICS_BIND` listener. Labels carry only status +//! classes, decision kinds, and deny-reason codes, never identifiers. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use actix_web::{HttpResponse, web}; + +#[derive(Default)] +pub struct Metrics { + requests: [AtomicU64; 5], + request_seconds_micros: AtomicU64, + auth_failures: AtomicU64, + rate_limited: AtomicU64, + audit_events: AtomicU64, + audit_sequence: AtomicU64, + decisions: Mutex>, +} + +pub static METRICS: std::sync::LazyLock = std::sync::LazyLock::new(Metrics::default); + +impl Metrics { + pub fn request(&self, status: u16, micros: u64) { + let class = usize::from((status / 100).clamp(1, 5)) - 1; + self.requests[class].fetch_add(1, Ordering::Relaxed); + self.request_seconds_micros + .fetch_add(micros, Ordering::Relaxed); + } + + pub fn auth_failure(&self) { + self.auth_failures.fetch_add(1, Ordering::Relaxed); + } + + pub fn rate_limited(&self) { + self.rate_limited.fetch_add(1, Ordering::Relaxed); + } + + pub fn audit_appended(&self, sequence: u64) { + self.audit_events.fetch_add(1, Ordering::Relaxed); + self.audit_head(sequence); + } + + /// Raises the audit head gauge, for example from the database at startup. + pub fn audit_head(&self, sequence: u64) { + self.audit_sequence.fetch_max(sequence, Ordering::Relaxed); + } + + /// One authorization decision: `allow`, or `deny` with its reason code. + pub fn decision(&self, decision: &'static str, reason: &'static str) { + *self + .decisions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .entry((decision, reason)) + .or_default() += 1; + } + + #[must_use] + pub fn render(&self) -> String { + let mut out = String::new(); + let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed); + let _ = writeln!( + out, + "# HELP fleet_http_requests_total HTTP requests by status class." + ); + let _ = writeln!(out, "# TYPE fleet_http_requests_total counter"); + let mut total = 0; + for (index, class) in ["1xx", "2xx", "3xx", "4xx", "5xx"].iter().enumerate() { + let count = load(&self.requests[index]); + total += count; + let _ = writeln!( + out, + "fleet_http_requests_total{{class=\"{class}\"}} {count}" + ); + } + let _ = writeln!( + out, + "# HELP fleet_http_request_duration_seconds Total time spent serving requests." + ); + let _ = writeln!(out, "# TYPE fleet_http_request_duration_seconds summary"); + #[allow(clippy::cast_precision_loss)] + let seconds = load(&self.request_seconds_micros) as f64 / 1_000_000.0; + let _ = writeln!(out, "fleet_http_request_duration_seconds_sum {seconds}"); + let _ = writeln!(out, "fleet_http_request_duration_seconds_count {total}"); + for (name, help, counter) in [ + ( + "fleet_auth_failures_total", + "Rejected bearer tokens.", + &self.auth_failures, + ), + ( + "fleet_rate_limited_total", + "Requests refused by a rate limit.", + &self.rate_limited, + ), + ( + "fleet_audit_events_total", + "Audit events appended by this process.", + &self.audit_events, + ), + ] { + let _ = writeln!(out, "# HELP {name} {help}"); + let _ = writeln!(out, "# TYPE {name} counter"); + let _ = writeln!(out, "{name} {}", load(counter)); + } + let _ = writeln!( + out, + "# HELP fleet_audit_sequence Highest audit sequence in the chain." + ); + let _ = writeln!(out, "# TYPE fleet_audit_sequence gauge"); + let _ = writeln!(out, "fleet_audit_sequence {}", load(&self.audit_sequence)); + let _ = writeln!( + out, + "# HELP fleet_authorization_decisions_total Per-request grant decisions." + ); + let _ = writeln!(out, "# TYPE fleet_authorization_decisions_total counter"); + for ((decision, reason), count) in self + .decisions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + { + let _ = writeln!( + out, + "fleet_authorization_decisions_total{{decision=\"{decision}\",reason=\"{reason}\"}} {count}" + ); + } + out + } +} + +pub async fn serve_metrics() -> HttpResponse { + HttpResponse::Ok() + .content_type("text/plain; version=0.0.4; charset=utf-8") + .insert_header((actix_web::http::header::CACHE_CONTROL, "no-store")) + .body(METRICS.render()) +} + +pub fn configure(config: &mut web::ServiceConfig) { + config.route("/metrics", web::get().to(serve_metrics)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renders_counters_without_identifiers() { + let metrics = Metrics::default(); + metrics.request(200, 1_500_000); + metrics.request(404, 500_000); + metrics.decision("deny", "stale_policy"); + metrics.decision("allow", "none"); + metrics.audit_appended(7); + let text = metrics.render(); + assert!(text.contains("fleet_http_requests_total{class=\"2xx\"} 1")); + assert!(text.contains("fleet_http_requests_total{class=\"4xx\"} 1")); + assert!(text.contains("fleet_http_request_duration_seconds_sum 2")); + assert!(text.contains("fleet_http_request_duration_seconds_count 2")); + assert!(text.contains( + "fleet_authorization_decisions_total{decision=\"deny\",reason=\"stale_policy\"} 1" + )); + assert!(text.contains("fleet_audit_sequence 7")); + } +} diff --git a/crates/fleet-server/src/oidc.rs b/crates/fleet-server/src/oidc.rs new file mode 100644 index 0000000..87c93af --- /dev/null +++ b/crates/fleet-server/src/oidc.rs @@ -0,0 +1,712 @@ +//! OpenID Connect bearer tokens from configured identity providers. +//! +//! People and machine identities (for example GitHub Actions) present a +//! signed JWT. The service accepts it only when: +//! +//! - its `iss` exactly matches a configured issuer and its `aud` contains one +//! of that issuer's audiences; +//! - its signature verifies with a key from the issuer's JWKS (fetched over +//! HTTPS, cached, and refreshed when an unknown key id appears), using an +//! algorithm the issuer allows (`RS256`, `ES256`, `EdDSA`); +//! - `exp` is in the future and `nbf`/`iat` are not, within a small leeway; +//! - required claims match exactly, and `email_verified` is true when the +//! principal comes from `email`. +//! +//! The principal is `:` and must fit +//! the shared identifier grammar. Signatures are checked with `ring`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ring::signature::{self, UnparsedPublicKey}; +use sendbox_governance::{Clock, PrincipalId}; +use serde::Deserialize; +use serde_json::{Map, Value}; +use thiserror::Error; + +use crate::auth::CallerKind; +use crate::config::{ConfigError, OIDC_CONFIG_VAR}; + +const MAX_CONFIG_BYTES: u64 = 64 * 1024; +const MAX_ISSUERS: usize = 16; +const MAX_DOCUMENT_BYTES: usize = 64 * 1024; +const MAX_JWKS_BYTES: usize = 256 * 1024; +const MAX_KEYS: usize = 64; +const FETCH_TIMEOUT: Duration = Duration::from_secs(5); +const MIN_REFRESH_INTERVAL: Duration = Duration::from_secs(30); +const MAX_LEEWAY_SECONDS: u64 = 300; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)] +pub enum Algorithm { + RS256, + ES256, + EdDSA, +} + +impl Algorithm { + fn parse(value: &str) -> Option { + match value { + "RS256" => Some(Self::RS256), + "ES256" => Some(Self::ES256), + "EdDSA" => Some(Self::EdDSA), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IssuerKind { + User, + Worker, +} + +impl From for CallerKind { + fn from(kind: IssuerKind) -> Self { + match kind { + IssuerKind::User => Self::User, + IssuerKind::Worker => Self::Worker, + } + } +} + +/// One trusted identity provider. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IssuerConfig { + /// Exact `iss` claim, for example `https://token.actions.githubusercontent.com`. + pub issuer: String, + /// Accepted `aud` values; at least one must be present in the token. + pub audiences: Vec, + pub kind: IssuerKind, + /// Claim that names the principal, such as `email`, `sub`, or `repository_id`. + pub principal_claim: String, + /// Prefix of the principal id, such as `oidc` or `github-actions`. + pub principal_prefix: String, + /// Defaults to true when `principal_claim` is `email`. + #[serde(default)] + pub require_email_verified: Option, + /// Create unknown principals (with no roles) on first use. + #[serde(default)] + pub auto_provision: bool, + /// Skips discovery when set. + #[serde(default)] + pub jwks_uri: Option, + #[serde(default = "default_algorithms")] + pub algorithms: Vec, + /// Claims that must equal these strings, for example + /// `repository_owner: example` for GitHub Actions. + #[serde(default)] + pub required_claims: BTreeMap, + #[serde(default = "default_cache_seconds")] + pub jwks_cache_seconds: u64, + #[serde(default = "default_leeway_seconds")] + pub leeway_seconds: u64, +} + +fn default_algorithms() -> Vec { + vec![Algorithm::RS256, Algorithm::ES256, Algorithm::EdDSA] +} + +const fn default_cache_seconds() -> u64 { + 600 +} + +const fn default_leeway_seconds() -> u64 { + 60 +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OidcConfig { + pub issuers: Vec, +} + +/// `https://`, or `http://` to a loopback host for local testing. +pub(crate) fn trusted_url(value: &str) -> Option { + let url = reqwest::Url::parse(value).ok()?; + let loopback = match url.host() { + Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + None => false, + }; + let scheme_ok = url.scheme() == "https" || (url.scheme() == "http" && loopback); + (scheme_ok && url.username().is_empty() && url.password().is_none() && url.fragment().is_none()) + .then_some(url) +} + +impl OidcConfig { + pub fn load(path: &Path) -> Result { + use std::io::Read as _; + let invalid = |reason: String| ConfigError::Invalid { + name: OIDC_CONFIG_VAR, + reason, + }; + let mut bytes = Vec::new(); + std::fs::File::open(path) + .and_then(|file| file.take(MAX_CONFIG_BYTES + 1).read_to_end(&mut bytes)) + .map_err(|error| invalid(format!("cannot read {}: {error}", path.display())))?; + if bytes.len() as u64 > MAX_CONFIG_BYTES { + return Err(invalid(format!("{} is too large", path.display()))); + } + let text = std::str::from_utf8(&bytes).map_err(|_| invalid("must be UTF-8".to_owned()))?; + let config: Self = + serde_yaml_ng::from_str(text).map_err(|error| invalid(error.to_string()))?; + config.validate().map_err(invalid)?; + Ok(config) + } + + fn validate(&self) -> Result<(), String> { + if self.issuers.is_empty() || self.issuers.len() > MAX_ISSUERS { + return Err(format!("list 1 to {MAX_ISSUERS} issuers")); + } + let mut issuers = BTreeSet::new(); + let mut prefixes = BTreeSet::new(); + for issuer in &self.issuers { + let name = &issuer.issuer; + if trusted_url(name).is_none() { + return Err(format!( + "issuer `{name}` must be an https URL (http only for loopback)" + )); + } + if !issuers.insert(name.as_str()) { + return Err(format!("issuer `{name}` is listed twice")); + } + if issuer.audiences.is_empty() + || issuer + .audiences + .iter() + .any(|audience| audience.is_empty() || audience.len() > 256) + { + return Err(format!("issuer `{name}` needs 1 or more bounded audiences")); + } + let prefix = &issuer.principal_prefix; + let valid_prefix = !prefix.is_empty() + && prefix.len() <= 32 + && prefix + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte == b'-') + && prefix != "local-user"; + if !valid_prefix || !prefixes.insert(prefix.as_str()) { + return Err(format!( + "issuer `{name}` needs a unique principal_prefix of 1-32 lowercase letters or `-`, not `local-user`" + )); + } + if issuer.principal_claim.is_empty() || issuer.principal_claim.len() > 64 { + return Err(format!("issuer `{name}` needs a principal_claim")); + } + if issuer.algorithms.is_empty() { + return Err(format!("issuer `{name}` must allow at least one algorithm")); + } + if let Some(uri) = &issuer.jwks_uri + && trusted_url(uri).is_none() + { + return Err(format!("issuer `{name}` jwks_uri must be an https URL")); + } + if !(60..=86_400).contains(&issuer.jwks_cache_seconds) { + return Err(format!( + "issuer `{name}` jwks_cache_seconds must be 60..=86400" + )); + } + if issuer.leeway_seconds > MAX_LEEWAY_SECONDS { + return Err(format!( + "issuer `{name}` leeway_seconds must be at most {MAX_LEEWAY_SECONDS}" + )); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum OidcError { + /// The token is not acceptable; the caller should see `401`. The reason + /// is a fixed code for the server log, never shown to the caller. + #[error("identity token was not accepted: {0}")] + Rejected(&'static str), + /// The issuer's keys could not be fetched; the caller should see `503`. + #[error("identity provider keys are unavailable")] + Unavailable, +} + +/// A validated identity-provider caller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OidcIdentity { + pub principal: PrincipalId, + pub kind: CallerKind, + pub issuer: String, + pub auto_provision: bool, +} + +#[derive(Debug, Clone)] +struct PublicKey { + kid: Option, + algorithm: Algorithm, + /// Encoded for `ring`: RSA (n, e), an uncompressed P-256 point, or raw + /// Ed25519 bytes. + material: KeyMaterial, +} + +#[derive(Debug, Clone)] +enum KeyMaterial { + Rsa { n: Vec, e: Vec }, + Raw(Vec), +} + +struct CachedKeys { + keys: Vec, + fetched: Instant, +} + +struct IssuerState { + config: IssuerConfig, + cache: tokio::sync::Mutex>, + last_refresh: Mutex>, +} + +/// Validates bearer JWTs against the configured issuers. +pub struct OidcVerifier { + issuers: Vec, + http: reqwest::Client, + clock: Arc, + min_refresh: Duration, +} + +fn b64(value: &str) -> Result, OidcError> { + if value.contains('=') { + return Err(OidcError::Rejected("malformed")); + } + URL_SAFE_NO_PAD + .decode(value) + .map_err(|_| OidcError::Rejected("malformed")) +} + +fn object(bytes: &[u8]) -> Result, OidcError> { + match serde_json::from_slice(bytes) { + Ok(Value::Object(map)) => Ok(map), + _ => Err(OidcError::Rejected("malformed")), + } +} + +/// Parses one JWK, or `None` when it is unsupported or not a signing key. +fn parse_jwk(jwk: &Map) -> Option { + let text = |name: &str| jwk.get(name).and_then(Value::as_str); + if text("use").is_some_and(|value| value != "sig") { + return None; + } + let declared = text("alg").map(Algorithm::parse); + let decode = |name: &str| text(name).and_then(|value| URL_SAFE_NO_PAD.decode(value).ok()); + let (algorithm, material) = match (text("kty")?, text("crv")) { + ("RSA", _) => { + let n = decode("n")?; + if n.len() < 256 { + return None; + } + (Algorithm::RS256, KeyMaterial::Rsa { n, e: decode("e")? }) + } + ("EC", Some("P-256")) => { + let (x, y) = (decode("x")?, decode("y")?); + if x.len() != 32 || y.len() != 32 { + return None; + } + let mut point = vec![0x04]; + point.extend_from_slice(&x); + point.extend_from_slice(&y); + (Algorithm::ES256, KeyMaterial::Raw(point)) + } + ("OKP", Some("Ed25519")) => { + let x = decode("x")?; + if x.len() != 32 { + return None; + } + (Algorithm::EdDSA, KeyMaterial::Raw(x)) + } + _ => return None, + }; + if declared.is_some_and(|declared| declared != Some(algorithm)) { + return None; + } + Some(PublicKey { + kid: text("kid").map(str::to_owned), + algorithm, + material, + }) +} + +/// Verifies a JWS signature with one public key. +fn verify_signature(key: &PublicKey, message: &[u8], signature_bytes: &[u8]) -> bool { + match (&key.material, key.algorithm) { + (KeyMaterial::Rsa { n, e }, Algorithm::RS256) => signature::RsaPublicKeyComponents { n, e } + .verify( + &signature::RSA_PKCS1_2048_8192_SHA256, + message, + signature_bytes, + ) + .is_ok(), + (KeyMaterial::Raw(point), Algorithm::ES256) => { + UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_FIXED, point) + .verify(message, signature_bytes) + .is_ok() + } + (KeyMaterial::Raw(public), Algorithm::EdDSA) => { + UnparsedPublicKey::new(&signature::ED25519, public) + .verify(message, signature_bytes) + .is_ok() + } + _ => false, + } +} + +impl OidcVerifier { + pub fn new(config: OidcConfig, clock: Arc) -> Result { + // reqwest is built without a bundled crypto provider; use ring, as the + // rest of the service does. Installing twice is harmless. + let _ = rustls::crypto::ring::default_provider().install_default(); + let http = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(FETCH_TIMEOUT) + .build() + .map_err(|error| ConfigError::Invalid { + name: OIDC_CONFIG_VAR, + reason: format!("cannot build the HTTPS client: {error}"), + })?; + Ok(Self { + issuers: config + .issuers + .into_iter() + .map(|config| IssuerState { + config, + cache: tokio::sync::Mutex::new(None), + last_refresh: Mutex::new(None), + }) + .collect(), + http, + clock, + min_refresh: MIN_REFRESH_INTERVAL, + }) + } + + /// Sets the minimum time between JWKS refreshes forced by unknown key + /// ids (default 30 seconds). + #[must_use] + pub fn with_min_refresh_interval(mut self, interval: Duration) -> Self { + self.min_refresh = interval; + self + } + + async fn fetch(&self, url: &str, limit: usize) -> Result, OidcError> { + let url = trusted_url(url).ok_or(OidcError::Unavailable)?; + let response = self + .http + .get(url) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .await + .map_err(|error| { + tracing::warn!(error = %error.without_url(), "identity provider request failed"); + OidcError::Unavailable + })?; + if !response.status().is_success() { + tracing::warn!(status = %response.status(), "identity provider returned an error"); + return Err(OidcError::Unavailable); + } + if response + .content_length() + .is_some_and(|length| length > limit as u64) + { + return Err(OidcError::Unavailable); + } + let bytes = response.bytes().await.map_err(|_| OidcError::Unavailable)?; + if bytes.len() > limit { + return Err(OidcError::Unavailable); + } + object(&bytes).map_err(|_| OidcError::Unavailable) + } + + async fn load_keys(&self, issuer: &IssuerConfig) -> Result, OidcError> { + let jwks_uri = match &issuer.jwks_uri { + Some(uri) => uri.clone(), + None => { + let discovery = format!( + "{}/.well-known/openid-configuration", + issuer.issuer.trim_end_matches('/') + ); + let document = self.fetch(&discovery, MAX_DOCUMENT_BYTES).await?; + if document.get("issuer").and_then(Value::as_str) != Some(issuer.issuer.as_str()) { + tracing::warn!(issuer = %issuer.issuer, "discovery document names another issuer"); + return Err(OidcError::Unavailable); + } + document + .get("jwks_uri") + .and_then(Value::as_str) + .ok_or(OidcError::Unavailable)? + .to_owned() + } + }; + let jwks = self.fetch(&jwks_uri, MAX_JWKS_BYTES).await?; + let keys = jwks + .get("keys") + .and_then(Value::as_array) + .ok_or(OidcError::Unavailable)? + .iter() + .take(MAX_KEYS) + .filter_map(Value::as_object) + .filter_map(parse_jwk) + .filter(|key| issuer.algorithms.contains(&key.algorithm)) + .collect::>(); + if keys.is_empty() { + tracing::warn!(issuer = %issuer.issuer, "identity provider published no usable keys"); + return Err(OidcError::Unavailable); + } + Ok(keys) + } + + /// Cached keys, refreshed after `jwks_cache_seconds` or (at most every + /// 30 seconds) when `force` reports an unknown key id. + async fn keys(&self, state: &IssuerState, force: bool) -> Result, OidcError> { + let mut cache = state.cache.lock().await; + let ttl = Duration::from_secs(state.config.jwks_cache_seconds); + let fresh = cache + .as_ref() + .is_some_and(|cached| cached.fetched.elapsed() < ttl); + let may_refresh = { + let mut last = state + .last_refresh + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let allowed = last.is_none_or(|at| at.elapsed() >= self.min_refresh); + if (!fresh || force) && allowed { + *last = Some(Instant::now()); + } + allowed + }; + if (!fresh || force) && may_refresh { + match self.load_keys(&state.config).await { + Ok(keys) => { + *cache = Some(CachedKeys { + keys, + fetched: Instant::now(), + }); + } + Err(error) if cache.is_none() || !fresh => return Err(error), + Err(_) => {} + } + } + cache + .as_ref() + .map(|cached| cached.keys.clone()) + .ok_or(OidcError::Unavailable) + } + + /// Whether `token` looks like a compact JWS this verifier should handle. + #[must_use] + pub fn handles(token: &str) -> bool { + token.split('.').count() == 3 + } + + pub async fn verify(&self, token: &str) -> Result { + let mut parts = token.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(OidcError::Rejected("malformed")); + }; + let header_json = object(&b64(header)?)?; + let claims = object(&b64(payload)?)?; + let signature_bytes = b64(signature)?; + if header_json.contains_key("crit") { + return Err(OidcError::Rejected("critical_header")); + } + let algorithm = header_json + .get("alg") + .and_then(Value::as_str) + .and_then(Algorithm::parse) + .ok_or(OidcError::Rejected("unsupported_algorithm"))?; + let kid = header_json.get("kid").and_then(Value::as_str); + let issuer = claims + .get("iss") + .and_then(Value::as_str) + .ok_or(OidcError::Rejected("missing_issuer"))?; + let state = self + .issuers + .iter() + .find(|state| state.config.issuer == issuer) + .ok_or(OidcError::Rejected("unknown_issuer"))?; + let config = &state.config; + if !config.algorithms.contains(&algorithm) { + return Err(OidcError::Rejected("algorithm_not_allowed")); + } + let message = &token.as_bytes()[..header.len() + 1 + payload.len()]; + let candidates = |keys: &[PublicKey]| { + keys.iter() + .filter(|key| { + key.algorithm == algorithm + && kid.is_none_or(|kid| key.kid.as_deref() == Some(kid)) + }) + .cloned() + .collect::>() + }; + let mut matching = candidates(&self.keys(state, false).await?); + if matching.is_empty() && kid.is_some() { + matching = candidates(&self.keys(state, true).await?); + } + if matching.is_empty() { + return Err(OidcError::Rejected("unknown_key")); + } + if kid.is_none() && matching.len() != 1 { + return Err(OidcError::Rejected("ambiguous_key")); + } + if !matching + .iter() + .any(|key| verify_signature(key, message, &signature_bytes)) + { + return Err(OidcError::Rejected("bad_signature")); + } + self.check_claims(config, &claims)?; + let value = claims + .get(&config.principal_claim) + .and_then(|value| match value { + Value::String(text) => Some(text.clone()), + Value::Number(number) => Some(number.to_string()), + _ => None, + }) + .ok_or(OidcError::Rejected("missing_principal_claim"))?; + let principal = PrincipalId::new(format!("{}:{value}", config.principal_prefix)) + .map_err(|_| OidcError::Rejected("invalid_principal"))?; + Ok(OidcIdentity { + principal, + kind: config.kind.into(), + issuer: config.issuer.clone(), + auto_provision: config.auto_provision, + }) + } + + fn check_claims( + &self, + config: &IssuerConfig, + claims: &Map, + ) -> Result<(), OidcError> { + let now = self.clock.now_unix(); + let leeway = config.leeway_seconds; + let time = |name: &str| claims.get(name).and_then(Value::as_u64); + let expires = time("exp").ok_or(OidcError::Rejected("missing_expiry"))?; + if now >= expires.saturating_add(leeway) { + return Err(OidcError::Rejected("expired")); + } + if time("nbf").is_some_and(|not_before| now.saturating_add(leeway) < not_before) + || time("iat").is_some_and(|issued| now.saturating_add(leeway) < issued) + || claims.get("nbf").is_some_and(|value| !value.is_u64()) + || claims.get("iat").is_some_and(|value| !value.is_u64()) + { + return Err(OidcError::Rejected("not_yet_valid")); + } + let audience_ok = match claims.get("aud") { + Some(Value::String(audience)) => config.audiences.contains(audience), + Some(Value::Array(audiences)) => audiences + .iter() + .filter_map(Value::as_str) + .any(|audience| config.audiences.iter().any(|allowed| allowed == audience)), + _ => false, + }; + if !audience_ok { + return Err(OidcError::Rejected("audience_mismatch")); + } + if !config + .required_claims + .iter() + .all(|(name, expected)| claims.get(name).and_then(Value::as_str) == Some(expected)) + { + return Err(OidcError::Rejected("required_claim_mismatch")); + } + let email_verified = config + .require_email_verified + .unwrap_or(config.principal_claim == "email"); + if email_verified && claims.get("email_verified") != Some(&Value::Bool(true)) { + return Err(OidcError::Rejected("email_not_verified")); + } + Ok(()) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// RFC 7515 Appendix A.2: RS256 key and signature. + #[test] + fn rs256_signatures_verify_against_the_rfc_7515_example() { + let jwk = serde_json::json!({ + "kty": "RSA", + "n": "ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ", + "e": "AQAB" + }); + let key = parse_jwk(jwk.as_object().unwrap()).expect("rsa key"); + let header = "eyJhbGciOiJSUzI1NiJ9"; + let payload = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"; + let signature = "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"; + let message = format!("{header}.{payload}"); + let bytes = URL_SAFE_NO_PAD.decode(signature).unwrap(); + assert!(verify_signature(&key, message.as_bytes(), &bytes)); + assert!(!verify_signature(&key, b"tampered", &bytes)); + } + + #[test] + fn jwks_reject_mismatched_or_weak_keys() { + let ed = |x: &str, alg: &str| serde_json::json!({ "kty": "OKP", "crv": "Ed25519", "x": x, "alg": alg }); + let x = URL_SAFE_NO_PAD.encode([7_u8; 32]); + assert!(parse_jwk(ed(&x, "EdDSA").as_object().unwrap()).is_some()); + assert!(parse_jwk(ed(&x, "RS256").as_object().unwrap()).is_none()); + let short = URL_SAFE_NO_PAD.encode([7_u8; 31]); + assert!(parse_jwk(ed(&short, "EdDSA").as_object().unwrap()).is_none()); + let weak_rsa = serde_json::json!({ + "kty": "RSA", "n": URL_SAFE_NO_PAD.encode([1_u8; 128]), "e": "AQAB" + }); + assert!(parse_jwk(weak_rsa.as_object().unwrap()).is_none()); + let encryption = serde_json::json!({ + "kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc" + }); + assert!(parse_jwk(encryption.as_object().unwrap()).is_none()); + } + + #[test] + fn issuer_configuration_is_validated() { + let issuer = |name: &str, prefix: &str| IssuerConfig { + issuer: name.to_owned(), + audiences: vec!["sendbox-fleet".to_owned()], + kind: IssuerKind::User, + principal_claim: "email".to_owned(), + principal_prefix: prefix.to_owned(), + require_email_verified: None, + auto_provision: false, + jwks_uri: None, + algorithms: default_algorithms(), + required_claims: BTreeMap::new(), + jwks_cache_seconds: 600, + leeway_seconds: 60, + }; + let valid = OidcConfig { + issuers: vec![ + issuer("https://login.example.com", "oidc"), + issuer("http://127.0.0.1:9000", "ci"), + ], + }; + assert!(valid.validate().is_ok()); + for broken in [ + vec![issuer("http://login.example.com", "oidc")], + vec![issuer("https://login.example.com", "local-user")], + vec![ + issuer("https://a.example.com", "oidc"), + issuer("https://b.example.com", "oidc"), + ], + vec![], + ] { + assert!(OidcConfig { issuers: broken }.validate().is_err()); + } + } +} diff --git a/crates/fleet-server/src/problem.rs b/crates/fleet-server/src/problem.rs index 9f69e25..02c2b1d 100644 --- a/crates/fleet-server/src/problem.rs +++ b/crates/fleet-server/src/problem.rs @@ -25,6 +25,8 @@ pub struct Problem { pub capability: Option<&'static str>, #[serde(skip)] challenge: Option<&'static str>, + #[serde(skip)] + retry_after: Option, } impl Problem { @@ -41,6 +43,7 @@ impl Problem { detail, capability: None, challenge: None, + retry_after: None, } } @@ -117,6 +120,18 @@ impl Problem { } } + /// A 429 with `Retry-After`. + #[must_use] + pub fn too_many_requests(retry_after_seconds: u64) -> Self { + Self { + retry_after: Some(retry_after_seconds), + ..Self::new( + StatusCode::TOO_MANY_REQUESTS, + format!("rate limit exceeded; retry after {retry_after_seconds} seconds"), + ) + } + } + #[must_use] pub fn service_unavailable(detail: impl Into) -> Self { Self::new(StatusCode::SERVICE_UNAVAILABLE, detail) @@ -143,6 +158,9 @@ impl ResponseError for Problem { if let Some(challenge) = self.challenge { response.insert_header((header::WWW_AUTHENTICATE, challenge)); } + if let Some(seconds) = self.retry_after { + response.insert_header((header::RETRY_AFTER, seconds.to_string())); + } response.json(self) } } diff --git a/crates/fleet-server/src/ratelimit.rs b/crates/fleet-server/src/ratelimit.rs new file mode 100644 index 0000000..316bf8a --- /dev/null +++ b/crates/fleet-server/src/ratelimit.rs @@ -0,0 +1,123 @@ +//! In-process token-bucket rate limits. +//! +//! - Every authenticated principal may make `FLEET_RATE_LIMIT_PER_MINUTE` +//! `/v1` requests per minute (burst of the same size). +//! - Every peer address may fail authentication +//! `FLEET_AUTH_FAILURES_PER_MINUTE` times per minute; once exhausted, its +//! requests are refused before any token is checked. +//! +//! Limits are per process. Behind a reverse proxy, every client shares the +//! proxy's address for the failure limit, so also limit at the proxy. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// Entries idle this long are dropped when the table grows. +const IDLE: Duration = Duration::from_secs(10 * 60); +const PRUNE_ABOVE: usize = 10_000; + +struct Bucket { + tokens: f64, + updated: Instant, +} + +pub struct RateLimiter { + per_minute: u32, + buckets: Mutex>, +} + +impl RateLimiter { + /// `per_minute == 0` disables the limit. + #[must_use] + pub fn new(per_minute: u32) -> Self { + Self { + per_minute, + buckets: Mutex::new(HashMap::new()), + } + } + + fn refill(&self, bucket: &mut Bucket, now: Instant) { + let rate = f64::from(self.per_minute) / 60.0; + let elapsed = now.saturating_duration_since(bucket.updated).as_secs_f64(); + bucket.tokens = (bucket.tokens + elapsed * rate).min(f64::from(self.per_minute)); + bucket.updated = now; + } + + /// Seconds to wait when `key` has no budget left, without spending any. + pub fn exhausted(&self, key: &str, now: Instant) -> Option { + if self.per_minute == 0 { + return None; + } + let mut buckets = self + .buckets + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let bucket = buckets.get_mut(key)?; + self.refill(bucket, now); + (bucket.tokens < 1.0).then(|| self.retry_after(bucket.tokens)) + } + + /// Spends one unit for `key`, or returns the seconds to wait. + pub fn spend(&self, key: &str, now: Instant) -> Result<(), u64> { + if self.per_minute == 0 { + return Ok(()); + } + let mut buckets = self + .buckets + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if buckets.len() > PRUNE_ABOVE { + buckets.retain(|_, bucket| now.saturating_duration_since(bucket.updated) < IDLE); + } + let bucket = buckets.entry(key.to_owned()).or_insert(Bucket { + tokens: f64::from(self.per_minute), + updated: now, + }); + self.refill(bucket, now); + if bucket.tokens >= 1.0 { + bucket.tokens -= 1.0; + Ok(()) + } else { + Err(self.retry_after(bucket.tokens)) + } + } + + fn retry_after(&self, tokens: f64) -> u64 { + let rate = f64::from(self.per_minute) / 60.0; + // Truncation is fine: the value is a small positive wait in seconds. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let seconds = ((1.0 - tokens) / rate).ceil() as u64; + seconds.max(1) + } +} + +/// Both limits, shared through application data. +pub struct Limits { + pub requests: RateLimiter, + pub auth_failures: RateLimiter, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buckets_refill_over_time_and_zero_disables() { + let limiter = RateLimiter::new(2); + let start = Instant::now(); + assert!(limiter.spend("a", start).is_ok()); + assert!(limiter.spend("a", start).is_ok()); + let wait = limiter.spend("a", start).unwrap_err(); + assert_eq!(wait, 30); + assert!(limiter.spend("b", start).is_ok(), "keys are independent"); + assert_eq!(limiter.exhausted("a", start), Some(30)); + assert!(limiter.exhausted("c", start).is_none()); + assert!(limiter.spend("a", start + Duration::from_secs(30)).is_ok()); + + let unlimited = RateLimiter::new(0); + for _ in 0..1000 { + assert!(unlimited.spend("a", start).is_ok()); + } + } +} diff --git a/crates/fleet-server/src/routes/v1/audit.rs b/crates/fleet-server/src/routes/v1/audit.rs index ac6f3c5..58db07f 100644 --- a/crates/fleet-server/src/routes/v1/audit.rs +++ b/crates/fleet-server/src/routes/v1/audit.rs @@ -38,7 +38,8 @@ pub struct AuditPage { pub fn configure(config: &mut web::ServiceConfig) { config .service(resource("/audit/events").route(web::get().to(list))) - .service(resource("/audit/verify").route(web::get().to(verify))); + .service(resource("/audit/verify").route(web::get().to(verify))) + .service(resource("/audit/head").route(web::get().to(head))); } async fn list( @@ -97,3 +98,23 @@ async fn verify( require_operator(&caller, "verify the audit chain")?; Ok(web::Json(audit::verify_chain(&state.database).await?)) } + +/// The current chain head, signed with the service's audit key, for storage +/// outside the database. +async fn head( + state: State, + Authenticated(caller): Authenticated, +) -> Result, Problem> { + require_operator(&caller, "read the signed audit head")?; + let signer = state.audit_signer.as_ref().ok_or_else(|| { + Problem::service_unavailable( + "the audit signing key is not configured; set FLEET_AUDIT_SIGNING_KEY", + ) + })?; + let head = + crate::anchor::current_head(&state.database, &state.authority_id, state.now()).await?; + signer.sign(head).map(web::Json).map_err(|error| { + tracing::error!(%error, "audit head signing failed"); + Problem::internal() + }) +} diff --git a/crates/fleet-server/src/routes/v1/authorize.rs b/crates/fleet-server/src/routes/v1/authorize.rs index bd5177a..3134a4c 100644 --- a/crates/fleet-server/src/routes/v1/authorize.rs +++ b/crates/fleet-server/src/routes/v1/authorize.rs @@ -84,8 +84,14 @@ async fn authorize( } }; let (decision_code, deny_reason) = match &decision { - Decision::Allow(_) => (AuditDecision::Allow, None), - Decision::Deny { reason } => (AuditDecision::Deny, Some(*reason)), + Decision::Allow(_) => { + crate::metrics::METRICS.decision("allow", "none"); + (AuditDecision::Allow, None) + } + Decision::Deny { reason } => { + crate::metrics::METRICS.decision("deny", reason.code()); + (AuditDecision::Deny, Some(*reason)) + } }; let grant = stored.as_ref().map(|stored| &stored.grant); audit::append( diff --git a/crates/fleet-server/src/routes/v1/grants.rs b/crates/fleet-server/src/routes/v1/grants.rs index 424b134..ef852b8 100644 --- a/crates/fleet-server/src/routes/v1/grants.rs +++ b/crates/fleet-server/src/routes/v1/grants.rs @@ -3,7 +3,7 @@ //! material; the provider credential stays in the SendBox host broker. use actix_web::{HttpResponse, web}; -use sendbox_governance::api::RevokeGrantRequest; +use sendbox_governance::api::{ReportedOutcome, RequestOutcomeReport, RevokeGrantRequest}; use sendbox_governance::grant::{validate_method, validate_path_prefix}; use sendbox_governance::{ CONTRACT_VERSION, CredentialGrant, DenyReason, GrantId, GrantRequest, RevocationReason, @@ -11,7 +11,7 @@ use sendbox_governance::{ }; use super::{State, actor, invalid, refuse}; -use crate::audit::{self, AuditDecision, AuditRecord}; +use crate::audit::{self, AuditDecision, AuditOutcome, AuditRecord}; use crate::auth::{Authenticated, Caller}; use crate::db::Tx; use crate::governance::{self, ProjectRole, SessionStatus, StoredGrant}; @@ -26,7 +26,8 @@ pub fn configure(config: &mut web::ServiceConfig) { config .service(resource("/grants").route(web::post().to(issue))) .service(resource("/grants/{grant_id:[^/:]+}:renew").route(web::post().to(renew))) - .service(resource("/grants/{grant_id:[^/:]+}:revoke").route(web::post().to(revoke))); + .service(resource("/grants/{grant_id:[^/:]+}:revoke").route(web::post().to(revoke))) + .service(resource("/grants/{grant_id:[^/:]+}:outcome").route(web::post().to(outcome))); } fn base(caller: &Caller, grant: &CredentialGrant) -> AuditRecord { @@ -425,3 +426,61 @@ async fn revoke( tx.commit().await?; Ok(HttpResponse::NoContent().finish()) } + +/// Records how one brokered stream ended, as reported by the grant's host. +/// Outcomes are evidence only: they never change a grant or a decision. +async fn outcome( + state: State, + Authenticated(caller): Authenticated, + grant_id: web::Path, + report: web::Json, +) -> Result { + let grant_id = grant_id.into_inner(); + let report = report.into_inner(); + report.validate().map_err(invalid)?; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let stored = governance::grant(&mut tx, &grant_id) + .await? + .ok_or_else(|| Problem::missing(format!("grant `{grant_id}` does not exist")))?; + if stored.grant.principal != caller.principal { + return Err(Problem::forbidden( + "only the grant's principal can report its outcomes", + )); + } + if report.service != stored.grant.service { + return Err(Problem::bad_request("the report names another service")); + } + let path = if sendbox_governance::validate_request_path(&report.path).is_ok() { + report.path.chars().take(400).collect::() + } else { + "".to_owned() + }; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "request.outcome", + outcome: Some(match report.outcome { + ReportedOutcome::Succeeded => AuditOutcome::Succeeded, + ReportedOutcome::Failed => AuditOutcome::Failed, + ReportedOutcome::Unknown => AuditOutcome::Unknown, + }), + target: Some(format!("{} {}{path}", report.method, report.service)), + detail: Some(format!( + "reason={} status={} request_bytes={} response_bytes={} duration_ms={}", + report.reason, + report + .status + .map_or_else(|| "none".to_owned(), |status| status.to_string()), + report.request_bytes, + report.response_bytes, + report.duration_ms + )), + ..base(&caller, &stored.grant) + }, + ) + .await?; + tx.commit().await?; + Ok(HttpResponse::NoContent().finish()) +} diff --git a/crates/fleet-server/src/routes/v1/mod.rs b/crates/fleet-server/src/routes/v1/mod.rs index 3ce884d..b203e4b 100644 --- a/crates/fleet-server/src/routes/v1/mod.rs +++ b/crates/fleet-server/src/routes/v1/mod.rs @@ -10,6 +10,7 @@ pub mod grants; pub mod profiles; pub mod projects; pub mod sessions; +pub mod tokens; pub mod whoami; use actix_web::web; @@ -25,6 +26,7 @@ use crate::state::AppState; pub fn configure(config: &mut web::ServiceConfig) { config .configure(whoami::configure) + .configure(tokens::configure) .configure(sessions::configure) .configure(grants::configure) .configure(authorize::configure) diff --git a/crates/fleet-server/src/routes/v1/tokens.rs b/crates/fleet-server/src/routes/v1/tokens.rs new file mode 100644 index 0000000..873fa23 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/tokens.rs @@ -0,0 +1,220 @@ +//! Self-service tokens: exchange an identity-provider login for a service +//! token that a SendBox host can store, and list or revoke your own tokens. +//! +//! Only callers authenticated by an identity provider may exchange, so a +//! leaked service token cannot mint fresh ones. Only the token's SHA-256 is +//! stored. + +use actix_web::{HttpResponse, web}; +use serde::{Deserialize, Serialize}; + +use sendbox_governance::api::{IssuedToken, TokenRequest}; + +use super::{State, actor}; +use crate::audit::{self, AuditRecord}; +use crate::auth::{AuthMethod, Authenticated, token_from_bytes}; +use crate::problem::Problem; +use crate::routes::resource; +use crate::state::{from_db, to_db}; + +/// Live tokens one principal may hold at once. +const MAX_LIVE_TOKENS: usize = 20; +const MAX_DESCRIPTION_CHARS: usize = 200; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TokenSummary { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub created_at_unix: u64, + pub expires_at_unix: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revoked_at_unix: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TokenList { + pub tokens: Vec, +} + +pub fn configure(config: &mut web::ServiceConfig) { + config + .service( + resource("/tokens") + .route(web::post().to(exchange)) + .route(web::get().to(list)), + ) + .service(resource("/tokens/{token_id}").route(web::delete().to(revoke))); +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +async fn exchange( + state: State, + Authenticated(caller): Authenticated, + request: web::Json, +) -> Result { + let request = request.into_inner(); + if caller.method != AuthMethod::IdentityProvider { + return Err(Problem::forbidden( + "exchange needs an identity-provider token; a service token cannot mint another", + )); + } + if let Some(description) = &request.description + && (description.trim().is_empty() + || description.chars().count() > MAX_DESCRIPTION_CHARS + || description.chars().any(char::is_control)) + { + return Err(Problem::bad_request(format!( + "description must be 1 to {MAX_DESCRIPTION_CHARS} characters without control characters" + ))); + } + let limits = state.tokens; + let ttl = request.ttl_seconds.unwrap_or(limits.default_seconds); + if !(60..=limits.max_seconds).contains(&ttl) { + return Err(Problem::bad_request(format!( + "ttl_seconds must be between 60 and {}", + limits.max_seconds + ))); + } + let now = state.now(); + let expires_at_unix = now.saturating_add(ttl); + let mut tx = state.database.begin_write().await?; + let live = tx + .fetch_all( + "SELECT id FROM api_tokens WHERE principal_id = $1 AND revoked_at_unix IS NULL \ + AND expires_at_unix > $2", + &[caller.principal.as_str().into(), to_db(now)?.into()], + ) + .await? + .len(); + if live >= MAX_LIVE_TOKENS { + return Err(Problem::conflict(format!( + "you already hold {MAX_LIVE_TOKENS} live tokens; revoke one first" + ))); + } + let id = hex(&state.new_id()?); + let mut secret = [0_u8; 32]; + getrandom::fill(&mut secret).map_err(|error| { + tracing::error!(%error, "token generation failed"); + Problem::internal() + })?; + let (token, digest) = token_from_bytes(&secret); + tx.execute( + "INSERT INTO api_tokens (id, principal_id, token_sha256, description, created_at_unix, \ + expires_at_unix) VALUES ($1, $2, $3, $4, $5, $6)", + &[ + id.clone().into(), + caller.principal.as_str().into(), + digest.into(), + request.description.clone().into(), + to_db(now)?.into(), + to_db(expires_at_unix)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "token.issued", + actor: actor(&caller), + principal: Some(caller.principal.to_string()), + detail: Some(format!( + "token_id={id} expires_at_unix={expires_at_unix} method=identity_provider" + )), + ..AuditRecord::default() + }, + ) + .await?; + tx.commit().await?; + Ok(HttpResponse::Created() + .insert_header((actix_web::http::header::CACHE_CONTROL, "no-store")) + .json(IssuedToken { + id, + token, + principal: caller.principal, + expires_at_unix, + })) +} + +async fn list( + state: State, + Authenticated(caller): Authenticated, +) -> Result, Problem> { + let rows = state + .database + .fetch_all( + "SELECT id, description, created_at_unix, expires_at_unix, revoked_at_unix \ + FROM api_tokens WHERE principal_id = $1 ORDER BY created_at_unix DESC, id LIMIT 100", + &[caller.principal.as_str().into()], + ) + .await?; + let tokens = rows + .iter() + .map(|row| { + Ok(TokenSummary { + id: row.text("id")?, + description: row.opt_text("description")?, + created_at_unix: from_db(row.int("created_at_unix")?)?, + expires_at_unix: from_db(row.int("expires_at_unix")?)?, + revoked_at_unix: row.opt_int("revoked_at_unix")?.map(from_db).transpose()?, + }) + }) + .collect::, Problem>>()?; + Ok(web::Json(TokenList { tokens })) +} + +/// Revokes one of the caller's tokens; operators may revoke any token. +async fn revoke( + state: State, + Authenticated(caller): Authenticated, + token_id: web::Path, +) -> Result { + let token_id = token_id.into_inner(); + if token_id.len() != 32 || !token_id.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(Problem::bad_request( + "token ids are 32 hexadecimal characters", + )); + } + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let owner = tx + .fetch_optional( + "SELECT principal_id, revoked_at_unix FROM api_tokens WHERE id = $1", + &[token_id.clone().into()], + ) + .await?; + let Some(owner) = owner else { + return Err(Problem::missing("no such token")); + }; + let principal = owner.text("principal_id")?; + if principal != caller.principal.as_str() && !caller.operator { + return Err(Problem::missing("no such token")); + } + if owner.opt_int("revoked_at_unix")?.is_none() { + tx.execute( + "UPDATE api_tokens SET revoked_at_unix = $2 WHERE id = $1", + &[token_id.clone().into(), to_db(now)?.into()], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "token.revoked", + actor: actor(&caller), + principal: Some(principal), + detail: Some(format!("token_id={token_id}")), + ..AuditRecord::default() + }, + ) + .await?; + } + tx.commit().await?; + Ok(HttpResponse::NoContent().finish()) +} diff --git a/crates/fleet-server/src/server.rs b/crates/fleet-server/src/server.rs index 33da3f5..b12f3ed 100644 --- a/crates/fleet-server/src/server.rs +++ b/crates/fleet-server/src/server.rs @@ -14,10 +14,11 @@ use thiserror::Error; use time::OffsetDateTime; use tokio::task::JoinHandle; -use crate::auth::{self, DatabaseAuthenticator, SharedAuthenticator}; +use crate::auth::{self, FleetAuthenticator, SharedAuthenticator}; use crate::config::{Config, ConfigError, ProfileTrust}; use crate::db::{Database, DbError}; use crate::logging::{self, retention}; +use crate::oidc::{OidcConfig, OidcVerifier}; use crate::problem; use crate::routes; use crate::state::{AppState, os_random}; @@ -31,6 +32,8 @@ pub enum ServerError { #[error(transparent)] Config(#[from] ConfigError), #[error(transparent)] + Anchor(#[from] crate::anchor::AnchorError), + #[error(transparent)] Database(#[from] DbError), #[error("cannot listen on {address}: {source}")] Bind { @@ -70,9 +73,39 @@ pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { .as_deref() .map(ProfileTrust::load) .transpose()?; + let audit_signer = config + .audit + .signing_key + .as_deref() + .map(crate::anchor::AuditSigner::load) + .transpose()? + .map(Arc::new); + if let Some(directory) = &config.audit.directory { + std::fs::create_dir_all(directory).map_err(|source| crate::anchor::AnchorError::Io { + context: "create audit anchor directory", + path: directory.clone(), + source, + })?; + } let retention = spawn_retention(log_dir.clone(), config.logging.retention_days); let database = Database::connect(&config.database_url).await?; - database.migrate().await?; + if config.migrate { + database.migrate().await?; + } else { + database.check_migrated().await?; + } + match database + .fetch_optional("SELECT MAX(sequence) AS head FROM audit_events", &[]) + .await + { + Ok(Some(row)) => { + if let Ok(Some(head)) = row.opt_int("head") { + crate::metrics::METRICS.audit_head(u64::try_from(head).unwrap_or(0)); + } + } + Ok(None) => {} + Err(error) => tracing::warn!(%error, "cannot read the audit chain head for metrics"), + } tracing::info!( bind = %config.bind, database = %config.database_url, @@ -88,16 +121,66 @@ pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { } let clock: Arc = Arc::new(sendbox_governance::SystemClock); + let oidc = config + .oidc + .as_deref() + .map(OidcConfig::load) + .transpose()? + .map(|oidc| OidcVerifier::new(oidc, Arc::clone(&clock))) + .transpose()?; + if oidc.is_none() { + tracing::info!("FLEET_OIDC_CONFIG is not set; only service tokens authenticate"); + } let state = web::Data::new(AppState { database: database.clone(), clock: Arc::clone(&clock), random: Arc::new(os_random), authority_id: config.authority_id.clone(), profile_trust, + tokens: config.tokens, + audit_signer: audit_signer.clone(), + limits: Arc::new(crate::ratelimit::Limits { + requests: crate::ratelimit::RateLimiter::new(config.rate_limit_per_minute), + auth_failures: crate::ratelimit::RateLimiter::new(config.auth_failures_per_minute), + }), }); - let authenticator = auth::shared(Arc::new(DatabaseAuthenticator::new( + let metrics = match config.metrics_bind { + Some(address) => { + let server = HttpServer::new(|| App::new().configure(crate::metrics::configure)) + .workers(1) + .shutdown_timeout(5) + .bind(address) + .map_err(|source| ServerError::Bind { address, source })? + .run(); + let handle = server.handle(); + actix_web::rt::spawn(server); + tracing::info!(%address, "serving metrics"); + Some(handle) + } + None => None, + }; + let anchoring = match (&audit_signer, &config.audit.directory) { + (Some(signer), Some(directory)) => { + tracing::info!( + directory = %directory.display(), + fingerprint = %signer.identity.fingerprint, + "anchoring the audit chain head" + ); + Some(crate::anchor::spawn_anchoring( + database.clone(), + Arc::clone(signer), + config.authority_id.clone(), + directory.clone(), + Duration::from_secs(config.audit.interval_seconds), + Arc::clone(&clock), + )) + } + _ => None, + }; + let authenticator = auth::shared(Arc::new(FleetAuthenticator::new( database.clone(), clock, + oidc, ))); let server = HttpServer::new(move || app(state.clone(), authenticator.clone())) .shutdown_timeout(SHUTDOWN_GRACE_SECONDS) @@ -109,7 +192,13 @@ pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { .run(); let served = server.await.map_err(ServerError::Serve); + if let Some(metrics) = metrics { + metrics.stop(true).await; + } retention.abort(); + if let Some(anchoring) = anchoring { + anchoring.abort(); + } database.close().await; tracing::info!("sendbox-fleet stopped"); served diff --git a/crates/fleet-server/src/state.rs b/crates/fleet-server/src/state.rs index 478687f..27d866b 100644 --- a/crates/fleet-server/src/state.rs +++ b/crates/fleet-server/src/state.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use sendbox_governance::{Clock, GovernanceError}; use sendbox_security::provenance::TrustStore; +use crate::config::TokenLimits; use crate::db::Database; use crate::problem::Problem; @@ -20,6 +21,10 @@ pub struct AppState { /// Operator signers that profile publications must satisfy. Publication /// is refused while this is unset. pub profile_trust: Option, + pub tokens: TokenLimits, + /// Signs audit chain heads; `None` disables `GET /v1/audit/head`. + pub audit_signer: Option>, + pub limits: Arc, } impl AppState { diff --git a/crates/fleet-server/tests/http.rs b/crates/fleet-server/tests/http.rs index 5963f97..582a25d 100644 --- a/crates/fleet-server/tests/http.rs +++ b/crates/fleet-server/tests/http.rs @@ -1,6 +1,8 @@ //! HTTP behaviour of the shared governance service: authentication before //! validation, project roles, signed profiles, session admission, grants, -//! authorization, exceptions, and the audit chain. All data is synthetic. +//! authorization, exceptions, the audit chain, identity-provider sign-in, +//! token exchange, signed audit heads, and rate limits. All data and keys are +//! synthetic. //! //! Runs against in-memory SQLite by default. Set `FLEET_TEST_DATABASE_URL` to //! a PostgreSQL database whose name ends in `_test` to run the same requests @@ -9,17 +11,28 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; use actix_web::body::MessageBody; use actix_web::dev::{Service, ServiceResponse}; use actix_web::http::{Method, StatusCode, header}; -use actix_web::{test, web}; -use fleet_server::auth::{self, DatabaseAuthenticator, token_from_bytes}; -use fleet_server::config::DatabaseUrl; +use actix_web::{App, HttpResponse, HttpServer, test, web}; +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use fleet_server::anchor::{self, AuditSigner}; +use fleet_server::auth::{self, FleetAuthenticator, token_from_bytes}; +use fleet_server::config::{DatabaseUrl, TokenLimits}; use fleet_server::db::{Arg, Database}; +use fleet_server::oidc::{OidcConfig, OidcVerifier}; +use fleet_server::ratelimit::{Limits, RateLimiter}; use fleet_server::server; use fleet_server::state::AppState; +use ring::rand::SystemRandom; +use ring::signature::{ + ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair, Ed25519KeyPair, KeyPair as _, +}; use sendbox_governance::{ AuthorityRef, CONTRACT_VERSION, Clock, ExceptionId, GovernanceBinding, PrincipalId, ProfileRef, ProjectId, ServiceId, SessionRef, Sha256Digest, @@ -114,6 +127,16 @@ struct Fleet { clock: Arc, key: SigningKeyMaterial, tokens: HashMap<&'static str, String>, + audit_signer: Option>, +} + +/// Optional features; everything is off by default. +#[derive(Default)] +struct Setup { + oidc: Option, + audit_signer: Option>, + /// Per-principal requests and per-peer failures per minute. + limits: (u32, u32), } async fn fleet() -> Fleet< @@ -122,6 +145,18 @@ async fn fleet() -> Fleet< Response = ServiceResponse, Error = actix_web::Error, >, +> { + fleet_with(Setup::default()).await +} + +async fn fleet_with( + setup: Setup, +) -> Fleet< + impl Service< + actix_http::Request, + Response = ServiceResponse, + Error = actix_web::Error, + >, > { let url = std::env::var("FLEET_TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".to_owned()); @@ -200,10 +235,22 @@ async fn fleet() -> Fleet< random: Arc::new(fleet_server::state::os_random), authority_id: AUTHORITY.to_owned(), profile_trust: Some(trust), + tokens: TokenLimits::default(), + audit_signer: setup.audit_signer.clone(), + limits: Arc::new(Limits { + requests: RateLimiter::new(setup.limits.0), + auth_failures: RateLimiter::new(setup.limits.1), + }), }); - let authenticator = auth::shared(Arc::new(DatabaseAuthenticator::new( + let oidc = setup.oidc.map(|config| { + OidcVerifier::new(config, clock.clone()) + .unwrap() + .with_min_refresh_interval(Duration::ZERO) + }); + let authenticator = auth::shared(Arc::new(FleetAuthenticator::new( database.clone(), clock.clone(), + oidc, ))); let service = test::init_service(server::app(state, authenticator)).await; Fleet { @@ -212,6 +259,7 @@ async fn fleet() -> Fleet< clock, key, tokens, + audit_signer: setup.audit_signer, } } @@ -227,7 +275,23 @@ where token: Option<&str>, body: Option<&Value>, ) -> (StatusCode, Value) { + let (status, _, value) = self.respond(None, method, path, token, body).await; + (status, value) + } + + /// Sends a request from `peer` and returns the headers as well. + async fn respond( + &self, + peer: Option<&str>, + method: Method, + path: &str, + token: Option<&str>, + body: Option<&Value>, + ) -> (StatusCode, header::HeaderMap, Value) { let mut request = test::TestRequest::default().method(method).uri(path); + if let Some(peer) = peer { + request = request.peer_addr(peer.parse().unwrap()); + } if let Some(token) = token { request = request.insert_header((header::AUTHORIZATION, format!("Bearer {token}"))); } @@ -237,6 +301,7 @@ where }; let response = test::call_service(&self.service, request).await; let status = response.status(); + let headers = response.headers().clone(); let bytes = test::read_body(response).await; let value = if bytes.is_empty() { Value::Null @@ -251,7 +316,7 @@ where .is_some_and(|detail| !detail.is_empty()) ); } - (status, value) + (status, headers, value) } async fn call( @@ -1285,3 +1350,895 @@ async fn invalid_contract_bodies_and_transport_errors_are_problems() { let response = test::call_service(&fleet.service, request).await; assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); } + +/// A synthetic identity-provider signing key. +enum IdpKey { + Ed25519 { + kid: &'static str, + pair: Ed25519KeyPair, + }, + Es256 { + kid: &'static str, + pair: EcdsaKeyPair, + }, +} + +impl IdpKey { + fn ed25519(kid: &'static str) -> Self { + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap(); + Self::Ed25519 { + kid, + pair: Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(), + } + } + + fn es256(kid: &'static str) -> Self { + let random = SystemRandom::new(); + let pkcs8 = + EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &random).unwrap(); + Self::Es256 { + kid, + pair: EcdsaKeyPair::from_pkcs8( + &ECDSA_P256_SHA256_FIXED_SIGNING, + pkcs8.as_ref(), + &random, + ) + .unwrap(), + } + } + + fn jwk(&self) -> Value { + match self { + Self::Ed25519 { kid, pair } => json!({ + "kty": "OKP", "crv": "Ed25519", "use": "sig", "alg": "EdDSA", "kid": kid, + "x": URL_SAFE_NO_PAD.encode(pair.public_key().as_ref()), + }), + Self::Es256 { kid, pair } => { + let point = pair.public_key().as_ref(); + json!({ + "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256", "kid": kid, + "x": URL_SAFE_NO_PAD.encode(&point[1..33]), + "y": URL_SAFE_NO_PAD.encode(&point[33..65]), + }) + } + } + } + + fn sign(&self, claims: &Value) -> String { + let (algorithm, kid) = match self { + Self::Ed25519 { kid, .. } => ("EdDSA", kid), + Self::Es256 { kid, .. } => ("ES256", kid), + }; + let encode = |value: &Value| URL_SAFE_NO_PAD.encode(serde_json::to_vec(value).unwrap()); + let message = format!( + "{}.{}", + encode(&json!({ "alg": algorithm, "kid": kid, "typ": "JWT" })), + encode(claims) + ); + let signature = match self { + Self::Ed25519 { pair, .. } => pair.sign(message.as_bytes()).as_ref().to_vec(), + Self::Es256 { pair, .. } => pair + .sign(&SystemRandom::new(), message.as_bytes()) + .unwrap() + .as_ref() + .to_vec(), + }; + format!("{message}.{}", URL_SAFE_NO_PAD.encode(signature)) + } +} + +/// Key sets served by the local identity provider; `None` answers `500`. +struct IdpState { + base: String, + users: Mutex>, + ci: Mutex>, +} + +async fn discovery(state: web::Data) -> HttpResponse { + HttpResponse::Ok().json(json!({ + "issuer": format!("{}/users", state.base), + "jwks_uri": format!("{}/users/jwks", state.base), + })) +} + +fn key_set(keys: &Mutex>) -> HttpResponse { + match keys.lock().unwrap().clone() { + Some(keys) => HttpResponse::Ok().json(keys), + None => HttpResponse::InternalServerError().finish(), + } +} + +async fn users_jwks(state: web::Data) -> HttpResponse { + key_set(&state.users) +} + +async fn ci_jwks(state: web::Data) -> HttpResponse { + key_set(&state.ci) +} + +/// A loopback identity provider: `/users` uses discovery, `/ci` a fixed +/// JWKS URI. +async fn identity_provider(users: &[&IdpKey], ci: &[&IdpKey]) -> web::Data { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let keys = + |keys: &[&IdpKey]| json!({ "keys": keys.iter().map(|key| key.jwk()).collect::>() }); + let state = web::Data::new(IdpState { + base: format!("http://{}", listener.local_addr().unwrap()), + users: Mutex::new(Some(keys(users))), + ci: Mutex::new(Some(keys(ci))), + }); + let shared = state.clone(); + let server = HttpServer::new(move || { + App::new() + .app_data(shared.clone()) + .route( + "/users/.well-known/openid-configuration", + web::get().to(discovery), + ) + .route("/users/jwks", web::get().to(users_jwks)) + .route("/ci/jwks", web::get().to(ci_jwks)) + }) + .workers(1) + .listen(listener) + .unwrap() + .run(); + actix_web::rt::spawn(server); + state +} + +fn oidc_config(base: &str) -> OidcConfig { + serde_json::from_value(json!({ "issuers": [ + { + "issuer": format!("{base}/users"), + "audiences": ["sendbox-fleet"], + "kind": "user", + "principal_claim": "email", + "principal_prefix": "oidc", + }, + { + "issuer": format!("{base}/ci"), + "audiences": ["sendbox-fleet"], + "kind": "worker", + "principal_claim": "repository_id", + "principal_prefix": "ci", + "auto_provision": true, + "jwks_uri": format!("{base}/ci/jwks"), + "algorithms": ["ES256"], + "required_claims": { "repository_owner": "example" }, + }, + ]})) + .unwrap() +} + +fn person(base: &str, email: &str, now: u64) -> Value { + json!({ + "iss": format!("{base}/users"), + "aud": "sendbox-fleet", + "sub": "synthetic-subject", + "email": email, + "email_verified": true, + "iat": now, + "exp": now + 300, + }) +} + +fn pipeline(base: &str, repository_id: u64, now: u64) -> Value { + json!({ + "iss": format!("{base}/ci"), + "aud": ["other", "sendbox-fleet"], + "repository_id": repository_id, + "repository_owner": "example", + "iat": now, + "nbf": now, + "exp": now + 300, + }) +} + +impl Fleet +where + S: Service, Error = actix_web::Error>, + B: MessageBody, +{ + async fn sign_in(&self, token: &str) -> StatusCode { + self.send(Method::GET, "/v1/tokens", Some(token), None) + .await + .0 + } + + async fn exchange(&self, token: &str, body: Value) -> (StatusCode, header::HeaderMap, Value) { + self.respond(None, Method::POST, "/v1/tokens", Some(token), Some(&body)) + .await + } +} + +#[actix_web::test] +async fn identity_provider_tokens_need_a_trusted_signature_and_exact_claims() { + let user_key = IdpKey::ed25519("user-1"); + let ci_key = IdpKey::es256("ci-1"); + let idp = identity_provider(&[&user_key], &[&ci_key]).await; + let base = idp.base.as_str(); + let fleet = fleet_with(Setup { + oidc: Some(oidc_config(base)), + ..Setup::default() + }) + .await; + let now = fleet.now(); + let alice = person(base, "alice@example.com", now); + assert_eq!(fleet.sign_in(&user_key.sign(&alice)).await, StatusCode::OK); + + let mut tampered = user_key.sign(&alice); + let forged = URL_SAFE_NO_PAD + .encode(serde_json::to_vec(&person(base, "olivia@example.com", now)).unwrap()); + let parts = tampered.split('.').map(str::to_owned).collect::>(); + tampered = format!("{}.{forged}.{}", parts[0], parts[2]); + let unsigned = |algorithm: &str, signature: &str| { + let encode = |value: &Value| URL_SAFE_NO_PAD.encode(serde_json::to_vec(value).unwrap()); + format!( + "{}.{}.{signature}", + encode(&json!({ "alg": algorithm, "kid": "user-1" })), + encode(&alice) + ) + }; + let impostor = IdpKey::ed25519("user-1"); + let unpublished = IdpKey::ed25519("user-9"); + let with = |change: &dyn Fn(&mut Value)| { + let mut claims = alice.clone(); + change(&mut claims); + user_key.sign(&claims) + }; + for (case, token) in [ + ("tampered payload", tampered), + ("alg none", unsigned("none", "")), + ("HMAC", unsigned("HS256", "c2lnbmF0dXJl")), + ("same kid, other key", impostor.sign(&alice)), + ("unpublished key", unpublished.sign(&alice)), + ( + "expired", + with(&|claims| { + claims["iat"] = json!(now - 600); + claims["exp"] = json!(now - 61); + }), + ), + ( + "not yet valid", + with(&|claims| claims["nbf"] = json!(now + 120)), + ), + ( + "issued in the future", + with(&|claims| claims["iat"] = json!(now + 120)), + ), + ( + "wrong audience", + with(&|claims| claims["aud"] = json!("other")), + ), + ( + "unknown issuer", + with(&|claims| claims["iss"] = json!(format!("{base}/elsewhere"))), + ), + ( + "unverified email", + with(&|claims| claims["email_verified"] = json!(false)), + ), + ( + "no email_verified", + with(&|claims| { + claims.as_object_mut().unwrap().remove("email_verified"); + }), + ), + ( + "no expiry", + with(&|claims| { + claims.as_object_mut().unwrap().remove("exp"); + }), + ), + ( + "unregistered", + user_key.sign(&person(base, "nobody@example.com", now)), + ), + ( + "not a principal id", + user_key.sign(&person(base, "a b@example.com", now)), + ), + ("ci key on the user issuer", ci_key.sign(&alice)), + ( + "wrong owner claim", + ci_key.sign(&{ + let mut claims = pipeline(base, 4242, now); + claims["repository_owner"] = json!("someone-else"); + claims + }), + ), + ( + "algorithm not allowed", + IdpKey::ed25519("ci-1").sign(&pipeline(base, 4242, now)), + ), + ] { + assert_eq!( + fleet.sign_in(&token).await, + StatusCode::UNAUTHORIZED, + "{case}" + ); + } + + let mut tx = fleet.database.begin_write().await.unwrap(); + tx.execute( + "UPDATE principals SET disabled_at_unix = $2 WHERE id = $1", + &[BOB.into(), Arg::from(i64::try_from(now).unwrap())], + ) + .await + .unwrap(); + tx.execute( + "INSERT INTO principals (id, kind, created_at_unix) VALUES ('ci:777', 'user', 0)", + &[], + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + let bob = user_key.sign(&person(base, "bob@example.com", now)); + assert_eq!( + fleet.sign_in(&bob).await, + StatusCode::UNAUTHORIZED, + "disabled" + ); + let mismatched = ci_key.sign(&pipeline(base, 777, now)); + assert_eq!( + fleet.sign_in(&mismatched).await, + StatusCode::UNAUTHORIZED, + "a worker issuer cannot sign in as a user" + ); + + let ci = ci_key.sign(&pipeline(base, 4242, now)); + assert_eq!(fleet.sign_in(&ci).await, StatusCode::OK, "auto-provisioned"); + assert_eq!(fleet.sign_in(&ci).await, StatusCode::OK); + let provisioned = fleet + .events("principal=ci:4242") + .await + .into_iter() + .filter(|event| event["event_type"] == "principal.provisioned") + .collect::>(); + assert_eq!(provisioned.len(), 1); + assert_eq!( + provisioned[0]["detail"], + format!("kind=worker issuer={base}/ci") + ); + let row = fleet + .database + .fetch_optional( + "SELECT kind, is_operator AS operator FROM principals WHERE id = 'ci:4242'", + &[], + ) + .await + .unwrap() + .unwrap(); + assert_eq!(row.text("kind").unwrap(), "worker"); + assert!( + !row.flag("operator").unwrap(), + "provisioned principals hold no roles" + ); + let (status, _) = fleet + .send( + Method::POST, + "/v1/projects", + Some(&ci), + Some(&json!({ "project": "github:example/other", "owner": "ci:4242" })), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); +} + +#[actix_web::test] +async fn identity_provider_keys_rotate_and_outages_fail_closed() { + let first = IdpKey::ed25519("user-1"); + let second = IdpKey::es256("user-2"); + let ci_key = IdpKey::es256("ci-1"); + let idp = identity_provider(&[&first], &[&ci_key]).await; + let base = idp.base.clone(); + let fleet = fleet_with(Setup { + oidc: Some(oidc_config(&base)), + ..Setup::default() + }) + .await; + let alice = person(&base, "alice@example.com", fleet.now()); + assert_eq!(fleet.sign_in(&first.sign(&alice)).await, StatusCode::OK); + + *idp.users.lock().unwrap() = Some(json!({ "keys": [second.jwk()] })); + assert_eq!( + fleet.sign_in(&second.sign(&alice)).await, + StatusCode::OK, + "an unknown key id refreshes the key set" + ); + assert_eq!( + fleet.sign_in(&first.sign(&alice)).await, + StatusCode::UNAUTHORIZED, + "retired keys stop working once the key set is refreshed" + ); + + *idp.users.lock().unwrap() = None; + assert_eq!( + fleet.sign_in(&second.sign(&alice)).await, + StatusCode::OK, + "cached keys survive a provider outage" + ); + assert_eq!( + fleet.sign_in(&IdpKey::ed25519("user-3").sign(&alice)).await, + StatusCode::UNAUTHORIZED + ); + *idp.ci.lock().unwrap() = None; + let (status, body) = fleet + .send( + Method::GET, + "/v1/tokens", + Some(&ci_key.sign(&pipeline(&base, 4242, fleet.now()))), + None, + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}"); + let (status, _) = fleet + .send(Method::GET, "/v1/tokens", Some(&first.sign(&alice)), None) + .await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + let plain = fleet_with(Setup::default()).await; + assert_eq!( + plain.sign_in(&second.sign(&alice)).await, + StatusCode::UNAUTHORIZED, + "identity-provider tokens need FLEET_OIDC_CONFIG" + ); +} + +#[actix_web::test] +async fn sign_in_exchanges_for_short_lived_service_tokens() { + let key = IdpKey::ed25519("user-1"); + let idp = identity_provider(&[&key], &[]).await; + let fleet = fleet_with(Setup { + oidc: Some(oidc_config(&idp.base)), + ..Setup::default() + }) + .await; + let now = fleet.now(); + let alice = key.sign(&person(&idp.base, "alice@example.com", now)); + + let (status, headers, issued) = fleet + .exchange( + &alice, + json!({ "ttl_seconds": 3_600, "description": "Synthetic laptop" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{issued}"); + assert_eq!(headers.get(header::CACHE_CONTROL).unwrap(), "no-store"); + assert_eq!(issued["principal"], MEMBER); + assert_eq!(issued["expires_at_unix"], now + 3_600); + let token = issued["token"].as_str().unwrap().to_owned(); + let id = issued["id"].as_str().unwrap().to_owned(); + assert!(token.starts_with("sbf_")); + assert_eq!(id.len(), 32); + + let (_, _, default) = fleet.exchange(&alice, json!({})).await; + assert_eq!( + default["expires_at_unix"], + now + TokenLimits::default().default_seconds + ); + let max = TokenLimits::default().max_seconds; + for body in [ + json!({ "ttl_seconds": 59 }), + json!({ "ttl_seconds": max + 1 }), + json!({ "description": "\u{0007}" }), + json!({ "description": " " }), + ] { + assert_eq!( + fleet.exchange(&alice, body.clone()).await.0, + StatusCode::BAD_REQUEST, + "{body}" + ); + } + for service_token in [token.as_str(), fleet.tokens[MEMBER].as_str()] { + assert_eq!( + fleet.exchange(service_token, json!({})).await.0, + StatusCode::FORBIDDEN, + "a service token cannot mint another" + ); + } + + let (status, list) = fleet + .send(Method::GET, "/v1/tokens", Some(&token), None) + .await; + assert_eq!(status, StatusCode::OK); + let tokens = list["tokens"].as_array().unwrap(); + assert_eq!(tokens.len(), 3, "the seeded token and two exchanged tokens"); + let summary = tokens.iter().find(|summary| summary["id"] == id).unwrap(); + assert_eq!(summary["description"], "Synthetic laptop"); + assert!(!list.to_string().contains("sbf_")); + + let revoke = format!("/v1/tokens/{id}"); + assert_eq!( + fleet.call(BOB, Method::DELETE, &revoke, None).await.0, + StatusCode::NOT_FOUND + ); + assert_eq!( + fleet + .call(BOB, Method::DELETE, "/v1/tokens/not-hex", None) + .await + .0, + StatusCode::BAD_REQUEST + ); + let (status, _) = fleet + .send(Method::DELETE, &revoke, Some(&alice), None) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _) = fleet + .send(Method::DELETE, &revoke, Some(&alice), None) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "revocation is idempotent"); + assert_eq!(fleet.sign_in(&token).await, StatusCode::UNAUTHORIZED); + let other = default["token"].as_str().unwrap(); + assert_eq!(fleet.sign_in(other).await, StatusCode::OK); + let (status, _) = fleet + .call( + OPERATOR, + Method::DELETE, + &format!("/v1/tokens/{}", default["id"].as_str().unwrap()), + None, + ) + .await; + assert_eq!( + status, + StatusCode::NO_CONTENT, + "operators may revoke any token" + ); + assert_eq!(fleet.sign_in(other).await, StatusCode::UNAUTHORIZED); + + let (_, _, short) = fleet.exchange(&alice, json!({ "ttl_seconds": 60 })).await; + fleet.advance(61); + assert_eq!( + fleet.sign_in(short["token"].as_str().unwrap()).await, + StatusCode::UNAUTHORIZED, + "exchanged tokens expire" + ); + + let mut issued_tokens = Vec::new(); + let conflict = loop { + let (status, _, body) = fleet.exchange(&alice, json!({ "ttl_seconds": 600 })).await; + if status != StatusCode::CREATED { + break status; + } + issued_tokens.push(body["token"].as_str().unwrap().to_owned()); + assert!(issued_tokens.len() <= 20); + }; + assert_eq!(conflict, StatusCode::CONFLICT); + assert_eq!( + issued_tokens.len(), + 19, + "20 live tokens including the seeded one" + ); + + let events = fleet + .events("principal=oidc:alice@example.com&limit=500") + .await; + let count = |kind: &str| { + events + .iter() + .filter(|event| event["event_type"] == kind) + .count() + }; + assert_eq!(count("token.issued"), 22); + assert_eq!(count("token.revoked"), 2); + let serialized = serde_json::to_string(&events).unwrap(); + for secret in issued_tokens.iter().chain([&token]) { + assert!(!serialized.contains(secret.as_str())); + } +} + +#[actix_web::test] +async fn outcome_reports_are_attributed_evidence_that_never_change_decisions() { + let fleet = fleet().await; + let profile = fleet.project().await; + let plain = binding(MEMBER, &profile, vec![]); + let id = session('c'); + assert_eq!(fleet.admit(MEMBER, &plain, &id).await.0, StatusCode::OK); + let (_, grant) = fleet + .call( + MEMBER, + Method::POST, + "/v1/grants", + Some(grant_request(&plain, &id)), + ) + .await; + let path = format!("/v1/grants/{}:outcome", grant["grant_id"].as_str().unwrap()); + let report = json!({ + "service": "anthropic", + "method": "POST", + "path": "/v1/messages", + "outcome": "failed", + "reason": "upstream_error", + "status": 502, + "request_bytes": 10, + "response_bytes": 20, + "duration_ms": 30, + }); + let changed = |field: &str, value: Value| { + let mut report = report.clone(); + report[field] = value; + Some(report) + }; + assert_eq!( + fleet + .call(BOB, Method::POST, &path, Some(report.clone())) + .await + .0, + StatusCode::FORBIDDEN + ); + for (field, value, expected) in [ + ("service", json!("openai"), StatusCode::BAD_REQUEST), + ("reason", json!("Not A Code"), StatusCode::BAD_REQUEST), + ("method", json!("post"), StatusCode::BAD_REQUEST), + ("status", json!(42), StatusCode::BAD_REQUEST), + ("headers", json!({}), StatusCode::BAD_REQUEST), + ] { + let (status, body) = fleet + .call(MEMBER, Method::POST, &path, changed(field, value)) + .await; + assert_eq!(status, expected, "{field}: {body}"); + } + let missing = format!("/v1/grants/{}:outcome", "f".repeat(32)); + assert_eq!( + fleet + .call(MEMBER, Method::POST, &missing, Some(report.clone())) + .await + .0, + StatusCode::NOT_FOUND + ); + assert_eq!( + fleet + .call(MEMBER, Method::POST, &path, Some(report)) + .await + .0, + StatusCode::NO_CONTENT + ); + let (_, body) = fleet + .call( + MEMBER, + Method::POST, + "/v1/authorize", + Some(context(&grant, "/v1/messages")), + ) + .await; + assert_eq!(decision(&body), "allow", "outcomes are evidence only"); + + let events = fleet.events(&format!("session={id}")).await; + let outcome = events + .iter() + .find(|event| event["event_type"] == "request.outcome") + .unwrap(); + assert_eq!(outcome["outcome"], "failed"); + assert_eq!(outcome["actor"], MEMBER); + assert_eq!(outcome["target"], "POST anthropic/v1/messages"); + assert_eq!( + outcome["detail"], + "reason=upstream_error status=502 request_bytes=10 response_bytes=20 duration_ms=30" + ); +} + +#[actix_web::test] +async fn signed_audit_heads_anchor_the_chain_and_reveal_rewrites() { + { + let unsigned = fleet().await; + let (status, _) = unsigned + .call(OPERATOR, Method::GET, "/v1/audit/head", None) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + } + let signer = Arc::new(AuditSigner::from_key( + SigningKeyMaterial::generate().unwrap(), + )); + let fleet = fleet_with(Setup { + audit_signer: Some(signer.clone()), + ..Setup::default() + }) + .await; + assert!(fleet.audit_signer.is_some()); + fleet.project().await; + assert_eq!( + fleet + .call(OWNER, Method::GET, "/v1/audit/head", None) + .await + .0, + StatusCode::FORBIDDEN + ); + let (status, head) = fleet + .call(OPERATOR, Method::GET, "/v1/audit/head", None) + .await; + assert_eq!(status, StatusCode::OK, "{head}"); + let last = fleet.events("limit=500").await.last().unwrap().clone(); + assert_eq!(head["head"]["sequence"], last["sequence"]); + assert_eq!(head["head"]["event_hash"], last["event_hash"]); + assert_eq!(head["head"]["authority_id"], AUTHORITY); + + let directory = tempfile::tempdir().unwrap(); + let signed: anchor::SignedAuditHead = serde_json::from_value(head.clone()).unwrap(); + let path = anchor::write_anchor(directory.path(), &signed) + .unwrap() + .unwrap(); + assert!( + anchor::write_anchor(directory.path(), &signed) + .unwrap() + .is_none(), + "anchors are never overwritten" + ); + let check = |file: std::path::PathBuf| { + let database = fleet.database.clone(); + let identity = signer.identity.clone(); + async move { + anchor::check_anchor(&database, &identity, &file) + .await + .unwrap() + } + }; + assert!(check(path.clone()).await.valid); + + fleet.approved_exception(&fleet.publish(4).await).await; + assert!( + check(path.clone()).await.valid, + "a growing chain keeps old anchors valid" + ); + + let other = AuditSigner::from_key(SigningKeyMaterial::generate().unwrap()); + let foreign = directory.path().join("foreign.json"); + std::fs::write( + &foreign, + serde_json::to_vec(&other.sign(signed.head.clone()).unwrap()).unwrap(), + ) + .unwrap(); + assert!(!check(foreign).await.valid, "another key's anchor"); + let mut edited = head.clone(); + edited["head"]["signed_at_unix"] = json!(NOW + 1); + let edited_path = directory.path().join("edited.json"); + std::fs::write(&edited_path, serde_json::to_vec(&edited).unwrap()).unwrap(); + assert!(!check(edited_path).await.valid, "an edited anchor"); + + let mut tx = fleet.database.begin_write().await.unwrap(); + let drop_trigger = match fleet.database { + Database::Postgres(_) => "DROP TRIGGER audit_events_reject_update_delete ON audit_events", + Database::Sqlite(_) => "DROP TRIGGER audit_events_reject_update", + }; + tx.execute(drop_trigger, &[]).await.unwrap(); + tx.execute( + "UPDATE audit_events SET event_hash = $2 WHERE sequence = $1", + &[ + Arg::from(i64::try_from(signed.head.sequence).unwrap()), + "0".repeat(64).into(), + ], + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + let rewritten = check(path).await; + assert!(!rewritten.valid); + assert_eq!( + rewritten.reason.as_deref(), + Some("the database holds a different event at this sequence") + ); + let (_, verification) = fleet + .call(OPERATOR, Method::GET, "/v1/audit/verify", None) + .await; + assert_eq!(verification["valid"], false); +} + +#[actix_web::test] +async fn rate_limits_refuse_with_retry_after() { + let fleet = fleet_with(Setup { + limits: (3, 2), + ..Setup::default() + }) + .await; + let attacker = Some("192.0.2.1:40000"); + for token in [Some("sbf_not-a-token"), None] { + let (status, _, _) = fleet + .respond(attacker, Method::GET, "/v1/tokens", token, None) + .await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + let (status, headers, _) = fleet + .respond( + attacker, + Method::GET, + "/v1/tokens", + Some(&fleet.tokens[MEMBER]), + None, + ) + .await; + assert_eq!( + status, + StatusCode::TOO_MANY_REQUESTS, + "even valid tokens wait" + ); + assert_eq!(headers.get(header::RETRY_AFTER).unwrap(), "30"); + let (status, _, _) = fleet + .respond(attacker, Method::GET, "/healthz", None, None) + .await; + assert_eq!(status, StatusCode::OK, "probes are not limited"); + + let office = Some("192.0.2.2:40000"); + for _ in 0..3 { + let (status, _, _) = fleet + .respond( + office, + Method::GET, + "/v1/tokens", + Some(&fleet.tokens[VIEWER]), + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + } + let (status, headers, _) = fleet + .respond( + office, + Method::GET, + "/v1/tokens", + Some(&fleet.tokens[VIEWER]), + None, + ) + .await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(headers.get(header::RETRY_AFTER).unwrap(), "20"); + let (status, _, _) = fleet + .respond( + office, + Method::GET, + "/v1/tokens", + Some(&fleet.tokens[BOB]), + None, + ) + .await; + assert_eq!(status, StatusCode::OK, "limits are per principal"); +} + +#[actix_web::test] +async fn metrics_are_served_only_on_their_own_listener() { + let fleet = fleet().await; + assert_eq!( + fleet.call(MEMBER, Method::GET, "/v1/tokens", None).await.0, + StatusCode::OK + ); + let response = test::call_service( + &fleet.service, + test::TestRequest::get().uri("/metrics").to_request(), + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); + + let metrics = test::init_service(App::new().configure(fleet_server::metrics::configure)).await; + let response = test::call_service( + &metrics, + test::TestRequest::get().uri("/metrics").to_request(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert!( + response + .headers() + .get(header::CONTENT_TYPE) + .unwrap() + .to_str() + .unwrap() + .starts_with("text/plain; version=0.0.4") + ); + let text = String::from_utf8(test::read_body(response).await.to_vec()).unwrap(); + let successes = text + .lines() + .find_map(|line| line.strip_prefix("fleet_http_requests_total{class=\"2xx\"} ")) + .unwrap() + .parse::() + .unwrap(); + assert!(successes >= 1); + for name in [ + "fleet_auth_failures_total", + "fleet_rate_limited_total", + "fleet_audit_events_total", + "fleet_audit_sequence", + "fleet_http_request_duration_seconds_sum", + ] { + assert!(text.contains(&format!("\n{name} ")), "{name}"); + } + assert!(!text.contains("@example.com") && !text.contains("sbf_")); +} diff --git a/crates/fleet-server/tests/migrations.rs b/crates/fleet-server/tests/migrations.rs index 3c97b37..506d5f8 100644 --- a/crates/fleet-server/tests/migrations.rs +++ b/crates/fleet-server/tests/migrations.rs @@ -28,9 +28,19 @@ const SESSION: &str = "0123456789abcdef0123456789abcdef"; const PROFILE_SHA: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; const BINDING_SHA: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; +fn test_url() -> String { + std::env::var("FLEET_TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".to_owned()) +} + async fn database() -> Database { - let url = - std::env::var("FLEET_TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".to_owned()); + let database = unmigrated().await; + database.migrate().await.unwrap(); + database +} + +/// A connection to an empty schema. +async fn unmigrated() -> Database { + let url = test_url(); let database = Database::connect(&DatabaseUrl::parse(&url).unwrap()) .await .unwrap(); @@ -48,7 +58,6 @@ async fn database() -> Database { .await .unwrap(); } - database.migrate().await.unwrap(); database } @@ -335,3 +344,77 @@ async fn tokens_are_digests_with_bounded_lifetimes() { ) .await; } + +#[actix_web::test] +async fn startup_without_migrations_needs_an_applied_schema() { + let database = unmigrated().await; + let error = database.check_migrated().await.unwrap_err().to_string(); + assert!(error.contains("migrations 1, 2 are not applied"), "{error}"); + assert!(error.contains("sendbox-fleet admin migrate"), "{error}"); + database.migrate().await.unwrap(); + database.check_migrated().await.unwrap(); + exec(&database, "DELETE FROM _sqlx_migrations WHERE version = 2") + .await + .unwrap(); + let error = database.check_migrated().await.unwrap_err().to_string(); + assert!(error.contains("migrations 2 are not applied"), "{error}"); +} + +/// `deploy/postgres/roles.sql`: the runtime role cannot rewrite the audit +/// log, the migration ledger, or the schema. PostgreSQL only. +#[actix_web::test] +async fn postgres_runtime_role_keeps_the_audit_log_append_only() { + let url = test_url(); + if !url.starts_with("postgres") { + return; + } + let script = include_str!("../../../deploy/postgres/roles.sql"); + let admin = unmigrated().await; + exec(&admin, script).await.unwrap(); + let as_role = |role: &str| { + let mut url = url::Url::parse(&url).unwrap(); + url.set_username(role).unwrap(); + url.set_password(None).unwrap(); + DatabaseUrl::parse(url.as_str()).unwrap() + }; + let owner = Database::connect(&as_role("sendbox_fleet_owner")) + .await + .unwrap(); + owner.migrate().await.unwrap(); + exec(&admin, script).await.unwrap(); + let app = Database::connect(&as_role("sendbox_fleet_app")) + .await + .unwrap(); + app.check_migrated().await.unwrap(); + + accept( + &app, + "INSERT INTO principals (id, kind, created_at_unix) VALUES ('oidc:a@example.com', 'user', 0)", + ) + .await; + accept( + &app, + "UPDATE principals SET disabled_at_unix = 1 WHERE id = 'oidc:a@example.com'", + ) + .await; + accept(&app, &audit_sql(1, ZERO_HASH, &"1".repeat(64))).await; + for statement in [ + "UPDATE audit_events SET outcome = 'failed'", + "DELETE FROM audit_events", + "TRUNCATE audit_events", + "ALTER TABLE audit_events DISABLE TRIGGER USER", + "DROP TRIGGER audit_events_reject_update_delete ON audit_events", + "DELETE FROM _sqlx_migrations", + "INSERT INTO _sqlx_migrations (version, description, success, checksum, execution_time) \ + VALUES (99, 'x', TRUE, '\\x00', 0)", + "CREATE TABLE extra (id INTEGER)", + "DROP TABLE principals CASCADE", + ] { + let error = exec(&app, statement).await.unwrap_err().to_string(); + assert!( + error.contains("permission denied") || error.contains("must be owner"), + "{statement}: {error}" + ); + } + assert_eq!(count(&admin, "audit_events").await, 1); +} diff --git a/deploy/postgres/roles.sql b/deploy/postgres/roles.sql new file mode 100644 index 0000000..7ed759a --- /dev/null +++ b/deploy/postgres/roles.sql @@ -0,0 +1,56 @@ +-- Least-privilege PostgreSQL roles for sendbox-fleet. +-- +-- sendbox_fleet_owner owns the schema and runs `sendbox-fleet admin migrate`. +-- sendbox_fleet_app runs the server with FLEET_MIGRATE=false. It can read and +-- write operational tables but can only SELECT and INSERT audit events, and +-- cannot touch the migration ledger. +-- +-- Run as a superuser (or the database owner) in the fleet database: +-- 1. psql -v ON_ERROR_STOP=1 -f deploy/postgres/roles.sql (creates roles) +-- 2. set passwords: ALTER ROLE ... PASSWORD '...'; +-- 3. FLEET_DATABASE_URL=postgres://sendbox_fleet_owner@... sendbox-fleet admin migrate +-- 4. psql -v ON_ERROR_STOP=1 -f deploy/postgres/roles.sql (grants) +-- Rerun step 4 after every upgrade that ships a migration. Safe to rerun. + +DO $$ +BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'sendbox_fleet_owner') THEN + CREATE ROLE sendbox_fleet_owner LOGIN; + END IF; + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'sendbox_fleet_app') THEN + CREATE ROLE sendbox_fleet_app LOGIN; + END IF; +END +$$; + +GRANT CREATE, USAGE ON SCHEMA public TO sendbox_fleet_owner; +GRANT USAGE ON SCHEMA public TO sendbox_fleet_app; +REVOKE CREATE ON SCHEMA public FROM sendbox_fleet_app; + +DO $$ +DECLARE + table_name text; +BEGIN + IF to_regclass('public._sqlx_migrations') IS NULL THEN + RAISE NOTICE 'schema not migrated yet; rerun after `sendbox-fleet admin migrate`'; + RETURN; + END IF; + FOR table_name IN + SELECT tablename FROM pg_tables + WHERE schemaname = 'public' AND tableowner = 'sendbox_fleet_owner' + LOOP + EXECUTE format('REVOKE ALL ON public.%I FROM sendbox_fleet_app', table_name); + IF table_name = '_sqlx_migrations' THEN + EXECUTE format('GRANT SELECT ON public.%I TO sendbox_fleet_app', table_name); + ELSIF table_name = 'audit_events' THEN + EXECUTE format('GRANT SELECT, INSERT ON public.%I TO sendbox_fleet_app', table_name); + ELSE + EXECUTE format( + 'GRANT SELECT, INSERT, UPDATE, DELETE ON public.%I TO sendbox_fleet_app', + table_name + ); + END IF; + END LOOP; + GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO sendbox_fleet_app; +END +$$; diff --git a/docker-compose.yml b/docker-compose.yml index 5948bff..f79dfbf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,10 +37,24 @@ services: FLEET_AUTHORITY_ID: ${FLEET_AUTHORITY_ID:-sendbox-fleet} # Container path of the profile signer file, mounted by a compose override. FLEET_PROFILE_TRUST: ${FLEET_PROFILE_TRUST:-} + # Container path of the OIDC issuer file; empty disables identity-provider sign-in. + FLEET_OIDC_CONFIG: ${FLEET_OIDC_CONFIG:-} + FLEET_TOKEN_TTL_SECONDS: ${FLEET_TOKEN_TTL_SECONDS:-43200} + FLEET_TOKEN_MAX_TTL_SECONDS: ${FLEET_TOKEN_MAX_TTL_SECONDS:-604800} + # Container path of the audit-head signing key; empty disables signed heads. + FLEET_AUDIT_SIGNING_KEY: ${FLEET_AUDIT_SIGNING_KEY:-} + FLEET_AUDIT_ANCHOR_DIR: ${FLEET_AUDIT_ANCHOR_DIR:-} + FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS: ${FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS:-3600} + FLEET_RATE_LIMIT_PER_MINUTE: ${FLEET_RATE_LIMIT_PER_MINUTE:-1200} + FLEET_AUTH_FAILURES_PER_MINUTE: ${FLEET_AUTH_FAILURES_PER_MINUTE:-60} + FLEET_METRICS_BIND: ${FLEET_METRICS_BIND:-} + FLEET_MIGRATE: ${FLEET_MIGRATE:-true} + FLEET_LOG_MAX_BYTES: ${FLEET_LOG_MAX_BYTES:-104857600} ports: - "127.0.0.1:${FLEET_PORT:-8080}:8080" volumes: - fleet-logs:/var/log/sendbox-fleet + - fleet-anchors:/var/lib/sendbox-fleet/anchors read_only: true cap_drop: - ALL @@ -52,6 +66,7 @@ services: volumes: postgres-data: fleet-logs: + fleet-anchors: networks: backend: diff --git a/docs/architecture.md b/docs/architecture.md index 44a62c7..7d356b3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,10 +5,13 @@ It is increment 2 of that issue: the authenticated, multi-user management API and central authority that increment 1 deliberately left out. -It authenticates every `/v1` caller, enforces project-scoped roles, verifies -and publishes operator-signed profiles, admits governed sessions, issues and -checks credential grants, records bounded and expiring exceptions, and keeps a -hash-chained central audit log. See [roadmap.md](roadmap.md) for what remains. +It authenticates every `/v1` caller (service tokens or OpenID Connect), +enforces project-scoped roles, verifies and publishes operator-signed +profiles, admits governed sessions, issues and checks credential grants, +records bounded and expiring exceptions and host-reported request outcomes, +and keeps a hash-chained central audit log whose signed heads can be anchored +outside the database. See [roadmap.md](roadmap.md) for what remains and +[deployment.md](deployment.md) for running it. ## Relationship to SendBox increment 1 @@ -75,10 +78,26 @@ flowchart LR request is rejected with `401` before its body is read. Only `Authorization: Bearer ` is accepted. Identity headers such as `X-Forwarded-User`, `X-Remote-User`, or `X-Sendbox-Principal` are ignored. - `DatabaseAuthenticator` accepts opaque `sbf_` tokens issued with - `sendbox-fleet admin token issue`: only their SHA-256 is stored, and a token - works while it is unexpired (at most 90 days), unrevoked, and its principal - is not disabled. A failed token lookup is `503`, never an implicit allow. + Two kinds of bearer token are accepted: + - **Service tokens** (`sbf_…`), issued with `sendbox-fleet admin token + issue` or exchanged at `POST /v1/tokens`. Only their SHA-256 is stored, + and a token works while it is unexpired (at most 90 days), unrevoked, and + its principal is not disabled. + - **Identity-provider JWTs** from an issuer in `FLEET_OIDC_CONFIG`. The + signature must verify with the issuer's published keys, and `iss`, `aud`, + `exp`, `nbf`, `iat`, required claims, and `email_verified` (for email + principals) must pass. The principal is `:`; it must exist, + be active, and have the issuer's kind, unless the issuer may auto-provision + it (with no roles). See [deployment](deployment.md#identity-providers). + + A failed token lookup or unreachable key set is `503`, never an implicit + allow. Repeated failures from one peer address, and too many requests from + one principal, get `429` with `Retry-After`. +- **Token exchange.** `POST /v1/tokens` turns an identity-provider sign-in + into a service token for hosts (`sendbox governance login`). Only JWT + callers may exchange, so a service token cannot mint another. Lifetime + defaults to `FLEET_TOKEN_TTL_SECONDS` and is capped by + `FLEET_TOKEN_MAX_TTL_SECONDS`; a principal holds at most 20 live tokens. - **Authorization** answers "may this caller do this". It combines the caller kind (`user` or `worker`), the fleet-wide `operator` flag, project roles, the current profile revision, admitted sessions, grants, and exceptions, @@ -123,6 +142,10 @@ sessions as itself: it needs `member` or higher in the project. | List exceptions | `GET /v1/exceptions?project=…&state=active\|pending\|all`, `GET /v1/exceptions/{id}` | Any role in the project (or operator) | | Query audit events | `GET /v1/audit/events` | Operators read everything; others must pass a `project` in which they hold a role. Cursor pagination | | Verify the chain | `GET /v1/audit/verify` | Operator; recomputes every hash and link | +| Signed chain head | `GET /v1/audit/head` | Operator; the current sequence and hash signed with `FLEET_AUDIT_SIGNING_KEY` (`503` without it) | +| Exchange a sign-in | `POST /v1/tokens` | Identity-provider caller only; `ttl_seconds` in 60 to the maximum; returns the token once with `Cache-Control: no-store` | +| List or revoke tokens | `GET /v1/tokens`, `DELETE /v1/tokens/{id}` | Callers see and revoke their own tokens (never the secret); operators may revoke any | +| Report an outcome | `POST /v1/grants/{grant}:outcome` | Grant principal; service must match the grant. Records the redacted method, path, outcome, reason, status, sizes, and duration as `request.outcome`. Outcomes are evidence only and never change a grant or a decision | Project identifiers contain a slash (`github:owner/repo`), so clients percent-encode it in paths: `/v1/projects/github:owner%2Frepo/roles`. @@ -140,8 +163,9 @@ standard reason phrase as `title`, and a specific `detail`. | `404` / `405` | Unknown resource or path, or unsupported method | | `409` | Stale profile revision, stale or inactive exception, already-decided exception, ended session, duplicate admission, last owner | | `413` / `415` | Body too large (64 KiB, 1 MiB for profile publication) or not JSON | +| `429` | Rate limit; `Retry-After` gives the seconds to wait | | `500` | Internal failure; the cause is logged, never returned | -| `503` | Authentication or `/readyz` cannot reach the database, or profile publication without `FLEET_PROFILE_TRUST` | +| `503` | Authentication or `/readyz` cannot reach the database or identity-provider keys, profile publication without `FLEET_PROFILE_TRUST`, or `GET /v1/audit/head` without a signing key | A per-request authorization denial is a `200` with `{"decision": "deny", "reason": …}`; hosts deny on any other answer. @@ -152,13 +176,15 @@ unauthenticated and reveal nothing beyond availability. ## Persistence `migrations/postgres` and `migrations/sqlite` define the same schema; the -server applies the matching set at startup. PostgreSQL is the shared -deployment target; SQLite is for local development and tests. +server applies the matching set at startup, or with `FLEET_MIGRATE=false` +only checks that every migration was applied (by `sendbox-fleet admin +migrate` under a schema-owner role). PostgreSQL is the shared deployment +target; SQLite is for local development and tests. | Table | Holds | | --- | --- | | `principals` | Authenticated users and workers (never `local-user:`), with the operator flag | -| `api_tokens` | SHA-256 of each bearer token, expiry (at most 90 days), revocation | +| `api_tokens` | SHA-256 of each service token (admin-issued or exchanged), description, expiry (at most 90 days), revocation | | `projects` | `github:owner/repo` or `path-sha256:` projects | | `role_bindings` | One project-scoped role per principal per project | | `profiles` | Exact signed bytes, digest, signatures, validity window per revision | @@ -194,13 +220,26 @@ request or response bodies, and exception reasons are never recorded. `event_hash` is the SHA-256 of the RFC 8785 canonical JSON of the event as returned by `GET /v1/audit/events` without `event_hash` (so it includes `previous_hash`). The first event links to 64 zeros. `GET /v1/audit/verify` -recomputes the chain; anchoring chain heads outside the database is on the -roadmap. +recomputes the chain. + +The chain alone cannot stop someone who can rewrite the table and recompute +every hash, such as a database owner. With `FLEET_AUDIT_SIGNING_KEY`, the +service signs chain heads (`sendbox-fleet-audit-head` v1: authority, +sequence, event hash, time) with an Ed25519 key in SendBox's provenance +envelope. With `FLEET_AUDIT_ANCHOR_DIR`, it writes one to that directory at +startup and on every interval in which the chain advanced, never overwriting +an anchor. `sendbox-fleet admin audit verify --identity … --anchor …` +recomputes the chain and checks each anchor's signature and that the database +still holds its hash at its sequence. + +Other audit events added for authentication: `principal.provisioned`, +`token.issued`, and `token.revoked` (token ids, never tokens). ## Logging Structured JSON lines go to stdout and to `sendbox-fleet.YYYY-MM-DD.log` in -`FLEET_LOG_DIR`, rotated at each UTC day and pruned after 30 days. Request +`FLEET_LOG_DIR`, rotated at each UTC day and at `FLEET_LOG_MAX_BYTES`, and +pruned after 30 days. Request bodies, headers, and query strings are never logged. Details in [development.md](development.md#logs). @@ -209,17 +248,22 @@ bodies, headers, and query strings are never logged. Details in ```text crates/fleet-server/src/ main.rs process entry: serve (default) or `admin` subcommands - admin.rs bootstrap: principals, tokens, projects (direct database access) - server.rs app assembly, startup, graceful shutdown, retention timer + admin.rs bootstrap: principals, tokens, projects, audit keys, migrate + server.rs app assembly, startup, graceful shutdown, background tasks config.rs environment configuration and profile trust loading - state.rs shared state: database, clock, random ids, authority id, trust + state.rs shared state: database, clock, random ids, authority id, trust, limits + oidc.rs identity-provider configuration and JWT/JWKS verification + anchor.rs signed audit heads, anchoring, anchor verification + ratelimit.rs per-principal and per-peer token buckets + metrics.rs Prometheus counters and the metrics listener logging.rs subscriber setup and request logging middleware - logging/retention.rs + logging/rotation.rs, logging/retention.rs db.rs pools, migrations, readiness, backend-neutral transactions and rows governance.rs stored roles, profiles, sessions, grants, and exceptions audit.rs hash-chained append, queries, chain verification problem.rs RFC 9457 problem responses - auth.rs bearer authentication middleware and DatabaseAuthenticator + auth.rs bearer middleware, service-token and identity-provider authenticators routes/ health probes and the /v1 API migrations/{postgres,sqlite}/ +deploy/postgres/roles.sql least-privilege owner and runtime roles ``` diff --git a/docs/contract.md b/docs/contract.md index 45f48e5..67467b3 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -54,6 +54,8 @@ cargo test --locked --workspace | `PolicyException`, `ExceptionScope`, `ExceptionId`, `api::ExceptionList` | `/v1/exceptions` responses; scopes are checked with `GovernanceProfile::permits_exception` | | `ProjectId`, `PrincipalId` | Role, exception, and audit endpoints | | `Sha256Digest`, `canonical_digest` | Digests in responses, binding storage, and audit event hashes | +| `api::TokenRequest`, `api::IssuedToken` | `POST /v1/tokens` body and response | +| `api::RequestOutcomeReport`, `api::ReportedOutcome` | `POST /v1/grants/{grant}:outcome` body, checked with `RequestOutcomeReport::validate` | Validation is the contract's own: identifier grammars, `deny_unknown_fields`, `GovernanceBinding::validate`, `validate_method`, `validate_path_prefix`, and @@ -62,8 +64,8 @@ Validation is the contract's own: identifier grammars, `deny_unknown_fields`, Wire types a SendBox host also uses live in `sendbox_governance::api`. Types only people use live here, in the route module that uses them: `CreateProject`, `ProjectRole` and `RoleBinding`, `ExceptionRequest`, -`ProfilePublication` and `MinimumRevision`, and the audit query, page, and -event types. Profile signatures use SendBox's signing envelope +`ProfilePublication` and `MinimumRevision`, `TokenSummary` and `TokenList`, +and the audit query, page, event, and signed-head types. Profile signatures use SendBox's signing envelope (`sendbox_security::provenance::DetachedSignature` in a `sendbox.governance-signatures` bundle), verified with the same trust store code as hosts. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..fa4c31c --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,254 @@ +# Deployment + +How to run `sendbox-fleet` for a team. [Development](development.md) covers +local runs; this page covers a shared, production-like setup. Every setting +here is an environment variable listed in +[development.md](development.md#configuration). + +```mermaid +flowchart LR + hosts["SendBox hosts and people"] -- "HTTPS" --> proxy["Reverse proxy
(TLS, request limits)"] + proxy -- "HTTP on a private network" --> fleet["sendbox-fleet
FLEET_MIGRATE=false"] + fleet -- "sendbox_fleet_app role" --> pg[("PostgreSQL")] + fleet -. "JWKS over HTTPS" .-> idp["Identity providers"] + fleet -- "signed audit heads" --> anchors[("Write-once storage")] + prom["Prometheus"] -- "FLEET_METRICS_BIND" --> fleet +``` + +## Checklist + +1. PostgreSQL with the least-privilege roles below. SQLite is for development + only. +2. A reverse proxy that terminates TLS. The service itself speaks plain HTTP. +3. `FLEET_AUTHORITY_ID` set to the value every host puts under `authority:`. +4. `FLEET_PROFILE_TRUST` naming the operators who sign profiles. +5. `FLEET_OIDC_CONFIG` for people and CI, or admin-issued tokens only. +6. An audit signing key and an anchor directory on storage the database + administrators cannot rewrite. +7. Metrics on a private address, log shipping from stdout or `FLEET_LOG_DIR`, + and database backups. + +## TLS and the reverse proxy + +Bearer tokens must only travel over TLS. Run the service on a private address +(`FLEET_BIND=10.0.0.5:8080`, or the Compose network) behind a proxy such as +nginx, Caddy, Envoy, or a cloud load balancer that: + +- terminates TLS 1.2 or later with a certificate hosts trust; +- forwards the `Authorization` header unchanged and adds no identity headers + (the service ignores `X-Forwarded-User` and similar anyway); +- does not cache responses (token exchange already sends + `Cache-Control: no-store`); +- limits request rates per client address. + +The service rate limits per process: `FLEET_RATE_LIMIT_PER_MINUTE` requests +per authenticated principal, and `FLEET_AUTH_FAILURES_PER_MINUTE` failed +authentications per peer address. Behind a proxy every client shares the +proxy's address, so the failure limit throttles all clients together when one +of them sends bad tokens. Either set `FLEET_AUTH_FAILURES_PER_MINUTE=0` and +rely on the proxy's per-client limit, or raise it well above normal traffic. +`X-Forwarded-For` is not trusted. + +Limits are per instance. With several instances, the effective limit is the +per-instance value times the instance count. + +## PostgreSQL roles and migrations + +[`deploy/postgres/roles.sql`](../deploy/postgres/roles.sql) creates two +roles: + +| Role | Can | +| --- | --- | +| `sendbox_fleet_owner` | Owns the schema; runs `sendbox-fleet admin migrate` | +| `sendbox_fleet_app` | Reads and writes operational tables; only `SELECT` and `INSERT` on `audit_events`; only `SELECT` on `_sqlx_migrations`; cannot create, alter, or drop anything | + +```sh +psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql # as a superuser +psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_owner PASSWORD '…'" +psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_app PASSWORD '…'" +FLEET_DATABASE_URL=postgres://sendbox_fleet_owner:…@db/sendbox_fleet sendbox-fleet admin migrate +psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql # grants on the new tables +``` + +Then run the service as `sendbox_fleet_app` with `FLEET_MIGRATE=false`. It +refuses to start while a migration is missing and names the fix. Admin +commands run with `FLEET_MIGRATE=false` also check instead of migrating, so +they work with the app role. On upgrade: stop the old version, run +`admin migrate` as the owner, rerun `roles.sql`, then start the new version. + +The audit triggers stop the app role and anyone without `ALTER` on the table. +The owner and superusers can still disable them, which is what audit +anchoring is for. + +## Identity providers + +`FLEET_OIDC_CONFIG` points at a YAML file of trusted issuers. Without it, only +service tokens from `sendbox-fleet admin token issue` authenticate. + +```yaml +issuers: + # People: the principal is `oidc:`. + - issuer: https://accounts.google.com + audiences: ["123456789-example.apps.googleusercontent.com"] + kind: user + principal_claim: email + principal_prefix: oidc + # CI: GitHub Actions jobs from one organization, as `github-actions:`. + - issuer: https://token.actions.githubusercontent.com + audiences: [sendbox-fleet] + kind: worker + principal_claim: repository_id + principal_prefix: github-actions + required_claims: + repository_owner: example + auto_provision: true +``` + +| Field | Default | Meaning | +| --- | --- | --- | +| `issuer` | required | Exact `iss`; `https://` (or `http://` on loopback for tests) | +| `audiences` | required | At least one must appear in `aud` | +| `kind` | required | `user` or `worker`; an existing principal of the other kind is refused | +| `principal_claim` | required | Claim that names the principal; string or number | +| `principal_prefix` | required | Unique per issuer, lowercase letters or `-`, not `local-user` | +| `require_email_verified` | true when the claim is `email` | Require `email_verified: true` | +| `auto_provision` | `false` | Create unknown principals on first sign-in, with no roles and no operator flag, audited as `principal.provisioned` | +| `jwks_uri` | from discovery | Skip `/.well-known/openid-configuration` | +| `algorithms` | `RS256`, `ES256`, `EdDSA` | Accepted signature algorithms | +| `required_claims` | none | Claims that must equal these strings | +| `jwks_cache_seconds` | `600` | Key cache lifetime (60 to 86400) | +| `leeway_seconds` | `60` | Clock skew for `exp`, `nbf`, and `iat` (at most 300) | + +Keys are fetched over HTTPS with the system CA bundle, without proxies or +redirects, and cached. An unknown key id refreshes the key set at most every +30 seconds. If keys cannot be fetched and none are cached, callers get `503`; +cached keys keep working through an outage. + +Keep `auto_provision` off for people unless anyone who can sign in to the +provider may hold a principal; roles still have to be granted per project. +For CI, `required_claims` is what limits which repositories can sign in. + +### Signing in from a SendBox host + +A JWT from a configured issuer authenticates any `/v1` call directly, but +provider tokens are short-lived. Hosts exchange one for a fleet service token: + +```sh +my-idp print-id-token | sendbox governance login +``` + +`POST /v1/tokens` accepts only identity-provider callers, so a leaked service +token cannot mint more. Exchanged tokens last `FLEET_TOKEN_TTL_SECONDS` +(12 hours) unless the request asks for less or up to +`FLEET_TOKEN_MAX_TTL_SECONDS` (7 days); a principal holds at most 20 live +tokens. `GET /v1/tokens` lists the caller's tokens and +`DELETE /v1/tokens/{id}` revokes one; operators can revoke any token. + +In GitHub Actions, request an ID token with the fleet's audience (the job +needs `permissions: id-token: write`), then pass it to `sendbox governance +login --identity-token-file`. + +## Audit anchoring + +The audit chain detects edits by anyone who cannot recompute every later hash. +A database owner can. Anchors fix that: a signed copy of the chain head, kept +where the database administrators cannot rewrite it. + +```sh +sendbox-fleet admin audit keygen --output /etc/sendbox-fleet/audit.key > audit-identity.json +``` + +The key file is created with mode `0600`; the service refuses to load a key +that group or others can access. Keep it off the database host and out of database backups; publish +`audit-identity.json` to whoever verifies the log. + +| Setting | Effect | +| --- | --- | +| `FLEET_AUDIT_SIGNING_KEY` | Enables `GET /v1/audit/head` (operators): the current head, signed | +| `FLEET_AUDIT_ANCHOR_DIR` | Writes `audit-head-.json` there at startup and every `FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS` (default 3600) when the chain has advanced | + +Point `FLEET_AUDIT_ANCHOR_DIR` at write-once storage, such as an object-store +bucket with object lock mounted into the container, or a directory another +system collects. Anchors are never overwritten. Without a mounted directory, +an external job can call `GET /v1/audit/head` or run +`sendbox-fleet admin audit anchor --output DIR`. + +To check the log: + +```sh +sendbox-fleet admin audit verify --identity audit-identity.json \ + --anchor anchors/audit-head-00000000000000001234.json … +``` + +It recomputes the chain and checks that each anchor's signature verifies and +that the database still holds the anchored hash at that sequence. It prints +one JSON line per result and exits non-zero on any failure. + +## Metrics + +Set `FLEET_METRICS_BIND` (for example `10.0.0.5:9090`) to serve Prometheus +text at `/metrics` on a second listener. It has no authentication, so keep it +on a private network; it is never served on `FLEET_BIND`. + +| Metric | Type | Meaning | +| --- | --- | --- | +| `fleet_http_requests_total{class}` | counter | Requests by status class (`2xx`, `4xx`, …) | +| `fleet_http_request_duration_seconds_sum` / `_count` | summary | Request time | +| `fleet_auth_failures_total` | counter | Rejected bearer tokens | +| `fleet_rate_limited_total` | counter | `429` answers | +| `fleet_authorization_decisions_total{decision,reason}` | counter | `/v1/authorize` results by deny reason | +| `fleet_audit_events_total` | counter | Events appended by this process | +| `fleet_audit_sequence` | gauge | Highest audit sequence | + +Labels never contain principals, projects, sessions, or tokens. Useful alerts: +a rising `5xx` rate, `fleet_auth_failures_total` spikes, and +`fleet_authorization_decisions_total{reason="authority_unavailable"}`. + +## Logs + +Logs go to stdout and `FLEET_LOG_DIR`. Files rotate at UTC midnight and when +they reach `FLEET_LOG_MAX_BYTES` (100 MiB), and are pruned after +`FLEET_LOG_RETENTION_DAYS`. In containers, ship stdout and keep the volume +small. See [development.md](development.md#logs). + +## Backups and restore + +- **PostgreSQL**: `pg_dump --format=custom sendbox_fleet` on a schedule, or + continuous archiving for point-in-time recovery. Store dumps encrypted and + away from the database host. +- **SQLite** (development only): `sqlite3 sendbox-fleet.db ".backup copy.db"` + while the service runs. +- Back up `FLEET_PROFILE_TRUST`, `FLEET_OIDC_CONFIG`, and the audit identity + with the deployment configuration. Back up the audit signing key separately. + +The database holds token digests, not tokens, so a restored backup cannot be +used to sign in. Tokens revoked after the backup become valid again after a +restore, as do principals disabled after it: revoke and disable them again. + +After a restore, run `sendbox-fleet admin audit verify` with the newest +anchors. Anchors newer than the backup fail with "the database no longer +holds this sequence", which documents exactly what the restore lost. + +## Compose + +[`docker-compose.yml`](../docker-compose.yml) passes every setting through +from `.env` and mounts a `fleet-anchors` volume at +`/var/lib/sendbox-fleet/anchors`. Mount the trust file, OIDC file, and audit +key with an override file: + +```yaml +# docker-compose.override.yml +services: + fleet: + environment: + FLEET_PROFILE_TRUST: /etc/sendbox-fleet/profile-trust.yaml + FLEET_OIDC_CONFIG: /etc/sendbox-fleet/oidc.yaml + FLEET_AUDIT_SIGNING_KEY: /run/sendbox-fleet/audit.key + FLEET_AUDIT_ANCHOR_DIR: /var/lib/sendbox-fleet/anchors + volumes: + - ./config:/etc/sendbox-fleet:ro + - ./audit-key:/run/sendbox-fleet:ro +``` + +The service runs as uid 10001, so `./audit-key/audit.key` must be owned by +that uid with mode `0600` or `0400`. diff --git a/docs/development.md b/docs/development.md index 55b5dac..2313331 100644 --- a/docs/development.md +++ b/docs/development.md @@ -2,8 +2,8 @@ ## Prerequisites -- [rustup](https://rustup.rs). The pinned toolchain (Rust 1.93.1 with clippy - and rustfmt) installs automatically from `rust-toolchain.toml`. +- [rustup](https://rustup.rs). The pinned toolchain (Rust 1.100.0 with + clippy and rustfmt) installs automatically from `rust-toolchain.toml`. - A Docker-compatible engine with Compose, only for the PostgreSQL stack. ## Configuration @@ -20,6 +20,17 @@ with status `2` and a message naming the variable when a value is invalid. | `FLEET_LOG_RETENTION_DAYS` | `30` | Days to keep rotated log files (1 to 3650) | | `FLEET_AUTHORITY_ID` | `sendbox-fleet` | Authority id hosts put in `authority:` of their operator configuration and bind into every session; not `local` | | `FLEET_PROFILE_TRUST` | unset | YAML or JSON file with `threshold` and `signers` (the same shape as a host operator configuration's `trust` section). Profile publication is refused until it is set | +| `FLEET_OIDC_CONFIG` | unset | YAML file of trusted identity providers ([format](deployment.md#identity-providers)). Unset: only service tokens authenticate | +| `FLEET_TOKEN_TTL_SECONDS` | `43200` (12 h) | Default lifetime of tokens from `POST /v1/tokens` | +| `FLEET_TOKEN_MAX_TTL_SECONDS` | `604800` (7 d) | Longest lifetime a caller may request (at most 90 days) | +| `FLEET_AUDIT_SIGNING_KEY` | unset | Key from `admin audit keygen` (no group or other access). Enables `GET /v1/audit/head` | +| `FLEET_AUDIT_ANCHOR_DIR` | unset | Directory for periodic signed heads; needs the signing key | +| `FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS` | `3600` | Anchoring interval (60 to 86400) | +| `FLEET_RATE_LIMIT_PER_MINUTE` | `1200` | `/v1` requests per principal per minute; `0` disables | +| `FLEET_AUTH_FAILURES_PER_MINUTE` | `60` | Failed authentications per peer address per minute; `0` disables | +| `FLEET_METRICS_BIND` | unset | Separate listener for Prometheus `/metrics`; must differ from `FLEET_BIND` | +| `FLEET_MIGRATE` | `true` | `false`: never change the schema; refuse to start until `admin migrate` has run | +| `FLEET_LOG_MAX_BYTES` | `104857600` (100 MiB) | Rotate the log file at this size (1 MiB to 10 GiB) | Database credentials in `FLEET_DATABASE_URL` are never logged. @@ -41,7 +52,8 @@ closes the database pool, and flushes logs. ## Bootstrap principals, tokens, and projects `sendbox-fleet admin` acts on the database directly and needs only -`FLEET_DATABASE_URL`. Every change is audited with the actor `cli:admin`. +`FLEET_DATABASE_URL` (and honors `FLEET_MIGRATE`). Every change is audited +with the actor `cli:admin`. ```sh sendbox-fleet admin principal add oidc:olivia@example.com --kind user --operator @@ -78,6 +90,19 @@ jq -n --rawfile document acme.yaml --slurpfile signatures acme.yaml.sig.json \ On each SendBox host, the operator configuration names this service and the caller stores their own token: `sendbox secrets add SENDBOX_FLEET_TOKEN`. +With `FLEET_OIDC_CONFIG`, people and CI sign in with their identity provider +instead, and hosts exchange that sign-in for a service token with +`sendbox governance login`. See [deployment](deployment.md#identity-providers). + +Other admin commands: + +```sh +sendbox-fleet admin migrate # apply migrations only +sendbox-fleet admin audit keygen --output audit.key > audit-identity.json +FLEET_AUDIT_SIGNING_KEY=audit.key sendbox-fleet admin audit anchor --output anchors/ +sendbox-fleet admin audit verify --identity audit-identity.json --anchor anchors/audit-head-*.json +``` + ## Run with PostgreSQL (Compose) ```sh @@ -104,6 +129,9 @@ tests against PostgreSQL, point `FLEET_TEST_DATABASE_URL` at a disposable database whose name ends in `_test` (the tests drop and recreate its `public` schema): +The PostgreSQL run also checks `deploy/postgres/roles.sql` by connecting as +its roles, which the trust authentication below allows. + ```sh docker run -d --name sendbox-fleet-pg-test -p 127.0.0.1:55432:5432 \ -e POSTGRES_DB=sendbox_fleet_test -e POSTGRES_USER=sendbox_fleet \ @@ -120,19 +148,20 @@ plus a start, probe, and graceful-stop run of the server on PostgreSQL; and ## Logs - Every event is a JSON line written to stdout and to - `FLEET_LOG_DIR/sendbox-fleet.YYYY-MM-DD.log`. The live file is the one for - the current UTC date; a new file starts at each UTC midnight. + `FLEET_LOG_DIR/sendbox-fleet.YYYY-MM-DD.log`. A new file starts at each UTC + midnight, and whenever the live file reaches `FLEET_LOG_MAX_BYTES` the next + part continues in `sendbox-fleet.YYYY-MM-DD.1.log`, `.2.log`, and so on. + Files are created with mode `0600`. - Retention runs at startup and then hourly. It deletes only regular files - named `sendbox-fleet.YYYY-MM-DD.log` whose UTC day ended at least - `FLEET_LOG_RETENTION_DAYS` days ago, judged by the date in the name rather - than the modification time. Other files, directories, and symlinks are left + named `sendbox-fleet.YYYY-MM-DD.log` or `sendbox-fleet.YYYY-MM-DD.N.log` + whose UTC day ended at least `FLEET_LOG_RETENTION_DAYS` days ago, judged by + the date in the name rather than the modification time. Other files, directories, and symlinks are left alone; deletion failures are logged and retried at the next run. - The log directory is created with mode `0700`. - File writes go through a bounded queue of 16,384 events. When it is full, logging callers wait instead of dropping events. - Never logged: request bodies, headers (including `Authorization`), query strings, and database credentials. -- Rotation is daily only; size-based rotation is a roadmap item. ## Migrations @@ -153,3 +182,9 @@ invariant. | Every `/v1` call returns `401 bearer token was not accepted` | The token is unknown, expired, revoked, or its principal is disabled; issue a new one with `sendbox-fleet admin token issue` | | `503 profile signers are not configured` on profile publication | Set `FLEET_PROFILE_TRUST` | | `409 ... is not the current revision` on session admission | The host's local profile differs from the newest published revision; install the same signed bytes on the host | +| `migrations … are not applied; run sendbox-fleet admin migrate` | `FLEET_MIGRATE=false` and the schema is behind; run `admin migrate` as the schema owner | +| `permission denied for schema public` at startup | The runtime role cannot migrate; set `FLEET_MIGRATE=false` and migrate as the owner | +| `401` for an identity-provider token | Issuer, audience, expiry, key, required claim, or `email_verified` did not match, or the principal is unknown, disabled, or of the other kind. The server log names the reason (for example `expired`, `audience_mismatch`, `not_registered`); callers only see `401` | +| `503 identity provider keys are unavailable` | The issuer's discovery or JWKS endpoint is unreachable and no keys are cached | +| `429 rate limit exceeded` | Wait `Retry-After` seconds; behind a proxy, see [deployment](deployment.md#tls-and-the-reverse-proxy) | +| `… must not be accessible by group or others` | `chmod 600` the audit signing key | diff --git a/docs/roadmap.md b/docs/roadmap.md index eaa4f14..eae98c2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -51,22 +51,36 @@ invariants, CI, and these documents. Increment 2 then delivered: - **Central audit** (AC6, AC7). Hash-chained events for every decision with actor, principal, project, session, grant, exception, revision, decision, redacted target, and detail; role-scoped queries; chain verification. +- **Identity providers** (AC7). Any OpenID Connect issuer for people and + machine identities such as GitHub Actions: JWKS verification with `ring` + (`RS256`, `ES256`, `EdDSA`), exact issuer and audience, required claims, + verified email, optional auto-provisioning without roles. `POST + /v1/tokens` exchanges a sign-in for a short-lived service token, which + `sendbox governance login` stores on the host; tokens can be listed and + revoked. +- **Outcomes and anchoring** (AC6, AC7). Hosts report each brokered stream's + outcome (`succeeded`, `failed`, `unknown`) to `POST + /v1/grants/{grant}:outcome`, recorded as `request.outcome`. Chain heads are + signed (`GET /v1/audit/head`), written periodically to an anchor directory, + and checked with `sendbox-fleet admin audit verify`. +- **Operations** (AC8). Least-privilege PostgreSQL roles + (`deploy/postgres/roles.sql`, no `UPDATE`/`DELETE` on audit for the + runtime role), `FLEET_MIGRATE=false` with `admin migrate`, per-principal and + per-peer rate limits, Prometheus metrics on a separate listener, size and + daily log rotation, and [deployment](deployment.md) guidance for TLS, + identity providers, anchoring, metrics, and backups. +- **Dependencies.** Rust 1.100.0 and sqlx 0.9, which removed the unused + `rsa` advisory exception. ## Remaining -1. **Identity provider** (AC7 hardening). Replace or complement admin-issued - tokens with OIDC for people and mTLS or signed short-lived tokens for - workers; self-service token issuance. -2. **Live end-to-end runs.** Run Apple and Kata governed sessions against a - deployed fleet and real model providers. -3. **Audit anchoring and outcomes.** Anchor chain heads outside the database; - accept host-reported stream outcomes (`succeeded`, `failed`, `unknown`). -4. **Operations** (AC8). TLS termination guidance, rate limiting, metrics, - backups, database role hardening (no `UPDATE`/`DELETE` on audit), - deployment docs, and size-based log rotation. -5. **Dependency follow-ups.** Move the contract pin to a merged sendbox - commit; upgrade to sqlx 0.9 once the toolchain moves to Rust 1.94 or later - and drop the `cargo audit` exceptions in `.cargo/audit.toml`. +1. **Live end-to-end runs.** Run Apple and Kata governed sessions against a + deployed fleet and real model providers. The provider path (broker, + relay, credential injection) is host-side, so this is tracked in SendBox: + [mbianchidev/sendbox#96](https://github.com/mbianchidev/sendbox/issues/96). +2. **`RUSTSEC-2026-0459`.** Drop the exception in `.cargo/audit.toml` once an + sqlx release allows libsqlite3-sys 0.39. It affects only SQLite, which + production does not use. ## Non-goals diff --git a/docs/threat-model.md b/docs/threat-model.md index e061792..de1057b 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -4,8 +4,9 @@ Scope: the shared governance service in this repository and its interfaces to SendBox hosts, people, and its database. The SendBox VM boundary, host broker, and increment-1 local authority are covered in the sendbox repository. -Status column: **implemented** means implemented and tested here; **planned** -means designed but not implemented (see [roadmap.md](roadmap.md)). +Status column: **implemented** means implemented and tested here; +**documented** means the mitigation is deployment guidance in +[deployment.md](deployment.md). Remaining work is in [roadmap.md](roadmap.md). ## Assets @@ -29,6 +30,7 @@ SendBox host broker and never reach the fleet. | Workload (agent inside a VM) | Untrusted; never talks to the fleet directly | | Network attacker | Untrusted | | Database administrator | Can bypass application controls; mitigated by evidence anchoring | +| Identity provider in `FLEET_OIDC_CONFIG` | Trusted to name principals under its own prefix, within its audience and required claims; nothing else | ## Threats and mitigations @@ -36,26 +38,31 @@ SendBox host broker and never reach the fleet. | --- | --- | --- | --- | | T1 | Caller spoofs identity with headers such as `X-Forwarded-User` | Only bearer tokens authenticate; identity headers are ignored; auth runs before routing | Implemented (tested) | | T2 | Workload-supplied identity in a body is trusted | Binding and grant principals must equal the authenticated caller; projects and sessions are checked against stored state; `local-user:` principals rejected by API and schema | Implemented (tested) | -| T3 | Stolen or replayed bearer token | Tokens stored only as SHA-256, expiring within 90 days, revocable, void when the principal is disabled; TLS in front of the service | Implemented; identity provider and audience binding planned | +| T3 | Stolen or replayed bearer token | Service tokens stored only as SHA-256, expiring within 90 days (exchanged ones within `FLEET_TOKEN_MAX_TTL_SECONDS`, 7 days by default), listable and revocable by their owner, void when the principal is disabled; a service token cannot mint another; identity-provider JWTs need this service's audience and expire in minutes; TLS in front of the service ([deployment](deployment.md#tls-and-the-reverse-proxy)) | Implemented (tested) | | T4 | Compromised worker acts for sessions it does not run | A caller can only admit, use, renew, or end sessions bound to its own principal; grants bound to session, principal, project, binding digest, and profile revision (composite foreign key) | Implemented (tested) | | T5 | Stale policy or approval authorizes changed work | Sessions, grants, and exceptions reference an exact profile revision and digest; a new revision or raised minimum makes them stale; approvals of stale requests are refused; sessions bound to a revoked or expired exception are denied | Implemented (tested) | | T6 | Grant wider than the profile allows | Methods and path prefixes must be inside the profile service; lifetime capped by the profile TTL, profile expiry, exception expiry, and 7 days | Implemented (tested) | -| T7 | Audit evidence altered or deleted | Append-only triggers, contiguous hash chain computed by the service and enforced on insert, `GET /v1/audit/verify`; service role without `UPDATE`/`DELETE`; external anchoring of chain heads against a database administrator | Implemented except role hardening and anchoring (planned) | +| T7 | Audit evidence altered or deleted | Append-only triggers, contiguous hash chain computed by the service and enforced on insert, `GET /v1/audit/verify`; runtime role without `UPDATE`, `DELETE`, `TRUNCATE`, or `ALTER` on audit (`deploy/postgres/roles.sql`); Ed25519-signed chain heads anchored outside the database and checked by `admin audit verify` | Implemented (tested) | | T8 | Secrets leak into logs or audit | No request bodies, headers, or query strings logged; database URL credentials redacted; tokens stored only as digests; no credential columns; audit keeps a redacted target without query strings (schema check) and omits exception reasons | Implemented (tested) | | T9 | Authority outage silently allows requests | Hosts deny with `authority_unavailable` on any non-200 answer, timeout, or redirect; a token lookup failure is `503` | Implemented (host client tested in sendbox) | | T10 | Exception abuse or self-approval | Only denials the signed revision lists as liftable; reason; expiry at most the profile's `exceptions.max_ttl_seconds` and 7 days; approver is a different `owner` or `admin` (also a schema check); lifting never widens the ceiling; every request, decision, refusal, use, and revocation audited | Implemented (tested) | -| T11 | Revocation does not stop in-flight traffic | New requests denied at once; open streams bounded by the profile grace window (at most 60 seconds) on the host; uncertain outcomes audited on the host as `aborted_uncertain` | Implemented; central outcome reporting planned | -| T12 | Resource exhaustion | Body limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, bounded list sizes, non-lossy bounded log queue | Implemented; rate limiting planned | +| T11 | Revocation does not stop in-flight traffic | New requests denied at once; open streams bounded by the profile grace window (at most 60 seconds) on the host; uncertain outcomes audited on the host as `aborted_uncertain` and centrally as `request.outcome` with outcome `unknown` | Implemented (tested) | +| T12 | Resource exhaustion | Body limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, bounded list sizes, non-lossy bounded log queue, per-principal request and per-peer authentication-failure rate limits, at most 20 live exchanged tokens per principal, bounded and throttled JWKS fetches, size-capped log files | Implemented (tested); limits are per instance | | T13 | Supply-chain compromise | Actions pinned by commit SHA, images pinned by digest, `Cargo.lock` committed, contract pinned by git revision, `cargo audit` in CI with documented exceptions | Implemented | +| T14 | Forged or misdirected identity-provider token | Exact issuer match against an operator-written list (HTTPS, or HTTP to loopback for tests), audience required, keys only from that issuer's JWKS (no `jku`, `x5u`, or embedded keys, no `none` or HMAC algorithms, `crit` refused), per-issuer algorithm allowlist, required claims (for example `repository_owner`), verified email, unique principal prefixes, kind bound to the issuer; auto-provisioned principals get no roles | Implemented (tested) | +| T15 | Rate-limit bypass or lockout behind a proxy | The failure limit keys on the TCP peer and ignores `X-Forwarded-For`; deployment guidance to limit per client at the proxy | Documented | +| T16 | Metrics leak identities | Metrics on a separate listener, labels limited to status classes and decision codes | Implemented (tested) | ## Known accepted risks -- `RUSTSEC-2026-0459` (bundled SQLite older than 3.54): SQLite is used only - for local development and tests on files the service creates. Fixing it - needs sqlx 0.9, which needs Rust 1.94; this workspace matches SendBox's - pinned Rust 1.93.1. Tracked in [roadmap.md](roadmap.md). -- `RUSTSEC-2023-0071` (`rsa`): present in `Cargo.lock` only through sqlx's - optional MySQL support and never compiled. -- Database triggers do not stop a database superuser. Production must run the - service with a least-privilege role, and chain heads must be anchored - outside the database. +- `RUSTSEC-2026-0459` (bundled SQLite older than the fix): SQLite is used + only for local development and tests on files the service creates. The fix + is libsqlite3-sys 0.39, which sqlx 0.9.0 does not allow yet. Tracked in + [roadmap.md](roadmap.md). +- Database triggers do not stop a database owner or superuser. Run the + service with `sendbox_fleet_app` and anchor chain heads on storage those + administrators cannot rewrite; then a rewrite is detected, though not + prevented. +- An identity-provider compromise can sign in as any principal that provider + names. Limit each issuer's prefix, audience, and required claims, and keep + `auto_provision` off where it is not needed. From 93f777bd558c899ed338e948c0b1af203dd45b9f Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 18:15:19 +0100 Subject: [PATCH 3/3] Pin the contract to sendbox main after #97 merged --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e9e4faf..96e12c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -717,7 +717,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1682,7 +1682,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1738,7 +1738,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1832,7 +1832,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#3cab6149330895ad9c1eae4b1f2780fc7ae473c2" dependencies = [ "serde", ] @@ -1840,7 +1840,7 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#3cab6149330895ad9c1eae4b1f2780fc7ae473c2" dependencies = [ "sendbox-core", "serde", @@ -1854,7 +1854,7 @@ dependencies = [ [[package]] name = "sendbox-security" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=cp-desktop-fleet-project-roles-exceptions#a0366ea6bbd9bfe11cac4f113b0394bba7076598" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#3cab6149330895ad9c1eae4b1f2780fc7ae473c2" dependencies = [ "base64 0.22.1", "ed25519-dalek", @@ -2320,7 +2320,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2822,7 +2822,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 8edfff5..bbc2534 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,8 +19,8 @@ getrandom = "0.4.3" reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider"] } ring = "0.17.14" rustls = { version = "0.23.46", default-features = false, features = ["ring", "std"] } -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "cp-desktop-fleet-project-roles-exceptions" } -sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "cp-desktop-fleet-project-roles-exceptions" } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } serde_json_canonicalizer = "0.3.2" serde_yaml_ng = { package = "yaml_serde", version = "0.10.7" } sha2 = "0.11.0"