[repo] Merge: feature/v0.1 (Legatus v0.1: protocol v1, enrollment, mTLS, the signature check, the Linux target, PR #1)
This commit was merged in pull request #1.
This commit is contained in:
Generated
+1110
File diff suppressed because it is too large
Load Diff
+44
@@ -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 = { git = "https://gitea.marek-novak.cz/mnovak/domi-pki", tag = "v1.0.0" }
|
||||
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
|
||||
@@ -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
|
||||
@@ -0,0 +1,209 @@
|
||||
// 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 Fabrica server, as the agent talks to it (docs/02_protocol.md).
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use legatus_protocol::msg::{
|
||||
EnrollRequest, EnrollResponse, ErrorBody, Hello, HostFacts, RenewRequest, Renewed, V, Welcome,
|
||||
};
|
||||
use legatus_protocol::{EnrollmentCode, MAX_BODY, Report, decode, encode};
|
||||
use rustls::ClientConfig;
|
||||
|
||||
use crate::http::{self, HttpError, Server};
|
||||
use crate::tls::{self, PinnedRoot, TlsError};
|
||||
|
||||
/// Why a call failed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ClientError {
|
||||
/// The connection.
|
||||
#[error("{0}")]
|
||||
Http(#[from] HttpError),
|
||||
/// TLS could not be set up.
|
||||
#[error("{0}")]
|
||||
Tls(#[from] TlsError),
|
||||
/// The server said no.
|
||||
#[error("the server refused ({status} {code}): {message}")]
|
||||
Refused {
|
||||
/// HTTP status.
|
||||
status: u16,
|
||||
/// Stable code.
|
||||
code: String,
|
||||
/// Its message.
|
||||
message: String,
|
||||
},
|
||||
/// The server's answer is not what the protocol says.
|
||||
#[error("the server's answer cannot be used: {0}")]
|
||||
BadAnswer(String),
|
||||
}
|
||||
|
||||
impl ClientError {
|
||||
/// The stable code, when the server refused.
|
||||
pub fn code(&self) -> Option<&str> {
|
||||
match self {
|
||||
ClientError::Refused { code, .. } => Some(code),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(status: u16, body: &[u8]) -> ClientError {
|
||||
match serde_json::from_slice::<ErrorBody>(body) {
|
||||
Ok(e) => ClientError::Refused {
|
||||
status,
|
||||
code: e.error.chars().take(64).collect(),
|
||||
message: e.message.chars().take(500).collect(),
|
||||
},
|
||||
Err(_) => ClientError::Refused {
|
||||
status,
|
||||
code: "http".into(),
|
||||
message: String::from_utf8_lossy(body.get(..body.len().min(200)).unwrap_or_default())
|
||||
.into_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Enroll: send the code's secret and the CSR to the server the code names, trusting only the
|
||||
/// root the code pins.
|
||||
pub fn enroll(
|
||||
code: &EnrollmentCode,
|
||||
csr_pem: &str,
|
||||
host: HostFacts,
|
||||
) -> Result<EnrollResponse, ClientError> {
|
||||
let server = Server::parse(code.server())?;
|
||||
let cfg = tls::enroll_config(PinnedRoot::by_hash(*code.root_sha256()))?;
|
||||
let body = encode(&EnrollRequest {
|
||||
v: V,
|
||||
secret: code.secret_hex(),
|
||||
csr: csr_pem.to_owned(),
|
||||
host,
|
||||
});
|
||||
let r = http::request(
|
||||
&cfg,
|
||||
&server,
|
||||
"POST",
|
||||
"/legatus/v1/enroll",
|
||||
Some(&body),
|
||||
MAX_BODY as u64,
|
||||
TIMEOUT,
|
||||
)?;
|
||||
if r.status != 200 {
|
||||
return Err(refused(r.status, &r.body));
|
||||
}
|
||||
decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string()))
|
||||
}
|
||||
|
||||
/// The server, over mTLS.
|
||||
#[derive(Clone)]
|
||||
pub struct Fabrica {
|
||||
server: Server,
|
||||
cfg: Arc<ClientConfig>,
|
||||
}
|
||||
|
||||
impl Fabrica {
|
||||
/// A client for `server` with this mTLS configuration.
|
||||
pub fn new(server_url: &str, cfg: Arc<ClientConfig>) -> Result<Fabrica, ClientError> {
|
||||
Ok(Fabrica {
|
||||
server: Server::parse(server_url)?,
|
||||
cfg,
|
||||
})
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&[u8]>,
|
||||
timeout: Duration,
|
||||
) -> Result<http::Response, ClientError> {
|
||||
Ok(http::request(
|
||||
&self.cfg,
|
||||
&self.server,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
MAX_BODY as u64,
|
||||
timeout,
|
||||
)?)
|
||||
}
|
||||
|
||||
/// `POST hello`.
|
||||
pub fn hello(&self, hello: &Hello) -> Result<Welcome, ClientError> {
|
||||
let r = self.call("POST", "/legatus/v1/hello", Some(&encode(hello)), TIMEOUT)?;
|
||||
if r.status != 200 {
|
||||
return Err(refused(r.status, &r.body));
|
||||
}
|
||||
decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string()))
|
||||
}
|
||||
|
||||
/// `GET jobs?wait=`: the next job's bytes, or `None`.
|
||||
pub fn next_job(&self, wait_seconds: u32) -> Result<Option<Vec<u8>>, ClientError> {
|
||||
let wait = wait_seconds.min(55);
|
||||
let path = format!("/legatus/v1/jobs?wait={wait}");
|
||||
let r = self.call(
|
||||
"GET",
|
||||
&path,
|
||||
None,
|
||||
Duration::from_secs(u64::from(wait) + 20),
|
||||
)?;
|
||||
match r.status {
|
||||
200 => Ok(Some(r.body)),
|
||||
204 => Ok(None),
|
||||
s => Err(refused(s, &r.body)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST reports`.
|
||||
pub fn report(&self, report: &Report) -> Result<(), ClientError> {
|
||||
let r = self.call(
|
||||
"POST",
|
||||
"/legatus/v1/reports",
|
||||
Some(&encode(report)),
|
||||
TIMEOUT,
|
||||
)?;
|
||||
match r.status {
|
||||
200 | 202 | 204 => Ok(()),
|
||||
s => Err(refused(s, &r.body)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST renew`.
|
||||
pub fn renew(&self, csr_pem: &str) -> Result<Renewed, ClientError> {
|
||||
let body = encode(&RenewRequest {
|
||||
v: V,
|
||||
csr: csr_pem.to_owned(),
|
||||
});
|
||||
let r = self.call("POST", "/legatus/v1/renew", Some(&body), TIMEOUT)?;
|
||||
if r.status != 200 {
|
||||
return Err(refused(r.status, &r.body));
|
||||
}
|
||||
decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string()))
|
||||
}
|
||||
|
||||
/// `GET artifacts/<job>/<name>` into `out`, at most `max` bytes.
|
||||
pub fn artifact(
|
||||
&self,
|
||||
job: &str,
|
||||
name: &str,
|
||||
max: u64,
|
||||
out: &mut dyn Write,
|
||||
) -> Result<u64, ClientError> {
|
||||
let path = format!("/legatus/v1/artifacts/{job}/{name}");
|
||||
let timeout = Duration::from_secs(300);
|
||||
let (status, n) = http::download(&self.cfg, &self.server, &path, max, out, timeout)?;
|
||||
if status != 200 {
|
||||
return Err(ClientError::Refused {
|
||||
status,
|
||||
code: "download".into(),
|
||||
message: "the artifact could not be downloaded".into(),
|
||||
});
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
// 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 small HTTP/1.1 client over rustls: one request per connection, bodies framed by
|
||||
//! `Content-Length` or chunked encoding, every size bounded. The server's answers are hostile.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use rustls::{ClientConfig, ClientConnection, StreamOwned};
|
||||
use rustls_pki_types::ServerName;
|
||||
|
||||
const MAX_HEAD: usize = 16 * 1024;
|
||||
|
||||
/// Why a request failed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum HttpError {
|
||||
/// The server address.
|
||||
#[error("the server address cannot be used: {0}")]
|
||||
Address(String),
|
||||
/// Could not connect.
|
||||
#[error("cannot reach the Fabrica server: {0}")]
|
||||
Connect(String),
|
||||
/// TLS failed (often: the server is not the one the code names, or a certificate is refused).
|
||||
#[error("the secure connection failed: {0}")]
|
||||
Tls(String),
|
||||
/// The answer is not HTTP as expected.
|
||||
#[error("the server's answer cannot be read: {0}")]
|
||||
Protocol(String),
|
||||
/// The body is larger than allowed.
|
||||
#[error("the server's answer is too large")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// `https://host[:port]`, split.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Server {
|
||||
host: String,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Parse a server URL as an enrollment code carries it.
|
||||
pub fn parse(url: &str) -> Result<Server, HttpError> {
|
||||
let bad = || HttpError::Address(url.chars().take(100).collect());
|
||||
let auth = url.strip_prefix("https://").ok_or_else(bad)?;
|
||||
let (host, port) = if let Some(rest) = auth.strip_prefix('[') {
|
||||
let (h, after) = rest.split_once(']').ok_or_else(bad)?;
|
||||
match after.strip_prefix(':') {
|
||||
Some(p) => (h, Some(p)),
|
||||
None if after.is_empty() => (h, None),
|
||||
None => return Err(bad()),
|
||||
}
|
||||
} else {
|
||||
match auth.split_once(':') {
|
||||
Some((h, p)) => (h, Some(p)),
|
||||
None => (auth, None),
|
||||
}
|
||||
};
|
||||
let port = match port {
|
||||
Some(p) => p.parse::<u16>().map_err(|_| bad())?,
|
||||
None => 443,
|
||||
};
|
||||
if host.is_empty() || host.contains('/') {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(Server {
|
||||
host: host.to_owned(),
|
||||
port,
|
||||
})
|
||||
}
|
||||
|
||||
/// Host name or address.
|
||||
pub fn host(&self) -> &str {
|
||||
&self.host
|
||||
}
|
||||
|
||||
/// Port.
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
fn host_header(&self) -> String {
|
||||
let h = if self.host.contains(':') {
|
||||
format!("[{}]", self.host)
|
||||
} else {
|
||||
self.host.clone()
|
||||
};
|
||||
if self.port == 443 {
|
||||
h
|
||||
} else {
|
||||
format!("{h}:{}", self.port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Tls = StreamOwned<ClientConnection, TcpStream>;
|
||||
|
||||
fn open(cfg: &Arc<ClientConfig>, server: &Server, timeout: Duration) -> Result<Tls, HttpError> {
|
||||
let name = ServerName::try_from(server.host.clone())
|
||||
.map_err(|_| HttpError::Address(server.host.clone()))?;
|
||||
let addr = (server.host.as_str(), server.port)
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| HttpError::Connect(e.to_string()))?
|
||||
.next()
|
||||
.ok_or_else(|| HttpError::Connect("no address".into()))?;
|
||||
let tcp = TcpStream::connect_timeout(&addr, Duration::from_secs(10))
|
||||
.map_err(|e| HttpError::Connect(e.to_string()))?;
|
||||
tcp.set_read_timeout(Some(timeout))
|
||||
.and_then(|()| tcp.set_write_timeout(Some(timeout)))
|
||||
.map_err(|e| HttpError::Connect(e.to_string()))?;
|
||||
let conn =
|
||||
ClientConnection::new(cfg.clone(), name).map_err(|e| HttpError::Tls(e.to_string()))?;
|
||||
let mut s = StreamOwned::new(conn, tcp);
|
||||
// Finish the handshake now, so TLS refusals are reported as such.
|
||||
while s.conn.is_handshaking() {
|
||||
s.conn
|
||||
.complete_io(&mut s.sock)
|
||||
.map_err(|e| HttpError::Tls(tls_reason(&e)))?;
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn tls_reason(e: &io::Error) -> String {
|
||||
match e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>()) {
|
||||
Some(r) => r.to_string(),
|
||||
None => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn io_err(e: io::Error) -> HttpError {
|
||||
if e.get_ref().is_some_and(|i| i.is::<rustls::Error>()) {
|
||||
HttpError::Tls(tls_reason(&e))
|
||||
} else {
|
||||
HttpError::Protocol(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
struct Head {
|
||||
status: u16,
|
||||
framing: Framing,
|
||||
rest: Vec<u8>,
|
||||
}
|
||||
|
||||
enum Framing {
|
||||
Length(u64),
|
||||
Chunked,
|
||||
}
|
||||
|
||||
fn send(
|
||||
s: &mut Tls,
|
||||
server: &Server,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&[u8]>,
|
||||
) -> Result<Head, HttpError> {
|
||||
let mut req = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: {}\r\nUser-Agent: legatus/{}\r\nAccept: application/json\r\nConnection: close\r\n",
|
||||
server.host_header(),
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!(
|
||||
"Content-Type: application/json\r\nContent-Length: {}\r\n",
|
||||
b.len()
|
||||
));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
s.write_all(req.as_bytes()).map_err(io_err)?;
|
||||
if let Some(b) = body {
|
||||
s.write_all(b).map_err(io_err)?;
|
||||
}
|
||||
s.flush().map_err(io_err)?;
|
||||
read_head(s)
|
||||
}
|
||||
|
||||
fn read_head(s: &mut Tls) -> Result<Head, HttpError> {
|
||||
let mut buf = Vec::with_capacity(1024);
|
||||
let mut chunk = [0u8; 2048];
|
||||
loop {
|
||||
let n = s.read(&mut chunk).map_err(io_err)?;
|
||||
if n == 0 {
|
||||
return Err(HttpError::Protocol("the connection closed early".into()));
|
||||
}
|
||||
buf.extend_from_slice(chunk.get(..n).unwrap_or_default());
|
||||
let mut headers = [httparse::EMPTY_HEADER; 64];
|
||||
let mut resp = httparse::Response::new(&mut headers);
|
||||
match resp.parse(&buf) {
|
||||
Ok(httparse::Status::Complete(len)) => {
|
||||
let status = resp
|
||||
.code
|
||||
.ok_or_else(|| HttpError::Protocol("no status".into()))?;
|
||||
let mut framing = None;
|
||||
for h in resp.headers.iter() {
|
||||
let v = std::str::from_utf8(h.value).unwrap_or("").trim();
|
||||
if h.name.eq_ignore_ascii_case("content-length") {
|
||||
let n = v
|
||||
.parse::<u64>()
|
||||
.map_err(|_| HttpError::Protocol("bad Content-Length".into()))?;
|
||||
if matches!(framing, Some(Framing::Length(m)) if m != n) {
|
||||
return Err(HttpError::Protocol("two Content-Lengths".into()));
|
||||
}
|
||||
framing.get_or_insert(Framing::Length(n));
|
||||
} else if h.name.eq_ignore_ascii_case("transfer-encoding") {
|
||||
if !v.eq_ignore_ascii_case("chunked") {
|
||||
return Err(HttpError::Protocol("unknown transfer encoding".into()));
|
||||
}
|
||||
framing = Some(Framing::Chunked);
|
||||
}
|
||||
}
|
||||
let framing = match framing {
|
||||
Some(f) => f,
|
||||
None if status == 204 || status == 304 => Framing::Length(0),
|
||||
None => return Err(HttpError::Protocol("no body length".into())),
|
||||
};
|
||||
return Ok(Head {
|
||||
status,
|
||||
framing,
|
||||
rest: buf.get(len..).unwrap_or_default().to_vec(),
|
||||
});
|
||||
}
|
||||
Ok(httparse::Status::Partial) if buf.len() < MAX_HEAD => {}
|
||||
Ok(httparse::Status::Partial) => return Err(HttpError::TooLarge),
|
||||
Err(e) => return Err(HttpError::Protocol(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the body after `head` into `out`, at most `max` bytes.
|
||||
fn read_body(s: &mut Tls, head: Head, max: u64, out: &mut dyn Write) -> Result<u64, HttpError> {
|
||||
let mut src = io::Cursor::new(head.rest).chain(s);
|
||||
match head.framing {
|
||||
Framing::Length(n) => {
|
||||
if n > max {
|
||||
return Err(HttpError::TooLarge);
|
||||
}
|
||||
let got = io::copy(&mut (&mut src).take(n), out).map_err(io_err)?;
|
||||
if got != n {
|
||||
return Err(HttpError::Protocol("the body was cut short".into()));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
Framing::Chunked => {
|
||||
let mut total = 0u64;
|
||||
loop {
|
||||
let line = read_line(&mut src)?;
|
||||
let size_text = line.split(';').next().unwrap_or("").trim();
|
||||
if size_text.is_empty() || size_text.len() > 16 {
|
||||
return Err(HttpError::Protocol("bad chunk size".into()));
|
||||
}
|
||||
let size = u64::from_str_radix(size_text, 16)
|
||||
.map_err(|_| HttpError::Protocol("bad chunk size".into()))?;
|
||||
if size == 0 {
|
||||
// Trailers, then the empty line.
|
||||
for _ in 0..64 {
|
||||
if read_line(&mut src)?.is_empty() {
|
||||
return Ok(total);
|
||||
}
|
||||
}
|
||||
return Err(HttpError::Protocol("too many trailers".into()));
|
||||
}
|
||||
total = total.saturating_add(size);
|
||||
if total > max {
|
||||
return Err(HttpError::TooLarge);
|
||||
}
|
||||
let got = io::copy(&mut (&mut src).take(size), out).map_err(io_err)?;
|
||||
if got != size || !read_line(&mut src)?.is_empty() {
|
||||
return Err(HttpError::Protocol("a chunk was cut short".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_line(r: &mut impl Read) -> Result<String, HttpError> {
|
||||
let mut line = Vec::new();
|
||||
let mut b = [0u8; 1];
|
||||
loop {
|
||||
let n = r.read(&mut b).map_err(io_err)?;
|
||||
if n == 0 {
|
||||
return Err(HttpError::Protocol("the connection closed early".into()));
|
||||
}
|
||||
if b[0] == b'\n' {
|
||||
if line.last() == Some(&b'\r') {
|
||||
line.pop();
|
||||
}
|
||||
return String::from_utf8(line).map_err(|_| HttpError::Protocol("not text".into()));
|
||||
}
|
||||
line.push(b[0]);
|
||||
if line.len() > 1024 {
|
||||
return Err(HttpError::TooLarge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A response: its status and body.
|
||||
#[derive(Debug)]
|
||||
pub struct Response {
|
||||
/// HTTP status.
|
||||
pub status: u16,
|
||||
/// The body.
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One request: `body` as JSON, the answer at most `max` bytes.
|
||||
pub fn request(
|
||||
cfg: &Arc<ClientConfig>,
|
||||
server: &Server,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&[u8]>,
|
||||
max: u64,
|
||||
timeout: Duration,
|
||||
) -> Result<Response, HttpError> {
|
||||
let mut s = open(cfg, server, timeout)?;
|
||||
let head = send(&mut s, server, method, path, body)?;
|
||||
let status = head.status;
|
||||
let mut out = Vec::new();
|
||||
read_body(&mut s, head, max, &mut out)?;
|
||||
Ok(Response { status, body: out })
|
||||
}
|
||||
|
||||
/// A GET whose body (when the status is 200) is written to `out`, at most `max` bytes. Returns
|
||||
/// the status and the bytes written; any other status's body is returned as an error message.
|
||||
pub fn download(
|
||||
cfg: &Arc<ClientConfig>,
|
||||
server: &Server,
|
||||
path: &str,
|
||||
max: u64,
|
||||
out: &mut dyn Write,
|
||||
timeout: Duration,
|
||||
) -> Result<(u16, u64), HttpError> {
|
||||
let mut s = open(cfg, server, timeout)?;
|
||||
let head = send(&mut s, server, "GET", path, None)?;
|
||||
let status = head.status;
|
||||
if status != 200 {
|
||||
let mut sink = Vec::new();
|
||||
let _ = read_body(&mut s, head, 64 * 1024, &mut sink);
|
||||
return Ok((status, 0));
|
||||
}
|
||||
let n = read_body(&mut s, head, max, out)?;
|
||||
Ok((status, n))
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// 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/.
|
||||
|
||||
//! Legatus, the Fabrica Domi agent (docs/01_legatus.md): enroll with a one-time code, then
|
||||
//! long-poll the Fabrica server over mTLS for jobs, and run them only when the release is signed
|
||||
//! by the team.
|
||||
|
||||
pub mod client;
|
||||
pub mod http;
|
||||
pub mod pipeline;
|
||||
pub mod state;
|
||||
pub mod target;
|
||||
pub mod tls;
|
||||
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use legatus_protocol::msg::{Capabilities, Hello, HostFacts, V, Welcome};
|
||||
use legatus_protocol::{EnrollmentCode, JobGuard};
|
||||
|
||||
use crate::client::{ClientError, Fabrica};
|
||||
use crate::pipeline::{Context, Fetch, Target};
|
||||
use crate::state::{AgentFile, Enrolled, State, StateError};
|
||||
use crate::tls::PinnedRoot;
|
||||
|
||||
/// This Legatus's version.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Unix seconds now.
|
||||
pub fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Why the agent stopped or refused.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AgentError {
|
||||
/// The code.
|
||||
#[error("{0}")]
|
||||
Code(#[from] legatus_protocol::CodeError),
|
||||
/// The server.
|
||||
#[error("{0}")]
|
||||
Client(#[from] ClientError),
|
||||
/// The state dir.
|
||||
#[error("{0}")]
|
||||
State(#[from] StateError),
|
||||
/// TLS.
|
||||
#[error("{0}")]
|
||||
Tls(#[from] tls::TlsError),
|
||||
/// The CA.
|
||||
#[error("{0}")]
|
||||
Pki(#[from] domi_pki::PkiError),
|
||||
/// Already enrolled.
|
||||
#[error("this machine is already enrolled as {0}; use --force to enroll again")]
|
||||
AlreadyEnrolled(String),
|
||||
/// The server's answer does not hold up.
|
||||
#[error("the server's answer cannot be trusted: {0}")]
|
||||
Untrusted(String),
|
||||
}
|
||||
|
||||
/// This machine.
|
||||
pub fn host_facts() -> HostFacts {
|
||||
let hostname = std::env::var("HOSTNAME")
|
||||
.ok()
|
||||
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
|
||||
.or_else(|| std::env::var("COMPUTERNAME").ok())
|
||||
.unwrap_or_else(|| "unknown".into());
|
||||
HostFacts {
|
||||
hostname: hostname.trim().chars().take(64).collect(),
|
||||
os: std::env::consts::OS.into(),
|
||||
arch: std::env::consts::ARCH.into(),
|
||||
version: VERSION.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn chain_der(pem: &str) -> Result<Vec<Vec<u8>>, AgentError> {
|
||||
domi_pki::chain_der(pem).map_err(|e| AgentError::Untrusted(e.to_string()))
|
||||
}
|
||||
|
||||
/// Enroll this machine with a pasted code. The key is made here and never leaves; the server
|
||||
/// must chain to the pinned root; what it sends back is checked before anything is saved.
|
||||
pub fn enroll(state: &State, code_text: &str, force: bool) -> Result<AgentFile, AgentError> {
|
||||
let code = EnrollmentCode::parse(code_text)?;
|
||||
if state.is_enrolled() && !force {
|
||||
let who = state
|
||||
.load()
|
||||
.map(|e| format!("{}/{}", e.file.team, e.file.agent))
|
||||
.unwrap_or_else(|_| "an agent".into());
|
||||
return Err(AgentError::AlreadyEnrolled(who));
|
||||
}
|
||||
let key = domi_pki::generate_key()?;
|
||||
let csr = domi_pki::agent_csr(&key, "legatus")?;
|
||||
let resp = client::enroll(&code, &csr, host_facts())?;
|
||||
// The root must be the one the code pins.
|
||||
let roots = chain_der(&resp.root)?;
|
||||
let [root_der] = roots.as_slice() else {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the root is not one certificate".into(),
|
||||
));
|
||||
};
|
||||
if PinnedRoot::with_der(*code.root_sha256(), root_der.clone()).is_none() {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the root is not the one in the code".into(),
|
||||
));
|
||||
}
|
||||
// The certificate must be an agent certificate for our own key, under that root.
|
||||
let chain = chain_der(&resp.chain)?;
|
||||
let id = domi_pki::verify_agent(&chain, root_der, now())
|
||||
.map_err(|e| AgentError::Untrusted(format!("the agent certificate: {e}")))?;
|
||||
if id.team != resp.team || id.agent != resp.agent {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the certificate names another agent".into(),
|
||||
));
|
||||
}
|
||||
if domi_pki::public_key_der(&resp.chain)? != key.public_key_der() {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the certificate is not for this machine's key".into(),
|
||||
));
|
||||
}
|
||||
if resp.release_keys.is_empty() || resp.release_keys.len() > 8 {
|
||||
return Err(AgentError::Untrusted(
|
||||
"1 to 8 release keys are needed".into(),
|
||||
));
|
||||
}
|
||||
for k in &resp.release_keys {
|
||||
if minisign_key_ok(k).is_none() {
|
||||
return Err(AgentError::Untrusted("a release key cannot be read".into()));
|
||||
}
|
||||
}
|
||||
let file = AgentFile {
|
||||
v: V,
|
||||
server: code.server().to_owned(),
|
||||
team: resp.team.clone(),
|
||||
agent: resp.agent.clone(),
|
||||
roles: resp.roles,
|
||||
release_keys: resp.release_keys.clone(),
|
||||
root_sha256: legatus_protocol::hex(code.root_sha256()),
|
||||
poll_seconds: resp.poll_seconds.clamp(5, 55),
|
||||
};
|
||||
state.save_enrollment(&file, &resp.root, &resp.chain, &key.serialize_pem())?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn minisign_key_ok(k: &str) -> Option<()> {
|
||||
// `Ed` + 8-byte id + 32-byte key, base64.
|
||||
let k = k.trim();
|
||||
(k.len() == 56 && k.starts_with("RW")).then_some(())
|
||||
}
|
||||
|
||||
/// An enrolled agent's connection to Fabrica.
|
||||
pub struct Session {
|
||||
state: State,
|
||||
enrolled: Enrolled,
|
||||
fabrica: Fabrica,
|
||||
ctx: Context,
|
||||
guard: JobGuard,
|
||||
}
|
||||
|
||||
fn pinned(e: &Enrolled) -> Result<PinnedRoot, AgentError> {
|
||||
let mut sha = [0u8; 32];
|
||||
let raw = (0..32)
|
||||
.map(|i| u8::from_str_radix(e.file.root_sha256.get(2 * i..2 * i + 2).unwrap_or("zz"), 16))
|
||||
.collect::<Result<Vec<u8>, _>>()
|
||||
.map_err(|_| AgentError::Untrusted("the pinned root".into()))?;
|
||||
sha.copy_from_slice(&raw);
|
||||
PinnedRoot::with_der(sha, e.root_der.clone())
|
||||
.ok_or_else(|| AgentError::Untrusted("the pinned root".into()))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Load the state and set up mTLS.
|
||||
pub fn open(state: State) -> Result<Session, AgentError> {
|
||||
let enrolled = state.load()?;
|
||||
let cfg = tls::agent_config(pinned(&enrolled)?, &enrolled.chain_pem, &enrolled.key_pem)?;
|
||||
let fabrica = Fabrica::new(&enrolled.file.server, cfg)?;
|
||||
let ctx = Context {
|
||||
team: enrolled.file.team.clone(),
|
||||
roles: enrolled.file.roles,
|
||||
release_keys: enrolled.file.release_keys.clone(),
|
||||
downloads: state.downloads(),
|
||||
};
|
||||
let guard = state.load_guard()?;
|
||||
Ok(Session {
|
||||
state,
|
||||
enrolled,
|
||||
fabrica,
|
||||
ctx,
|
||||
guard,
|
||||
})
|
||||
}
|
||||
|
||||
/// Who this agent is: `team/agent`.
|
||||
pub fn who(&self) -> String {
|
||||
format!("{}/{}", self.enrolled.file.team, self.enrolled.file.agent)
|
||||
}
|
||||
|
||||
/// The current roles.
|
||||
pub fn roles(&self) -> legatus_protocol::Roles {
|
||||
self.ctx.roles
|
||||
}
|
||||
|
||||
/// `hello`: say what this machine is and runs; take the roles Fabrica holds.
|
||||
pub fn hello(&mut self, target: &dyn Target) -> Result<Welcome, AgentError> {
|
||||
let h = host_facts();
|
||||
let w = self.fabrica.hello(&Hello {
|
||||
v: V,
|
||||
version: VERSION.into(),
|
||||
os: h.os,
|
||||
arch: h.arch,
|
||||
hostname: h.hostname,
|
||||
capabilities: Capabilities {
|
||||
deploy: target.kinds(),
|
||||
build: Vec::new(),
|
||||
},
|
||||
deployed: target.deployed(),
|
||||
})?;
|
||||
if w.team != self.enrolled.file.team || w.agent != self.enrolled.file.agent {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the server greets another agent".into(),
|
||||
));
|
||||
}
|
||||
self.set_roles(w.roles)?;
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
fn set_roles(&mut self, roles: legatus_protocol::Roles) -> Result<(), AgentError> {
|
||||
if self.enrolled.file.roles != roles {
|
||||
self.enrolled.file.roles = roles;
|
||||
self.ctx.roles = roles;
|
||||
self.state.save_file(&self.enrolled.file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait for one job (long poll) and handle it. `true` when there was one.
|
||||
pub fn poll_once(&mut self, target: &dyn Target) -> Result<bool, AgentError> {
|
||||
let Some(bytes) = self.fabrica.next_job(self.enrolled.file.poll_seconds)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fabrica = self.fabrica.clone();
|
||||
let mut send = |r: legatus_protocol::Report| {
|
||||
if let Err(e) = fabrica.report(&r) {
|
||||
eprintln!("legatus: a report for job {} was not delivered: {e}", r.job);
|
||||
}
|
||||
};
|
||||
let done = pipeline::handle(
|
||||
&bytes,
|
||||
now(),
|
||||
&mut self.ctx,
|
||||
&mut self.guard,
|
||||
&self.fabrica,
|
||||
target,
|
||||
&mut send,
|
||||
);
|
||||
if done.guard_changed {
|
||||
self.state.save_guard(&self.guard)?;
|
||||
}
|
||||
if done.roles_changed {
|
||||
let roles = self.ctx.roles;
|
||||
self.enrolled.file.roles = roles;
|
||||
self.state.save_file(&self.enrolled.file)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Renew the certificate when it is due (or `force`): a new key, a CSR, the new chain checked
|
||||
/// and stored, mTLS set up again. `true` when renewed.
|
||||
pub fn renew_if_due(&mut self, force: bool) -> Result<bool, AgentError> {
|
||||
let leaf = domi_pki::inspect(&self.enrolled.chain_pem)?;
|
||||
if !force && !domi_pki::agent_renewal_due(leaf.not_after, now()) {
|
||||
return Ok(false);
|
||||
}
|
||||
let key = domi_pki::generate_key()?;
|
||||
let csr = domi_pki::agent_csr(&key, "legatus")?;
|
||||
let r = self.fabrica.renew(&csr)?;
|
||||
let chain = chain_der(&r.chain)?;
|
||||
let id = domi_pki::verify_agent(&chain, &self.enrolled.root_der, now())
|
||||
.map_err(|e| AgentError::Untrusted(format!("the renewed certificate: {e}")))?;
|
||||
if id.team != self.enrolled.file.team || id.agent != self.enrolled.file.agent {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the renewed certificate names another agent".into(),
|
||||
));
|
||||
}
|
||||
if domi_pki::public_key_der(&r.chain)? != key.public_key_der() {
|
||||
return Err(AgentError::Untrusted(
|
||||
"the renewed certificate is not for the new key".into(),
|
||||
));
|
||||
}
|
||||
let key_pem = key.serialize_pem();
|
||||
self.state.save_identity(&r.chain, &key_pem)?;
|
||||
let cfg = tls::agent_config(pinned(&self.enrolled)?, &r.chain, &key_pem)?;
|
||||
self.fabrica = Fabrica::new(&self.enrolled.file.server, cfg)?;
|
||||
self.enrolled.chain_pem = r.chain;
|
||||
self.enrolled.key_pem = key_pem;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl Fetch for Fabrica {
|
||||
fn fetch(
|
||||
&self,
|
||||
job: &str,
|
||||
name: &str,
|
||||
max: u64,
|
||||
out: &mut dyn std::io::Write,
|
||||
) -> Result<u64, String> {
|
||||
self.artifact(job, name, max, out)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Run until stopped: hello, then jobs; reconnect with back-off on errors.
|
||||
pub fn run(state: State, target: &dyn Target) -> Result<(), AgentError> {
|
||||
let mut backoff = Duration::from_secs(5);
|
||||
loop {
|
||||
let mut s = match Session::open(state.clone()) {
|
||||
Ok(s) => s,
|
||||
// Not enrolled or damaged state: stop; systemd shows why.
|
||||
Err(e @ (AgentError::State(_) | AgentError::Tls(_) | AgentError::Untrusted(_))) => {
|
||||
return Err(e);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("legatus: {e}");
|
||||
std::thread::sleep(backoff);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = (|| -> Result<(), AgentError> {
|
||||
let w = s.hello(target)?;
|
||||
eprintln!(
|
||||
"legatus: connected as {}; build {}, deploy {}",
|
||||
s.who(),
|
||||
if w.roles.build { "on" } else { "off" },
|
||||
if w.roles.deploy { "on" } else { "off" }
|
||||
);
|
||||
s.renew_if_due(w.renew)?;
|
||||
loop {
|
||||
s.poll_once(target)?;
|
||||
s.renew_if_due(false)?;
|
||||
}
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
eprintln!("legatus: {e}; trying again in {} s", backoff.as_secs());
|
||||
std::thread::sleep(backoff);
|
||||
backoff = (backoff * 2).min(Duration::from_secs(60));
|
||||
} else {
|
||||
backoff = Duration::from_secs(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// 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/.
|
||||
|
||||
//! `legatus`: enroll, run, status.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use legatus::state::{State, default_dir};
|
||||
use legatus::target::Linux;
|
||||
|
||||
const USAGE: &str = "legatus: the Fabrica Domi agent
|
||||
|
||||
usage:
|
||||
legatus enroll <code> [--force] enroll this machine with the one-time code from Fabrica
|
||||
legatus run connect to Fabrica and run jobs (the systemd service runs this)
|
||||
legatus status who this agent is and what runs here
|
||||
legatus version
|
||||
|
||||
options:
|
||||
--state <dir> state dir (default /var/lib/legatus, or $LEGATUS_STATE)
|
||||
--apps <dir> where releases go (default /var/lib/legatus/apps)
|
||||
";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut take = |flag: &str| -> Option<String> {
|
||||
let i = args.iter().position(|a| a == flag)?;
|
||||
args.remove(i);
|
||||
(i < args.len()).then(|| args.remove(i))
|
||||
};
|
||||
let state = State::new(
|
||||
take("--state")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(default_dir),
|
||||
);
|
||||
let apps = take("--apps")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(legatus_linux::DEFAULT_ROOT));
|
||||
let force = match args.iter().position(|a| a == "--force") {
|
||||
Some(i) => {
|
||||
args.remove(i);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
let words: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
match words.as_slice() {
|
||||
["enroll", code] => match legatus::enroll(&state, code, force) {
|
||||
Ok(f) => {
|
||||
println!(
|
||||
"Enrolled as {}/{} with {}. Build here: {}. Deploy here: {}.",
|
||||
f.team,
|
||||
f.agent,
|
||||
f.server,
|
||||
if f.roles.build { "on" } else { "off" },
|
||||
if f.roles.deploy { "on" } else { "off" }
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("legatus: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
["run"] => {
|
||||
let target = Linux::new(apps);
|
||||
match legatus::run(state, &target) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("legatus: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
["status"] => match state.load() {
|
||||
Ok(e) => {
|
||||
let leaf = domi_pki::inspect(&e.chain_pem).ok();
|
||||
println!("agent {}/{}", e.file.team, e.file.agent);
|
||||
println!("server {}", e.file.server);
|
||||
println!(
|
||||
"roles build {}, deploy {}",
|
||||
e.file.roles.build, e.file.roles.deploy
|
||||
);
|
||||
if let Some(l) = leaf {
|
||||
println!("certificate valid until {} (unix)", l.not_after);
|
||||
}
|
||||
println!("release keys pinned: {}", e.file.release_keys.len());
|
||||
for d in legatus::pipeline::Target::deployed(&Linux::new(apps)) {
|
||||
println!("running {} {}", d.app, d.version);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("legatus: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
["version"] | ["--version"] => {
|
||||
println!("legatus {}", legatus::VERSION);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
_ => {
|
||||
eprint!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
// 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/.
|
||||
|
||||
//! One job, start to end: guard, role, signature and manifest, download, size and SHA-256, and
|
||||
//! only then the target. Every refusal is reported; nothing unsigned reaches a target.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use legatus_linux::{DeployError, Outcome, UnpackError};
|
||||
use legatus_protocol::msg::{DeployJob, Deployed, Target as JobTarget};
|
||||
use legatus_protocol::{
|
||||
Expected, JobBody, JobGuard, Report, Roles, Status, Step, check_artifact, parse_job,
|
||||
verify_release,
|
||||
};
|
||||
|
||||
/// Where artifacts come from (the Fabrica server over mTLS; a fake in tests).
|
||||
pub trait Fetch {
|
||||
/// Write the artifact `name` of job `job` into `out`, at most `max` bytes; the bytes written.
|
||||
fn fetch(&self, job: &str, name: &str, max: u64, out: &mut dyn Write) -> Result<u64, String>;
|
||||
}
|
||||
|
||||
/// A place releases go (the Linux backend; a fake in tests).
|
||||
pub trait Target {
|
||||
/// Target kinds it handles (`linux`).
|
||||
fn kinds(&self) -> Vec<String>;
|
||||
/// Deploy an artifact that already matches the signed manifest.
|
||||
fn deploy(
|
||||
&self,
|
||||
job: &DeployJob,
|
||||
artifact: &Path,
|
||||
sha256: &str,
|
||||
) -> Result<Outcome, DeployError>;
|
||||
/// What runs here.
|
||||
fn deployed(&self) -> Vec<Deployed>;
|
||||
}
|
||||
|
||||
/// What the pipeline needs to know about the agent.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Context {
|
||||
/// The agent's team.
|
||||
pub team: String,
|
||||
/// Current roles.
|
||||
pub roles: Roles,
|
||||
/// The pinned release keys.
|
||||
pub release_keys: Vec<String>,
|
||||
/// Where downloads go while checked.
|
||||
pub downloads: PathBuf,
|
||||
}
|
||||
|
||||
/// What handling a job changed in the agent.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Handled {
|
||||
/// The roles changed (save them).
|
||||
pub roles_changed: bool,
|
||||
/// The guard remembered a new id (save it).
|
||||
pub guard_changed: bool,
|
||||
}
|
||||
|
||||
struct Hashing<'a> {
|
||||
out: &'a mut dyn Write,
|
||||
ctx: ring::digest::Context,
|
||||
}
|
||||
|
||||
impl Write for Hashing<'_> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let n = self.out.write(buf)?;
|
||||
self.ctx.update(buf.get(..n).unwrap_or_default());
|
||||
Ok(n)
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.out.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one job's bytes at `now`. Reports go to `report` as they happen.
|
||||
pub fn handle(
|
||||
bytes: &[u8],
|
||||
now: i64,
|
||||
ctx: &mut Context,
|
||||
guard: &mut JobGuard,
|
||||
fetch: &dyn Fetch,
|
||||
target: &dyn Target,
|
||||
report: &mut dyn FnMut(Report),
|
||||
) -> Handled {
|
||||
let mut done = Handled::default();
|
||||
let job = match parse_job(bytes) {
|
||||
Ok(j) => j,
|
||||
// Not even the id can be trusted: nothing to report to.
|
||||
Err(_) => return done,
|
||||
};
|
||||
let id = job.header.id.clone();
|
||||
if let Err(e) = guard.check(&job.header, now) {
|
||||
report(Report::refused(
|
||||
&id,
|
||||
now,
|
||||
Step::Guard,
|
||||
e.code(),
|
||||
&e.to_string(),
|
||||
));
|
||||
return done;
|
||||
}
|
||||
done.guard_changed = true;
|
||||
match job.body {
|
||||
JobBody::Unsupported(kind) => report(Report::refused(
|
||||
&id,
|
||||
now,
|
||||
Step::Guard,
|
||||
"unsupported",
|
||||
&format!("this Legatus cannot run {kind} jobs"),
|
||||
)),
|
||||
JobBody::Invalid(why) => {
|
||||
report(Report::refused(&id, now, Step::Guard, "bad_request", &why))
|
||||
}
|
||||
JobBody::Config(c) => {
|
||||
ctx.roles = c.roles;
|
||||
done.roles_changed = true;
|
||||
report(Report::succeeded(
|
||||
&id,
|
||||
now,
|
||||
&format!(
|
||||
"roles: build {}, deploy {}",
|
||||
on(c.roles.build),
|
||||
on(c.roles.deploy)
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
JobBody::Deploy(d) if !ctx.roles.deploy => {
|
||||
let _ = d;
|
||||
report(Report::refused(
|
||||
&id,
|
||||
now,
|
||||
Step::Role,
|
||||
"role_off",
|
||||
"deploy here is off for this agent in Fabrica",
|
||||
));
|
||||
}
|
||||
JobBody::Deploy(d) => deploy(&id, &d, now, ctx, fetch, target, report),
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
fn on(b: bool) -> &'static str {
|
||||
if b { "on" } else { "off" }
|
||||
}
|
||||
|
||||
fn deploy(
|
||||
id: &str,
|
||||
d: &DeployJob,
|
||||
now: i64,
|
||||
ctx: &Context,
|
||||
fetch: &dyn Fetch,
|
||||
target: &dyn Target,
|
||||
report: &mut dyn FnMut(Report),
|
||||
) {
|
||||
let kind = match &d.target {
|
||||
JobTarget::Linux(_) => "linux",
|
||||
};
|
||||
if !target.kinds().iter().any(|k| k == kind) {
|
||||
report(Report::refused(
|
||||
id,
|
||||
now,
|
||||
Step::Guard,
|
||||
"unsupported",
|
||||
&format!("this machine has no {kind} target"),
|
||||
));
|
||||
return;
|
||||
}
|
||||
// 1. The signature and the manifest, before anything is downloaded.
|
||||
let expect = Expected {
|
||||
team: &ctx.team,
|
||||
app: &d.app,
|
||||
version: &d.version,
|
||||
artifact: &d.artifact,
|
||||
};
|
||||
let approved = match verify_release(
|
||||
d.release.manifest.as_bytes(),
|
||||
&d.release.signature,
|
||||
&ctx.release_keys,
|
||||
&expect,
|
||||
) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
report(Report::refused(
|
||||
id,
|
||||
now,
|
||||
Step::Verify,
|
||||
e.code(),
|
||||
&e.to_string(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
report(Report {
|
||||
status: Status::Accepted,
|
||||
..Report::running(
|
||||
id,
|
||||
now,
|
||||
Step::Download,
|
||||
&format!("{} {} is signed by the team; downloading", d.app, d.version),
|
||||
)
|
||||
});
|
||||
// 2. The artifact, bounded by the signed size, hashed as it arrives.
|
||||
let path = ctx.downloads.join(format!("{id}.part"));
|
||||
let result = download(&path, id, &approved.name, approved.size, fetch);
|
||||
let (len, sha) = match result {
|
||||
Ok(x) => x,
|
||||
Err(why) => {
|
||||
let _ = fs::remove_file(&path);
|
||||
report(Report::failed(id, now, Step::Download, &why, false));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = check_artifact(&approved, &sha, len) {
|
||||
let _ = fs::remove_file(&path);
|
||||
report(Report::refused(
|
||||
id,
|
||||
now,
|
||||
Step::Download,
|
||||
e.code(),
|
||||
&e.to_string(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
// 3. Only now does the target see it.
|
||||
let outcome = target.deploy(d, &path, &sha);
|
||||
let _ = fs::remove_file(&path);
|
||||
report(match outcome {
|
||||
Ok(Outcome::Succeeded { previous }) => Report::succeeded(
|
||||
id,
|
||||
now,
|
||||
&match previous {
|
||||
Some(p) => format!("{} {} is running (was {p})", d.app, d.version),
|
||||
None => format!("{} {} is running", d.app, d.version),
|
||||
},
|
||||
Some(Deployed {
|
||||
app: d.app.clone(),
|
||||
version: d.version.clone(),
|
||||
}),
|
||||
),
|
||||
Ok(Outcome::RolledBack {
|
||||
to,
|
||||
healthy,
|
||||
reason,
|
||||
}) => {
|
||||
let state = if healthy {
|
||||
"and it is healthy"
|
||||
} else {
|
||||
"but it is not healthy either"
|
||||
};
|
||||
let mut r = Report::failed(
|
||||
id,
|
||||
now,
|
||||
Step::Health,
|
||||
&format!("{reason}; rolled back to {to}, {state}"),
|
||||
true,
|
||||
);
|
||||
r.deployed = Some(Deployed {
|
||||
app: d.app.clone(),
|
||||
version: to,
|
||||
});
|
||||
r
|
||||
}
|
||||
Ok(Outcome::Failed { reason }) => Report::failed(
|
||||
id,
|
||||
now,
|
||||
Step::Health,
|
||||
&format!("{reason}; there was no earlier release to roll back to"),
|
||||
false,
|
||||
),
|
||||
Err(DeployError::Unpack(UnpackError::Archive(e))) => {
|
||||
Report::refused(id, now, Step::Unpack, e.code(), &e.to_string())
|
||||
}
|
||||
Err(DeployError::Unpack(e)) => {
|
||||
Report::refused(id, now, Step::Unpack, "bad_archive", &e.to_string())
|
||||
}
|
||||
Err(DeployError::Unit) => Report::refused(
|
||||
id,
|
||||
now,
|
||||
Step::Unpack,
|
||||
"bad_request",
|
||||
"the unit name is not valid",
|
||||
),
|
||||
Err(DeployError::Switch(e)) => Report::failed(id, now, Step::Switch, &e, false),
|
||||
});
|
||||
}
|
||||
|
||||
fn download(
|
||||
path: &Path,
|
||||
id: &str,
|
||||
name: &str,
|
||||
size: u64,
|
||||
fetch: &dyn Fetch,
|
||||
) -> Result<(u64, String), String> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let _ = fs::remove_file(path);
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut h = Hashing {
|
||||
out: &mut file,
|
||||
ctx: ring::digest::Context::new(&ring::digest::SHA256),
|
||||
};
|
||||
// One byte more than signed, so a longer artifact is seen as such.
|
||||
let n = fetch.fetch(id, name, size.saturating_add(1), &mut h)?;
|
||||
let sha = legatus_protocol::hex(h.ctx.finish().as_ref());
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
Ok((n, sha))
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// 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 state dir: who it is, what it trusts, and the job ids it has seen.
|
||||
//!
|
||||
//! ```text
|
||||
//! agent.json server, team, agent, roles, pinned release keys, root SHA-256, poll seconds
|
||||
//! root.pem the Domi root (hashes to the code's pin)
|
||||
//! chain.pem the agent certificate and the agents intermediate
|
||||
//! key.pem the agent key (0600; never leaves the machine)
|
||||
//! jobs.seen the job guard
|
||||
//! downloads/ artifacts while they are checked (deleted after each job)
|
||||
//! ```
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use legatus_protocol::{JobGuard, Roles};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What `agent.json` holds.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AgentFile {
|
||||
/// Always 1.
|
||||
pub v: u32,
|
||||
/// `https://host[:port]`.
|
||||
pub server: String,
|
||||
/// Team id.
|
||||
pub team: String,
|
||||
/// Agent id.
|
||||
pub agent: String,
|
||||
/// Current roles.
|
||||
pub roles: Roles,
|
||||
/// The team's release keys, pinned at enrollment.
|
||||
pub release_keys: Vec<String>,
|
||||
/// SHA-256 of the Domi root, lowercase hex.
|
||||
pub root_sha256: String,
|
||||
/// Long-poll seconds.
|
||||
pub poll_seconds: u32,
|
||||
}
|
||||
|
||||
/// Everything an enrolled agent loads.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Enrolled {
|
||||
/// `agent.json`.
|
||||
pub file: AgentFile,
|
||||
/// The root's DER.
|
||||
pub root_der: Vec<u8>,
|
||||
/// `chain.pem`.
|
||||
pub chain_pem: String,
|
||||
/// `key.pem`.
|
||||
pub key_pem: String,
|
||||
}
|
||||
|
||||
/// Why the state cannot be used.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StateError {
|
||||
/// Not enrolled yet.
|
||||
#[error("this machine is not enrolled; run: legatus enroll <code>")]
|
||||
NotEnrolled,
|
||||
/// A file is unreadable or inconsistent.
|
||||
#[error("the state in {0} is damaged: {1}")]
|
||||
Damaged(String, String),
|
||||
/// The disk.
|
||||
#[error("the state could not be written: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
/// The state dir.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct State {
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
/// The default state dir for this OS.
|
||||
pub fn default_dir() -> PathBuf {
|
||||
if let Some(d) = std::env::var_os("LEGATUS_STATE") {
|
||||
return PathBuf::from(d);
|
||||
}
|
||||
if cfg!(windows) {
|
||||
let base = std::env::var_os("ProgramData").unwrap_or_else(|| "C:\\ProgramData".into());
|
||||
PathBuf::from(base).join("Legatus")
|
||||
} else {
|
||||
PathBuf::from("/var/lib/legatus")
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state in `dir`.
|
||||
pub fn new(dir: impl Into<PathBuf>) -> State {
|
||||
State { dir: dir.into() }
|
||||
}
|
||||
|
||||
/// The dir.
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.dir.join(name)
|
||||
}
|
||||
|
||||
/// Where artifacts are kept while checked.
|
||||
pub fn downloads(&self) -> PathBuf {
|
||||
self.path("downloads")
|
||||
}
|
||||
|
||||
/// Is there an enrollment?
|
||||
pub fn is_enrolled(&self) -> bool {
|
||||
self.path("agent.json").exists()
|
||||
}
|
||||
|
||||
/// Load the enrollment.
|
||||
pub fn load(&self) -> Result<Enrolled, StateError> {
|
||||
if !self.is_enrolled() {
|
||||
return Err(StateError::NotEnrolled);
|
||||
}
|
||||
let damaged = |what: &str, e: String| StateError::Damaged(what.to_owned(), e);
|
||||
let text = fs::read_to_string(self.path("agent.json"))
|
||||
.map_err(|e| damaged("agent.json", e.to_string()))?;
|
||||
let file: AgentFile =
|
||||
serde_json::from_str(&text).map_err(|e| damaged("agent.json", e.to_string()))?;
|
||||
let root_pem = fs::read_to_string(self.path("root.pem"))
|
||||
.map_err(|e| damaged("root.pem", e.to_string()))?;
|
||||
let root_der = domi_pki::chain_der(&root_pem)
|
||||
.ok()
|
||||
.and_then(|mut v| (v.len() == 1).then(|| v.remove(0)))
|
||||
.ok_or_else(|| damaged("root.pem", "not one certificate".into()))?;
|
||||
if legatus_protocol::sha256_hex(&root_der) != file.root_sha256 {
|
||||
return Err(damaged("root.pem", "it is not the pinned root".into()));
|
||||
}
|
||||
Ok(Enrolled {
|
||||
file,
|
||||
root_der,
|
||||
chain_pem: fs::read_to_string(self.path("chain.pem"))
|
||||
.map_err(|e| damaged("chain.pem", e.to_string()))?,
|
||||
key_pem: fs::read_to_string(self.path("key.pem"))
|
||||
.map_err(|e| damaged("key.pem", e.to_string()))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Save a new enrollment (replacing any earlier one).
|
||||
pub fn save_enrollment(
|
||||
&self,
|
||||
file: &AgentFile,
|
||||
root_pem: &str,
|
||||
chain_pem: &str,
|
||||
key_pem: &str,
|
||||
) -> Result<(), StateError> {
|
||||
fs::create_dir_all(&self.dir)?;
|
||||
write_atomic(&self.path("key.pem"), key_pem.as_bytes(), true)?;
|
||||
write_atomic(&self.path("chain.pem"), chain_pem.as_bytes(), false)?;
|
||||
write_atomic(&self.path("root.pem"), root_pem.as_bytes(), false)?;
|
||||
let _ = fs::remove_file(self.path("jobs.seen"));
|
||||
// agent.json last: until it exists, the machine is not enrolled.
|
||||
self.save_file(file)
|
||||
}
|
||||
|
||||
/// Save `agent.json`.
|
||||
pub fn save_file(&self, file: &AgentFile) -> Result<(), StateError> {
|
||||
let text = serde_json::to_vec_pretty(file)
|
||||
.map_err(|e| StateError::Damaged("agent.json".into(), e.to_string()))?;
|
||||
write_atomic(&self.path("agent.json"), &text, false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Save a renewed certificate and its key.
|
||||
pub fn save_identity(&self, chain_pem: &str, key_pem: &str) -> Result<(), StateError> {
|
||||
write_atomic(&self.path("key.pem"), key_pem.as_bytes(), true)?;
|
||||
write_atomic(&self.path("chain.pem"), chain_pem.as_bytes(), false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The job guard as saved (a damaged file is an error: replays must not slip through).
|
||||
pub fn load_guard(&self) -> Result<JobGuard, StateError> {
|
||||
match fs::read_to_string(self.path("jobs.seen")) {
|
||||
Ok(t) => JobGuard::load(&t)
|
||||
.map_err(|e| StateError::Damaged("jobs.seen".into(), e.to_string())),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(JobGuard::new()),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the job guard.
|
||||
pub fn save_guard(&self, g: &JobGuard) -> Result<(), StateError> {
|
||||
write_atomic(&self.path("jobs.seen"), g.save().as_bytes(), false)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Write through a temporary file renamed into place; `secret` files are 0600 on Unix.
|
||||
pub(crate) fn write_atomic(path: &Path, data: &[u8], secret: bool) -> io::Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("no parent dir"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
|
||||
let tmp = parent.join(format!(".{name}.tmp-{}", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
let mut o = fs::OpenOptions::new();
|
||||
o.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
o.mode(if secret { 0o600 } else { 0o644 });
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = secret;
|
||||
let mut f = o.open(&tmp)?;
|
||||
f.write_all(data)?;
|
||||
f.sync_all()?;
|
||||
drop(f);
|
||||
fs::rename(&tmp, path)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// 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 targets this machine offers: Linux (systemd) on Linux, none elsewhere in v0.1.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use legatus_linux::{DeployError, HttpHealth, Layout, LinuxBackend, Outcome, Plan, Systemctl};
|
||||
use legatus_protocol::msg::{DeployJob, Deployed, Target as JobTarget};
|
||||
|
||||
use crate::pipeline::Target;
|
||||
|
||||
/// The Linux target with real systemd.
|
||||
pub struct Linux {
|
||||
backend: LinuxBackend<Systemctl, HttpHealth>,
|
||||
}
|
||||
|
||||
impl Linux {
|
||||
/// Apps under `root` (normally `/var/lib/legatus/apps`).
|
||||
pub fn new(root: impl Into<std::path::PathBuf>) -> Linux {
|
||||
Linux {
|
||||
backend: LinuxBackend::new(Layout::new(root), Systemctl, HttpHealth),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Target for Linux {
|
||||
fn kinds(&self) -> Vec<String> {
|
||||
if cfg!(target_os = "linux") {
|
||||
vec!["linux".into()]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn deploy(
|
||||
&self,
|
||||
job: &DeployJob,
|
||||
artifact: &Path,
|
||||
sha256: &str,
|
||||
) -> Result<Outcome, DeployError> {
|
||||
let JobTarget::Linux(t) = &job.target;
|
||||
let file = std::fs::File::open(artifact).map_err(|e| DeployError::Switch(e.to_string()))?;
|
||||
let plan = Plan {
|
||||
app: &job.app,
|
||||
version: &job.version,
|
||||
unit: &t.unit,
|
||||
health_url: t.health_url.as_deref(),
|
||||
health_timeout: Duration::from_secs(u64::from(t.health_timeout_seconds)),
|
||||
keep: t.keep,
|
||||
};
|
||||
self.backend
|
||||
.deploy(&plan, std::io::BufReader::new(file), sha256)
|
||||
}
|
||||
|
||||
fn deployed(&self) -> Vec<Deployed> {
|
||||
self.backend
|
||||
.deployed()
|
||||
.into_iter()
|
||||
.map(|(app, version)| Deployed { app, version })
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// 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/.
|
||||
|
||||
//! TLS to the Fabrica server: the server is accepted only when its chain ends at the pinned Domi
|
||||
//! root and its leaf is valid for the server's name; the agent presents its own certificate
|
||||
//! (mTLS) on every connection after enrollment.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms};
|
||||
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
|
||||
use rustls_pki_types::pem::PemObject;
|
||||
use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
|
||||
|
||||
/// The Domi root, pinned by its SHA-256 (from the enrollment code) and, once known, its DER.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PinnedRoot {
|
||||
sha256: [u8; 32],
|
||||
der: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl PinnedRoot {
|
||||
/// Pinned by fingerprint only (enrollment: the server must present the root itself).
|
||||
pub fn by_hash(sha256: [u8; 32]) -> PinnedRoot {
|
||||
PinnedRoot { sha256, der: None }
|
||||
}
|
||||
|
||||
/// Pinned by the stored certificate (after enrollment). `None` if it does not hash to `sha256`.
|
||||
pub fn with_der(sha256: [u8; 32], der: Vec<u8>) -> Option<PinnedRoot> {
|
||||
(digest(&der) == sha256).then_some(PinnedRoot {
|
||||
sha256,
|
||||
der: Some(der),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(rustls::crypto::ring::default_provider())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Verifier {
|
||||
root: PinnedRoot,
|
||||
algs: WebPkiSupportedAlgorithms,
|
||||
}
|
||||
|
||||
fn tls_err(e: domi_pki::VerifyError) -> rustls::Error {
|
||||
use domi_pki::VerifyError as V;
|
||||
use rustls::CertificateError as C;
|
||||
rustls::Error::InvalidCertificate(match e {
|
||||
V::Expired => C::Expired,
|
||||
V::NotYetValid => C::NotValidYet,
|
||||
V::UnknownIssuer => C::UnknownIssuer,
|
||||
V::BadSignature => C::BadSignature,
|
||||
V::WrongName => C::NotValidForName,
|
||||
V::WrongUsage => C::InvalidPurpose,
|
||||
other => C::Other(rustls::OtherError(Arc::new(other))),
|
||||
})
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for Verifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
end_entity: &CertificateDer<'_>,
|
||||
intermediates: &[CertificateDer<'_>],
|
||||
server_name: &ServerName<'_>,
|
||||
_ocsp: &[u8],
|
||||
now: UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
// The root: the stored one, or the presented certificate that hashes to the pin.
|
||||
let root = match &self.root.der {
|
||||
Some(d) => d.clone(),
|
||||
None => intermediates
|
||||
.iter()
|
||||
.find(|c| digest(c.as_ref()) == self.root.sha256)
|
||||
.map(|c| c.as_ref().to_vec())
|
||||
.ok_or(rustls::Error::InvalidCertificate(
|
||||
rustls::CertificateError::UnknownIssuer,
|
||||
))?,
|
||||
};
|
||||
let mut chain = vec![end_entity.as_ref().to_vec()];
|
||||
chain.extend(
|
||||
intermediates
|
||||
.iter()
|
||||
.filter(|c| c.as_ref() != root.as_slice())
|
||||
.take(4)
|
||||
.map(|c| c.as_ref().to_vec()),
|
||||
);
|
||||
let secs = i64::try_from(now.as_secs()).unwrap_or(i64::MAX);
|
||||
domi_pki::verify_server(&chain, &root, &server_name.to_str(), secs).map_err(tls_err)?;
|
||||
Ok(ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.algs.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a TLS configuration could not be made.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TlsError {
|
||||
/// The agent's certificate or key cannot be read.
|
||||
#[error("the agent's certificate or key cannot be read: {0}")]
|
||||
Identity(String),
|
||||
/// rustls refused the configuration.
|
||||
#[error("TLS could not be set up: {0}")]
|
||||
Config(String),
|
||||
}
|
||||
|
||||
/// A client configuration that trusts only `root`, without a client certificate (enrollment).
|
||||
pub fn enroll_config(root: PinnedRoot) -> Result<Arc<ClientConfig>, TlsError> {
|
||||
let p = provider();
|
||||
let algs = p.signature_verification_algorithms;
|
||||
let cfg = ClientConfig::builder_with_provider(p)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| TlsError::Config(e.to_string()))?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(Verifier { root, algs }))
|
||||
.with_no_client_auth();
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
|
||||
/// A client configuration that trusts only `root` and presents the agent's chain and key (mTLS).
|
||||
pub fn agent_config(
|
||||
root: PinnedRoot,
|
||||
chain_pem: &str,
|
||||
key_pem: &str,
|
||||
) -> Result<Arc<ClientConfig>, TlsError> {
|
||||
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(chain_pem.as_bytes())
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|e| TlsError::Identity(e.to_string()))?;
|
||||
let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes())
|
||||
.map_err(|_| TlsError::Identity("the key".into()))?;
|
||||
let p = provider();
|
||||
let algs = p.signature_verification_algorithms;
|
||||
let cfg = ClientConfig::builder_with_provider(p)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| TlsError::Config(e.to_string()))?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(Verifier { root, algs }))
|
||||
.with_client_auth_cert(chain, key)
|
||||
.map_err(|e| TlsError::Identity(e.to_string()))?;
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
// 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());
|
||||
}
|
||||
|
||||
/// The server refused our client certificate in the TLS handshake. With TLS 1.3 the client may
|
||||
/// already have sent its request, so it sees either the alert or the reset that follows it.
|
||||
fn handshake_refused(e: &AgentError) -> bool {
|
||||
use legatus::http::HttpError;
|
||||
match e {
|
||||
AgentError::Client(ClientError::Http(HttpError::Tls(_))) => true,
|
||||
AgentError::Client(ClientError::Http(HttpError::Protocol(m))) => {
|
||||
let m = m.to_lowercase();
|
||||
[
|
||||
"reset",
|
||||
"forcibly closed",
|
||||
"closed early",
|
||||
"broken pipe",
|
||||
"aborted",
|
||||
]
|
||||
.iter()
|
||||
.any(|w| m.contains(w))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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!(handshake_refused(&e), "{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!(handshake_refused(&e), "{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());
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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/.
|
||||
|
||||
//! TEST ONLY: drives the Linux backend with real systemd for tests/linux (the container test).
|
||||
//! It skips the signature check on purpose, so it is an example, never part of a release.
|
||||
//!
|
||||
//! deploy <root> <app> <version> <unit> <health-url|-> <archive.tar.gz>
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use legatus_linux::{HttpHealth, Layout, LinuxBackend, Outcome, Plan, Systemctl};
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
let [root, app, version, unit, health, archive] = a.as_slice() else {
|
||||
eprintln!("usage: deploy <root> <app> <version> <unit> <health-url|-> <archive.tar.gz>");
|
||||
std::process::exit(2);
|
||||
};
|
||||
let bytes = std::fs::read(archive).expect("the archive");
|
||||
let sha = legatus_protocol::sha256_hex(&bytes);
|
||||
let backend = LinuxBackend::new(Layout::new(root), Systemctl, HttpHealth);
|
||||
let plan = Plan {
|
||||
app,
|
||||
version,
|
||||
unit,
|
||||
health_url: (health != "-").then_some(health.as_str()),
|
||||
health_timeout: Duration::from_secs(15),
|
||||
keep: 3,
|
||||
};
|
||||
match backend.deploy(&plan, &bytes[..], &sha) {
|
||||
Ok(Outcome::Succeeded { previous }) => {
|
||||
println!(
|
||||
"succeeded previous={}",
|
||||
previous.unwrap_or_else(|| "-".into())
|
||||
)
|
||||
}
|
||||
Ok(Outcome::RolledBack {
|
||||
to,
|
||||
healthy,
|
||||
reason,
|
||||
}) => {
|
||||
println!("rolled_back to={to} healthy={healthy} reason={reason}")
|
||||
}
|
||||
Ok(Outcome::Failed { reason }) => println!("failed reason={reason}"),
|
||||
Err(e) => println!("error {e}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
// 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/.
|
||||
|
||||
//! Legatus's Linux (systemd) target (docs/01_legatus.md):
|
||||
//!
|
||||
//! ```text
|
||||
//! <root>/<app>/releases/<version>/ one dir per release, unpacked from the signed artifact
|
||||
//! <root>/<app>/current -> releases/<version>
|
||||
//! <root>/<app>/sums/<version> the artifact's SHA-256 the dir was made from
|
||||
//! <root>/<app>/history versions switched to, oldest first
|
||||
//! ```
|
||||
//!
|
||||
//! [`unpack`] makes a release dir from a `.tar.gz` (which the agent has already checked against
|
||||
//! the signed manifest). [`LinuxBackend::deploy`] switches `current` atomically, restarts the
|
||||
//! unit, checks health, and rolls back to the previous release when the check fails.
|
||||
//!
|
||||
//! The caller has verified the release's signature before any of this runs.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use legatus_protocol::{
|
||||
ArchiveError, EntryKind, MAX_ARCHIVE_BYTES, MAX_ARCHIVE_ENTRIES, check_entry, msg::valid_unit,
|
||||
valid_version,
|
||||
};
|
||||
|
||||
/// Where apps live by default.
|
||||
pub const DEFAULT_ROOT: &str = "/var/lib/legatus/apps";
|
||||
|
||||
/// The paths of the release layout under one root.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Layout {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// A layout under `root` (normally [`DEFAULT_ROOT`]).
|
||||
pub fn new(root: impl Into<PathBuf>) -> Layout {
|
||||
Layout { root: root.into() }
|
||||
}
|
||||
|
||||
/// `<root>/<app>`.
|
||||
pub fn app_dir(&self, app: &str) -> PathBuf {
|
||||
self.root.join(app)
|
||||
}
|
||||
|
||||
/// `<root>/<app>/releases`.
|
||||
pub fn releases_dir(&self, app: &str) -> PathBuf {
|
||||
self.app_dir(app).join("releases")
|
||||
}
|
||||
|
||||
/// `<root>/<app>/releases/<version>`.
|
||||
pub fn release_dir(&self, app: &str, version: &str) -> PathBuf {
|
||||
self.releases_dir(app).join(version)
|
||||
}
|
||||
|
||||
/// `<root>/<app>/current`.
|
||||
pub fn current_link(&self, app: &str) -> PathBuf {
|
||||
self.app_dir(app).join("current")
|
||||
}
|
||||
|
||||
fn sum_file(&self, app: &str, version: &str) -> PathBuf {
|
||||
self.app_dir(app).join("sums").join(version)
|
||||
}
|
||||
|
||||
fn history_file(&self, app: &str) -> PathBuf {
|
||||
self.app_dir(app).join("history")
|
||||
}
|
||||
|
||||
/// The version `current` points at, if any.
|
||||
pub fn current(&self, app: &str) -> Option<String> {
|
||||
let target = fs::read_link(self.current_link(app)).ok()?;
|
||||
let mut parts = target.components();
|
||||
let first = parts.next()?.as_os_str().to_str()?;
|
||||
let v = parts.next()?.as_os_str().to_str()?.to_owned();
|
||||
(first == "releases" && parts.next().is_none() && valid_version(&v)).then_some(v)
|
||||
}
|
||||
|
||||
/// The release dir `current` points at, if any.
|
||||
pub fn current_dir(&self, app: &str) -> Option<PathBuf> {
|
||||
self.current(app).map(|v| self.release_dir(app, &v))
|
||||
}
|
||||
|
||||
fn history(&self, app: &str) -> Vec<String> {
|
||||
fs::read_to_string(self.history_file(app))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter(|l| valid_version(l))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a release dir was not made. Nothing that runs was changed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum UnpackError {
|
||||
/// An app or version name that cannot be a path.
|
||||
#[error("the app or version name cannot be used")]
|
||||
Name,
|
||||
/// This version is already here with other content.
|
||||
#[error("this version is already on this host with different content")]
|
||||
VersionClash,
|
||||
/// The archive is refused.
|
||||
#[error("{0}")]
|
||||
Archive(#[from] ArchiveError),
|
||||
/// The disk.
|
||||
#[error("the release could not be written: {0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
fn io_err(e: io::Error) -> UnpackError {
|
||||
UnpackError::Io(e.to_string())
|
||||
}
|
||||
|
||||
static NONCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn nonce() -> String {
|
||||
let n = NONCE.fetch_add(1, Ordering::Relaxed);
|
||||
let t = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.subsec_nanos())
|
||||
.unwrap_or(0);
|
||||
format!("{}-{n}-{t}", std::process::id())
|
||||
}
|
||||
|
||||
/// Unpack a `.tar.gz` into `releases/<version>` (atomically: a staging dir renamed into place),
|
||||
/// remembering that it was made from an artifact with SHA-256 `sha256`. The same version with
|
||||
/// the same SHA-256 again is reused; with another one it is refused.
|
||||
pub fn unpack(
|
||||
layout: &Layout,
|
||||
app: &str,
|
||||
version: &str,
|
||||
archive: impl Read,
|
||||
sha256: &str,
|
||||
) -> Result<PathBuf, UnpackError> {
|
||||
if !domi_like_id(app) || !valid_version(version) {
|
||||
return Err(UnpackError::Name);
|
||||
}
|
||||
let dir = layout.release_dir(app, version);
|
||||
let sum_file = layout.sum_file(app, version);
|
||||
if dir.exists() {
|
||||
return match fs::read_to_string(&sum_file) {
|
||||
Ok(s) if s.trim() == sha256 => Ok(dir),
|
||||
_ => Err(UnpackError::VersionClash),
|
||||
};
|
||||
}
|
||||
let releases = layout.releases_dir(app);
|
||||
fs::create_dir_all(&releases).map_err(io_err)?;
|
||||
let staging = releases.join(format!(".incoming-{version}-{}", nonce()));
|
||||
fs::create_dir(&staging).map_err(io_err)?;
|
||||
let result = extract(archive, &staging).and_then(|()| {
|
||||
fs::rename(&staging, &dir).map_err(io_err)?;
|
||||
write_atomic(&sum_file, sha256.as_bytes()).map_err(io_err)
|
||||
});
|
||||
if let Err(e) = result {
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// App ids are domi-pki ids (`a-z 0-9 -`).
|
||||
fn domi_like_id(id: &str) -> bool {
|
||||
(1..=40).contains(&id.len())
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
&& !id.starts_with('-')
|
||||
&& !id.ends_with('-')
|
||||
}
|
||||
|
||||
fn extract(archive: impl Read, into: &Path) -> Result<(), UnpackError> {
|
||||
let gz = flate2::read::GzDecoder::new(archive);
|
||||
let mut tar = tar::Archive::new(gz);
|
||||
let entries = tar.entries().map_err(|_| ArchiveError::Corrupt)?;
|
||||
let (mut count, mut total, mut files) = (0usize, 0u64, 0usize);
|
||||
for entry in entries {
|
||||
let mut entry = entry.map_err(|_| ArchiveError::Corrupt)?;
|
||||
count += 1;
|
||||
if count > MAX_ARCHIVE_ENTRIES {
|
||||
return Err(ArchiveError::TooMany.into());
|
||||
}
|
||||
let kind = match entry.header().entry_type() {
|
||||
tar::EntryType::Regular | tar::EntryType::Continuous => EntryKind::File,
|
||||
tar::EntryType::Directory => EntryKind::Dir,
|
||||
tar::EntryType::Symlink => EntryKind::Symlink,
|
||||
tar::EntryType::Link => EntryKind::Hardlink,
|
||||
_ => EntryKind::Other,
|
||||
};
|
||||
let size = entry.header().size().map_err(|_| ArchiveError::Corrupt)?;
|
||||
let path_bytes = entry.path_bytes().into_owned();
|
||||
let path = std::str::from_utf8(&path_bytes).map_err(|_| ArchiveError::Path)?;
|
||||
let parts = check_entry(kind, path, size)?;
|
||||
total = total.saturating_add(size);
|
||||
if total > MAX_ARCHIVE_BYTES {
|
||||
return Err(ArchiveError::TooLarge.into());
|
||||
}
|
||||
let mut target = into.to_path_buf();
|
||||
for p in &parts {
|
||||
target.push(p);
|
||||
}
|
||||
match kind {
|
||||
EntryKind::Dir => fs::create_dir_all(&target).map_err(io_err)?,
|
||||
_ => {
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent).map_err(io_err)?;
|
||||
}
|
||||
let mode = entry.header().mode().unwrap_or(0o644);
|
||||
let mut out = create_new(&target, mode & 0o111 != 0).map_err(io_err)?;
|
||||
let written = io::copy(&mut (&mut entry).take(size), &mut out).map_err(io_err)?;
|
||||
if written != size {
|
||||
return Err(ArchiveError::Corrupt.into());
|
||||
}
|
||||
out.sync_all().map_err(io_err)?;
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if files == 0 {
|
||||
return Err(ArchiveError::Corrupt.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_new(path: &Path, exec: bool) -> io::Result<fs::File> {
|
||||
let mut o = fs::OpenOptions::new();
|
||||
o.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
o.mode(if exec { 0o755 } else { 0o644 });
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = exec;
|
||||
o.open(path)
|
||||
}
|
||||
|
||||
fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("no parent dir"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let tmp = parent.join(format!(".tmp-{}", nonce()));
|
||||
fs::write(&tmp, data)?;
|
||||
fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ services and health
|
||||
|
||||
/// systemd, as the backend needs it.
|
||||
pub trait Services {
|
||||
/// `systemctl restart <unit>`.
|
||||
fn restart(&self, unit: &str) -> Result<(), String>;
|
||||
/// `systemctl is-active <unit>`.
|
||||
fn is_active(&self, unit: &str) -> bool;
|
||||
}
|
||||
|
||||
/// The local health endpoint.
|
||||
pub trait Health {
|
||||
/// One attempt: does `url` answer 2xx?
|
||||
fn check(&self, url: &str) -> bool;
|
||||
}
|
||||
|
||||
/// The real systemd, through `systemctl`.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct Systemctl;
|
||||
|
||||
impl Services for Systemctl {
|
||||
fn restart(&self, unit: &str) -> Result<(), String> {
|
||||
if !valid_unit(unit) {
|
||||
return Err("the unit name is not valid".into());
|
||||
}
|
||||
let out = std::process::Command::new("systemctl")
|
||||
.args(["restart", "--", unit])
|
||||
.output()
|
||||
.map_err(|e| format!("systemctl could not run: {e}"))?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
let msg: String = String::from_utf8_lossy(&out.stderr)
|
||||
.chars()
|
||||
.take(300)
|
||||
.collect();
|
||||
Err(format!("systemctl restart {unit} failed: {}", msg.trim()))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_active(&self, unit: &str) -> bool {
|
||||
valid_unit(unit)
|
||||
&& std::process::Command::new("systemctl")
|
||||
.args(["is-active", "--quiet", "--", unit])
|
||||
.status()
|
||||
.is_ok_and(|s| s.success())
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain HTTP/1.1 GET to a local URL (the protocol only allows 127.0.0.1, localhost, [::1]).
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct HttpHealth;
|
||||
|
||||
impl Health for HttpHealth {
|
||||
fn check(&self, url: &str) -> bool {
|
||||
http_status(url).is_some_and(|s| (200..300).contains(&s))
|
||||
}
|
||||
}
|
||||
|
||||
fn http_status(url: &str) -> Option<u16> {
|
||||
use std::io::Write;
|
||||
use std::net::ToSocketAddrs;
|
||||
if !legatus_protocol::msg::local_http_url(url) {
|
||||
return None;
|
||||
}
|
||||
let rest = url.strip_prefix("http://")?;
|
||||
let (auth, path) = match rest.find('/') {
|
||||
Some(i) => rest.split_at(i),
|
||||
None => (rest, "/"),
|
||||
};
|
||||
let addr = if auth.starts_with('[') || auth.contains(':') {
|
||||
auth.to_owned()
|
||||
} else {
|
||||
format!("{auth}:80")
|
||||
};
|
||||
let sock = addr.to_socket_addrs().ok()?.next()?;
|
||||
let t = Duration::from_secs(2);
|
||||
let mut s = std::net::TcpStream::connect_timeout(&sock, t).ok()?;
|
||||
s.set_read_timeout(Some(t)).ok()?;
|
||||
s.set_write_timeout(Some(t)).ok()?;
|
||||
write!(s, "GET {path} HTTP/1.1\r\nHost: {auth}\r\nConnection: close\r\nUser-Agent: legatus-health\r\n\r\n").ok()?;
|
||||
let mut buf = [0u8; 64];
|
||||
let n = s.read(&mut buf).ok()?;
|
||||
let line = std::str::from_utf8(buf.get(..n)?).ok()?;
|
||||
let mut words = line.split_whitespace();
|
||||
if !words.next()?.starts_with("HTTP/1.") {
|
||||
return None;
|
||||
}
|
||||
words.next()?.parse().ok()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ deploying
|
||||
|
||||
/// One deploy, as the job gives it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Plan<'a> {
|
||||
/// App id.
|
||||
pub app: &'a str,
|
||||
/// Version.
|
||||
pub version: &'a str,
|
||||
/// The systemd unit.
|
||||
pub unit: &'a str,
|
||||
/// A local health URL, if any.
|
||||
pub health_url: Option<&'a str>,
|
||||
/// How long the health check may take.
|
||||
pub health_timeout: Duration,
|
||||
/// Releases kept.
|
||||
pub keep: u32,
|
||||
}
|
||||
|
||||
/// How a deploy ended.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// The new release runs and is healthy.
|
||||
Succeeded {
|
||||
/// The release that ran before, if any.
|
||||
previous: Option<String>,
|
||||
},
|
||||
/// The new release failed; `current` points at `to` again and it was restarted.
|
||||
RolledBack {
|
||||
/// The release running again.
|
||||
to: String,
|
||||
/// Did the rolled-back release pass its health check?
|
||||
healthy: bool,
|
||||
/// Why the new release failed.
|
||||
reason: String,
|
||||
},
|
||||
/// The new release failed and there was nothing to roll back to.
|
||||
Failed {
|
||||
/// Why.
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// Why it failed ("" when it did not).
|
||||
pub fn reason(&self) -> &str {
|
||||
match self {
|
||||
Outcome::Succeeded { .. } => "",
|
||||
Outcome::RolledBack { reason, .. } | Outcome::Failed { reason } => reason,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a deploy did not start: nothing that runs was changed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DeployError {
|
||||
/// The archive or the names.
|
||||
#[error("{0}")]
|
||||
Unpack(#[from] UnpackError),
|
||||
/// The unit name.
|
||||
#[error("the unit name is not valid")]
|
||||
Unit,
|
||||
/// The symlink could not be switched.
|
||||
#[error("the release could not be switched: {0}")]
|
||||
Switch(String),
|
||||
}
|
||||
|
||||
/// The Linux target.
|
||||
pub struct LinuxBackend<S: Services, H: Health> {
|
||||
layout: Layout,
|
||||
services: S,
|
||||
health: H,
|
||||
poll: Duration,
|
||||
}
|
||||
|
||||
impl<S: Services, H: Health> LinuxBackend<S, H> {
|
||||
/// A backend over `layout` with these services and health check.
|
||||
pub fn new(layout: Layout, services: S, health: H) -> LinuxBackend<S, H> {
|
||||
LinuxBackend {
|
||||
layout,
|
||||
services,
|
||||
health,
|
||||
poll: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// How often the health check is tried (tests make it short).
|
||||
pub fn with_poll(mut self, poll: Duration) -> Self {
|
||||
self.poll = poll;
|
||||
self
|
||||
}
|
||||
|
||||
/// The layout.
|
||||
pub fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The services.
|
||||
pub fn services(&self) -> &S {
|
||||
&self.services
|
||||
}
|
||||
|
||||
/// Every app with a current release: `(app, version)`, sorted.
|
||||
pub fn deployed(&self) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(rd) = fs::read_dir(&self.layout.root) {
|
||||
for e in rd.flatten() {
|
||||
let Some(app) = e.file_name().to_str().map(str::to_owned) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(v) = self.layout.current(&app) {
|
||||
out.push((app, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Point `current` at `releases/<version>` atomically: a new symlink renamed over the old
|
||||
/// one, so `current` always names a whole release. Returns the version it pointed at before.
|
||||
#[cfg(unix)]
|
||||
pub fn switch(&self, app: &str, version: &str) -> Result<Option<String>, DeployError> {
|
||||
if !domi_like_id(app) || !valid_version(version) {
|
||||
return Err(UnpackError::Name.into());
|
||||
}
|
||||
let sw = |e: io::Error| DeployError::Switch(e.to_string());
|
||||
if !self.layout.release_dir(app, version).is_dir() {
|
||||
return Err(DeployError::Switch(format!(
|
||||
"release {version} is not on disk"
|
||||
)));
|
||||
}
|
||||
let previous = self.layout.current(app);
|
||||
let app_dir = self.layout.app_dir(app);
|
||||
let tmp = app_dir.join(format!(".current-{}", nonce()));
|
||||
std::os::unix::fs::symlink(Path::new("releases").join(version), &tmp).map_err(sw)?;
|
||||
if let Err(e) = fs::rename(&tmp, self.layout.current_link(app)) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(sw(e));
|
||||
}
|
||||
fs::File::open(&app_dir)
|
||||
.and_then(|d| d.sync_all())
|
||||
.map_err(sw)?;
|
||||
let mut history = self.layout.history(app);
|
||||
history.retain(|v| v != version);
|
||||
history.push(version.to_owned());
|
||||
let keep_from = history.len().saturating_sub(100);
|
||||
let text: String = history[keep_from..]
|
||||
.iter()
|
||||
.map(|v| format!("{v}\n"))
|
||||
.collect();
|
||||
write_atomic(&self.layout.history_file(app), text.as_bytes()).map_err(sw)?;
|
||||
Ok(previous)
|
||||
}
|
||||
|
||||
/// Not available off Unix.
|
||||
#[cfg(not(unix))]
|
||||
pub fn switch(&self, _app: &str, _version: &str) -> Result<Option<String>, DeployError> {
|
||||
Err(DeployError::Switch(
|
||||
"the Linux target runs on Linux only".into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Wait until the unit is active and the health URL answers, twice in a row, within the
|
||||
/// timeout.
|
||||
fn wait_healthy(&self, plan: &Plan<'_>) -> Result<(), String> {
|
||||
let deadline = Instant::now() + plan.health_timeout;
|
||||
let mut passes = 0;
|
||||
loop {
|
||||
let active = self.services.is_active(plan.unit);
|
||||
let healthy = active && plan.health_url.is_none_or(|u| self.health.check(u));
|
||||
passes = if healthy { passes + 1 } else { 0 };
|
||||
if passes >= 2 {
|
||||
return Ok(());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(if active {
|
||||
format!(
|
||||
"the health check did not pass within {} s",
|
||||
plan.health_timeout.as_secs_f32()
|
||||
)
|
||||
} else {
|
||||
format!("{} is not active", plan.unit)
|
||||
});
|
||||
}
|
||||
std::thread::sleep(self.poll);
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self, plan: &Plan<'_>) -> Result<(), String> {
|
||||
self.services.restart(plan.unit)?;
|
||||
self.wait_healthy(plan)
|
||||
}
|
||||
|
||||
/// Deploy: unpack (or reuse) the release, switch, restart, check health, and roll back to the
|
||||
/// previous release when the check fails. `archive` must already match the signed manifest.
|
||||
pub fn deploy(
|
||||
&self,
|
||||
plan: &Plan<'_>,
|
||||
archive: impl Read,
|
||||
sha256: &str,
|
||||
) -> Result<Outcome, DeployError> {
|
||||
if !valid_unit(plan.unit) {
|
||||
return Err(DeployError::Unit);
|
||||
}
|
||||
unpack(&self.layout, plan.app, plan.version, archive, sha256)?;
|
||||
let previous = self.switch(plan.app, plan.version)?;
|
||||
match self.start(plan) {
|
||||
Ok(()) => {
|
||||
self.prune(
|
||||
plan.app,
|
||||
plan.keep,
|
||||
&[Some(plan.version), previous.as_deref()],
|
||||
);
|
||||
Ok(Outcome::Succeeded { previous })
|
||||
}
|
||||
Err(reason) => match previous.filter(|p| p != plan.version) {
|
||||
Some(to) => {
|
||||
self.switch(plan.app, &to)?;
|
||||
let healthy = self.start(plan).is_ok();
|
||||
Ok(Outcome::RolledBack {
|
||||
to,
|
||||
healthy,
|
||||
reason,
|
||||
})
|
||||
}
|
||||
None => Ok(Outcome::Failed { reason }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove old releases: keep the newest `keep` from the history and everything in `protect`.
|
||||
fn prune(&self, app: &str, keep: u32, protect: &[Option<&str>]) {
|
||||
let history = self.layout.history(app);
|
||||
let keep_n = usize::try_from(keep.max(1)).unwrap_or(1);
|
||||
let mut kept: Vec<&str> = history
|
||||
.iter()
|
||||
.rev()
|
||||
.take(keep_n)
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
kept.extend(protect.iter().flatten());
|
||||
let Ok(rd) = fs::read_dir(self.layout.releases_dir(app)) else {
|
||||
return;
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with('.') || !valid_version(&name) || kept.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if fs::remove_dir_all(e.path()).is_ok() {
|
||||
let _ = fs::remove_file(self.layout.sum_file(app, &name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// 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::Write;
|
||||
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
|
||||
/// A .tar.gz of regular files (path, contents, executable).
|
||||
pub fn targz(files: &[(&str, &[u8], bool)]) -> Vec<u8> {
|
||||
let mut b = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast()));
|
||||
for (path, data, exec) in files {
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_size(data.len() as u64);
|
||||
h.set_mode(if *exec { 0o755 } else { 0o644 });
|
||||
h.set_entry_type(tar::EntryType::Regular);
|
||||
b.append_data(&mut h, path, *data).unwrap();
|
||||
}
|
||||
b.into_inner().unwrap().finish().unwrap()
|
||||
}
|
||||
|
||||
/// A .tar.gz with one raw entry whose name and type the tar crate would not let us write.
|
||||
pub fn raw_targz(name: &[u8], kind: tar::EntryType, data: &[u8], link: &[u8]) -> Vec<u8> {
|
||||
let mut h = tar::Header::new_old();
|
||||
{
|
||||
let old = h.as_old_mut();
|
||||
old.name[..name.len()].copy_from_slice(name);
|
||||
old.linkname[..link.len()].copy_from_slice(link);
|
||||
}
|
||||
h.set_size(data.len() as u64);
|
||||
h.set_mode(0o644);
|
||||
h.set_entry_type(kind);
|
||||
h.set_cksum();
|
||||
let mut tarball = Vec::new();
|
||||
tarball.extend_from_slice(h.as_bytes());
|
||||
tarball.extend_from_slice(data);
|
||||
tarball.resize(tarball.len().div_ceil(512) * 512, 0);
|
||||
tarball.extend_from_slice(&[0u8; 1024]);
|
||||
let mut gz = GzEncoder::new(Vec::new(), Compression::fast());
|
||||
gz.write_all(&tarball).unwrap();
|
||||
gz.finish().unwrap()
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
// 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 Linux target (mandatory, tests first): the atomic symlink switch, the restart, the health
|
||||
//! check, and auto rollback when the check fails. Real files and symlinks; systemd and the health
|
||||
//! endpoint are fakes here (the container test, tests/linux, uses real systemd).
|
||||
|
||||
#![cfg(any(target_os = "linux", target_os = "android"))]
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use legatus_linux::{Health, Layout, LinuxBackend, Outcome, Plan, Services};
|
||||
|
||||
/// systemd as the tests see it: records restarts; a release is "active" unless its dir holds BROKEN.
|
||||
struct FakeSystemd {
|
||||
layout: Layout,
|
||||
calls: RefCell<Vec<String>>,
|
||||
fail_restart_of: Option<String>,
|
||||
}
|
||||
|
||||
impl Services for FakeSystemd {
|
||||
fn restart(&self, unit: &str) -> Result<(), String> {
|
||||
let v = self.layout.current("shop").unwrap_or_default();
|
||||
self.calls.borrow_mut().push(format!("restart {unit} @{v}"));
|
||||
if self.fail_restart_of.as_deref() == Some(v.as_str()) {
|
||||
return Err(format!("Job for {unit} failed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn is_active(&self, _unit: &str) -> bool {
|
||||
let cur = self.layout.current_dir("shop");
|
||||
cur.is_some_and(|d| !d.join("BROKEN").exists())
|
||||
}
|
||||
}
|
||||
|
||||
/// The health URL answers 2xx unless the current release holds UNHEALTHY.
|
||||
struct FakeHealth(Layout);
|
||||
impl Health for FakeHealth {
|
||||
fn check(&self, _url: &str) -> bool {
|
||||
self.0
|
||||
.current_dir("shop")
|
||||
.is_some_and(|d| !d.join("UNHEALTHY").exists())
|
||||
}
|
||||
}
|
||||
|
||||
fn backend(
|
||||
fail_restart_of: Option<&str>,
|
||||
) -> (tempfile::TempDir, LinuxBackend<FakeSystemd, FakeHealth>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let layout = Layout::new(dir.path().join("apps"));
|
||||
let sd = FakeSystemd {
|
||||
layout: layout.clone(),
|
||||
calls: RefCell::new(Vec::new()),
|
||||
fail_restart_of: fail_restart_of.map(str::to_owned),
|
||||
};
|
||||
let b = LinuxBackend::new(layout.clone(), sd, FakeHealth(layout))
|
||||
.with_poll(Duration::from_millis(5));
|
||||
(dir, b)
|
||||
}
|
||||
|
||||
fn plan(version: &str) -> Plan<'_> {
|
||||
Plan {
|
||||
app: "shop",
|
||||
version,
|
||||
unit: "shop.service",
|
||||
health_url: Some("http://127.0.0.1:8080/health"),
|
||||
health_timeout: Duration::from_millis(200),
|
||||
keep: 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn good(v: &str) -> Vec<u8> {
|
||||
targz(&[("bin/shop", format!("version {v}").as_bytes(), true)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_healthy_release_is_switched_to_and_restarted() {
|
||||
let (_d, b) = backend(None);
|
||||
let out = b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
assert_eq!(out, Outcome::Succeeded { previous: None });
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
let out = b.deploy(&plan("1.1.0"), &good("2")[..], "s2").unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::Succeeded {
|
||||
previous: Some("1.0.0".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.1.0"));
|
||||
assert_eq!(
|
||||
*b.services().calls.borrow(),
|
||||
vec![
|
||||
"restart shop.service @1.0.0".to_owned(),
|
||||
"restart shop.service @1.1.0".to_owned()
|
||||
]
|
||||
);
|
||||
// `current` is a relative symlink into releases/.
|
||||
let link = std::fs::read_link(b.layout().current_link("shop")).unwrap();
|
||||
assert_eq!(link, PathBuf::from("releases/1.1.0"));
|
||||
assert_eq!(b.deployed(), vec![("shop".to_owned(), "1.1.0".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_health_check_rolls_back_automatically() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::RolledBack {
|
||||
to: "1.0.0".into(),
|
||||
healthy: true,
|
||||
reason: out.reason().to_owned()
|
||||
}
|
||||
);
|
||||
assert!(out.reason().contains("health"), "{}", out.reason());
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
// Restarted on the new release, then again on the old one.
|
||||
assert_eq!(
|
||||
*b.services().calls.borrow(),
|
||||
vec![
|
||||
"restart shop.service @1.0.0".to_owned(),
|
||||
"restart shop.service @2.0.0".to_owned(),
|
||||
"restart shop.service @1.0.0".to_owned()
|
||||
]
|
||||
);
|
||||
// The failed release stays on disk for a look, but is not current.
|
||||
assert!(b.layout().release_dir("shop", "2.0.0").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inactive_unit_rolls_back_even_without_a_health_url() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let crashes = targz(&[("bin/shop", b"v2", true), ("BROKEN", b"", false)]);
|
||||
let mut p = plan("2.0.0");
|
||||
p.health_url = None;
|
||||
let out = b.deploy(&p, &crashes[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { ref to, healthy: true, .. } if to == "1.0.0"),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_restart_rolls_back() {
|
||||
let (_d, b) = backend(Some("2.0.0"));
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let out = b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { ref to, .. } if to == "1.0.0"),
|
||||
"{out:?}"
|
||||
);
|
||||
assert!(out.reason().contains("failed"), "{}", out.reason());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_release_that_fails_has_nothing_to_roll_back_to() {
|
||||
let (_d, b) = backend(None);
|
||||
let bad = targz(&[("bin/shop", b"v1", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("1.0.0"), &bad[..], "s1").unwrap();
|
||||
assert!(matches!(out, Outcome::Failed { .. }), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rollback_that_is_unhealthy_too_says_so() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
// The old release breaks meanwhile (say, a database it needs is gone).
|
||||
std::fs::write(
|
||||
b.layout().release_dir("shop", "1.0.0").join("UNHEALTHY"),
|
||||
b"",
|
||||
)
|
||||
.unwrap();
|
||||
let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { healthy: false, .. }),
|
||||
"{out:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switch_is_atomic() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap();
|
||||
let link = b.layout().current_link("shop");
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (link, stop) = (link.clone(), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut reads = 0u64;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
// `current` always exists and always points at a whole release.
|
||||
let target = std::fs::read_link(&link).expect("current vanished during a switch");
|
||||
let s = target.to_string_lossy().into_owned();
|
||||
assert!(s == "releases/1.0.0" || s == "releases/2.0.0", "{s}");
|
||||
assert!(link.join("bin/shop").exists(), "current pointed at nothing");
|
||||
reads += 1;
|
||||
}
|
||||
reads
|
||||
})
|
||||
};
|
||||
for i in 0..400 {
|
||||
let v = if i % 2 == 0 { "1.0.0" } else { "2.0.0" };
|
||||
b.switch("shop", v).unwrap();
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let reads = reader.join().unwrap();
|
||||
assert!(reads > 0);
|
||||
// No temporary links are left behind.
|
||||
let names: Vec<String> = std::fs::read_dir(b.layout().app_dir("shop"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names.iter().filter(|n| n.starts_with('.')).count(),
|
||||
0,
|
||||
"{names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_releases_are_pruned_but_current_and_previous_kept() {
|
||||
let (_d, b) = backend(None);
|
||||
for (i, v) in ["1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut p = plan(v);
|
||||
p.keep = 2;
|
||||
b.deploy(&p, &good(&i.to_string())[..], &format!("s{i}"))
|
||||
.unwrap();
|
||||
}
|
||||
let mut left: Vec<String> = std::fs::read_dir(b.layout().releases_dir("shop"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| !n.ends_with(".sha256"))
|
||||
.collect();
|
||||
left.sort();
|
||||
assert_eq!(left, vec!["1.3.0".to_owned(), "1.4.0".to_owned()]);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// 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/.
|
||||
|
||||
//! Unpacking (tests first): a signed archive can still hold a mistake; nothing escapes the
|
||||
//! release dir, links and special files are refused, and a refused archive leaves nothing behind.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use legatus_linux::{Layout, UnpackError, unpack};
|
||||
|
||||
fn layout() -> (tempfile::TempDir, Layout) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let l = Layout::new(dir.path().join("apps"));
|
||||
(dir, l)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_good_archive_becomes_a_release_dir() {
|
||||
let (_d, l) = layout();
|
||||
let a = targz(&[
|
||||
("bin/shop", b"#!/bin/sh\necho hi\n", true),
|
||||
("static/index.html", b"<p>hi</p>", false),
|
||||
]);
|
||||
let dir = unpack(&l, "shop", "1.4.0", &a[..], "sha-one").unwrap();
|
||||
assert_eq!(dir, l.release_dir("shop", "1.4.0"));
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join("static/index.html")).unwrap(),
|
||||
b"<p>hi</p>"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(dir.join("bin/shop"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o755);
|
||||
let mode = std::fs::metadata(dir.join("static/index.html"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o644);
|
||||
}
|
||||
// The same version with the same content again: reused, not unpacked twice.
|
||||
assert_eq!(unpack(&l, "shop", "1.4.0", &a[..], "sha-one").unwrap(), dir);
|
||||
// The same version with other content: refused, the existing one untouched.
|
||||
let other = targz(&[("bin/shop", b"evil", true)]);
|
||||
assert!(matches!(
|
||||
unpack(&l, "shop", "1.4.0", &other[..], "sha-two"),
|
||||
Err(UnpackError::VersionClash)
|
||||
));
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join("bin/shop")).unwrap(),
|
||||
b"#!/bin/sh\necho hi\n"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_refused_and_clean(l: &Layout, archive: &[u8]) {
|
||||
let r = unpack(l, "shop", "2.0.0", archive, "sha");
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(!l.release_dir("shop", "2.0.0").exists());
|
||||
let releases = l.releases_dir("shop");
|
||||
if releases.exists() {
|
||||
let left: Vec<_> = std::fs::read_dir(&releases).unwrap().collect();
|
||||
assert!(left.is_empty(), "staging left behind: {left:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_that_climb_out_are_refused() {
|
||||
let (d, l) = layout();
|
||||
for name in [
|
||||
&b"../evil"[..],
|
||||
b"/etc/evil",
|
||||
b"a/../../evil",
|
||||
b"a\\..\\evil",
|
||||
] {
|
||||
assert_refused_and_clean(&l, &raw_targz(name, tar::EntryType::Regular, b"x", b""));
|
||||
}
|
||||
assert!(!d.path().join("evil").exists());
|
||||
assert!(!d.path().join("apps").join("evil").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_and_special_files_are_refused() {
|
||||
let (_d, l) = layout();
|
||||
assert_refused_and_clean(
|
||||
&l,
|
||||
&raw_targz(b"link", tar::EntryType::Symlink, b"", b"/etc/passwd"),
|
||||
);
|
||||
assert_refused_and_clean(
|
||||
&l,
|
||||
&raw_targz(b"hard", tar::EntryType::Link, b"", b"/etc/passwd"),
|
||||
);
|
||||
assert_refused_and_clean(&l, &raw_targz(b"dev", tar::EntryType::Char, b"", b""));
|
||||
assert_refused_and_clean(&l, &raw_targz(b"fifo", tar::EntryType::Fifo, b"", b""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_and_duplicates_are_refused() {
|
||||
let (_d, l) = layout();
|
||||
assert_refused_and_clean(&l, b"not gzip at all");
|
||||
let dup = targz(&[("a", b"1", false), ("a", b"2", false)]);
|
||||
assert_refused_and_clean(&l, &dup);
|
||||
assert_refused_and_clean(&l, &targz(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_app_or_version_names_never_reach_the_disk() {
|
||||
let (_d, l) = layout();
|
||||
let a = targz(&[("x", b"1", false)]);
|
||||
for (app, version) in [
|
||||
("../shop", "1"),
|
||||
("shop", "../1"),
|
||||
("shop", ".."),
|
||||
("Shop", "1"),
|
||||
("shop", ""),
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
unpack(&l, app, version, &a[..], "s"),
|
||||
Err(UnpackError::Name)
|
||||
),
|
||||
"{app} {version}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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<Vec<String>, 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)
|
||||
}
|
||||
@@ -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<Encoding, CodeError> {
|
||||
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::<u32>().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<EnrollmentCode, CodeError> {
|
||||
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<EnrollmentCode, CodeError> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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<i64>,
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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<String, CodeRecord>,
|
||||
}
|
||||
|
||||
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<Grant, EnrollError> {
|
||||
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<Item = &CodeRecord> {
|
||||
self.records.values()
|
||||
}
|
||||
}
|
||||
@@ -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<String, i64>,
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// `<id> <expires_at>` 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<JobGuard, GuardError> {
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
if !s.len().is_multiple_of(2) {
|
||||
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())
|
||||
}
|
||||
@@ -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<u32>,
|
||||
}
|
||||
|
||||
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<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, MsgError> {
|
||||
peek(bytes)?;
|
||||
serde_json::from_slice(bytes).map_err(|e| MsgError::Malformed(e.to_string()))
|
||||
}
|
||||
|
||||
/// Write a message as JSON.
|
||||
pub fn encode<T: Serialize>(msg: &T) -> Vec<u8> {
|
||||
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<String>,
|
||||
/// 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<String>,
|
||||
/// Build kinds it runs.
|
||||
pub build: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<Deployed>,
|
||||
}
|
||||
|
||||
/// 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, `<name>.service`.
|
||||
pub unit: String,
|
||||
/// A local URL that answers 2xx when the app is healthy.
|
||||
#[serde(default)]
|
||||
pub health_url: Option<String>,
|
||||
/// 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<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
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<Job, MsgError> {
|
||||
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::<ConfigJob>(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::<LinuxTarget>)
|
||||
{
|
||||
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: `<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::<u32>().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<u8> {
|
||||
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<Step>,
|
||||
/// 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<bool>,
|
||||
/// What now runs.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deployed: Option<Deployed>,
|
||||
}
|
||||
|
||||
fn clip(s: &str, n: usize) -> String {
|
||||
s.chars().take(n).collect()
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn new(job: &str, at: i64, status: Status, step: Option<Step>, 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<Deployed>) -> Report {
|
||||
let mut r = Report::new(job, at, Status::Succeeded, None, message.to_owned());
|
||||
r.deployed = deployed;
|
||||
r
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
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<u8>],
|
||||
root_der: &[u8],
|
||||
now: i64,
|
||||
) -> Result<AgentIdentity, Refusal> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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<ArtifactEntry>,
|
||||
}
|
||||
|
||||
/// 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<Approved, ReleaseError> {
|
||||
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<minisign_verify::PublicKey> = 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<Manifest, ReleaseError> {
|
||||
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<Vec<u8>> {
|
||||
data_encoding::BASE64.decode(s.as_bytes()).ok()
|
||||
}
|
||||
@@ -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(_))
|
||||
));
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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<Vec<u8>>, 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()
|
||||
)
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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::<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();
|
||||
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}"
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
# Legatus installer, served by the Fabrica server at /legatus/install.sh:
|
||||
# curl -fsSL https://<fabrica>/legatus/install.sh | sudo sh -s -- lgt1-<code>
|
||||
# Downloads the Legatus binary for this machine from the same server, checks its SHA-256 against
|
||||
# the SHA256SUMS beside it (and the minisign signature when minisign is installed), installs it,
|
||||
# enrolls with the one-time code, and starts legatus.service.
|
||||
set -eu
|
||||
|
||||
CODE=${1:-}
|
||||
BASE=${LEGATUS_BASE:-} # Fabrica sets this in the script it serves, e.g. https://fabrica.example
|
||||
KEY=${LEGATUS_RELEASE_KEY:-} # and the minisign key Legatus releases are signed with
|
||||
|
||||
die() { echo "legatus install: $*" >&2; exit 1; }
|
||||
[ -n "$CODE" ] || die "usage: install.sh lgt1-<code>"
|
||||
case "$CODE" in lgt1-*) ;; *) die "that is not an enrollment code" ;; esac
|
||||
[ -n "$BASE" ] || die "this script must be served by Fabrica (LEGATUS_BASE is not set)"
|
||||
[ "$(id -u)" = 0 ] || die "run it with sudo"
|
||||
command -v systemctl >/dev/null || die "systemd is needed"
|
||||
command -v sha256sum >/dev/null || die "sha256sum is needed"
|
||||
|
||||
case "$(uname -m)" in
|
||||
x86_64|amd64) ARCH=x86_64 ;;
|
||||
aarch64|arm64) ARCH=aarch64 ;;
|
||||
*) die "this CPU ($(uname -m)) is not supported yet" ;;
|
||||
esac
|
||||
FILE="legatus-linux-$ARCH"
|
||||
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
curl -fsSL --proto '=https' --tlsv1.2 -o "$TMP/$FILE" "$BASE/legatus/download/$FILE"
|
||||
curl -fsSL --proto '=https' --tlsv1.2 -o "$TMP/SHA256SUMS" "$BASE/legatus/download/SHA256SUMS"
|
||||
if [ -n "$KEY" ] && command -v minisign >/dev/null; then
|
||||
curl -fsSL --proto '=https' --tlsv1.2 -o "$TMP/SHA256SUMS.minisig" "$BASE/legatus/download/SHA256SUMS.minisig"
|
||||
minisign -Vm "$TMP/SHA256SUMS" -P "$KEY" >/dev/null || die "SHA256SUMS is not signed by the Legatus release key"
|
||||
fi
|
||||
WANT=$(awk -v f="$FILE" '$2 == f || $2 == "*"f { print $1 }' "$TMP/SHA256SUMS")
|
||||
[ -n "$WANT" ] || die "SHA256SUMS does not list $FILE"
|
||||
GOT=$(sha256sum "$TMP/$FILE" | cut -d' ' -f1)
|
||||
[ "$WANT" = "$GOT" ] || die "the download does not match SHA256SUMS"
|
||||
|
||||
install -m 755 "$TMP/$FILE" /usr/local/bin/legatus
|
||||
install -d -m 700 /var/lib/legatus
|
||||
/usr/local/bin/legatus enroll "$CODE"
|
||||
|
||||
cat > /etc/systemd/system/legatus.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Legatus, the Fabrica Domi agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/local/bin/legatus run
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
StateDirectory=legatus
|
||||
StateDirectoryMode=0700
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now legatus.service
|
||||
echo "Legatus is running. It shows up in Fabrica under Targets."
|
||||
@@ -0,0 +1,8 @@
|
||||
# The Linux target's integration test: Debian with real systemd as PID 1.
|
||||
FROM docker.io/library/debian:trixie-slim
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends systemd systemd-sysv python3 curl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& systemctl mask systemd-logind.service getty.target console-getty.service
|
||||
STOPSIGNAL SIGRTMIN+3
|
||||
CMD ["/sbin/init"]
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
# The Linux target against real systemd, in a container (Docker or Podman).
|
||||
# tests/linux/run.sh # from the repo root
|
||||
# Builds the test-only `deploy` example in a Rust container, starts Debian with systemd as PID 1,
|
||||
# and runs scenario.sh in it. On Mark's PC the container engine keeps its data on D:.
|
||||
set -eu
|
||||
|
||||
ENGINE=${ENGINE:-$(command -v podman || command -v docker || true)}
|
||||
[ -n "$ENGINE" ] || { echo "run.sh: needs podman or docker" >&2; exit 2; }
|
||||
REPO=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
NAME=legatus-linux-it
|
||||
RUST_IMAGE=${RUST_IMAGE:-docker.io/library/rust:1.89-slim-trixie}
|
||||
|
||||
cleanup() { "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "== building the test driver"
|
||||
"$ENGINE" volume create legatus-it-cargo >/dev/null
|
||||
"$ENGINE" run --rm -v "$REPO:/src:ro" -v legatus-it-cargo:/cargo -e CARGO_HOME=/cargo/home \
|
||||
-e CARGO_TARGET_DIR=/cargo/target -w /src "$RUST_IMAGE" \
|
||||
sh -c 'cargo build --locked --example deploy -p legatus-linux && cp /cargo/target/debug/examples/deploy /cargo/legatus-deploy-test'
|
||||
|
||||
echo "== starting systemd"
|
||||
"$ENGINE" build -q -t legatus-systemd "$REPO/tests/linux" >/dev/null
|
||||
cleanup
|
||||
"$ENGINE" run -d --name "$NAME" --privileged --cgroupns=host \
|
||||
--tmpfs /run --tmpfs /run/lock -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
|
||||
-v legatus-it-cargo:/cargo:ro legatus-systemd >/dev/null
|
||||
"$ENGINE" exec "$NAME" install -m 755 /cargo/legatus-deploy-test /usr/local/bin/legatus-deploy-test
|
||||
"$ENGINE" cp "$REPO/tests/linux/scenario.sh" "$NAME:/scenario.sh"
|
||||
|
||||
echo "== scenario"
|
||||
"$ENGINE" exec "$NAME" sh /scenario.sh
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
# Runs inside the systemd container: four releases of a small web app through the Linux target.
|
||||
# 1.0.0 healthy, 2.0.0 healthy, 3.0.0 crashes at start, 4.0.0 runs but its health URL fails.
|
||||
# Expected: 1 and 2 succeed; 3 and 4 are rolled back to 2.0.0, which keeps running.
|
||||
set -eu
|
||||
|
||||
ROOT=/var/lib/legatus/apps
|
||||
DEPLOY=/usr/local/bin/legatus-deploy-test
|
||||
HEALTH=http://127.0.0.1:8080/health
|
||||
fail() { echo "FAIL: $*"; exit 1; }
|
||||
|
||||
# Wait for systemd to be up.
|
||||
for _ in $(seq 1 60); do
|
||||
s=$(systemctl is-system-running 2>/dev/null || true)
|
||||
[ "$s" = running ] || [ "$s" = degraded ] && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
cat > /etc/systemd/system/demo.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Legatus demo app
|
||||
[Service]
|
||||
ExecStart=/var/lib/legatus/apps/demo/current/run.sh
|
||||
Restart=no
|
||||
EOF
|
||||
systemctl daemon-reload
|
||||
|
||||
work=$(mktemp -d)
|
||||
release() { # version kind
|
||||
d="$work/$1"; mkdir -p "$d/www"
|
||||
case "$2" in
|
||||
good) echo "ok $1" > "$d/www/health"
|
||||
printf '#!/bin/sh\nexec python3 -m http.server 8080 --bind 127.0.0.1 --directory "$(dirname "$(readlink -f "$0")")/www"\n' > "$d/run.sh" ;;
|
||||
crash) printf '#!/bin/sh\necho "cannot start" >&2\nexit 1\n' > "$d/run.sh" ;;
|
||||
unhealthy) printf '#!/bin/sh\nexec python3 -m http.server 8080 --bind 127.0.0.1 --directory "$(dirname "$(readlink -f "$0")")/www"\n' > "$d/run.sh" ;;
|
||||
esac
|
||||
chmod 755 "$d/run.sh"
|
||||
tar -C "$d" -czf "$work/$1.tar.gz" .
|
||||
}
|
||||
release 1.0.0 good; release 2.0.0 good; release 3.0.0 crash; release 4.0.0 unhealthy
|
||||
|
||||
deploy() { "$DEPLOY" "$ROOT" demo "$1" demo.service "$HEALTH" "$work/$1.tar.gz"; }
|
||||
current() { readlink "$ROOT/demo/current"; }
|
||||
|
||||
out=$(deploy 1.0.0); echo "1.0.0: $out"
|
||||
case "$out" in "succeeded previous=-") ;; *) fail "1.0.0: $out";; esac
|
||||
[ "$(current)" = releases/1.0.0 ] || fail "current is $(current)"
|
||||
[ "$(curl -fsS $HEALTH)" = "ok 1.0.0" ] || fail "1.0.0 does not answer"
|
||||
|
||||
out=$(deploy 2.0.0); echo "2.0.0: $out"
|
||||
case "$out" in "succeeded previous=1.0.0") ;; *) fail "2.0.0: $out";; esac
|
||||
[ "$(curl -fsS $HEALTH)" = "ok 2.0.0" ] || fail "2.0.0 does not answer"
|
||||
|
||||
out=$(deploy 3.0.0); echo "3.0.0: $out"
|
||||
case "$out" in "rolled_back to=2.0.0 healthy=true"*) ;; *) fail "3.0.0: $out";; esac
|
||||
[ "$(current)" = releases/2.0.0 ] || fail "after 3.0.0 current is $(current)"
|
||||
systemctl is-active --quiet demo.service || fail "demo is not active after the rollback"
|
||||
[ "$(curl -fsS $HEALTH)" = "ok 2.0.0" ] || fail "2.0.0 does not answer after the rollback"
|
||||
|
||||
out=$(deploy 4.0.0); echo "4.0.0: $out"
|
||||
case "$out" in "rolled_back to=2.0.0 healthy=true"*) ;; *) fail "4.0.0: $out";; esac
|
||||
[ "$(curl -fsS $HEALTH)" = "ok 2.0.0" ] || fail "2.0.0 does not answer after the second rollback"
|
||||
|
||||
echo "PASS: atomic switch, systemd restart, health check and auto rollback with real systemd"
|
||||
Reference in New Issue
Block a user