[agent] Tests: end to end over TLS (single-use code, expired/replayed/foreign certificates both ways), nothing unsigned reaches a target (red: the code follows)

This commit is contained in:
2026-11-17 12:09:28 +01:00
parent 27194b7b00
commit f935a41ef8
3 changed files with 1105 additions and 0 deletions
+489
View File
@@ -0,0 +1,489 @@
// 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/.
//! A Domi CA in real time, team release keys, fake targets, and a mock Fabrica server that speaks
//! protocol v1 over real TLS with the reference logic (EnrollmentBook, Registry).
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::io::{Cursor, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use domi_pki::{self as pki, Intermediate};
use legatus::pipeline::{Fetch, Target};
use legatus_linux::{DeployError, Outcome};
use legatus_protocol::msg::{
DeployJob, Deployed, EnrollRequest, EnrollResponse, ErrorBody, LinuxTarget, RenewRequest,
Renewed, SignedRelease, Target as JobTarget, V, Welcome,
};
use legatus_protocol::{
EnrollmentBook, EnrollmentCode, JobBody, Registry, Report, Roles, decode, encode,
};
use rustls::server::WebPkiClientVerifier;
use rustls::{RootCertStore, ServerConfig, ServerConnection, StreamOwned};
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
pub const DAY: i64 = 86_400;
pub fn now() -> i64 {
legatus::now()
}
/// A Domi CA made four months ago, so certificates can be backdated.
pub struct Ca {
pub root_pem: String,
pub root_key: pki::KeyPair,
pub agents: Intermediate,
pub ianitor: Intermediate,
}
impl Ca {
pub fn new() -> Ca {
let t = now() - 120 * DAY;
let (root_pem, root_key) = pki::create_root_local(t).unwrap();
let int = |cn: &str| {
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, cn).unwrap();
let pem = pki::sign_intermediate(&root_pem, &root_key, &csr, cn, t).unwrap();
Intermediate::new(&pem, k).unwrap()
};
let agents = int(pki::AGENTS_INTERMEDIATE_CN);
let ianitor = int(pki::IANITOR_INTERMEDIATE_CN);
Ca {
root_pem,
root_key,
agents,
ianitor,
}
}
pub fn root_der(&self) -> Vec<u8> {
pki::chain_der(&self.root_pem).unwrap().remove(0)
}
pub fn root_sha256(&self) -> [u8; 32] {
let d = ring::digest::digest(&ring::digest::SHA256, &self.root_der());
d.as_ref().try_into().unwrap()
}
/// An agent chain and key issued at `at`.
pub fn agent(&self, team: &str, agent: &str, at: i64) -> (String, 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();
(a.chain_pem, key.serialize_pem())
}
}
/// A team release key.
pub struct ReleaseKey(pub minisign::KeyPair);
impl ReleaseKey {
pub fn new() -> ReleaseKey {
ReleaseKey(minisign::KeyPair::generate_unencrypted_keypair().unwrap())
}
pub fn public(&self) -> String {
self.0.pk.to_base64()
}
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 {
legatus_protocol::sha256_hex(b)
}
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":{},"artifacts":[{{"name":"{name}","sha256":"{}","size":{}}}]}}"#,
now(),
sha256_hex(artifact),
artifact.len()
)
}
pub fn job_id(n: u8) -> String {
format!("{n:02x}").repeat(16)
}
/// A deploy job for `shop` `version`, artifact `shop.tar.gz`, with this manifest and signature.
pub fn deploy_job(id: &str, version: &str, manifest: &str, signature: &str) -> Vec<u8> {
let body = JobBody::Deploy(DeployJob {
app: "shop".into(),
version: version.into(),
artifact: "shop.tar.gz".into(),
release: SignedRelease {
manifest: manifest.into(),
signature: signature.into(),
},
target: JobTarget::Linux(LinuxTarget {
unit: "shop.service".into(),
health_url: Some("http://127.0.0.1:8080/health".into()),
health_timeout_seconds: 5,
keep: 3,
}),
});
legatus_protocol::msg::job_json(id, now(), now() + 600, &body)
}
/// app, version, sha256, bytes.
pub type Call = (String, String, String, Vec<u8>);
/// A target that records what reached it.
pub struct FakeTarget {
pub calls: RefCell<Vec<Call>>,
pub outcome: RefCell<Result<Outcome, String>>,
}
impl FakeTarget {
pub fn new() -> FakeTarget {
FakeTarget {
calls: RefCell::new(Vec::new()),
outcome: RefCell::new(Ok(Outcome::Succeeded { previous: None })),
}
}
}
impl Target for FakeTarget {
fn kinds(&self) -> Vec<String> {
vec!["linux".into()]
}
fn deploy(
&self,
job: &DeployJob,
artifact: &Path,
sha256: &str,
) -> Result<Outcome, DeployError> {
let bytes = std::fs::read(artifact).unwrap();
self.calls.borrow_mut().push((
job.app.clone(),
job.version.clone(),
sha256.to_owned(),
bytes,
));
match &*self.outcome.borrow() {
Ok(o) => Ok(o.clone()),
Err(e) if e == "archive" => Err(DeployError::Unpack(
legatus_linux::UnpackError::Archive(legatus_protocol::ArchiveError::Path),
)),
Err(e) => Err(DeployError::Switch(e.clone())),
}
}
fn deployed(&self) -> Vec<Deployed> {
Vec::new()
}
}
/// Artifacts served from memory, counting fetches.
pub struct FakeFetch {
pub bytes: Vec<u8>,
pub fetched: RefCell<u32>,
}
impl Fetch for FakeFetch {
fn fetch(&self, _job: &str, _name: &str, max: u64, out: &mut dyn Write) -> Result<u64, String> {
*self.fetched.borrow_mut() += 1;
let n = (self.bytes.len() as u64).min(max) as usize;
out.write_all(&self.bytes[..n]).map_err(|e| e.to_string())?;
Ok(n as u64)
}
}
// ------------------------------------------------------------------ the mock Fabrica server
#[derive(Default)]
pub struct World {
pub book: EnrollmentBook,
pub registry: Registry,
pub roles: Roles,
pub release_keys: Vec<String>,
pub jobs: VecDeque<Vec<u8>>,
pub artifacts: HashMap<(String, String), Vec<u8>>,
pub reports: Vec<Report>,
pub requests: Vec<String>,
}
pub struct Mock {
pub url: String,
pub world: Arc<Mutex<World>>,
}
pub struct ServerCert {
pub chain_pem: String,
pub key_pem: String,
}
/// The server certificate Fabrica would present for 127.0.0.1: leaf, agents intermediate, root.
pub fn server_cert(ca: &Ca, at: i64) -> ServerCert {
let s = pki::issue_server(&ca.agents, "127.0.0.1", at).unwrap();
ServerCert {
chain_pem: format!("{}{}", s.chain_pem, ca.root_pem),
key_pem: s.key_pem,
}
}
/// Start a mock Fabrica: `trust` is the CA whose agents it accepts (its agents intermediate
/// issues agents), `cert` what it presents.
pub fn mock(trust: &Ca, cert: ServerCert, release_keys: Vec<String>) -> Mock {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut roots = RootCertStore::empty();
roots.add(CertificateDer::from(trust.root_der())).unwrap();
let verifier = WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider.clone())
.allow_unauthenticated()
.build()
.unwrap();
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(cert.chain_pem.as_bytes())
.collect::<Result<_, _>>()
.unwrap();
let key = PrivateKeyDer::from_pem_slice(cert.key_pem.as_bytes()).unwrap();
let cfg = Arc::new(
ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_client_cert_verifier(verifier)
.with_single_cert(chain, key)
.unwrap(),
);
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!(
"https://127.0.0.1:{}",
listener.local_addr().unwrap().port()
);
let world = Arc::new(Mutex::new(World {
release_keys,
..World::default()
}));
let w = world.clone();
let root_der = trust.root_der();
let agents_int = Intermediate::new(
trust.agents.cert_pem(),
pki::KeyPair::from_pem(&trust.agents.key().serialize_pem()).unwrap(),
)
.unwrap();
let root_pem = trust.root_pem.clone();
std::thread::spawn(move || {
for tcp in listener.incoming() {
let Ok(tcp) = tcp else { continue };
let _ = serve(tcp, &cfg, &w, &root_der, &root_pem, &agents_int);
}
});
Mock { url, world }
}
fn serve(
tcp: TcpStream,
cfg: &Arc<ServerConfig>,
world: &Arc<Mutex<World>>,
root_der: &[u8],
root_pem: &str,
agents: &Intermediate,
) -> std::io::Result<()> {
tcp.set_read_timeout(Some(Duration::from_secs(5)))?;
let conn = ServerConnection::new(cfg.clone()).map_err(std::io::Error::other)?;
let mut s = StreamOwned::new(conn, tcp);
while s.conn.is_handshaking() {
s.conn.complete_io(&mut s.sock)?;
}
// The request.
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
let (method, path, body) = loop {
let n = s.read(&mut chunk)?;
if n == 0 {
return Ok(());
}
buf.extend_from_slice(&chunk[..n]);
let mut headers = [httparse::EMPTY_HEADER; 32];
let mut req = httparse::Request::new(&mut headers);
if let httparse::Status::Complete(len) = req.parse(&buf).map_err(std::io::Error::other)? {
let cl: usize = req
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-length"))
.and_then(|h| std::str::from_utf8(h.value).ok()?.parse().ok())
.unwrap_or(0);
let (m, p) = (
req.method.unwrap_or("").to_owned(),
req.path.unwrap_or("").to_owned(),
);
let mut body = buf[len..].to_vec();
while body.len() < cl {
let n = s.read(&mut chunk)?;
if n == 0 {
break;
}
body.extend_from_slice(&chunk[..n]);
}
break (m, p, body);
}
};
let peer: Option<Vec<Vec<u8>>> = s
.conn
.peer_certificates()
.map(|c| c.iter().map(|d| d.as_ref().to_vec()).collect());
let (status, out) = route(
&method, &path, &body, peer, world, root_der, root_pem, agents,
);
let head = format!(
"HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
out.len()
);
s.write_all(head.as_bytes())?;
s.write_all(&out)?;
s.flush()?;
s.conn.send_close_notify();
let _ = s.conn.complete_io(&mut s.sock);
Ok(())
}
fn err(status: u16, code: &str) -> (u16, Vec<u8>) {
(
status,
encode(&ErrorBody {
error: code.into(),
message: code.replace('_', " "),
}),
)
}
#[allow(clippy::too_many_arguments)]
fn route(
method: &str,
path: &str,
body: &[u8],
peer: Option<Vec<Vec<u8>>>,
world: &Arc<Mutex<World>>,
root_der: &[u8],
root_pem: &str,
agents: &Intermediate,
) -> (u16, Vec<u8>) {
let mut w = world.lock().unwrap();
w.requests.push(format!("{method} {path}"));
let now = now();
if (method, path) == ("POST", "/legatus/v1/enroll") {
let Ok(r) = decode::<EnrollRequest>(body) else {
return err(400, "bad_request");
};
if domi_pki::csr_public_key_der(&r.csr).is_err() {
return err(400, "bad_csr");
}
let g = match w.book.redeem(&r.secret, now) {
Ok(g) => g,
Err(e) => return err(403, e.code()),
};
let Ok(a) = domi_pki::issue_agent(agents, &r.csr, &g.team, &g.agent, now) else {
return err(400, "bad_csr");
};
w.registry.enrolled(&g.team, &g.agent, &a.serial_hex);
let roles = g.roles;
w.roles = roles;
return (
200,
encode(&EnrollResponse {
v: V,
team: g.team,
agent: g.agent,
chain: a.chain_pem,
root: root_pem.to_owned(),
roles,
release_keys: w.release_keys.clone(),
poll_seconds: 5,
}),
);
}
// Everything else: the agent's certificate, checked by the registry.
let Some(chain) = peer else {
return err(401, "certificate_required");
};
let id = match w.registry.accept(&chain, root_der, now) {
Ok(id) => id,
Err(e) => return err(403, e.code()),
};
match (method, path.split('?').next().unwrap_or("")) {
("POST", "/legatus/v1/hello") => (
200,
encode(&Welcome {
v: V,
team: id.team,
agent: id.agent,
roles: w.roles,
server_time: now,
renew: false,
}),
),
("GET", "/legatus/v1/jobs") => match w.jobs.pop_front() {
Some(j) => (200, j),
None => (204, Vec::new()),
},
("POST", "/legatus/v1/reports") => match decode::<Report>(body) {
Ok(r) => {
w.reports.push(r);
(204, Vec::new())
}
Err(_) => err(400, "bad_request"),
},
("POST", "/legatus/v1/renew") => {
let Ok(r) = decode::<RenewRequest>(body) else {
return err(400, "bad_request");
};
let Ok(a) = domi_pki::issue_agent(agents, &r.csr, &id.team, &id.agent, now) else {
return err(400, "bad_csr");
};
w.registry
.renewed(&id.team, &id.agent, &a.serial_hex)
.unwrap();
(
200,
encode(&Renewed {
v: V,
chain: a.chain_pem,
}),
)
}
("GET", p) if p.starts_with("/legatus/v1/artifacts/") => {
let mut parts = p
.trim_start_matches("/legatus/v1/artifacts/")
.splitn(2, '/');
let (job, name) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
match w.artifacts.get(&(job.to_owned(), name.to_owned())) {
Some(b) => (200, b.clone()),
None => err(404, "not_found"),
}
}
_ => err(404, "not_found"),
}
}
impl Mock {
/// A fresh code for `team`/`agent` with `roles`, living `ttl` seconds.
pub fn code(&self, ca: &Ca, agent: &str, roles: Roles, ttl: i64) -> String {
let mut secret = [0u8; 16];
ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut secret).unwrap();
self.world
.lock()
.unwrap()
.book
.issue(secret, "acme", agent, roles, now(), ttl)
.unwrap();
EnrollmentCode::new(&self.url, ca.root_sha256(), secret)
.unwrap()
.encode()
}
}
+311
View File
@@ -0,0 +1,311 @@
// 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/.
//! End to end over real TLS against a mock Fabrica that uses the reference server logic
//! (mandatory, tests first): the enrollment code is single use; expired, replayed and foreign
//! certificates are refused in both directions; a deploy runs only with the team's signature.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use common::*;
use legatus::client::ClientError;
use legatus::state::State;
use legatus::{AgentError, Session};
use legatus_protocol::{Roles, Status};
const DEPLOY: Roles = Roles {
build: false,
deploy: true,
};
struct Setup {
ca: Ca,
key: ReleaseKey,
mock: Mock,
dir: tempfile::TempDir,
}
fn setup() -> Setup {
let ca = Ca::new();
let key = ReleaseKey::new();
let mock = mock(&ca, server_cert(&ca, now()), vec![key.public()]);
Setup {
ca,
key,
mock,
dir: tempfile::tempdir().unwrap(),
}
}
impl Setup {
fn state(&self, name: &str) -> State {
State::new(self.dir.path().join(name))
}
fn enrolled(&self) -> State {
let st = self.state("agent");
legatus::enroll(&st, &self.mock.code(&self.ca, "web-1", DEPLOY, 3600), false).unwrap();
st
}
}
fn refused_code(e: AgentError) -> String {
match e {
AgentError::Client(ClientError::Refused { code, .. }) => code,
other => panic!("expected a refusal, got {other:?}"),
}
}
#[test]
fn enroll_hello_deploy_report() {
let s = setup();
let st = s.enrolled();
let e = st.load().unwrap();
assert_eq!(
(e.file.team.as_str(), e.file.agent.as_str()),
("acme", "web-1")
);
assert_eq!(e.file.release_keys, vec![s.key.public()]);
assert!(e.file.roles.deploy);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(st.dir().join("key.pem"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
// A signed release, served by Fabrica.
let art = b"the shop, version 1.4.0".to_vec();
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", &art);
let id = job_id(7);
{
let mut w = s.mock.world.lock().unwrap();
w.jobs
.push_back(deploy_job(&id, "1.4.0", &m, &s.key.sign(m.as_bytes())));
w.artifacts
.insert((id.clone(), "shop.tar.gz".into()), art.clone());
}
let target = FakeTarget::new();
let mut session = Session::open(st.clone()).unwrap();
session.hello(&target).unwrap();
assert!(session.poll_once(&target).unwrap());
assert_eq!(target.calls.borrow().len(), 1);
assert_eq!(target.calls.borrow()[0].3, art);
let w = s.mock.world.lock().unwrap();
let statuses: Vec<Status> = w.reports.iter().map(|r| r.status).collect();
assert_eq!(statuses, vec![Status::Accepted, Status::Succeeded]);
drop(w);
// Nothing waiting: the poll returns without a job.
assert!(!session.poll_once(&target).unwrap());
}
#[test]
fn a_tampered_artifact_from_the_server_is_refused() {
let s = setup();
let st = s.enrolled();
let art = b"the shop, version 1.4.0".to_vec();
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", &art);
let id = job_id(8);
{
let mut w = s.mock.world.lock().unwrap();
w.jobs
.push_back(deploy_job(&id, "1.4.0", &m, &s.key.sign(m.as_bytes())));
w.artifacts.insert(
(id.clone(), "shop.tar.gz".into()),
b"the shop, version 6.6.6".to_vec(),
);
}
let target = FakeTarget::new();
let mut session = Session::open(st).unwrap();
session.poll_once(&target).unwrap();
assert!(target.calls.borrow().is_empty());
let w = s.mock.world.lock().unwrap();
let last = w.reports.last().unwrap();
assert_eq!(last.status, Status::Refused);
assert!(last.message.starts_with("tampered: "), "{}", last.message);
}
#[test]
fn the_enrollment_code_is_single_use() {
let s = setup();
let code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600);
legatus::enroll(&s.state("first"), &code, false).unwrap();
// The same code on a second machine.
let e = legatus::enroll(&s.state("second"), &code, false).unwrap_err();
assert_eq!(refused_code(e), "code_used");
assert!(!s.state("second").is_enrolled());
}
#[test]
fn an_expired_code_is_refused() {
let s = setup();
let code = s.mock.code(&s.ca, "web-1", DEPLOY, 1);
std::thread::sleep(std::time::Duration::from_millis(2100));
let e = legatus::enroll(&s.state("a"), &code, false).unwrap_err();
assert_eq!(refused_code(e), "code_expired");
}
#[test]
fn a_server_under_another_root_never_sees_the_secret() {
let ours = Ca::new();
let theirs = Ca::new();
// A server that presents a certificate from another Domi root, for the same address.
let impostor = mock(
&theirs,
server_cert(&theirs, now()),
vec![ReleaseKey::new().public()],
);
let mut secret = [0u8; 16];
secret[0] = 1;
let code = legatus_protocol::EnrollmentCode::new(&impostor.url, ours.root_sha256(), secret)
.unwrap()
.encode();
let dir = tempfile::tempdir().unwrap();
let e = legatus::enroll(&State::new(dir.path()), &code, false).unwrap_err();
assert!(
matches!(
e,
AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(_)))
),
"{e:?}"
);
assert!(
impostor.world.lock().unwrap().requests.is_empty(),
"no request reached the impostor"
);
}
#[test]
fn an_expired_server_certificate_is_refused() {
let ca = Ca::new();
let old = mock(
&ca,
server_cert(&ca, now() - 91 * DAY),
vec![ReleaseKey::new().public()],
);
let code = old.code(&ca, "web-1", DEPLOY, 3600);
let dir = tempfile::tempdir().unwrap();
let e = legatus::enroll(&State::new(dir.path()), &code, false).unwrap_err();
match e {
AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(m))) => {
assert!(m.to_lowercase().contains("expired"), "{m}")
}
other => panic!("{other:?}"),
}
assert!(old.world.lock().unwrap().requests.is_empty());
}
/// Replace the agent's certificate and key in its state (what an attacker with old or foreign
/// credentials would present).
fn swap_identity(st: &State, chain: &str, key: &str) {
st.save_identity(chain, key).unwrap();
}
#[test]
fn a_foreign_client_certificate_is_refused() {
let s = setup();
let st = s.enrolled();
let target = FakeTarget::new();
// An agent certificate from another Domi root, same ids: refused in the TLS handshake.
let other = Ca::new();
let (chain, key) = other.agent("acme", "web-1", now());
swap_identity(&st, &chain, &key);
let e = Session::open(st.clone())
.unwrap()
.hello(&target)
.unwrap_err();
assert!(
matches!(
e,
AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(_)))
),
"{e:?}"
);
// A phone's device certificate from our own root: through TLS, refused by the registry.
let dev = domi_pki::issue_device(&s.ca.ianitor, "phone", now()).unwrap();
swap_identity(&st, &dev.chain_pem, &dev.key_pem);
let e = Session::open(st.clone())
.unwrap()
.hello(&target)
.unwrap_err();
assert_eq!(refused_code(e), "certificate_refused");
// An agent of our root that was never enrolled here.
let (chain, key) = s.ca.agent("acme", "web-2", now());
swap_identity(&st, &chain, &key);
let e = Session::open(st).unwrap().hello(&target).unwrap_err();
assert_eq!(refused_code(e), "certificate_refused");
}
#[test]
fn an_expired_client_certificate_is_refused() {
let s = setup();
let st = s.enrolled();
let (chain, key) = s.ca.agent("acme", "web-1", now() - 31 * DAY);
swap_identity(&st, &chain, &key);
let e = Session::open(st)
.unwrap()
.hello(&FakeTarget::new())
.unwrap_err();
assert!(
matches!(
e,
AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(_)))
),
"{e:?}"
);
}
#[test]
fn a_replayed_client_certificate_is_refused() {
let s = setup();
let st = s.enrolled();
let target = FakeTarget::new();
let old = st.load().unwrap();
let mut session = Session::open(st.clone()).unwrap();
session.hello(&target).unwrap();
// Renew: a new key and certificate; once the new one is used, the old one is a replay.
assert!(session.renew_if_due(true).unwrap());
session.hello(&target).unwrap();
assert_ne!(st.load().unwrap().chain_pem, old.chain_pem);
swap_identity(&st, &old.chain_pem, &old.key_pem);
let e = Session::open(st).unwrap().hello(&target).unwrap_err();
assert_eq!(refused_code(e), "certificate_refused");
}
#[test]
fn no_certificate_no_service() {
let s = setup();
// Straight to hello without a client certificate (an enrollment-only TLS config).
let cfg =
legatus::tls::enroll_config(legatus::tls::PinnedRoot::by_hash(s.ca.root_sha256())).unwrap();
let f = legatus::client::Fabrica::new(&s.mock.url, cfg).unwrap();
let e = f.next_job(0).unwrap_err();
assert_eq!(e.code(), Some("certificate_required"));
}
#[test]
fn enrolling_twice_needs_force() {
let s = setup();
let st = s.enrolled();
let code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600);
assert!(matches!(
legatus::enroll(&st, &code, false),
Err(AgentError::AlreadyEnrolled(_))
));
legatus::enroll(&st, &code, true).unwrap();
}
#[test]
fn a_typo_in_the_code_never_reaches_the_network() {
let s = setup();
let mut code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600).into_bytes();
let i = code.len() / 2;
code[i] = if code[i] == b'a' { b'b' } else { b'a' };
let e = legatus::enroll(&s.state("x"), &String::from_utf8(code).unwrap(), false).unwrap_err();
assert!(matches!(e, AgentError::Code(_)), "{e:?}");
assert!(s.mock.world.lock().unwrap().requests.is_empty());
}
+305
View File
@@ -0,0 +1,305 @@
// 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 tampered artifact, a wrong key, a missing or
//! garbled signature, a release of something else: refused and reported, and the target is never
//! called. Also roles, replays and what the target's outcome becomes in the report.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use std::cell::RefCell;
use common::*;
use legatus::pipeline::{Context, handle};
use legatus_linux::Outcome;
use legatus_protocol::{JobGuard, Report, Roles, Status, Step};
const ART: &[u8] = b"pretend this is shop-1.4.0.tar.gz";
struct Run {
_dir: tempfile::TempDir,
ctx: Context,
guard: JobGuard,
key: ReleaseKey,
target: FakeTarget,
}
fn setup() -> Run {
let dir = tempfile::tempdir().unwrap();
let key = ReleaseKey::new();
let ctx = Context {
team: "acme".into(),
roles: Roles {
build: false,
deploy: true,
},
release_keys: vec![key.public()],
downloads: dir.path().join("downloads"),
};
Run {
_dir: dir,
ctx,
guard: JobGuard::new(),
key,
target: FakeTarget::new(),
}
}
impl Run {
fn go(&mut self, job: &[u8], served: &[u8]) -> (Vec<Report>, u32) {
let fetch = FakeFetch {
bytes: served.to_vec(),
fetched: RefCell::new(0),
};
let mut reports = Vec::new();
handle(
job,
now(),
&mut self.ctx,
&mut self.guard,
&fetch,
&self.target,
&mut |r| reports.push(r),
);
let n = *fetch.fetched.borrow();
(reports, n)
}
fn signed_job(&self, n: u8) -> Vec<u8> {
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", ART);
deploy_job(&job_id(n), "1.4.0", &m, &self.key.sign(m.as_bytes()))
}
fn untouched(&self) -> bool {
self.target.calls.borrow().is_empty()
}
fn no_leftovers(&self) -> bool {
std::fs::read_dir(&self.ctx.downloads)
.map(|d| d.count() == 0)
.unwrap_or(true)
}
}
fn last(r: &[Report]) -> &Report {
r.last().unwrap()
}
#[test]
fn a_signed_release_reaches_the_target_with_its_checked_bytes() {
let mut run = setup();
let (r, fetched) = run.go(&run.signed_job(1), ART);
assert_eq!(fetched, 1);
assert_eq!(r[0].status, Status::Accepted);
assert_eq!(last(&r).status, Status::Succeeded, "{r:?}");
assert_eq!(last(&r).deployed.as_ref().unwrap().version, "1.4.0");
let calls = run.target.calls.borrow();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].2, sha256_hex(ART));
assert_eq!(calls[0].3, ART);
drop(calls);
assert!(run.no_leftovers(), "the download is deleted after the job");
}
#[test]
fn a_tampered_artifact_is_refused() {
let mut run = setup();
let mut evil = ART.to_vec();
evil[5] ^= 1;
let (r, _) = run.go(&run.signed_job(1), &evil);
assert_eq!(last(&r).status, Status::Refused);
assert_eq!(last(&r).step, Some(Step::Download));
assert!(
last(&r).message.starts_with("tampered: "),
"{}",
last(&r).message
);
assert!(run.untouched());
assert!(run.no_leftovers());
// Longer than signed: refused too, and never more than one byte past the signed size is read.
let mut long = ART.to_vec();
long.extend_from_slice(&[0u8; 10_000]);
let (r, _) = run.go(&run.signed_job(2), &long);
assert!(
last(&r).message.starts_with("tampered: "),
"{}",
last(&r).message
);
assert!(run.untouched());
}
#[test]
fn a_wrong_key_is_refused_before_anything_is_downloaded() {
let mut run = setup();
let stranger = ReleaseKey::new();
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", ART);
let job = deploy_job(&job_id(1), "1.4.0", &m, &stranger.sign(m.as_bytes()));
let (r, fetched) = run.go(&job, ART);
assert_eq!(fetched, 0);
assert_eq!(r.len(), 1);
assert_eq!(r[0].status, Status::Refused);
assert_eq!(r[0].step, Some(Step::Verify));
assert!(
r[0].message.starts_with("unknown_key: "),
"{}",
r[0].message
);
assert!(run.untouched());
}
#[test]
fn a_missing_or_garbled_signature_is_refused() {
let mut run = setup();
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", ART);
let (r, fetched) = run.go(&deploy_job(&job_id(1), "1.4.0", &m, ""), ART);
assert!(r[0].message.starts_with("unsigned: "), "{}", r[0].message);
assert_eq!(fetched, 0);
let (r, fetched) = run.go(
&deploy_job(&job_id(2), "1.4.0", &m, "untrusted comment: x\nAAAA\n"),
ART,
);
assert!(
r[0].message.starts_with("bad_signature: "),
"{}",
r[0].message
);
assert_eq!(fetched, 0);
// A good signature over another manifest.
let other = manifest("acme", "shop", "1.4.0", "shop.tar.gz", b"other bytes");
let (r, _) = run.go(
&deploy_job(&job_id(3), "1.4.0", &m, &run.key.sign(other.as_bytes())),
ART,
);
assert!(
r[0].message.starts_with("bad_signature: "),
"{}",
r[0].message
);
assert!(run.untouched());
}
#[test]
fn a_signed_release_for_another_team_or_version_is_refused() {
let mut run = setup();
let m = manifest("globex", "shop", "1.4.0", "shop.tar.gz", ART);
let (r, _) = run.go(
&deploy_job(&job_id(1), "1.4.0", &m, &run.key.sign(m.as_bytes())),
ART,
);
assert!(
r[0].message.starts_with("wrong_release: "),
"{}",
r[0].message
);
// The job asks for 1.5.0 but carries 1.4.0's signed manifest (a downgrade in disguise).
let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", ART);
let (r, _) = run.go(
&deploy_job(&job_id(2), "1.5.0", &m, &run.key.sign(m.as_bytes())),
ART,
);
assert!(
r[0].message.starts_with("wrong_release: "),
"{}",
r[0].message
);
assert!(run.untouched());
}
#[test]
fn deploy_here_off_refuses_and_a_config_job_turns_it_on() {
let mut run = setup();
run.ctx.roles = Roles::default();
let (r, fetched) = run.go(&run.signed_job(1), ART);
assert!(r[0].message.starts_with("role_off: "), "{}", r[0].message);
assert_eq!(r[0].step, Some(Step::Role));
assert_eq!(fetched, 0);
let cfg = legatus_protocol::msg::job_json(
&job_id(2),
now(),
now() + 60,
&legatus_protocol::JobBody::Config(legatus_protocol::msg::ConfigJob {
roles: Roles {
build: false,
deploy: true,
},
}),
);
let (r, _) = run.go(&cfg, b"");
assert_eq!(r[0].status, Status::Succeeded);
assert!(run.ctx.roles.deploy);
let (r, _) = run.go(&run.signed_job(3), ART);
assert_eq!(last(&r).status, Status::Succeeded);
}
#[test]
fn a_replayed_job_is_refused() {
let mut run = setup();
let job = run.signed_job(1);
run.go(&job, ART);
let (r, fetched) = run.go(&job, ART);
assert_eq!(r.len(), 1);
assert!(r[0].message.starts_with("replayed: "), "{}", r[0].message);
assert_eq!(fetched, 0);
assert_eq!(
run.target.calls.borrow().len(),
1,
"deployed once, not twice"
);
}
#[test]
fn unknown_and_invalid_jobs_are_reported() {
let mut run = setup();
let unknown = format!(
r#"{{"v":1,"id":"{}","issued_at":{},"expires_at":{},"kind":"build","spec":{{}}}}"#,
job_id(1),
now(),
now() + 60
);
let (r, _) = run.go(unknown.as_bytes(), b"");
assert!(
r[0].message.starts_with("unsupported: "),
"{}",
r[0].message
);
let bad = String::from_utf8(run.signed_job(2))
.unwrap()
.replace(r#""unit":"shop.service""#, r#""unit":"../x""#);
let (r, _) = run.go(bad.as_bytes(), ART);
assert!(
r[0].message.starts_with("bad_request: "),
"{}",
r[0].message
);
// Garbage: no id, nothing to report to.
let (r, _) = run.go(b"{not json", ART);
assert!(r.is_empty());
assert!(run.untouched());
}
#[test]
fn the_targets_outcome_becomes_the_report() {
let mut run = setup();
*run.target.outcome.borrow_mut() = Ok(Outcome::RolledBack {
to: "1.3.0".into(),
healthy: true,
reason: "the health check did not pass within 5 s".into(),
});
let (r, _) = run.go(&run.signed_job(1), ART);
let l = last(&r);
assert_eq!(l.status, Status::Failed);
assert_eq!(l.rolled_back, Some(true));
assert_eq!(l.deployed.as_ref().unwrap().version, "1.3.0");
assert!(l.message.contains("rolled back to 1.3.0"), "{}", l.message);
*run.target.outcome.borrow_mut() = Err("archive".into());
let (r, _) = run.go(&run.signed_job(2), ART);
assert_eq!(last(&r).status, Status::Refused);
assert!(
last(&r).message.starts_with("bad_archive: "),
"{}",
last(&r).message
);
}