From 148a3a0ff99abc541623a5b8825f6ddb2c485af7 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:38:41 +0100 Subject: [PATCH] [protocol] Protocol v1: enrollment codes and book, messages, job guard, agent registry, release check, archive paths (32 tests) --- Cargo.lock | 1109 +++++++++++++++++++++++++++++++ crates/protocol/src/archive.rs | 85 +++ crates/protocol/src/code.rs | 219 ++++++ crates/protocol/src/enroll.rs | 168 +++++ crates/protocol/src/guard.rs | 133 ++++ crates/protocol/src/lib.rs | 62 ++ crates/protocol/src/msg.rs | 645 ++++++++++++++++++ crates/protocol/src/registry.rs | 119 ++++ crates/protocol/src/release.rs | 265 ++++++++ 9 files changed, 2805 insertions(+) create mode 100644 Cargo.lock create mode 100644 crates/protocol/src/archive.rs create mode 100644 crates/protocol/src/code.rs create mode 100644 crates/protocol/src/enroll.rs create mode 100644 crates/protocol/src/guard.rs create mode 100644 crates/protocol/src/lib.rs create mode 100644 crates/protocol/src/msg.rs create mode 100644 crates/protocol/src/registry.rs create mode 100644 crates/protocol/src/release.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..595520f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1109 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +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 = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ct-codecs" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "domi-pki" +version = "1.0.0" +dependencies = [ + "base64 0.22.1", + "rcgen", + "ring", + "rustls-pki-types", + "rustls-webpki", + "thiserror", + "time", + "x509-parser", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[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 = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "legatus" +version = "0.1.0" +dependencies = [ + "domi-pki", + "flate2", + "httparse", + "legatus-linux", + "legatus-protocol", + "minisign", + "ring", + "rustls", + "rustls-pki-types", + "rustls-webpki", + "serde", + "serde_json", + "tar", + "tempfile", + "thiserror", +] + +[[package]] +name = "legatus-linux" +version = "0.1.0" +dependencies = [ + "flate2", + "legatus-protocol", + "tar", + "tempfile", + "thiserror", +] + +[[package]] +name = "legatus-protocol" +version = "0.1.0" +dependencies = [ + "data-encoding", + "domi-pki", + "minisign", + "minisign-verify", + "ring", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "minisign" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26541387415a1e829df5d532aad019fb11bc723e2b5bc99edefa4cf5bfad0de7" +dependencies = [ + "ct-codecs", + "getrandom 0.2.17", + "rpassword", + "scrypt", +] + +[[package]] +name = "minisign-verify" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[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-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest", + "hmac", +] + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rpassword" +version = "7.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2", + "salsa20", + "sha2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[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-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 = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/protocol/src/archive.rs b/crates/protocol/src/archive.rs new file mode 100644 index 0000000..6a1a901 --- /dev/null +++ b/crates/protocol/src/archive.rs @@ -0,0 +1,85 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Archive entries (hostile even when signed: a release key can sign a mistake): what may be +//! unpacked, and where. + +/// Entries in one archive at most. +pub const MAX_ARCHIVE_ENTRIES: usize = 100_000; +/// Bytes unpacked from one archive at most (4 GiB). +pub const MAX_ARCHIVE_BYTES: u64 = 4 * 1024 * 1024 * 1024; + +/// The kind of an archive entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EntryKind { + /// A regular file. + File, + /// A directory. + Dir, + /// A symbolic link (refused). + Symlink, + /// A hard link (refused). + Hardlink, + /// Devices, FIFOs and anything else (refused). + Other, +} + +/// Why an archive is refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum ArchiveError { + /// Links, devices and other special entries are not unpacked. + #[error("the archive holds a link or a special file")] + Kind, + /// A path that is absolute, climbs out, or is not plain. + #[error("the archive holds a path outside the release")] + Path, + /// More bytes than allowed. + #[error("the archive is too large")] + TooLarge, + /// More entries than allowed. + #[error("the archive has too many entries")] + TooMany, + /// Not a readable archive. + #[error("the archive cannot be read")] + Corrupt, +} + +impl ArchiveError { + /// The stable code used in reports. + pub fn code(&self) -> &'static str { + "bad_archive" + } +} + +/// Check one entry and return its path as plain components (no `.`, never empty). +pub fn check_entry(kind: EntryKind, path: &str, size: u64) -> Result, ArchiveError> { + match kind { + EntryKind::File | EntryKind::Dir => {} + _ => return Err(ArchiveError::Kind), + } + if size > MAX_ARCHIVE_BYTES { + return Err(ArchiveError::TooLarge); + } + if path.is_empty() + || path.len() > 4096 + || path.starts_with('/') + || path + .bytes() + .any(|b| b == 0 || b == b'\\' || b == b':' || b.is_ascii_control()) + { + return Err(ArchiveError::Path); + } + let mut parts = Vec::new(); + for c in path.split('/') { + match c { + "" | "." => {} + ".." => return Err(ArchiveError::Path), + c => parts.push(c.to_owned()), + } + } + if parts.is_empty() { + return Err(ArchiveError::Path); + } + Ok(parts) +} diff --git a/crates/protocol/src/code.rs b/crates/protocol/src/code.rs new file mode 100644 index 0000000..fd59260 --- /dev/null +++ b/crates/protocol/src/code.rs @@ -0,0 +1,219 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The enrollment code: `lgt1-` and base32 of version, root SHA-256, secret, server URL, checksum. + +use std::fmt; + +use data_encoding::{Encoding, Specification}; + +use crate::hex; + +/// What every code starts with. +pub const CODE_PREFIX: &str = "lgt1-"; +const VERSION: u8 = 1; +const MAX_URL: usize = 200; +const MIN_LEN: usize = 1 + 32 + 16 + 1 + 1 + 4; + +/// Why a code cannot be read or made. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CodeError { + /// It does not start with `lgt1-`. + #[error("an enrollment code starts with lgt1-")] + Prefix, + /// Not base32. + #[error("the enrollment code has characters that do not belong in it")] + Encoding, + /// Too short or its parts do not add up. + #[error("the enrollment code is incomplete")] + Length, + /// A version this Legatus does not know. + #[error("the enrollment code is from a newer Fabrica; update Legatus")] + Version, + /// The checksum does not match: a typo or a cut copy. + #[error("the enrollment code has a typo; copy it again from Fabrica")] + Checksum, + /// The server URL is not a plain `https://host[:port]`. + #[error("the server address cannot be used: {0}")] + BadServer(String), +} + +/// An enrollment code: where the Fabrica server is, which Domi root it chains to, and the +/// one-time secret. `Debug` never shows the secret. +#[derive(Clone, PartialEq, Eq)] +pub struct EnrollmentCode { + server: String, + root_sha256: [u8; 32], + secret: [u8; 16], +} + +impl fmt::Debug for EnrollmentCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EnrollmentCode") + .field("server", &self.server) + .field("root_sha256", &hex(&self.root_sha256)) + .field("secret", &"…") + .finish() + } +} + +fn base32() -> Result { + let mut spec = Specification::new(); + spec.symbols.push_str("abcdefghijklmnopqrstuvwxyz234567"); + spec.encoding().map_err(|_| CodeError::Encoding) +} + +fn digest(b: &[u8]) -> [u8; 32] { + let d = ring::digest::digest(&ring::digest::SHA256, b); + let mut out = [0u8; 32]; + out.copy_from_slice(d.as_ref()); + out +} + +/// Is `url` exactly `https://host` or `https://host:port`? +pub(crate) fn check_server(url: &str) -> Result<(), CodeError> { + let bad = |why: &str| Err(CodeError::BadServer(why.to_owned())); + if url.len() > MAX_URL { + return bad("longer than 200 characters"); + } + let Some(auth) = url.strip_prefix("https://") else { + return bad("it must start with https://"); + }; + if auth.is_empty() { + return bad("no host"); + } + if auth + .bytes() + .any(|b| matches!(b, b'/' | b'?' | b'#' | b'@' | b'\\') || !b.is_ascii_graphic()) + { + return bad("only a host and a port, nothing else"); + } + let (host, port) = if let Some(rest) = auth.strip_prefix('[') { + let Some((h, after)) = rest.split_once(']') else { + return bad("an unclosed ["); + }; + if h.is_empty() + || !h + .bytes() + .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.') + { + return bad("not an IPv6 address"); + } + match after { + "" => (h, None), + p => match p.strip_prefix(':') { + Some(p) => (h, Some(p)), + None => return bad("garbage after the address"), + }, + } + } else { + match auth.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (auth, None), + } + }; + if host.is_empty() + || host.starts_with('.') + || host.starts_with('-') + || !host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':')) + { + return bad("not a host name"); + } + if let Some(p) = port { + let ok = !p.is_empty() + && p.len() <= 5 + && p.bytes().all(|b| b.is_ascii_digit()) + && p.parse::().is_ok_and(|n| (1..=65_535).contains(&n)); + if !ok { + return bad("the port must be 1 to 65535"); + } + } + Ok(()) +} + +impl EnrollmentCode { + /// A code for `server` (`https://host[:port]`), the root with SHA-256 `root_sha256`, and a + /// secret from a good random source. + pub fn new( + server: &str, + root_sha256: [u8; 32], + secret: [u8; 16], + ) -> Result { + check_server(server)?; + Ok(EnrollmentCode { + server: server.to_owned(), + root_sha256, + secret, + }) + } + + /// The server URL, `https://host[:port]`. + pub fn server(&self) -> &str { + &self.server + } + + /// SHA-256 of the Domi root certificate's DER. + pub fn root_sha256(&self) -> &[u8; 32] { + &self.root_sha256 + } + + /// The secret as 32 lowercase hex characters (what `enroll` sends). + pub fn secret_hex(&self) -> String { + hex(&self.secret) + } + + /// The text the person copies. + pub fn encode(&self) -> String { + let mut b = Vec::with_capacity(MIN_LEN + self.server.len()); + b.push(VERSION); + b.extend_from_slice(&self.root_sha256); + b.extend_from_slice(&self.secret); + // `new` keeps the URL at 200 bytes or fewer. + b.push(u8::try_from(self.server.len()).unwrap_or(u8::MAX)); + b.extend_from_slice(self.server.as_bytes()); + let check = digest(&b); + b.extend_from_slice(&check[..4]); + let body = base32().map(|e| e.encode(&b)).unwrap_or_default(); + format!("{CODE_PREFIX}{body}") + } + + /// Read a code someone pasted (surrounding whitespace and upper case are fine). + pub fn parse(text: &str) -> Result { + let t = text.trim(); + let body = t + .strip_prefix(CODE_PREFIX) + .ok_or(CodeError::Prefix)? + .to_ascii_lowercase(); + if body.len() > 1000 { + return Err(CodeError::Length); + } + let b = base32()? + .decode(body.as_bytes()) + .map_err(|_| CodeError::Encoding)?; + if b.len() < MIN_LEN { + return Err(CodeError::Length); + } + let (data, check) = b.split_at(b.len() - 4); + if digest(data)[..4] != *check { + return Err(CodeError::Checksum); + } + if data.first() != Some(&VERSION) { + return Err(CodeError::Version); + } + let mut root_sha256 = [0u8; 32]; + root_sha256.copy_from_slice(data.get(1..33).ok_or(CodeError::Length)?); + let mut secret = [0u8; 16]; + secret.copy_from_slice(data.get(33..49).ok_or(CodeError::Length)?); + let n = usize::from(*data.get(49).ok_or(CodeError::Length)?); + let url = data.get(50..).ok_or(CodeError::Length)?; + if url.len() != n { + return Err(CodeError::Length); + } + let server = + std::str::from_utf8(url).map_err(|_| CodeError::BadServer("not text".into()))?; + EnrollmentCode::new(server, root_sha256, secret) + } +} diff --git a/crates/protocol/src/enroll.rs b/crates/protocol/src/enroll.rs new file mode 100644 index 0000000..2fe282f --- /dev/null +++ b/crates/protocol/src/enroll.rs @@ -0,0 +1,168 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The server's side of enrollment codes: issue, and redeem exactly once. + +use std::collections::HashMap; + +use crate::msg::Roles; +use crate::{hex, unhex}; + +/// Codes live an hour by default. +pub const CODE_TTL_SECONDS: i64 = 3600; +/// And a day at most. +pub const CODE_MAX_TTL_SECONDS: i64 = 86_400; + +/// Why a code was not accepted. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum EnrollError { + /// No such code (or not 32 lowercase hex). + #[error("this enrollment code is not known; make a new one in Fabrica")] + Unknown, + /// Already used once. + #[error("this enrollment code was already used; make a new one in Fabrica")] + Used, + /// Past its expiry. + #[error("this enrollment code has expired; make a new one in Fabrica")] + Expired, +} + +impl EnrollError { + /// The stable error code on the wire. + pub fn code(&self) -> &'static str { + match self { + EnrollError::Unknown => "code_unknown", + EnrollError::Used => "code_used", + EnrollError::Expired => "code_expired", + } + } +} + +/// Why a code could not be issued. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum IssueError { + /// A team or agent id that is not a domi-pki id. + #[error("team and agent ids are 1 to 40 of a-z, 0-9 and '-'")] + BadId, + /// A lifetime outside 1 second to a day. + #[error("a code lives between 1 second and a day")] + BadLifetime, + /// The same secret again (a broken random source). + #[error("this secret is already in use")] + Duplicate, +} + +/// What redeeming a code gives the server: who is enrolling, with which roles. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Grant { + /// Team id. + pub team: String, + /// Agent id. + pub agent: String, + /// The roles the agent starts with. + pub roles: Roles, +} + +/// One code as the server stores it: the secret's SHA-256, never the secret. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodeRecord { + /// SHA-256 of the 16 secret bytes, lowercase hex. + pub digest: String, + /// Team id. + pub team: String, + /// Agent id. + pub agent: String, + /// Roles granted. + pub roles: Roles, + /// Unix seconds; the code is refused from this moment. + pub expires_at: i64, + /// When it was used, if it was. + pub used_at: Option, +} + +/// SHA-256 (hex) of the secret given as 32 lowercase hex characters, or `None` when it is not. +pub fn secret_digest(secret_hex: &str) -> Option { + if secret_hex.len() != 32 + || !secret_hex + .bytes() + .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) + { + return None; + } + let bytes = unhex(secret_hex)?; + Some(hex( + ring::digest::digest(&ring::digest::SHA256, &bytes).as_ref() + )) +} + +/// The reference logic for codes. Fabrica keeps the same records in its database and redeems in +/// one transaction; this in-memory book is what its tests and Legatus's compare against. +#[derive(Debug, Default)] +pub struct EnrollmentBook { + records: HashMap, +} + +impl EnrollmentBook { + /// An empty book. + pub fn new() -> EnrollmentBook { + EnrollmentBook::default() + } + + /// Record a new code for `secret` (16 random bytes the caller drew). + pub fn issue( + &mut self, + secret: [u8; 16], + team: &str, + agent: &str, + roles: Roles, + now: i64, + ttl_seconds: i64, + ) -> Result<(), IssueError> { + if !domi_pki::valid_id(team) || !domi_pki::valid_id(agent) { + return Err(IssueError::BadId); + } + if !(1..=CODE_MAX_TTL_SECONDS).contains(&ttl_seconds) { + return Err(IssueError::BadLifetime); + } + let digest = hex(ring::digest::digest(&ring::digest::SHA256, &secret).as_ref()); + if self.records.contains_key(&digest) { + return Err(IssueError::Duplicate); + } + self.records.insert( + digest.clone(), + CodeRecord { + digest, + team: team.to_owned(), + agent: agent.to_owned(), + roles, + expires_at: now.saturating_add(ttl_seconds), + used_at: None, + }, + ); + Ok(()) + } + + /// Use up the code with this secret: the first call that presents it, and only that one. + pub fn redeem(&mut self, secret_hex: &str, now: i64) -> Result { + let digest = secret_digest(secret_hex).ok_or(EnrollError::Unknown)?; + let r = self.records.get_mut(&digest).ok_or(EnrollError::Unknown)?; + if r.used_at.is_some() { + return Err(EnrollError::Used); + } + if now >= r.expires_at { + return Err(EnrollError::Expired); + } + r.used_at = Some(now); + Ok(Grant { + team: r.team.clone(), + agent: r.agent.clone(), + roles: r.roles, + }) + } + + /// Every record. + pub fn records(&self) -> impl Iterator { + self.records.values() + } +} diff --git a/crates/protocol/src/guard.rs b/crates/protocol/src/guard.rs new file mode 100644 index 0000000..2822bcb --- /dev/null +++ b/crates/protocol/src/guard.rs @@ -0,0 +1,133 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The agent's job guard: expired, future, too long-lived and replayed jobs are refused. + +use std::collections::BTreeMap; + +use crate::msg::JobHeader; + +/// A job lives at most an hour. +pub const MAX_JOB_SECONDS: i64 = 3600; +/// Clock skew allowed between agent and server. +pub const SKEW_SECONDS: i64 = 300; +/// Seen ids kept at most (a flood of jobs cannot exhaust memory). +const MAX_SEEN: usize = 100_000; + +/// Why a job is refused before anything else is looked at. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum GuardError { + /// The id is not 32 lowercase hex characters. + #[error("the job id is malformed")] + BadId, + /// Past its expiry. + #[error("the job has expired")] + Expired, + /// Issued in the future (beyond the allowed skew). + #[error("the job was issued in the future")] + Future, + /// Lives longer than an hour. + #[error("the job would live longer than an hour")] + TooLong, + /// Seen before. + #[error("the job was already received once")] + Replayed, + /// Too many live jobs at once. + #[error("too many jobs at once")] + Full, +} + +impl GuardError { + /// The stable code used in reports. + pub fn code(&self) -> &'static str { + match self { + GuardError::BadId => "bad_request", + GuardError::Expired => "expired", + GuardError::Future => "future", + GuardError::TooLong => "expired", + GuardError::Replayed => "replayed", + GuardError::Full => "busy", + } + } +} + +/// The ids of jobs seen and not yet expired. Saved to the agent's state so a restart does not +/// open a replay window. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct JobGuard { + seen: BTreeMap, +} + +pub(crate) fn valid_job_id(id: &str) -> bool { + id.len() == 32 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +impl JobGuard { + /// An empty guard. + pub fn new() -> JobGuard { + JobGuard::default() + } + + /// Accept the job at `now` (and remember its id), or say why not. + pub fn check(&mut self, h: &JobHeader, now: i64) -> Result<(), GuardError> { + self.prune(now); + if !valid_job_id(&h.id) { + return Err(GuardError::BadId); + } + if h.expires_at <= now { + return Err(GuardError::Expired); + } + if h.expires_at.saturating_sub(h.issued_at) > MAX_JOB_SECONDS { + return Err(GuardError::TooLong); + } + if h.issued_at > now.saturating_add(SKEW_SECONDS) { + return Err(GuardError::Future); + } + if self.seen.contains_key(&h.id) { + return Err(GuardError::Replayed); + } + if self.seen.len() >= MAX_SEEN { + return Err(GuardError::Full); + } + self.seen.insert(h.id.clone(), h.expires_at); + Ok(()) + } + + /// Forget ids whose jobs have expired by `now` (they would be refused as expired anyway). + pub fn prune(&mut self, now: i64) { + self.seen.retain(|_, exp| *exp > now); + } + + /// How many ids are remembered. + pub fn len(&self) -> usize { + self.seen.len() + } + + /// No ids remembered. + pub fn is_empty(&self) -> bool { + self.seen.is_empty() + } + + /// ` ` per line. + pub fn save(&self) -> String { + self.seen + .iter() + .map(|(id, exp)| format!("{id} {exp}\n")) + .collect() + } + + /// Read what [`save`](Self::save) wrote; anything else is an error. + pub fn load(text: &str) -> Result { + let mut seen = BTreeMap::new(); + for line in text.lines().filter(|l| !l.trim().is_empty()) { + let (id, exp) = line.trim().split_once(' ').ok_or(GuardError::BadId)?; + let exp: i64 = exp.parse().map_err(|_| GuardError::BadId)?; + if !valid_job_id(id) || seen.len() >= MAX_SEEN { + return Err(GuardError::BadId); + } + seen.insert(id.to_owned(), exp); + } + Ok(JobGuard { seen }) + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs new file mode 100644 index 0000000..9ac529f --- /dev/null +++ b/crates/protocol/src/lib.rs @@ -0,0 +1,62 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Legatus protocol v1 (docs/02_protocol.md): what Legatus and the Fabrica server say to +//! each other, and the checks both sides make. Pure: no files, no network, no clock; the caller +//! passes `now` (unix seconds) and the random bytes. +//! +//! - [`EnrollmentCode`]: the one-line code; [`EnrollmentBook`]: the server's single-use logic. +//! - [`msg`]: the messages; [`parse_job`] reads a job so that even a bad one can be reported. +//! - [`JobGuard`]: expired, future, too long-lived and replayed jobs are refused. +//! - [`Registry`]: the server's check that a certificate is the agent's current one. +//! - [`verify_release`], [`check_artifact`]: nothing unsigned runs. +//! - [`check_entry`]: what may be unpacked from an archive. + +#![warn(missing_docs)] + +mod archive; +mod code; +mod enroll; +mod guard; +pub mod msg; +mod registry; +mod release; + +pub use archive::{ArchiveError, EntryKind, MAX_ARCHIVE_BYTES, MAX_ARCHIVE_ENTRIES, check_entry}; +pub use code::{CODE_PREFIX, CodeError, EnrollmentCode}; +pub use enroll::{ + CODE_MAX_TTL_SECONDS, CODE_TTL_SECONDS, CodeRecord, EnrollError, EnrollmentBook, Grant, + IssueError, secret_digest, +}; +pub use guard::{GuardError, JobGuard, MAX_JOB_SECONDS, SKEW_SECONDS}; +pub use msg::{ + Job, JobBody, JobHeader, MAX_BODY, MsgError, Report, Roles, Status, Step, decode, encode, + parse_job, +}; +pub use registry::{Refusal, Registry}; +pub use release::{ + Approved, ArtifactEntry, Expected, MAX_ARTIFACT_BYTES, Manifest, ReleaseError, check_artifact, + valid_artifact_name, valid_version, verify_release, +}; + +/// Lowercase hex. +pub fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// Lowercase or uppercase hex to bytes. +pub(crate) fn unhex(s: &str) -> Option> { + if s.len() % 2 != 0 { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) + .collect() +} + +/// SHA-256 of `b`, lowercase hex. +pub fn sha256_hex(b: &[u8]) -> String { + hex(ring::digest::digest(&ring::digest::SHA256, b).as_ref()) +} diff --git a/crates/protocol/src/msg.rs b/crates/protocol/src/msg.rs new file mode 100644 index 0000000..9ddafb4 --- /dev/null +++ b/crates/protocol/src/msg.rs @@ -0,0 +1,645 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The messages of protocol v1 (docs/02_protocol.md). Strict: unknown fields are refused, every +//! body is bounded, every id and name is checked before anyone acts on it. + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::release::{valid_artifact_name, valid_version}; + +/// The protocol version. +pub const V: u32 = 1; +/// A JSON body is at most this many bytes. +pub const MAX_BODY: usize = 256 * 1024; +/// A report message is at most this many characters. +pub const MAX_MESSAGE: usize = 2000; + +/// Why a message is refused. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum MsgError { + /// Larger than [`MAX_BODY`]. + #[error("the message is too large")] + TooLarge, + /// `v` is not 1. + #[error("the message is from another protocol version")] + Version, + /// Not the expected JSON. + #[error("the message cannot be read: {0}")] + Malformed(String), +} + +#[derive(Deserialize)] +struct Peek { + v: Option, +} + +fn peek(bytes: &[u8]) -> Result<(), MsgError> { + if bytes.len() > MAX_BODY { + return Err(MsgError::TooLarge); + } + let p: Peek = serde_json::from_slice(bytes).map_err(|e| MsgError::Malformed(e.to_string()))?; + if p.v != Some(V) { + return Err(MsgError::Version); + } + Ok(()) +} + +/// Read a v1 message strictly. +pub fn decode(bytes: &[u8]) -> Result { + peek(bytes)?; + serde_json::from_slice(bytes).map_err(|e| MsgError::Malformed(e.to_string())) +} + +/// Write a message as JSON. +pub fn encode(msg: &T) -> Vec { + serde_json::to_vec(msg).unwrap_or_default() +} + +/// The roles Fabrica toggles. Both off until it turns them on. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Roles { + /// *Build here*: the agent runs builds. + pub build: bool, + /// *Deploy here*: the agent deploys releases. + pub deploy: bool, +} + +/// Facts about the machine, sent at enrollment. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HostFacts { + /// Host name. + pub hostname: String, + /// `linux`, `windows`, `macos`. + pub os: String, + /// `x86_64`, `aarch64`. + pub arch: String, + /// The Legatus version. + pub version: String, +} + +/// `POST enroll`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EnrollRequest { + /// Always 1. + pub v: u32, + /// The code's secret, 32 lowercase hex. + pub secret: String, + /// The agent's CSR (PEM). + pub csr: String, + /// The machine. + pub host: HostFacts, +} + +/// The answer to `enroll`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EnrollResponse { + /// Always 1. + pub v: u32, + /// Team id. + pub team: String, + /// Agent id. + pub agent: String, + /// Agent certificate, then the agents intermediate (PEM). + pub chain: String, + /// The Domi root (PEM); must match the code's SHA-256. + pub root: String, + /// Initial roles. + pub roles: Roles, + /// The team's release keys (minisign public key lines), 1 to 8. + pub release_keys: Vec, + /// How long to long-poll for jobs, seconds. + pub poll_seconds: u32, +} + +/// What this agent can do. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Capabilities { + /// Target kinds it deploys to. + pub deploy: Vec, + /// Build kinds it runs. + pub build: Vec, +} + +/// An app and the version running. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Deployed { + /// App id. + pub app: String, + /// Version. + pub version: String, +} + +/// `POST hello`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Hello { + /// Always 1. + pub v: u32, + /// Legatus version. + pub version: String, + /// OS. + pub os: String, + /// CPU. + pub arch: String, + /// Host name. + pub hostname: String, + /// What it can do. + pub capabilities: Capabilities, + /// What runs here. + pub deployed: Vec, +} + +/// The answer to `hello`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Welcome { + /// Always 1. + pub v: u32, + /// Team id. + pub team: String, + /// Agent id. + pub agent: String, + /// Current roles. + pub roles: Roles, + /// The server's clock. + pub server_time: i64, + /// Renew the certificate now. + pub renew: bool, +} + +/// `POST renew`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RenewRequest { + /// Always 1. + pub v: u32, + /// A CSR for the agent's new key. + pub csr: String, +} + +/// The answer to `renew`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Renewed { + /// Always 1. + pub v: u32, + /// The new chain (PEM). + pub chain: String, +} + +/// An error body. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ErrorBody { + /// Stable code. + pub error: String, + /// Plain English. + pub message: String, +} + +// ------------------------------------------------------------------ jobs + +/// The signed release a deploy job carries. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignedRelease { + /// The manifest JSON, exactly the signed bytes. + pub manifest: String, + /// The minisign signature file. + pub signature: String, +} + +/// The Linux (systemd) target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LinuxTarget { + /// The systemd unit to restart, `.service`. + pub unit: String, + /// A local URL that answers 2xx when the app is healthy. + #[serde(default)] + pub health_url: Option, + /// How long the health check may take. + #[serde(default = "default_timeout")] + pub health_timeout_seconds: u32, + /// Releases kept on disk. + #[serde(default = "default_keep")] + pub keep: u32, +} + +fn default_timeout() -> u32 { + 30 +} +fn default_keep() -> u32 { + 3 +} + +/// Where a release goes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Target { + /// Linux with systemd. + Linux(LinuxTarget), +} + +impl Serialize for Target { + fn serialize(&self, s: S) -> Result { + use serde::ser::SerializeMap; + let mut m = s.serialize_map(Some(2))?; + match self { + Target::Linux(l) => { + m.serialize_entry("kind", "linux")?; + m.serialize_entry("linux", l)?; + } + } + m.end() + } +} + +/// A deploy job. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DeployJob { + /// App id. + pub app: String, + /// Version. + pub version: String, + /// The artifact's name in the manifest. + pub artifact: String, + /// Manifest and signature. + pub release: SignedRelease, + /// Where. + pub target: Target, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawDeploy { + app: String, + version: String, + artifact: String, + release: SignedRelease, + target: serde_json::Value, +} + +/// A config job: roles toggled in Fabrica. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ConfigJob { + /// The new roles. + pub roles: Roles, +} + +/// The envelope fields every job has. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JobHeader { + /// 32 lowercase hex. + pub id: String, + /// Unix seconds. + pub issued_at: i64, + /// Unix seconds. + pub expires_at: i64, + /// The kind as sent. + pub kind: String, +} + +/// What a job asks for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JobBody { + /// Deploy a release. + Deploy(DeployJob), + /// Change roles. + Config(ConfigJob), + /// A kind (or target kind) this Legatus does not know: refused as `unsupported`. + Unsupported(String), + /// A known kind whose spec is wrong: refused as `bad_request`. + Invalid(String), +} + +impl JobBody { + /// May an agent with `roles` run it? Config jobs always (they are how roles change); + /// unsupported and invalid ones are refused for their own reason. + pub fn allowed_by(&self, roles: &Roles) -> bool { + match self { + JobBody::Deploy(_) => roles.deploy, + JobBody::Config(_) | JobBody::Unsupported(_) | JobBody::Invalid(_) => true, + } + } +} + +/// A job: header and body. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Job { + /// Id, times, kind. + pub header: JobHeader, + /// What it asks. + pub body: JobBody, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Envelope { + v: u32, + id: String, + issued_at: i64, + expires_at: i64, + kind: String, + spec: serde_json::Value, +} + +/// Read a job. An error means not even the id can be trusted (nothing to report to); a bad spec +/// of a known kind, or an unknown kind, is a job with an [`JobBody::Invalid`] or +/// [`JobBody::Unsupported`] body that the agent reports as refused. +pub fn parse_job(bytes: &[u8]) -> Result { + let e: Envelope = decode(bytes)?; + let header = JobHeader { + id: e.id, + issued_at: e.issued_at, + expires_at: e.expires_at, + kind: e.kind, + }; + let body = match header.kind.as_str() { + "deploy" => deploy_body(e.spec), + "config" => match serde_json::from_value::(e.spec) { + Ok(c) => JobBody::Config(c), + Err(err) => JobBody::Invalid(err.to_string()), + }, + other => JobBody::Unsupported(clip(other, 40)), + }; + Ok(Job { header, body }) +} + +fn deploy_body(spec: serde_json::Value) -> JobBody { + let raw: RawDeploy = match serde_json::from_value(spec) { + Ok(r) => r, + Err(e) => return JobBody::Invalid(e.to_string()), + }; + let kind = raw + .target + .get("kind") + .and_then(|k| k.as_str()) + .unwrap_or("") + .to_owned(); + let target = match kind.as_str() { + "linux" => { + let Some(obj) = raw.target.as_object() else { + return JobBody::Invalid("the target is not an object".into()); + }; + if obj.len() != 2 { + return JobBody::Invalid("the target has unknown fields".into()); + } + match obj + .get("linux") + .cloned() + .map(serde_json::from_value::) + { + Some(Ok(l)) => Target::Linux(l), + Some(Err(e)) => return JobBody::Invalid(e.to_string()), + None => return JobBody::Invalid("the linux target is missing".into()), + } + } + other => return JobBody::Unsupported(format!("target {}", clip(other, 40))), + }; + let job = DeployJob { + app: raw.app, + version: raw.version, + artifact: raw.artifact, + release: raw.release, + target, + }; + match check_deploy(&job) { + Ok(()) => JobBody::Deploy(job), + Err(why) => JobBody::Invalid(why.into()), + } +} + +fn check_deploy(j: &DeployJob) -> Result<(), &'static str> { + if !domi_pki::valid_id(&j.app) { + return Err("the app id is not valid"); + } + if !valid_version(&j.version) { + return Err("the version is not valid"); + } + if !valid_artifact_name(&j.artifact) { + return Err("the artifact name is not valid"); + } + if j.release.manifest.len() > 64 * 1024 || j.release.signature.len() > 4096 { + return Err("the release is too large"); + } + match &j.target { + Target::Linux(l) => { + if !valid_unit(&l.unit) { + return Err("the unit name is not valid"); + } + if let Some(u) = &l.health_url + && !local_http_url(u) + { + return Err("the health URL must be http:// on 127.0.0.1, localhost or [::1]"); + } + if !(1..=600).contains(&l.health_timeout_seconds) { + return Err("the health timeout must be 1 to 600 seconds"); + } + if !(1..=20).contains(&l.keep) { + return Err("keep must be 1 to 20"); + } + } + } + Ok(()) +} + +/// A systemd service unit name: `.service`, plain characters, not starting with `-` or `.`. +pub fn valid_unit(unit: &str) -> bool { + let Some(name) = unit.strip_suffix(".service") else { + return false; + }; + !name.is_empty() + && unit.len() <= 200 + && !name.starts_with('-') + && !name.starts_with('.') + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'@' | b'.' | b'_' | b'-' | b':')) +} + +/// `http://` on 127.0.0.1, localhost or [::1], with an optional port and a plain path. +pub fn local_http_url(url: &str) -> bool { + let Some(rest) = url.strip_prefix("http://") else { + return false; + }; + if url.len() > 300 || !rest.bytes().all(|b| b.is_ascii_graphic()) { + return false; + } + let (auth, path) = match rest.find('/') { + Some(i) => rest.split_at(i), + None => (rest, ""), + }; + if path.contains('#') || path.contains('\\') { + return false; + } + let (host, port) = if let Some(r) = auth.strip_prefix("[::1]") { + match r { + "" => ("[::1]", None), + r => match r.strip_prefix(':') { + Some(p) => ("[::1]", Some(p)), + None => return false, + }, + } + } else { + match auth.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (auth, None), + } + }; + if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") { + return false; + } + match port { + None => true, + Some(p) => { + !p.is_empty() + && p.len() <= 5 + && p.bytes().all(|b| b.is_ascii_digit()) + && p.parse::().is_ok_and(|n| (1..=65_535).contains(&n)) + } + } +} + +/// Write a job (the server's side; tests). +pub fn job_json(id: &str, issued_at: i64, expires_at: i64, body: &JobBody) -> Vec { + let (kind, spec) = match body { + JobBody::Deploy(d) => ("deploy".to_owned(), serde_json::to_value(d)), + JobBody::Config(c) => ("config".to_owned(), serde_json::to_value(c)), + JobBody::Unsupported(k) => (k.clone(), Ok(serde_json::Value::Object(Default::default()))), + JobBody::Invalid(_) => ("deploy".to_owned(), Ok(serde_json::Value::Null)), + }; + encode(&Envelope { + v: V, + id: id.to_owned(), + issued_at, + expires_at, + kind, + spec: spec.unwrap_or(serde_json::Value::Null), + }) +} + +// ------------------------------------------------------------------ reports + +/// The state a report gives. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Status { + /// Received and will run. + Accepted, + /// Refused: nothing was touched. + Refused, + /// In progress. + Running, + /// Done. + Succeeded, + /// Failed after something was touched (see `rolled_back`). + Failed, +} + +/// Where in a job a report is from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Step { + /// The job guard. + Guard, + /// The role check. + Role, + /// The signature and manifest check. + Verify, + /// The artifact download. + Download, + /// Unpacking. + Unpack, + /// The symlink switch. + Switch, + /// The service restart. + Restart, + /// The health check. + Health, + /// The rollback. + Rollback, +} + +/// `POST reports`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Report { + /// Always 1. + pub v: u32, + /// The job id. + pub job: String, + /// Unix seconds. + pub at: i64, + /// State. + pub status: Status, + /// Where. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub step: Option, + /// Plain English, prefixed by a stable code on refusals. + pub message: String, + /// After a failed switch: is the previous release running again? + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rolled_back: Option, + /// What now runs. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deployed: Option, +} + +fn clip(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +impl Report { + fn new(job: &str, at: i64, status: Status, step: Option, message: String) -> Report { + Report { + v: V, + job: clip(job, 64), + at, + status, + step, + message: clip(&message, MAX_MESSAGE), + rolled_back: None, + deployed: None, + } + } + + /// Refused at `step` with a stable `code`; nothing was touched. + pub fn refused(job: &str, at: i64, step: Step, code: &str, message: &str) -> Report { + Report::new( + job, + at, + Status::Refused, + Some(step), + format!("{code}: {message}"), + ) + } + + /// Failed at `step`; `rolled_back` says whether the previous release runs again. + pub fn failed(job: &str, at: i64, step: Step, message: &str, rolled_back: bool) -> Report { + let mut r = Report::new(job, at, Status::Failed, Some(step), message.to_owned()); + r.rolled_back = Some(rolled_back); + r + } + + /// A progress report. + pub fn running(job: &str, at: i64, step: Step, message: &str) -> Report { + Report::new(job, at, Status::Running, Some(step), message.to_owned()) + } + + /// Done; `deployed` is what now runs. + pub fn succeeded(job: &str, at: i64, message: &str, deployed: Option) -> Report { + let mut r = Report::new(job, at, Status::Succeeded, None, message.to_owned()); + r.deployed = deployed; + r + } +} diff --git a/crates/protocol/src/registry.rs b/crates/protocol/src/registry.rs new file mode 100644 index 0000000..0c7a726 --- /dev/null +++ b/crates/protocol/src/registry.rs @@ -0,0 +1,119 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The server's agent registry: which certificate is each agent's current one. + +use std::collections::HashMap; + +use domi_pki::{AgentIdentity, VerifyError}; + +/// Why an agent's certificate is refused. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Refusal { + /// The certificate itself: expired, not yet valid, foreign, not an agent's. + #[error("{0}")] + Certificate(VerifyError), + /// No such agent in this team (removed, or never enrolled here). + #[error("this agent is not enrolled")] + Unknown, + /// The agent was revoked in Fabrica. + #[error("this agent was revoked")] + Revoked, + /// A valid certificate that is no longer the agent's (renewed or re-enrolled): a replay. + #[error("this certificate is no longer the agent's current one")] + Superseded, +} + +impl Refusal { + /// The stable error code on the wire. + pub fn code(&self) -> &'static str { + "certificate_refused" + } +} + +#[derive(Debug, Clone)] +struct Record { + current: String, + pending: Option, + revoked: bool, +} + +/// The reference logic Fabrica runs on every request after the TLS handshake. +#[derive(Debug, Default)] +pub struct Registry { + agents: HashMap<(String, String), Record>, +} + +impl Registry { + /// An empty registry. + pub fn new() -> Registry { + Registry::default() + } + + /// `team`/`agent` enrolled (or re-enrolled) with certificate `serial_hex`: from now on only + /// that certificate is the agent's. + pub fn enrolled(&mut self, team: &str, agent: &str, serial_hex: &str) { + self.agents.insert( + (team.to_owned(), agent.to_owned()), + Record { + current: serial_hex.to_owned(), + pending: None, + revoked: false, + }, + ); + } + + /// A renewal issued `serial_hex`: it becomes current the first time it is used; until then + /// the old one still works (the agent may not have stored the new one yet). + pub fn renewed(&mut self, team: &str, agent: &str, serial_hex: &str) -> Result<(), Refusal> { + let r = self + .agents + .get_mut(&(team.to_owned(), agent.to_owned())) + .ok_or(Refusal::Unknown)?; + if r.revoked { + return Err(Refusal::Revoked); + } + r.pending = Some(serial_hex.to_owned()); + Ok(()) + } + + /// Revoke an agent: every certificate it has is refused. + pub fn revoke(&mut self, team: &str, agent: &str) { + if let Some(r) = self.agents.get_mut(&(team.to_owned(), agent.to_owned())) { + r.revoked = true; + } + } + + /// Forget an agent. + pub fn remove(&mut self, team: &str, agent: &str) { + self.agents.remove(&(team.to_owned(), agent.to_owned())); + } + + /// Check the chain an agent presented (leaf, agents intermediate; DER) against the Domi root + /// at `now`, and against this registry. + pub fn accept( + &mut self, + chain: &[Vec], + root_der: &[u8], + now: i64, + ) -> Result { + let id = domi_pki::verify_agent(chain, root_der, now).map_err(Refusal::Certificate)?; + let r = self + .agents + .get_mut(&(id.team.clone(), id.agent.clone())) + .ok_or(Refusal::Unknown)?; + if r.revoked { + return Err(Refusal::Revoked); + } + if r.current == id.serial_hex { + return Ok(id); + } + if r.pending.as_deref() == Some(id.serial_hex.as_str()) { + r.current = id.serial_hex.clone(); + r.pending = None; + return Ok(id); + } + Err(Refusal::Superseded) + } +} diff --git a/crates/protocol/src/release.rs b/crates/protocol/src/release.rs new file mode 100644 index 0000000..be6e4ef --- /dev/null +++ b/crates/protocol/src/release.rs @@ -0,0 +1,265 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Nothing unsigned runs: the release manifest, its minisign signature by a pinned team release +//! key, and the artifact's size and SHA-256. + +use std::collections::HashSet; + +use serde::{Deserialize, Serialize}; + +/// A manifest is at most 64 KiB. +pub const MAX_MANIFEST: usize = 64 * 1024; +/// Artifacts in one release at most. +pub const MAX_ARTIFACTS: usize = 64; +/// One artifact is at most 4 GiB. +pub const MAX_ARTIFACT_BYTES: u64 = 4 * 1024 * 1024 * 1024; + +/// Why a release is refused. Nothing has been touched when one of these is returned. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ReleaseError { + /// The agent has no pinned release key. + #[error("no release key is pinned; enroll again")] + NoKeys, + /// No signature at all. + #[error("the release is not signed")] + Unsigned, + /// Signed with a key that is not one of the team's. + #[error("the release is signed with a key that is not the team's release key")] + UnknownKey, + /// The signature is garbled or does not match the manifest. + #[error("the release signature does not verify")] + BadSignature, + /// Signed, but the manifest is not a valid v1 manifest. + #[error("the release manifest cannot be used: {0}")] + BadManifest(String), + /// Signed and valid, but not the release the job names (team, app, version, artifact). + #[error("the signed release is not the one the job asks for: {0}")] + WrongRelease(String), + /// The artifact's size or SHA-256 is not what the manifest says. + #[error("the artifact does not match the signed manifest: {0}")] + Tampered(String), +} + +impl ReleaseError { + /// The stable code used in reports. + pub fn code(&self) -> &'static str { + match self { + ReleaseError::NoKeys | ReleaseError::UnknownKey => "unknown_key", + ReleaseError::Unsigned => "unsigned", + ReleaseError::BadSignature => "bad_signature", + ReleaseError::BadManifest(_) => "bad_manifest", + ReleaseError::WrongRelease(_) => "wrong_release", + ReleaseError::Tampered(_) => "tampered", + } + } +} + +/// One artifact of a release. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArtifactEntry { + /// File name. + pub name: String, + /// SHA-256, lowercase hex. + pub sha256: String, + /// Bytes. + pub size: u64, +} + +/// The signed release manifest (docs/02_protocol.md). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + /// Always 1. + pub v: u32, + /// Team id. + pub team: String, + /// App id. + pub app: String, + /// Version. + pub version: String, + /// Unix seconds. + pub created_at: i64, + /// The artifacts. + pub artifacts: Vec, +} + +/// What the job says the release is. +#[derive(Debug, Clone, Copy)] +pub struct Expected<'a> { + /// The agent's team. + pub team: &'a str, + /// The job's app. + pub app: &'a str, + /// The job's version. + pub version: &'a str, + /// The job's artifact name. + pub artifact: &'a str, +} + +/// A release whose signature and manifest passed: the artifact to fetch and what it must be. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Approved { + /// The artifact's name. + pub name: String, + /// Its SHA-256 (lowercase hex). + pub sha256: String, + /// Its size. + pub size: u64, + /// The whole manifest. + pub manifest: Manifest, +} + +/// A version: 1 to 64 of `A-Z a-z 0-9 . _ + -`, not starting with `.` or `-`. +pub fn valid_version(v: &str) -> bool { + (1..=64).contains(&v.len()) + && !v.starts_with('.') + && !v.starts_with('-') + && v.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-')) +} + +/// An artifact name: 1 to 128 of `A-Z a-z 0-9 . _ + -`, not starting with `.` or `-`. +pub fn valid_artifact_name(n: &str) -> bool { + (1..=128).contains(&n.len()) + && !n.starts_with('.') + && !n.starts_with('-') + && n.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-')) +} + +fn is_sha256_hex(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// The 8-byte key id of a minisign public key line (base64 of `Ed` + id + key). +fn key_id(public_b64: &str) -> Option<[u8; 8]> { + let raw = b64(public_b64.trim())?; + if raw.len() != 42 || &raw[..2] != b"Ed" { + return None; + } + let mut id = [0u8; 8]; + id.copy_from_slice(&raw[2..10]); + Some(id) +} + +/// The key id a minisign signature file names (its second line). +fn signature_key_id(sig: &str) -> Option<[u8; 8]> { + let line = sig.lines().nth(1)?; + let raw = b64(line.trim())?; + if raw.len() != 74 { + return None; + } + let mut id = [0u8; 8]; + id.copy_from_slice(&raw[2..10]); + Some(id) +} + +/// Check the release a job carries before anything is downloaded or touched: the minisign +/// `signature` over the exact `manifest` bytes must be by one of `release_keys` (pinned at +/// enrollment), the manifest must be a strict v1 manifest, and it must be the release `expect` +/// names. +pub fn verify_release( + manifest: &[u8], + signature: &str, + release_keys: &[String], + expect: &Expected<'_>, +) -> Result { + if release_keys.is_empty() { + return Err(ReleaseError::NoKeys); + } + if signature.trim().is_empty() { + return Err(ReleaseError::Unsigned); + } + let sig = + minisign_verify::Signature::decode(signature).map_err(|_| ReleaseError::BadSignature)?; + let sig_id = signature_key_id(signature).ok_or(ReleaseError::BadSignature)?; + let candidates: Vec = release_keys + .iter() + .filter(|k| key_id(k) == Some(sig_id)) + .filter_map(|k| minisign_verify::PublicKey::from_base64(k.trim()).ok()) + .collect(); + if candidates.is_empty() { + return Err(ReleaseError::UnknownKey); + } + // Prehashed signatures only (what Custos makes); legacy ones are refused. + if !candidates + .iter() + .any(|k| k.verify(manifest, &sig, false).is_ok()) + { + return Err(ReleaseError::BadSignature); + } + let m = read_manifest(manifest)?; + let wrong = |what: String| Err(ReleaseError::WrongRelease(what)); + if m.team != expect.team { + return wrong(format!("it is team {}'s", m.team)); + } + if m.app != expect.app { + return wrong(format!("it is {}", m.app)); + } + if m.version != expect.version { + return wrong(format!("it is version {}", m.version)); + } + let Some(a) = m.artifacts.iter().find(|a| a.name == expect.artifact) else { + return wrong(format!("it has no artifact {}", expect.artifact)); + }; + Ok(Approved { + name: a.name.clone(), + sha256: a.sha256.clone(), + size: a.size, + manifest: m.clone(), + }) +} + +fn read_manifest(bytes: &[u8]) -> Result { + let bad = |why: &str| Err(ReleaseError::BadManifest(why.to_owned())); + if bytes.len() > MAX_MANIFEST { + return bad("larger than 64 KiB"); + } + let m: Manifest = + serde_json::from_slice(bytes).map_err(|e| ReleaseError::BadManifest(e.to_string()))?; + if m.v != 1 { + return bad("not a v1 manifest"); + } + if !domi_pki::valid_id(&m.team) || !domi_pki::valid_id(&m.app) { + return bad("the team or app id is not valid"); + } + if !valid_version(&m.version) { + return bad("the version is not valid"); + } + if m.artifacts.is_empty() || m.artifacts.len() > MAX_ARTIFACTS { + return bad("1 to 64 artifacts"); + } + let mut names = HashSet::new(); + for a in &m.artifacts { + if !valid_artifact_name(&a.name) || !is_sha256_hex(&a.sha256) || a.size > MAX_ARTIFACT_BYTES + { + return bad("an artifact entry is not valid"); + } + if !names.insert(a.name.as_str()) { + return bad("an artifact is named twice"); + } + } + Ok(m) +} + +/// After the download: the artifact must have exactly the size and SHA-256 the signed manifest +/// gives. +pub fn check_artifact(approved: &Approved, sha256_hex: &str, len: u64) -> Result<(), ReleaseError> { + if len != approved.size { + return Err(ReleaseError::Tampered(format!( + "{} bytes, the manifest says {}", + len, approved.size + ))); + } + if !sha256_hex.eq_ignore_ascii_case(&approved.sha256) { + return Err(ReleaseError::Tampered("its SHA-256 differs".into())); + } + Ok(()) +} + +fn b64(s: &str) -> Option> { + data_encoding::BASE64.decode(s.as_bytes()).ok() +}