[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
+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()
}
}