[protocol] Protocol v1: enrollment codes and book, messages, job guard, agent registry, release check, archive paths (32 tests)

This commit is contained in:
2026-11-17 11:38:41 +01:00
parent 304ad9cd1d
commit 148a3a0ff9
9 changed files with 2805 additions and 0 deletions
+85
View File
@@ -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)
}
+219
View File
@@ -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)
}
}
+168
View File
@@ -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()
}
}
+133
View File
@@ -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 })
}
}
+62
View File
@@ -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() % 2 != 0 {
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())
}
+645
View File
@@ -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
}
}
+119
View File
@@ -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)
}
}
+265
View File
@@ -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()
}