490 lines
16 KiB
Rust
490 lines
16 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/.
|
|
|
|
//! 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()
|
|
}
|
|
}
|