diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bf12e51 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,44 @@ +[workspace] +resolver = "3" +members = ["crates/protocol", "crates/linux", "crates/agent"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/Legatus" +publish = false + +[workspace.dependencies] +legatus-protocol = { path = "crates/protocol" } +legatus-linux = { path = "crates/linux" } +domi-pki = { path = "../domi-pki" } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.145" +thiserror = "2.0.17" +ring = "0.17.14" +data-encoding = "2.6" +minisign-verify = "0.3" +minisign = "0.7.9" +rustls = { version = "0.23.31", default-features = false, features = ["ring", "std", "tls12", "logging"] } +rustls-pki-types = "1.12" +webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "alloc"] } +httparse = "1.9" +tar = { version = "0.4.44", default-features = false } +flate2 = "1.1" +tempfile = "3.20" + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.lints.clippy] +# Hostile input never meets unwrap(): non-test code must handle every Result. +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml new file mode 100644 index 0000000..a0e7f3a --- /dev/null +++ b/crates/agent/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "legatus" +description = "Legatus: the Fabrica Domi agent. Outbound mTLS, nothing unsigned runs." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[[bin]] +name = "legatus" +path = "src/main.rs" + +[dependencies] +legatus-protocol.workspace = true +legatus-linux.workspace = true +domi-pki.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +ring.workspace = true +rustls.workspace = true +rustls-pki-types.workspace = true +webpki.workspace = true +httparse.workspace = true + +[dev-dependencies] +minisign.workspace = true +tempfile.workspace = true +tar.workspace = true +flate2.workspace = true + +[lints] +workspace = true diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs new file mode 100644 index 0000000..9a316a6 --- /dev/null +++ b/crates/agent/src/lib.rs @@ -0,0 +1 @@ +//! Legatus agent (code follows its tests). diff --git a/crates/agent/src/main.rs b/crates/agent/src/main.rs new file mode 100644 index 0000000..f328e4d --- /dev/null +++ b/crates/agent/src/main.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/crates/linux/Cargo.toml b/crates/linux/Cargo.toml new file mode 100644 index 0000000..0a678d5 --- /dev/null +++ b/crates/linux/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "legatus-linux" +description = "Legatus's Linux (systemd) target: versioned release dirs, atomic symlink switch, restart, health check, auto rollback." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +legatus-protocol.workspace = true +thiserror.workspace = true +tar.workspace = true +flate2.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/linux/src/lib.rs b/crates/linux/src/lib.rs new file mode 100644 index 0000000..ebf61a3 --- /dev/null +++ b/crates/linux/src/lib.rs @@ -0,0 +1 @@ +//! Legatus Linux target (code follows its tests). diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml new file mode 100644 index 0000000..88912db --- /dev/null +++ b/crates/protocol/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "legatus-protocol" +description = "The Legatus protocol v1: enrollment codes, messages, the job guard, the agent registry, the release check. Pure: no I/O." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +domi-pki.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +ring.workspace = true +data-encoding.workspace = true +minisign-verify.workspace = true + +[dev-dependencies] +minisign.workspace = true + +[lints] +workspace = true diff --git a/crates/protocol/tests/certificates.rs b/crates/protocol/tests/certificates.rs new file mode 100644 index 0000000..168d4a3 --- /dev/null +++ b/crates/protocol/tests/certificates.rs @@ -0,0 +1,135 @@ +// 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/. + +//! Agent certificates at the server (mandatory, tests first): expired, replayed and foreign +//! certificates are refused by `Registry::accept`, the check Fabrica runs on every request. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use domi_pki::{self as pki, VerifyError}; +use legatus_protocol::{Refusal, Registry}; + +fn registry_with(team: &str, agent: &str, serial: &str) -> Registry { + let mut r = Registry::new(); + r.enrolled(team, agent, serial); + r +} + +#[test] +fn the_current_certificate_is_accepted() { + let c = ca(); + let (chain, serial) = c.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &serial); + let id = r.accept(&chain, &c.root_der(), NOW + DAY).unwrap(); + assert_eq!((id.team.as_str(), id.agent.as_str()), ("acme", "web-1")); +} + +#[test] +fn an_expired_certificate_is_refused() { + let c = ca(); + let (chain, serial) = c.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &serial); + let later = NOW + (pki::AGENT_DAYS as i64 + 1) * DAY; + assert_eq!( + r.accept(&chain, &c.root_der(), later), + Err(Refusal::Certificate(VerifyError::Expired)) + ); + assert_eq!( + r.accept(&chain, &c.root_der(), NOW - DAY), + Err(Refusal::Certificate(VerifyError::NotYetValid)) + ); + assert_eq!( + r.accept(&chain, &c.root_der(), later).unwrap_err().code(), + "certificate_refused" + ); +} + +#[test] +fn a_replayed_certificate_is_refused() { + let c = ca(); + let (old, old_serial) = c.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &old_serial); + // Re-enrolled: the old certificate is still valid in itself, but no longer the agent's. + let (new, new_serial) = c.agent("acme", "web-1", NOW); + r.enrolled("acme", "web-1", &new_serial); + assert_eq!( + r.accept(&old, &c.root_der(), NOW + DAY), + Err(Refusal::Superseded) + ); + r.accept(&new, &c.root_der(), NOW + DAY).unwrap(); +} + +#[test] +fn renewal_keeps_the_old_certificate_until_the_new_one_is_used() { + let c = ca(); + let (old, old_serial) = c.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &old_serial); + let (new, new_serial) = c.agent("acme", "web-1", NOW + 20 * DAY); + r.renewed("acme", "web-1", &new_serial).unwrap(); + // The agent may not have stored the new one yet: the old still works... + r.accept(&old, &c.root_der(), NOW + 20 * DAY).unwrap(); + // ...until the new one is first used; from then on the old one is a replay. + r.accept(&new, &c.root_der(), NOW + 20 * DAY).unwrap(); + assert_eq!( + r.accept(&old, &c.root_der(), NOW + 20 * DAY), + Err(Refusal::Superseded) + ); + // Renewing an agent nobody enrolled is refused. + assert!(r.renewed("acme", "ghost", &new_serial).is_err()); +} + +#[test] +fn a_removed_or_revoked_agent_is_refused() { + let c = ca(); + let (chain, serial) = c.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &serial); + r.revoke("acme", "web-1"); + assert_eq!( + r.accept(&chain, &c.root_der(), NOW + DAY), + Err(Refusal::Revoked) + ); + let mut r = registry_with("acme", "web-1", &serial); + r.remove("acme", "web-1"); + assert_eq!( + r.accept(&chain, &c.root_der(), NOW + DAY), + Err(Refusal::Unknown) + ); +} + +#[test] +fn foreign_certificates_are_refused() { + let c = ca(); + let other = ca(); + // Another root's agent, with the same ids and a registry entry for its serial. + let (theirs, their_serial) = other.agent("acme", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &their_serial); + assert!(matches!( + r.accept(&theirs, &c.root_der(), NOW + DAY), + Err(Refusal::Certificate( + VerifyError::UnknownIssuer | VerifyError::BadSignature + )) + )); + // A phone's device certificate from the same root. + let dev = pki::issue_device(&c.ianitor, "phone", NOW).unwrap(); + let dev_chain = pki::chain_der(&dev.chain_pem).unwrap(); + assert_eq!( + r.accept(&dev_chain, &c.root_der(), NOW + DAY), + Err(Refusal::Certificate(VerifyError::NotAnAgent)) + ); + // An agent of another team, enrolled there: not this team's web-1. + let (other_team, ot_serial) = c.agent("globex", "web-1", NOW); + let mut r = registry_with("acme", "web-1", &ot_serial); + assert_eq!( + r.accept(&other_team, &c.root_der(), NOW + DAY), + Err(Refusal::Unknown) + ); + // No certificate at all. + assert!(matches!( + r.accept(&[], &c.root_der(), NOW), + Err(Refusal::Certificate(_)) + )); +} diff --git a/crates/protocol/tests/common/mod.rs b/crates/protocol/tests/common/mod.rs new file mode 100644 index 0000000..b0ed3b2 --- /dev/null +++ b/crates/protocol/tests/common/mod.rs @@ -0,0 +1,95 @@ +// 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/. + +#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Cursor; + +use domi_pki::{self as pki, Intermediate}; + +pub const NOW: i64 = 1_800_000_000; +pub const DAY: i64 = 86_400; + +/// A Domi root (local, as in tests) with Ianitor's and the agents' intermediates. +pub struct Ca { + pub root_pem: String, + pub root_key: pki::KeyPair, + pub agents: Intermediate, + pub ianitor: Intermediate, +} + +impl Ca { + pub fn root_der(&self) -> Vec { + pki::chain_der(&self.root_pem).unwrap().remove(0) + } + + /// A fresh agent certificate chain (DER, leaf first) for `team`/`agent`, issued at `at`. + pub fn agent(&self, team: &str, agent: &str, at: i64) -> (Vec>, String) { + let key = pki::generate_key().unwrap(); + let csr = pki::agent_csr(&key, "legatus").unwrap(); + let a = pki::issue_agent(&self.agents, &csr, team, agent, at).unwrap(); + (pki::chain_der(&a.chain_pem).unwrap(), a.serial_hex) + } +} + +fn intermediate(root_pem: &str, root_key: &pki::KeyPair, cn: &str) -> Intermediate { + let key = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&key, cn).unwrap(); + let pem = pki::sign_intermediate(root_pem, root_key, &csr, cn, NOW).unwrap(); + Intermediate::new(&pem, key).unwrap() +} + +pub fn ca() -> Ca { + let (root_pem, root_key) = pki::create_root_local(NOW).unwrap(); + let agents = intermediate(&root_pem, &root_key, pki::AGENTS_INTERMEDIATE_CN); + let ianitor = intermediate(&root_pem, &root_key, pki::IANITOR_INTERMEDIATE_CN); + Ca { + root_pem, + root_key, + agents, + ianitor, + } +} + +/// A team release key, as Custos keeps it. +pub struct ReleaseKey(pub minisign::KeyPair); + +impl ReleaseKey { + pub fn new() -> ReleaseKey { + ReleaseKey(minisign::KeyPair::generate_unencrypted_keypair().unwrap()) + } + /// The base64 key line Legatus pins. + pub fn public(&self) -> String { + self.0.pk.to_base64() + } + /// A minisign signature (prehashed, as Custos signs) of `bytes`. + pub fn sign(&self, bytes: &[u8]) -> String { + minisign::sign( + Some(&self.0.pk), + &self.0.sk, + Cursor::new(bytes), + Some("release"), + None, + ) + .unwrap() + .into_string() + } +} + +pub fn sha256_hex(b: &[u8]) -> String { + ring::digest::digest(&ring::digest::SHA256, b) + .as_ref() + .iter() + .map(|x| format!("{x:02x}")) + .collect() +} + +/// A manifest for one artifact, as Fabrica's release object would write it. +pub fn manifest(team: &str, app: &str, version: &str, name: &str, artifact: &[u8]) -> String { + format!( + r#"{{"v":1,"team":"{team}","app":"{app}","version":"{version}","created_at":{NOW},"artifacts":[{{"name":"{name}","sha256":"{}","size":{}}}]}}"#, + sha256_hex(artifact), + artifact.len() + ) +} diff --git a/crates/protocol/tests/enrollment.rs b/crates/protocol/tests/enrollment.rs new file mode 100644 index 0000000..fab2e44 --- /dev/null +++ b/crates/protocol/tests/enrollment.rs @@ -0,0 +1,194 @@ +// 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 (mandatory, tests first): it round-trips, typos are caught before anything +//! is sent, and it is single use: a second redeem is refused, as are expired and unknown codes. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use legatus_protocol::{ + CODE_TTL_SECONDS, CodeError, EnrollError, EnrollmentBook, EnrollmentCode, Roles, +}; + +const ROOT: [u8; 32] = [7; 32]; +const SECRET: [u8; 16] = [0xa5; 16]; + +fn code() -> EnrollmentCode { + EnrollmentCode::new("https://fabrica.example:8443", ROOT, SECRET).unwrap() +} + +#[test] +fn a_code_round_trips_and_says_where_to_go() { + let c = code(); + let text = c.encode(); + assert!(text.starts_with("lgt1-"), "{text}"); + assert!(text.len() < 200, "short enough to copy: {}", text.len()); + assert!( + text[5..] + .bytes() + .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b)) + ); + let back = EnrollmentCode::parse(&text).unwrap(); + assert_eq!(back, c); + assert_eq!(back.server(), "https://fabrica.example:8443"); + assert_eq!(back.root_sha256(), &ROOT); + assert_eq!(back.secret_hex(), "a5".repeat(16)); + // Surrounding spaces from a copy are fine. + assert_eq!(EnrollmentCode::parse(&format!(" {text}\n")).unwrap(), c); +} + +#[test] +fn the_secret_is_never_printed() { + let dbg = format!("{:?}", code()); + assert!(!dbg.contains(&"a5".repeat(4)), "{dbg}"); + assert!(dbg.contains("fabrica.example")); +} + +#[test] +fn a_typo_is_caught_before_anything_is_sent() { + let text = code().encode(); + // Change one character in the middle. + let mut b = text.clone().into_bytes(); + let i = b.len() / 2; + b[i] = if b[i] == b'a' { b'b' } else { b'a' }; + assert_eq!( + EnrollmentCode::parse(&String::from_utf8(b).unwrap()), + Err(CodeError::Checksum) + ); + // Cut short. + assert!(EnrollmentCode::parse(&text[..text.len() - 6]).is_err()); + // Not a code at all. + assert_eq!(EnrollmentCode::parse("lgt2-aaaa"), Err(CodeError::Prefix)); + assert_eq!(EnrollmentCode::parse("lgt1-!!!!"), Err(CodeError::Encoding)); + assert_eq!(EnrollmentCode::parse("lgt1-"), Err(CodeError::Length)); + assert_eq!(EnrollmentCode::parse(""), Err(CodeError::Prefix)); +} + +#[test] +fn only_a_plain_https_server_url_goes_in_a_code() { + for bad in [ + "http://fabrica.example", + "https://", + "https://fabrica.example/path", + "https://user@fabrica.example", + "https://fabrica.example?x=1", + "https://fabrica.example#x", + "https://fabrica example", + "https://fabrica.example:99999", + "https://fabrica.example:", + "ftp://fabrica.example", + ] { + assert!( + matches!( + EnrollmentCode::new(bad, ROOT, SECRET), + Err(CodeError::BadServer(_)) + ), + "{bad}" + ); + } + let long = format!("https://{}.example", "a".repeat(200)); + assert!(EnrollmentCode::new(&long, ROOT, SECRET).is_err()); + for good in [ + "https://fabrica.example", + "https://10.0.0.5:8443", + "https://[::1]:8443", + ] { + EnrollmentCode::new(good, ROOT, SECRET).unwrap(); + } +} + +fn book() -> EnrollmentBook { + let mut b = EnrollmentBook::new(); + let roles = Roles { + build: false, + deploy: true, + }; + b.issue(SECRET, "acme", "web-1", roles, NOW, CODE_TTL_SECONDS) + .unwrap(); + b +} + +#[test] +fn a_code_is_single_use() { + let mut b = book(); + let secret = code().secret_hex(); + let g = b.redeem(&secret, NOW + 10).unwrap(); + assert_eq!((g.team.as_str(), g.agent.as_str()), ("acme", "web-1")); + assert_eq!( + g.roles, + Roles { + build: false, + deploy: true + } + ); + // The same code again, a second later or from another machine: refused. + assert_eq!(b.redeem(&secret, NOW + 11), Err(EnrollError::Used)); + assert_eq!(b.redeem(&secret, NOW + 12).unwrap_err().code(), "code_used"); +} + +#[test] +fn an_expired_or_unknown_code_is_refused() { + let mut b = book(); + let secret = code().secret_hex(); + assert_eq!( + b.redeem(&secret, NOW + CODE_TTL_SECONDS), + Err(EnrollError::Expired) + ); + // Still expired later, never accepted. + assert_eq!( + b.redeem(&secret, NOW + CODE_TTL_SECONDS + 60), + Err(EnrollError::Expired) + ); + assert_eq!(b.redeem(&"00".repeat(16), NOW), Err(EnrollError::Unknown)); + assert_eq!(b.redeem("not hex", NOW), Err(EnrollError::Unknown)); + assert_eq!( + b.redeem(&"A5".repeat(16), NOW), + Err(EnrollError::Unknown), + "lowercase only" + ); +} + +#[test] +fn the_book_keeps_only_a_digest_of_the_secret() { + let b = book(); + let stored = b.records().next().unwrap(); + assert_eq!(stored.digest.len(), 64); + assert!(!stored.digest.contains(&"a5".repeat(16))); + assert_eq!( + stored.digest, + legatus_protocol::secret_digest(&"a5".repeat(16)).unwrap() + ); + assert_eq!(stored.used_at, None); +} + +#[test] +fn a_code_cannot_be_issued_twice_or_for_bad_ids() { + let mut b = book(); + assert!( + b.issue(SECRET, "acme", "web-2", Roles::default(), NOW, 60) + .is_err(), + "same secret" + ); + assert!( + b.issue([1; 16], "Acme", "web-2", Roles::default(), NOW, 60) + .is_err() + ); + assert!( + b.issue([1; 16], "acme", "web 2", Roles::default(), NOW, 60) + .is_err() + ); + assert!( + b.issue([1; 16], "acme", "web-2", Roles::default(), NOW, 0) + .is_err(), + "no lifetime" + ); + assert!( + b.issue([1; 16], "acme", "web-2", Roles::default(), NOW, 86_401) + .is_err(), + "a day at most" + ); +} diff --git a/crates/protocol/tests/jobs.rs b/crates/protocol/tests/jobs.rs new file mode 100644 index 0000000..c64aeb3 --- /dev/null +++ b/crates/protocol/tests/jobs.rs @@ -0,0 +1,269 @@ +// 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/. + +//! Messages and jobs (tests first): strict parsing with limits, the replay guard, roles, safe +//! archive paths, reports. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use legatus_protocol::{ + ArchiveError, EntryKind, GuardError, Job, JobBody, JobGuard, MAX_BODY, MAX_JOB_SECONDS, + MsgError, Report, Roles, Status, Step, check_entry, decode, encode, msg, parse_job, +}; + +fn deploy_job(id: &str, issued: i64, expires: i64) -> String { + format!( + r#"{{"v":1,"id":"{id}","issued_at":{issued},"expires_at":{expires},"kind":"deploy","spec":{{ + "app":"shop","version":"1.4.0","artifact":"shop.tar.gz", + "release":{{"manifest":"{{}}","signature":"sig"}}, + "target":{{"kind":"linux","linux":{{"unit":"shop.service","health_url":"http://127.0.0.1:8080/health","health_timeout_seconds":30,"keep":3}}}}}}}}"# + ) +} + +const ID: &str = "0123456789abcdef0123456789abcdef"; + +#[test] +fn a_deploy_job_parses() { + let job = parse_job(deploy_job(ID, NOW, NOW + 600).as_bytes()).unwrap(); + assert_eq!(job.header.id, ID); + let JobBody::Deploy(d) = &job.body else { + panic!("{:?}", job.body) + }; + assert_eq!((d.app.as_str(), d.version.as_str()), ("shop", "1.4.0")); + let msg::Target::Linux(l) = &d.target; + assert_eq!(l.unit, "shop.service"); + assert_eq!(l.keep, 3); +} + +#[test] +fn unknown_kinds_and_targets_are_reported_not_dropped() { + let j = format!( + r#"{{"v":1,"id":"{ID}","issued_at":{NOW},"expires_at":{},"kind":"build","spec":{{}}}}"#, + NOW + 60 + ); + let job: Job = parse_job(j.as_bytes()).unwrap(); + assert_eq!(job.body, JobBody::Unsupported("build".into())); + let docker = deploy_job(ID, NOW, NOW + 60) + .replace(r#""kind":"linux","linux""#, r#""kind":"docker","docker""#); + let job = parse_job(docker.as_bytes()).unwrap(); + assert!( + matches!(job.body, JobBody::Unsupported(ref k) if k == "target docker"), + "{:?}", + job.body + ); + // A known kind with a bad spec is answerable too: the id is known. + let bad = deploy_job(ID, NOW, NOW + 60).replace(r#""app":"shop""#, r#""app":"../etc""#); + let job = parse_job(bad.as_bytes()).unwrap(); + assert!(matches!(job.body, JobBody::Invalid(_)), "{:?}", job.body); +} + +#[test] +fn hostile_job_specs_are_invalid() { + for (from, to) in [ + (r#""unit":"shop.service""#, r#""unit":"../shop.service""#), + (r#""unit":"shop.service""#, r#""unit":"-shop.service""#), + (r#""unit":"shop.service""#, r#""unit":"shop""#), + ( + r#""health_url":"http://127.0.0.1:8080/health""#, + r#""health_url":"http://10.0.0.1/health""#, + ), + ( + r#""health_url":"http://127.0.0.1:8080/health""#, + r#""health_url":"https://127.0.0.1/health""#, + ), + ( + r#""health_url":"http://127.0.0.1:8080/health""#, + r#""health_url":"http://127.0.0.1@evil.example/""#, + ), + (r#""keep":3"#, r#""keep":0"#), + ( + r#""health_timeout_seconds":30"#, + r#""health_timeout_seconds":100000"#, + ), + (r#""version":"1.4.0""#, r#""version":"..""#), + (r#""artifact":"shop.tar.gz""#, r#""artifact":"a/b.tar.gz""#), + ] { + let j = deploy_job(ID, NOW, NOW + 60).replace(from, to); + assert!( + matches!(parse_job(j.as_bytes()).unwrap().body, JobBody::Invalid(_)), + "{to}" + ); + } + // localhost and [::1] are local too. + for ok in [ + "http://localhost:9000/up", + "http://[::1]:9000/", + "http://127.0.0.1/", + ] { + let j = deploy_job(ID, NOW, NOW + 60).replace("http://127.0.0.1:8080/health", ok); + assert!( + matches!(parse_job(j.as_bytes()).unwrap().body, JobBody::Deploy(_)), + "{ok}" + ); + } +} + +#[test] +fn messages_are_strict_and_bounded() { + let hello = r#"{"v":1,"version":"0.1.0","os":"linux","arch":"x86_64","hostname":"web-1","capabilities":{"deploy":["linux"],"build":[]},"deployed":[]}"#; + let h: msg::Hello = decode(hello.as_bytes()).unwrap(); + assert_eq!(h.hostname, "web-1"); + let back: msg::Hello = decode(&encode(&h)).unwrap(); + assert_eq!(back, h); + // An unknown field, another version, garbage, too big. + let extra = hello.replace(r#""v":1,"#, r#""v":1,"admin":true,"#); + assert!(matches!( + decode::(extra.as_bytes()), + Err(MsgError::Malformed(_)) + )); + let v2 = hello.replace(r#""v":1"#, r#""v":2"#); + assert_eq!(decode::(v2.as_bytes()), Err(MsgError::Version)); + assert!(decode::(b"\xff\xfe").is_err()); + let big = vec![b' '; MAX_BODY + 1]; + assert_eq!(decode::(&big), Err(MsgError::TooLarge)); + assert!(parse_job(&big).is_err()); +} + +#[test] +fn the_guard_refuses_expired_future_long_and_replayed_jobs() { + let mut g = JobGuard::new(); + let h = |id: &str, i: i64, e: i64| parse_job(deploy_job(id, i, e).as_bytes()).unwrap().header; + g.check(&h(ID, NOW, NOW + 600), NOW).unwrap(); + assert_eq!( + g.check(&h(ID, NOW, NOW + 600), NOW + 1), + Err(GuardError::Replayed) + ); + let id2 = "1".repeat(32); + assert_eq!( + g.check(&h(&id2, NOW - 700, NOW - 100), NOW), + Err(GuardError::Expired) + ); + assert_eq!( + g.check(&h(&id2, NOW + 301, NOW + 900), NOW), + Err(GuardError::Future) + ); + assert_eq!( + g.check(&h(&id2, NOW, NOW + MAX_JOB_SECONDS + 1), NOW), + Err(GuardError::TooLong) + ); + assert_eq!( + g.check(&h(&id2, NOW, NOW - 1), NOW), + Err(GuardError::Expired) + ); + for bad in ["short", &"g".repeat(32), &"A".repeat(32)] { + assert_eq!( + g.check(&h(bad, NOW, NOW + 60), NOW), + Err(GuardError::BadId), + "{bad}" + ); + } + assert_eq!(GuardError::Replayed.code(), "replayed"); +} + +#[test] +fn the_guard_survives_a_restart_and_forgets_only_expired_ids() { + let mut g = JobGuard::new(); + let h = |id: &str, i: i64, e: i64| parse_job(deploy_job(id, i, e).as_bytes()).unwrap().header; + g.check(&h(ID, NOW, NOW + 600), NOW).unwrap(); + let saved = g.save(); + let mut again = JobGuard::load(&saved).unwrap(); + assert_eq!( + again.check(&h(ID, NOW, NOW + 600), NOW + 5), + Err(GuardError::Replayed) + ); + // After its expiry the id is forgotten, and the job would be refused as expired anyway. + again.prune(NOW + 601); + assert_eq!(again.len(), 0); + assert_eq!( + again.check(&h(ID, NOW, NOW + 600), NOW + 601), + Err(GuardError::Expired) + ); + assert!(JobGuard::load("garbage").is_err()); +} + +#[test] +fn roles_gate_jobs() { + let off = Roles::default(); + assert!( + !off.build && !off.deploy, + "both off until Fabrica turns them on" + ); + let job = parse_job(deploy_job(ID, NOW, NOW + 60).as_bytes()).unwrap(); + assert!(!job.body.allowed_by(&off)); + assert!(job.body.allowed_by(&Roles { + build: false, + deploy: true + })); + let cfg = format!( + r#"{{"v":1,"id":"{ID}","issued_at":{NOW},"expires_at":{},"kind":"config","spec":{{"roles":{{"build":true,"deploy":false}}}}}}"#, + NOW + 60 + ); + let job = parse_job(cfg.as_bytes()).unwrap(); + assert_eq!( + job.body, + JobBody::Config(msg::ConfigJob { + roles: Roles { + build: true, + deploy: false + } + }) + ); + assert!( + job.body.allowed_by(&off), + "a config job is always allowed: it is how roles change" + ); +} + +#[test] +fn archive_entries_stay_inside_the_release() { + check_entry(EntryKind::File, "bin/shop", 10).unwrap(); + check_entry(EntryKind::Dir, "static/", 0).unwrap(); + check_entry(EntryKind::File, "./README", 10).unwrap(); + for (kind, path) in [ + (EntryKind::File, "/etc/passwd"), + (EntryKind::File, "../outside"), + (EntryKind::File, "a/../../outside"), + (EntryKind::File, "a\\..\\b"), + (EntryKind::File, ""), + (EntryKind::File, "a\0b"), + (EntryKind::File, "C:/x"), + (EntryKind::Symlink, "link"), + (EntryKind::Hardlink, "hard"), + (EntryKind::Other, "dev"), + ] { + assert!(check_entry(kind, path, 0).is_err(), "{kind:?} {path:?}"); + } + assert_eq!( + check_entry(EntryKind::Symlink, "x", 0).unwrap_err(), + ArchiveError::Kind + ); + assert_eq!( + check_entry(EntryKind::File, "../x", 0).unwrap_err().code(), + "bad_archive" + ); +} + +#[test] +fn reports_are_bounded_and_carry_a_stable_code() { + let r = Report::refused( + ID, + NOW, + Step::Verify, + "unsigned", + "the release has no signature", + ); + assert_eq!(r.status, Status::Refused); + assert!(r.message.starts_with("unsigned: ")); + let long = Report::failed(ID, NOW, Step::Health, &"x".repeat(5000), true); + assert!(long.message.chars().count() <= 2000); + assert_eq!(long.rolled_back, Some(true)); + let json = String::from_utf8(encode(&r)).unwrap(); + assert!( + json.contains(r#""status":"refused""#) && json.contains(r#""step":"verify""#), + "{json}" + ); +} diff --git a/crates/protocol/tests/release.rs b/crates/protocol/tests/release.rs new file mode 100644 index 0000000..ee40297 --- /dev/null +++ b/crates/protocol/tests/release.rs @@ -0,0 +1,216 @@ +// 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 (mandatory, tests first): a missing or garbled signature, a wrong key, a +//! manifest for another team, app or version, and a tampered artifact are all refused. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use legatus_protocol::{Expected, ReleaseError, check_artifact, verify_release}; + +const ART: &[u8] = b"pretend this is shop-1.4.0.tar.gz"; +const NAME: &str = "shop-linux-x86_64.tar.gz"; + +fn expect() -> Expected<'static> { + Expected { + team: "acme", + app: "shop", + version: "1.4.0", + artifact: NAME, + } +} + +#[test] +fn a_release_signed_by_the_team_key_is_approved() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let ok = verify_release( + m.as_bytes(), + &key.sign(m.as_bytes()), + &[key.public()], + &expect(), + ) + .unwrap(); + assert_eq!(ok.name, NAME); + assert_eq!(ok.sha256, sha256_hex(ART)); + assert_eq!(ok.size, ART.len() as u64); + check_artifact(&ok, &sha256_hex(ART), ART.len() as u64).unwrap(); + // Any of the pinned keys will do (a team may have two during a rotation). + let other = ReleaseKey::new(); + verify_release( + m.as_bytes(), + &key.sign(m.as_bytes()), + &[other.public(), key.public()], + &expect(), + ) + .unwrap(); +} + +#[test] +fn a_missing_signature_is_refused() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + for sig in ["", " \n"] { + let e = verify_release(m.as_bytes(), sig, &[key.public()], &expect()).unwrap_err(); + assert_eq!(e, ReleaseError::Unsigned); + assert_eq!(e.code(), "unsigned"); + } +} + +#[test] +fn a_garbled_signature_is_refused() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let e = verify_release( + m.as_bytes(), + "untrusted comment: x\nnot base64\n", + &[key.public()], + &expect(), + ) + .unwrap_err(); + assert_eq!(e, ReleaseError::BadSignature); +} + +#[test] +fn a_wrong_key_is_refused() { + let team = ReleaseKey::new(); + let stranger = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let e = verify_release( + m.as_bytes(), + &stranger.sign(m.as_bytes()), + &[team.public()], + &expect(), + ) + .unwrap_err(); + assert_eq!(e, ReleaseError::UnknownKey); + assert_eq!(e.code(), "unknown_key"); + // No pinned keys at all: nothing can be approved. + assert_eq!( + verify_release(m.as_bytes(), &team.sign(m.as_bytes()), &[], &expect()), + Err(ReleaseError::NoKeys) + ); +} + +#[test] +fn a_changed_manifest_breaks_the_signature() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let sig = key.sign(m.as_bytes()); + // Same key, but the manifest now points at another artifact. + let evil = manifest("acme", "shop", "1.4.0", NAME, b"something else"); + assert_eq!( + verify_release(evil.as_bytes(), &sig, &[key.public()], &expect()), + Err(ReleaseError::BadSignature) + ); + // Even one added space. + let spaced = format!("{m} "); + assert_eq!( + verify_release(spaced.as_bytes(), &sig, &[key.public()], &expect()), + Err(ReleaseError::BadSignature) + ); +} + +#[test] +fn a_signed_release_of_something_else_is_refused() { + let key = ReleaseKey::new(); + for (team, app, version, name) in [ + ("globex", "shop", "1.4.0", NAME), + ("acme", "blog", "1.4.0", NAME), + ("acme", "shop", "1.3.9", NAME), + ("acme", "shop", "1.4.0", "other.tar.gz"), + ] { + let m = manifest(team, app, version, name, ART); + let e = verify_release( + m.as_bytes(), + &key.sign(m.as_bytes()), + &[key.public()], + &expect(), + ) + .unwrap_err(); + assert!( + matches!(e, ReleaseError::WrongRelease(_)), + "{team} {app} {version} {name}: {e:?}" + ); + assert_eq!(e.code(), "wrong_release"); + } +} + +#[test] +fn a_tampered_artifact_is_refused() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let ok = verify_release( + m.as_bytes(), + &key.sign(m.as_bytes()), + &[key.public()], + &expect(), + ) + .unwrap(); + let mut evil = ART.to_vec(); + evil[3] ^= 1; + let e = check_artifact(&ok, &sha256_hex(&evil), evil.len() as u64).unwrap_err(); + assert!(matches!(e, ReleaseError::Tampered(_))); + assert_eq!(e.code(), "tampered"); + assert!(matches!( + check_artifact(&ok, &sha256_hex(ART), ART.len() as u64 + 1), + Err(ReleaseError::Tampered(_)) + )); +} + +#[test] +fn a_signed_but_malformed_manifest_is_refused() { + let key = ReleaseKey::new(); + let sha = sha256_hex(ART); + for m in [ + "not json".to_owned(), + r#"{"v":2,"team":"acme","app":"shop","version":"1.4.0","created_at":1,"artifacts":[]}"# + .to_owned(), + format!( + r#"{{"v":1,"team":"acme","app":"shop","version":"1.4.0","created_at":1,"artifacts":[{{"name":"{NAME}","sha256":"{sha}","size":1}}],"extra":1}}"# + ), + format!( + r#"{{"v":1,"team":"acme","app":"shop","version":"1.4.0","created_at":1,"artifacts":[{{"name":"{NAME}","sha256":"XYZ","size":1}}]}}"# + ), + format!( + r#"{{"v":1,"team":"acme","app":"shop","version":"1.4.0","created_at":1,"artifacts":[{{"name":"../{NAME}","sha256":"{sha}","size":1}}]}}"# + ), + format!( + r#"{{"v":1,"team":"acme","app":"shop","version":"1.4.0","created_at":1,"artifacts":[{{"name":"{NAME}","sha256":"{sha}","size":1}},{{"name":"{NAME}","sha256":"{sha}","size":1}}]}}"# + ), + format!( + r#"{{"v":1,"team":"acme","app":"shop","version":"../1","created_at":1,"artifacts":[{{"name":"{NAME}","sha256":"{sha}","size":1}}]}}"# + ), + ] { + let e = verify_release( + m.as_bytes(), + &key.sign(m.as_bytes()), + &[key.public()], + &expect(), + ) + .unwrap_err(); + assert!(matches!(e, ReleaseError::BadManifest(_)), "{m}: {e:?}"); + } +} + +#[test] +fn a_bad_pinned_key_is_skipped_not_trusted() { + let key = ReleaseKey::new(); + let m = manifest("acme", "shop", "1.4.0", NAME, ART); + let sig = key.sign(m.as_bytes()); + assert_eq!( + verify_release(m.as_bytes(), &sig, &["garbage".to_owned()], &expect()), + Err(ReleaseError::UnknownKey) + ); + verify_release( + m.as_bytes(), + &sig, + &["garbage".to_owned(), key.public()], + &expect(), + ) + .unwrap(); +}