Files
Legatus/crates/protocol/tests/jobs.rs
T

275 lines
9.6 KiB
Rust

// 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::<msg::Hello>(extra.as_bytes()),
Err(MsgError::Malformed(_))
));
let v2 = hello.replace(r#""v":1"#, r#""v":2"#);
assert_eq!(decode::<msg::Hello>(v2.as_bytes()), Err(MsgError::Version));
assert!(decode::<msg::Hello>(b"\xff\xfe").is_err());
let big = vec![b' '; MAX_BODY + 1];
assert_eq!(decode::<msg::Hello>(&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();
// `tar -C dir -czf x.tar.gz .` writes the root itself as `./`: allowed, and it names nothing.
assert!(check_entry(EntryKind::Dir, "./", 0).unwrap().is_empty());
assert!(check_entry(EntryKind::Dir, ".", 0).unwrap().is_empty());
assert!(check_entry(EntryKind::File, "./", 0).is_err());
assert!(check_entry(EntryKind::File, ".", 0).is_err());
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}"
);
}