Files
rust-discovery/crates/updater-worker/src/record.rs
T
2026-11-14 23:51:59 +01:00

945 lines
34 KiB
Rust

//! Deterministic record bytes and one live, fixed-namespace publication pass.
//! Neither a builder nor a namespace proof grants authority. The caller's real
//! guard must recheck Original/Health/clock/services and every other protected
//! file before committing each native claim and observation in the SAME ledger.
use crate::original::Original;
use anyhow::{Result, ensure};
use ed25519_dalek::{Signature, VerifyingKey};
use rmm_agent_core::update_handoff::NativeEffect;
use rmm_domain::{
agent_update::ResolvedAgentUpdate,
agent_update_provisioning::{ActivationEvidence, InstalledReleaseRecord, MAX_RECORD_BYTES},
jobs::hash,
};
use rmm_updater_handoff::{
Event, Evidence, HEALTH_DOMAIN, HealthReceipt, Journal, Phase, SignedHealth,
};
use rmm_updater_linux::{
Budget,
files::{Directory, FileProof, Identity},
};
use serde::Serialize;
use std::{
ffi::CString,
fs::{File, Metadata, OpenOptions},
io::Write,
os::{
fd::{AsRawFd, FromRawFd},
unix::fs::{FileExt, MetadataExt, OpenOptionsExt},
},
path::Path,
};
use uuid::Uuid;
const ROOT: &str = "/var/lib/rmm-agent-updater";
const CURRENT: &str = "installed-record.json";
/// Private construction binds all future namespace operations to these exact
/// original inputs. Deliberately neither Clone nor Deserialize nor a resume API.
pub struct BuiltRecord {
record: InstalledReleaseRecord,
raw: Vec<u8>,
prior_raw: Vec<u8>,
old_sha256: String,
sha256: String,
grant_id: Uuid,
owner_nonce: Uuid,
}
impl BuiltRecord {
pub fn build(
original: &Original,
prior_raw: &[u8],
journal: &Journal,
health_event_raw: &[u8],
) -> Result<Self> {
let header = original.handoff();
let handoff_sha256 = hash(&header.bytes()?);
ensure!(
journal.phase() == Phase::HealthVerified
&& journal.handoff_sha256() == handoff_sha256
&& !health_event_raw.is_empty()
&& health_event_raw.len() <= rmm_updater_handoff::MAX_EVENT_BYTES
&& hash(health_event_raw) == journal.head_sha256(),
"UPDATE_RECORD_HEALTH_HEAD"
);
let event: Event = serde_json::from_slice(health_event_raw)?;
ensure!(
serde_json::to_vec(&event)? == health_event_raw
&& event.handoff_sha256 == handoff_sha256
&& event.boot_id == header.boot_id,
"UPDATE_RECORD_HEALTH_EVENT"
);
let Evidence::HealthVerified { receipt: signed } = &event.evidence else {
anyhow::bail!("UPDATE_RECORD_HEALTH_REQUIRED")
};
ensure!(
!signed.payload.is_empty()
&& signed.payload.len() <= 4096
&& signed.signature.len() == 64,
"UPDATE_RECORD_HEALTH_LIMIT"
);
let receipt: HealthReceipt = serde_json::from_slice(&signed.payload)?;
ensure!(
serde_json::to_vec(&receipt)? == signed.payload,
"UPDATE_RECORD_HEALTH_NONCANONICAL"
);
// Journal possession is not independent key trust. Authenticate the
// exact receipt again with the ORIGINAL signed job's external key pin.
let raw: [u8; 32] = hex::decode(&original.update().updater.health_public_key_hex)?
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_RECORD_HEALTH_KEY"))?;
let public = VerifyingKey::from_bytes(&raw)?;
ensure!(!public.is_weak(), "UPDATE_RECORD_HEALTH_KEY");
let mut message = HEALTH_DOMAIN.to_vec();
message.extend_from_slice(&signed.payload);
public.verify_strict(&message, &Signature::from_slice(&signed.signature)?)?;
ensure!(
receipt.schema_version == 1
&& receipt.handoff_sha256 == handoff_sha256
&& receipt.owner_nonce == header.owner_nonce
&& receipt.boot_id == header.boot_id
&& receipt.helper_journal_id == header.helper_journal_id
&& receipt.agent_journal_id == header.agent_journal_id
&& receipt.connection_generation > header.connection_generation
&& !receipt.ready
&& receipt.issued_at >= header.consumed_at
&& receipt.issued_at <= event.observed_at
&& event.observed_at < receipt.valid_until
&& receipt.valid_until <= header.finish_before,
"UPDATE_RECORD_HEALTH_BINDING"
);
Self::assemble(
original.update(),
prior_raw,
&handoff_sha256,
signed,
&receipt,
header.attempt.grant_id,
header.owner_nonce,
)
}
fn assemble(
update: &ResolvedAgentUpdate,
prior_raw: &[u8],
handoff_sha256: &str,
signed: &SignedHealth,
receipt: &HealthReceipt,
grant_id: Uuid,
owner_nonce: Uuid,
) -> Result<Self> {
ensure!(
update.validate() && !grant_id.is_nil() && !owner_nonce.is_nil(),
"UPDATE_RECORD_INPUT"
);
let prior = InstalledReleaseRecord::from_bytes(prior_raw).map_err(anyhow::Error::msg)?;
let parent = prior
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
let target = update.manifest().map_err(anyhow::Error::msg)?;
let old_sha256 = hash(prior_raw);
ensure!(
!prior.rolled_back
&& old_sha256 == update.predecessor.installed_record_sha256
&& prior.manifest_sha256 == update.predecessor.manifest_sha256
&& parent.manifest.release_id == update.predecessor.release_id
&& parent.manifest.release_sequence == update.predecessor.release_sequence
&& parent.manifest.artifacts[0].sha256 == update.predecessor.agent_sha256
&& parent.manifest.artifacts[1].sha256 == update.predecessor.helper_sha256
&& prior.platform == target.platform
&& target.release_sequence > prior.activation_floor
&& receipt.issued_at >= prior.activated_at,
"UPDATE_RECORD_PREDECESSOR_OR_FLOOR"
);
let record = InstalledReleaseRecord {
schema_version: 1,
profile: "decoder_compatible_handoff_v1".into(),
platform: target.platform,
release_envelope: update.release_envelope.clone(),
manifest_sha256: update.manifest_sha256.clone(),
activation_floor: target.release_sequence,
activated_at: receipt.issued_at,
previous_record_sha256: Some(old_sha256.clone()),
activation_evidence: ActivationEvidence::Updated {
handoff_sha256: handoff_sha256.into(),
signed_health_sha256: hash(&serde_json::to_vec(signed)?),
},
rolled_back: false,
};
let raw = record.bytes().map_err(anyhow::Error::msg)?;
let sha256 = hash(&raw);
ensure!(sha256 != old_sha256, "UPDATE_RECORD_SAME_BYTES");
Ok(Self {
record,
raw,
prior_raw: prior_raw.to_vec(),
old_sha256,
sha256,
grant_id,
owner_nonce,
})
}
pub fn raw(&self) -> &[u8] {
&self.raw
}
pub fn record(&self) -> &InstalledReleaseRecord {
&self.record
}
pub fn sha256(&self) -> &str {
&self.sha256
}
pub fn old_sha256(&self) -> &str {
&self.old_sha256
}
pub fn grant_id(&self) -> Uuid {
self.grant_id
}
pub fn owner_nonce(&self) -> Uuid {
self.owner_nonce
}
}
/// The concrete Fullhelper adapter commits an original Core claim before each
/// rename and its original observation afterwards. No permissive implementation.
pub trait RecordFence {
fn before_effect(
&mut self,
effect: &NativeEffect,
namespace: &RecordNamespaceProof<'_>,
) -> Result<()>;
fn after_effect(
&mut self,
effect: &NativeEffect,
namespace: &RecordNamespaceProof<'_>,
observation_sha256: &str,
) -> Result<()>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordPhase {
Prepared,
Saved,
Published,
}
struct HeldDirectory {
protected: Directory,
fd: File,
identity: Identity,
}
fn identity(meta: &Metadata) -> Identity {
Identity {
device: meta.dev(),
inode: meta.ino(),
uid: meta.uid(),
gid: meta.gid(),
mode: meta.mode(),
links: meta.nlink(),
}
}
fn component(value: &str) -> Result<CString> {
ensure!(
!value.is_empty() && value != "." && value != ".." && !value.contains('/'),
"UPDATE_RECORD_COMPONENT"
);
Ok(CString::new(value)?)
}
fn openat(dir: &File, name: &str, flags: i32, mode: u32) -> Result<File> {
let name = component(name)?;
// SAFETY: live held dirfd and one validated NUL-terminated component. Each
// successful descriptor is immediately owned by exactly one File.
let fd = unsafe {
libc::openat(
dir.as_raw_fd(),
name.as_ptr(),
flags | libc::O_NOFOLLOW | libc::O_CLOEXEC,
mode,
)
};
ensure!(
fd >= 0,
"UPDATE_RECORD_OPEN: {}",
std::io::Error::last_os_error()
);
Ok(unsafe { File::from_raw_fd(fd) })
}
impl HeldDirectory {
fn open(path: &Path) -> Result<Self> {
let protected = Directory::open(path, 0, true)?;
let fd = OpenOptions::new()
.read(true)
.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)?;
let actual = identity(&fd.metadata()?);
ensure!(
&actual == protected.identity() && actual.mode & 0o777 == 0o700,
"UPDATE_RECORD_DIRECTORY_BINDING"
);
let result = Self {
protected,
fd,
identity: actual,
};
result.verify()?;
Ok(result)
}
fn verify(&self) -> Result<()> {
self.protected.verify()?;
ensure!(
identity(&self.fd.metadata()?) == self.identity,
"UPDATE_RECORD_DIRECTORY_CHANGED"
);
Ok(())
}
fn absent(&self, name: &str) -> Result<()> {
let name = component(name)?;
let mut value = std::mem::MaybeUninit::<libc::stat>::uninit();
let result = unsafe {
libc::fstatat(
self.fd.as_raw_fd(),
name.as_ptr(),
value.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
};
ensure!(
result < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT),
"UPDATE_RECORD_DESTINATION_EXISTS"
);
Ok(())
}
fn named(&self, name: &str, held: &RecordFile) -> Result<()> {
self.verify()?;
held.verify()?;
let named = openat(&self.fd, name, libc::O_RDONLY | libc::O_NONBLOCK, 0)?;
ensure!(
file_proof(&named.metadata()?, &held.proof.sha256)? == held.proof,
"UPDATE_RECORD_NAMED_FILE_CHANGED"
);
// A held inode and a same-byte different named inode are distinct.
held.verify()?;
self.verify()
}
fn sync(&self) -> Result<()> {
self.fd.sync_all()?;
Ok(())
}
fn rename_new(&self, from: &str, to: &str) -> Result<()> {
let from = component(from)?;
let to = component(to)?;
let result = unsafe {
libc::renameat2(
self.fd.as_raw_fd(),
from.as_ptr(),
self.fd.as_raw_fd(),
to.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
ensure!(
result == 0,
"UPDATE_RECORD_RENAME: {}",
std::io::Error::last_os_error()
);
self.sync()
}
fn create(&self, name: &str, raw: &[u8]) -> Result<RecordFile> {
self.verify()?;
ensure!(
!raw.is_empty() && raw.len() <= MAX_RECORD_BYTES,
"UPDATE_RECORD_SIZE"
);
let mut file = openat(
&self.fd,
name,
libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
0o600,
)?;
file.write_all(raw)?;
file.sync_all()?;
self.sync()?;
let held = RecordFile::from_file(file, raw)?;
self.named(name, &held)?;
Ok(held)
}
fn archive(&self, name: &str, raw: &[u8]) -> Result<RecordFile> {
let name_c = component(name)?;
let mut value = std::mem::MaybeUninit::<libc::stat>::uninit();
let result = unsafe {
libc::fstatat(
self.fd.as_raw_fd(),
name_c.as_ptr(),
value.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
};
if result < 0 {
ensure!(
std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT),
"UPDATE_RECORD_ARCHIVE_STAT"
);
return self.create(name, raw);
}
let file = RecordFile::open(self, name, raw)?;
self.named(name, &file)?;
Ok(file)
}
}
fn file_proof(meta: &Metadata, sha256: &str) -> Result<FileProof> {
ensure!(
meta.is_file()
&& meta.uid() == 0
&& meta.mode() & 0o7777 == 0o600
&& meta.nlink() == 1
&& meta.len() > 0
&& meta.len() <= MAX_RECORD_BYTES as u64,
"UPDATE_RECORD_PROTECTED_FILE"
);
Ok(FileProof {
identity: identity(meta),
bytes: meta.len(),
sha256: sha256.into(),
})
}
fn stamp(meta: &Metadata) -> (Identity, u64, i64, i64, i64, i64) {
(
identity(meta),
meta.len(),
meta.mtime(),
meta.mtime_nsec(),
meta.ctime(),
meta.ctime_nsec(),
)
}
struct RecordFile {
fd: File,
proof: FileProof,
}
impl RecordFile {
fn open(dir: &HeldDirectory, name: &str, raw: &[u8]) -> Result<Self> {
ensure!(
!raw.is_empty() && raw.len() <= MAX_RECORD_BYTES,
"UPDATE_RECORD_SIZE"
);
let fd = openat(&dir.fd, name, libc::O_RDONLY | libc::O_NONBLOCK, 0)?;
Self::from_file(fd, raw)
}
fn from_file(fd: File, raw: &[u8]) -> Result<Self> {
ensure!(
!raw.is_empty() && raw.len() <= MAX_RECORD_BYTES,
"UPDATE_RECORD_SIZE"
);
let proof = file_proof(&fd.metadata()?, &hash(raw))?;
ensure!(proof.bytes == raw.len() as u64, "UPDATE_RECORD_LENGTH");
let result = Self { fd, proof };
result.verify()?;
Ok(result)
}
fn verify(&self) -> Result<()> {
let before = self.fd.metadata()?;
ensure!(
file_proof(&before, &self.proof.sha256)? == self.proof,
"UPDATE_RECORD_HELD_FILE_CHANGED"
);
let mut raw = vec![0; self.proof.bytes as usize];
self.fd.read_exact_at(&mut raw, 0)?;
let mut extra = [0; 1];
ensure!(
self.fd.read_at(&mut extra, self.proof.bytes)? == 0
&& hash(&raw) == self.proof.sha256
&& stamp(&before) == stamp(&self.fd.metadata()?),
"UPDATE_RECORD_HELD_BYTES_CHANGED"
);
Ok(())
}
}
pub struct RecordTransition {
built: BuiltRecord,
directory: HeldDirectory,
archives: HeldDirectory,
old: RecordFile,
staged: RecordFile,
archived_old: RecordFile,
archived_new: RecordFile,
stage_name: String,
previous_name: String,
phase: RecordPhase,
poisoned: bool,
}
impl RecordTransition {
/// Call only after independently authorized, still-current original Health.
/// Creates bounded private staging/archive bytes; never changes Current.
pub fn prepare(built: BuiltRecord, budget: &Budget) -> Result<Self> {
Self::prepare_in(Path::new(ROOT), built, budget)
}
fn prepare_in(path: &Path, built: BuiltRecord, budget: &Budget) -> Result<Self> {
budget.check()?;
let directory = HeldDirectory::open(path)?;
let archives = HeldDirectory::open(&path.join("records"))?;
let stage_name = format!(".rmm-record-{}.stage", built.owner_nonce);
let previous_name = format!(".rmm-record-{}.previous", built.owner_nonce);
directory.absent(&stage_name)?;
directory.absent(&previous_name)?;
let old = RecordFile::open(&directory, CURRENT, &built.prior_raw)?;
directory.named(CURRENT, &old)?;
let archived_old =
archives.archive(&format!("{}.json", built.old_sha256), &built.prior_raw)?;
budget.check()?;
let archived_new = archives.archive(&format!("{}.json", built.sha256), &built.raw)?;
budget.check()?;
let staged = directory.create(&stage_name, &built.raw)?;
let result = Self {
built,
directory,
archives,
old,
staged,
archived_old,
archived_new,
stage_name,
previous_name,
phase: RecordPhase::Prepared,
poisoned: false,
};
result.namespace_proof().verify()?;
budget.check()?;
Ok(result)
}
pub fn namespace_proof(&self) -> RecordNamespaceProof<'_> {
RecordNamespaceProof { transition: self }
}
pub fn save_previous(&mut self, fence: &mut impl RecordFence, budget: &Budget) -> Result<()> {
ensure!(
!self.poisoned && self.phase == RecordPhase::Prepared,
"UPDATE_RECORD_NO_SAVE_RESUME"
);
self.poisoned = true;
let effect = NativeEffect::SaveInstalledRecord {
old_sha256: self.built.old_sha256.clone(),
new_sha256: self.built.sha256.clone(),
};
self.namespace_proof().verify()?;
budget.check()?;
fence.before_effect(&effect, &self.namespace_proof())?;
self.namespace_proof().verify()?;
budget.check()?;
self.directory.rename_new(CURRENT, &self.previous_name)?;
self.phase = RecordPhase::Saved;
self.namespace_proof().verify()?;
let observed = self.namespace_proof().observation_sha256()?;
fence.after_effect(&effect, &self.namespace_proof(), &observed)?;
budget.check()?;
self.poisoned = false;
Ok(())
}
pub fn publish(&mut self, fence: &mut impl RecordFence, budget: &Budget) -> Result<()> {
ensure!(
!self.poisoned && self.phase == RecordPhase::Saved,
"UPDATE_RECORD_NO_PUBLISH_RESUME"
);
self.poisoned = true;
let effect = NativeEffect::PublishInstalledRecord {
old_sha256: self.built.old_sha256.clone(),
new_sha256: self.built.sha256.clone(),
};
self.namespace_proof().verify()?;
budget.check()?;
fence.before_effect(&effect, &self.namespace_proof())?;
self.namespace_proof().verify()?;
budget.check()?;
self.directory.rename_new(&self.stage_name, CURRENT)?;
self.phase = RecordPhase::Published;
self.namespace_proof().verify()?;
let observed = self.namespace_proof().observation_sha256()?;
fence.after_effect(&effect, &self.namespace_proof(), &observed)?;
budget.check()?;
self.poisoned = false;
Ok(())
}
}
/// Borrowed held-descriptor proof, not serializable/constructible from IPC and
/// never a flag authorizing a general TrustState skip. verify() checks the whole
/// precise allowed namespace, including both create-only history copies.
pub struct RecordNamespaceProof<'a> {
transition: &'a RecordTransition,
}
impl RecordNamespaceProof<'_> {
pub fn phase(&self) -> RecordPhase {
self.transition.phase
}
pub fn record(&self) -> &BuiltRecord {
&self.transition.built
}
pub fn directory_identity(&self) -> &Identity {
&self.transition.directory.identity
}
pub fn old_file(&self) -> &FileProof {
&self.transition.old.proof
}
pub fn new_file(&self) -> &FileProof {
&self.transition.staged.proof
}
pub fn old_sha256(&self) -> &str {
self.transition.built.old_sha256()
}
pub fn new_sha256(&self) -> &str {
self.transition.built.sha256()
}
pub fn grant_id(&self) -> Uuid {
self.transition.built.grant_id()
}
pub fn owner_nonce(&self) -> Uuid {
self.transition.built.owner_nonce()
}
pub fn verify(&self) -> Result<()> {
let t = self.transition;
t.directory.verify()?;
t.archives.verify()?;
t.old.verify()?;
t.staged.verify()?;
t.archives
.named(&format!("{}.json", t.built.old_sha256), &t.archived_old)?;
t.archives
.named(&format!("{}.json", t.built.sha256), &t.archived_new)?;
ensure!(
t.old.proof.sha256 == t.built.old_sha256
&& t.staged.proof.sha256 == t.built.sha256
&& t.old.proof.identity.inode != t.staged.proof.identity.inode
&& t.old.proof.identity.device == t.staged.proof.identity.device,
"UPDATE_RECORD_PAIR_CHANGED"
);
match t.phase {
RecordPhase::Prepared => {
t.directory.named(CURRENT, &t.old)?;
t.directory.named(&t.stage_name, &t.staged)?;
t.directory.absent(&t.previous_name)?;
}
RecordPhase::Saved => {
t.directory.named(&t.previous_name, &t.old)?;
t.directory.named(&t.stage_name, &t.staged)?;
t.directory.absent(CURRENT)?;
}
RecordPhase::Published => {
t.directory.named(&t.previous_name, &t.old)?;
t.directory.named(CURRENT, &t.staged)?;
t.directory.absent(&t.stage_name)?;
}
}
t.directory.verify()?;
t.archives.verify()
}
pub fn observation_sha256(&self) -> Result<String> {
self.verify()?;
#[derive(Serialize)]
struct Observation<'a> {
grant_id: Uuid,
owner_nonce: Uuid,
phase: RecordPhase,
directory: &'a Identity,
archives: &'a Identity,
old: &'a FileProof,
new: &'a FileProof,
archived_old: &'a FileProof,
archived_new: &'a FileProof,
}
let t = self.transition;
Ok(hash(&serde_json::to_vec(&Observation {
grant_id: self.grant_id(),
owner_nonce: self.owner_nonce(),
phase: t.phase,
directory: &t.directory.identity,
archives: &t.archives.identity,
old: &t.old.proof,
new: &t.staged.proof,
archived_old: &t.archived_old.proof,
archived_new: &t.archived_new.proof,
})?))
}
}
#[cfg(test)]
mod tests {
// Structural record bytes and actual Root-owned scratch IO only. Synthetic
// codec signatures below are NOT accepted by the public authenticated build
// method, never a real release/Health/approval or a simulated target job.
use super::*;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use std::{fs, os::unix::fs::DirBuilderExt, path::PathBuf, time::Duration};
struct Fixture(PathBuf);
impl Fixture {
fn new(raw: &[u8]) -> Self {
assert_eq!(
unsafe { libc::geteuid() },
0,
"Run only in the isolated Root container scratch fixture, never as a host daemon"
);
let path = PathBuf::from(format!("/run/rmm-record-unit-{}", Uuid::new_v4()));
fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
fs::DirBuilder::new()
.mode(0o700)
.create(path.join("records"))
.unwrap();
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path.join(CURRENT))
.unwrap();
file.write_all(raw).unwrap();
file.sync_all().unwrap();
Self(path)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
fs::remove_dir_all(&self.0).unwrap();
}
}
fn budget() -> Budget {
let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id")
.unwrap()
.trim()
.parse()
.unwrap();
Budget::new(boot, Duration::from_secs(10)).unwrap()
}
fn fixture_record() -> BuiltRecord {
let golden: serde_json::Value = serde_json::from_str(include_str!(
"../../../tests/agent_update/codec-golden.json"
))
.unwrap();
let mut update: ResolvedAgentUpdate = serde_json::from_value(
golden["linux_full"]["payload"]["jobs"][0]["payload"]["action"]["update"].clone(),
)
.unwrap();
let mut prior_manifest = update.manifest().unwrap();
prior_manifest.release_id = update.predecessor.release_id;
prior_manifest.release_sequence = update.predecessor.release_sequence;
prior_manifest.artifacts[0].sha256 = update.predecessor.agent_sha256.clone();
prior_manifest.artifacts[1].sha256 = update.predecessor.helper_sha256.clone();
let mut prior_envelope = update.release_envelope.clone();
let payload = serde_json::to_vec(&prior_manifest).unwrap();
prior_envelope.payload_bytes = URL_SAFE_NO_PAD.encode(&payload);
let prior = InstalledReleaseRecord {
schema_version: 1,
profile: "decoder_compatible_handoff_v1".into(),
platform: prior_manifest.platform,
release_envelope: prior_envelope,
manifest_sha256: hash(&payload),
activation_floor: prior_manifest.release_sequence,
activated_at: 100,
previous_record_sha256: None,
activation_evidence: ActivationEvidence::Bootstrap {
qualification_receipt_sha256: "12".repeat(32),
},
rolled_back: false,
};
let prior_raw = prior.bytes().unwrap();
update.predecessor.installed_record_sha256 = hash(&prior_raw);
update.predecessor.manifest_sha256 = prior.manifest_sha256;
let receipt = HealthReceipt {
schema_version: 1,
handoff_sha256: "34".repeat(32),
owner_nonce: Uuid::new_v4(),
boot_id: Uuid::new_v4(),
helper_journal_id: Uuid::new_v4(),
agent_journal_id: Uuid::new_v4(),
connection_generation: 2,
service_processes: vec![],
ledger_identity_sha256: "56".repeat(32),
signed_sync_decision_id: Uuid::new_v4(),
signed_sync_request_sha256: "78".repeat(32),
signed_sync_response_sha256: "9a".repeat(32),
signed_sync_applied_at: 120,
ready: false,
inventory_message_id: Uuid::new_v4(),
inventory_received_at: 120,
inventory_ack_sha256: "bc".repeat(32),
issued_at: 123,
valid_until: 150,
};
let health = SignedHealth {
payload: serde_json::to_vec(&receipt).unwrap(),
signature: vec![0; 64],
};
let result = BuiltRecord::assemble(
&update,
&prior_raw,
&receipt.handoff_sha256,
&health,
&receipt,
Uuid::new_v4(),
receipt.owner_nonce,
)
.unwrap();
assert_eq!(result.record.activated_at, 123);
assert_eq!(
result.record.activation_floor,
update.manifest().unwrap().release_sequence
);
assert_eq!(
result.record.previous_record_sha256.as_deref(),
Some(hash(&prior_raw).as_str())
);
let ActivationEvidence::Updated {
signed_health_sha256,
..
} = &result.record.activation_evidence
else {
panic!("fixture")
};
assert_eq!(
*signed_health_sha256,
hash(&serde_json::to_vec(&health).unwrap())
);
result
}
#[derive(Default)]
struct CheckedFence {
calls: Vec<(bool, RecordPhase)>,
}
impl RecordFence for CheckedFence {
fn before_effect(
&mut self,
effect: &NativeEffect,
proof: &RecordNamespaceProof<'_>,
) -> Result<()> {
proof.verify()?;
let phase = match effect {
NativeEffect::SaveInstalledRecord {
old_sha256,
new_sha256,
} => {
ensure!(
old_sha256 == proof.old_sha256() && new_sha256 == proof.new_sha256(),
"fixture pair"
);
RecordPhase::Prepared
}
NativeEffect::PublishInstalledRecord {
old_sha256,
new_sha256,
} => {
ensure!(
old_sha256 == proof.old_sha256() && new_sha256 == proof.new_sha256(),
"fixture pair"
);
RecordPhase::Saved
}
_ => anyhow::bail!("fixture unexpected effect"),
};
ensure!(proof.phase() == phase, "fixture phase");
self.calls.push((true, phase));
Ok(())
}
fn after_effect(
&mut self,
effect: &NativeEffect,
proof: &RecordNamespaceProof<'_>,
observation: &str,
) -> Result<()> {
let phase = match effect {
NativeEffect::SaveInstalledRecord { .. } => RecordPhase::Saved,
NativeEffect::PublishInstalledRecord { .. } => RecordPhase::Published,
_ => anyhow::bail!("fixture unexpected effect"),
};
ensure!(
proof.phase() == phase && observation == proof.observation_sha256()?,
"fixture observation"
);
self.calls.push((false, phase));
Ok(())
}
}
#[test]
fn separate_record_renames_preserve_original_inode_and_both_raw_archives() {
let built = fixture_record();
let fixture = Fixture::new(&built.prior_raw);
let budget = budget();
let old_raw = built.prior_raw.clone();
let new_raw = built.raw.clone();
let old_hash = built.old_sha256.clone();
let new_hash = built.sha256.clone();
let mut transition = RecordTransition::prepare_in(&fixture.0, built, &budget).unwrap();
let original = transition.namespace_proof().old_file().identity.clone();
let mut fence = CheckedFence::default();
transition.save_previous(&mut fence, &budget).unwrap();
assert!(!fixture.0.join(CURRENT).exists());
assert_eq!(
fs::read(fixture.0.join(&transition.previous_name)).unwrap(),
old_raw
);
transition.publish(&mut fence, &budget).unwrap();
assert_eq!(fs::read(fixture.0.join(CURRENT)).unwrap(), new_raw);
assert_eq!(&transition.namespace_proof().old_file().identity, &original);
assert_eq!(
fs::read(fixture.0.join("records").join(format!("{old_hash}.json"))).unwrap(),
old_raw
);
assert_eq!(
fs::read(fixture.0.join("records").join(format!("{new_hash}.json"))).unwrap(),
new_raw
);
assert_eq!(
fence.calls,
vec![
(true, RecordPhase::Prepared),
(false, RecordPhase::Saved),
(true, RecordPhase::Saved),
(false, RecordPhase::Published)
]
);
assert!(transition.publish(&mut fence, &budget).is_err());
}
#[test]
fn same_byte_inode_substitution_and_foreign_current_block_without_resume() {
let built = fixture_record();
let fixture = Fixture::new(&built.prior_raw);
let budget = budget();
let old_raw = built.prior_raw.clone();
let mut transition = RecordTransition::prepare_in(&fixture.0, built, &budget).unwrap();
fs::rename(fixture.0.join(CURRENT), fixture.0.join("retained-original")).unwrap();
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(fixture.0.join(CURRENT))
.unwrap();
file.write_all(&old_raw).unwrap();
file.sync_all().unwrap();
let mut fence = CheckedFence::default();
assert!(transition.save_previous(&mut fence, &budget).is_err());
assert!(fence.calls.is_empty());
assert!(transition.save_previous(&mut fence, &budget).is_err());
assert_eq!(
fs::read(fixture.0.join("retained-original")).unwrap(),
old_raw
);
let built = fixture_record();
let other = Fixture::new(&built.prior_raw);
let mut transition = RecordTransition::prepare_in(&other.0, built, &budget).unwrap();
transition.save_previous(&mut fence, &budget).unwrap();
let mut foreign = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(other.0.join(CURRENT))
.unwrap();
foreign.write_all(b"foreign public fixture").unwrap();
foreign.sync_all().unwrap();
let calls = fence.calls.len();
assert!(transition.publish(&mut fence, &budget).is_err());
assert_eq!(fence.calls.len(), calls);
assert_eq!(
fs::read(other.0.join(CURRENT)).unwrap(),
b"foreign public fixture"
);
assert!(transition.publish(&mut fence, &budget).is_err());
}
}