Add typed updater handoff and preserving Linux Full renderer
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
Keep release verifier and native drivers unchanged. Independently reviewed as an isolated contract after provisioned-file-key correction; eight local release contracts and format/clippy checks pass. Runtime persistence, approvals, service ownership, apply and rollback remain unimplemented.
This commit is contained in:
@@ -0,0 +1,713 @@
|
||||
//! Draft, effect-free helper/updater handoff contract. No approval, grant,
|
||||
//! service operation, lock acquisition, persistence or general start lease.
|
||||
//!
|
||||
//! A platform adapter must authenticate the original request, atomically store
|
||||
//! consumption + its exact existing start witness + the handoff in the SAME
|
||||
//! helper ledger, and durably append each event before performing its action.
|
||||
//! This module validates retained bytes and sequencing; it cannot attest OS
|
||||
//! observations or make an uncommitted in-memory event durable.
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
mod linux_full;
|
||||
pub use linux_full::{LinuxFullTransition, LinuxFullTransitionProof, render_linux_full};
|
||||
|
||||
pub const MAX_RECORD_BYTES: usize = 16 * 1024;
|
||||
pub const MAX_EVENT_BYTES: usize = 16 * 1024;
|
||||
pub const MAX_EVENTS: usize = 16;
|
||||
pub const HEALTH_DOMAIN: &[u8] = b"rmm.agent-update-health.v1\0";
|
||||
|
||||
/// All fields below are untrusted wire data, never authorization capabilities.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AttemptBinding {
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub enrollment_generation: u64,
|
||||
pub assignment_version: u64,
|
||||
pub plan_id: Uuid,
|
||||
pub plan_sha256: String,
|
||||
pub job_id: Uuid,
|
||||
pub attempt_id: Uuid,
|
||||
pub job_payload_sha256: String,
|
||||
pub grant_id: Uuid,
|
||||
pub authorization_id: Uuid,
|
||||
pub original_request_sha256: String,
|
||||
pub original_start_witness_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CodePair {
|
||||
pub manifest_sha256: String,
|
||||
pub agent_sha256: String,
|
||||
pub helper_sha256: String,
|
||||
pub pin_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Service {
|
||||
LinuxAgent,
|
||||
LinuxGeneralHelper,
|
||||
LinuxAptHelper,
|
||||
LinuxFullHelper,
|
||||
WindowsAgent,
|
||||
WindowsHelper,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PinTransition {
|
||||
UnchangedLinuxGeneralV1,
|
||||
LinuxGeneralFullV1,
|
||||
WindowsCodePairV1,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FileRole {
|
||||
AgentBinary,
|
||||
HelperBinary,
|
||||
LinuxFullConfig,
|
||||
LinuxFullPin,
|
||||
WindowsSettings,
|
||||
WindowsPin,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FileTransition {
|
||||
pub role: FileRole,
|
||||
pub old_sha256: String,
|
||||
pub new_sha256: String,
|
||||
}
|
||||
|
||||
/// Hashes bind the retained, authenticated baseline; they are not substitutes
|
||||
/// for reading original rows/signatures/inodes through pinned OS handles.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Handoff {
|
||||
pub schema_version: u32,
|
||||
pub attempt: AttemptBinding,
|
||||
pub agent_journal_id: Uuid,
|
||||
pub helper_journal_id: Uuid,
|
||||
pub helper_checkpoint: u64,
|
||||
pub previous_decision_id: Uuid,
|
||||
pub boot_id: Uuid,
|
||||
pub connection_generation: u64,
|
||||
pub owner_nonce: Uuid,
|
||||
pub updater_sha256: String,
|
||||
pub updater_policy_sha256: String,
|
||||
pub predecessor_record_sha256: String,
|
||||
pub retained_state_sha256: String,
|
||||
pub ledger_identity_sha256: String,
|
||||
pub staged_files_sha256: String,
|
||||
pub predecessor: CodePair,
|
||||
pub target: CodePair,
|
||||
pub pin_transition: PinTransition,
|
||||
pub pin_transition_sha256: String,
|
||||
pub files: Vec<FileTransition>,
|
||||
/// Exact provisioned order. All installed helper profiles must be present.
|
||||
pub stop_set: Vec<Service>,
|
||||
pub consumed_at: u64,
|
||||
pub finish_before: u64,
|
||||
}
|
||||
|
||||
impl Handoff {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(self.schema_version == 1, "HANDOFF_SCHEMA");
|
||||
for id in [
|
||||
self.attempt.tenant_id,
|
||||
self.attempt.asset_id,
|
||||
self.attempt.agent_id,
|
||||
self.attempt.plan_id,
|
||||
self.attempt.job_id,
|
||||
self.attempt.attempt_id,
|
||||
self.attempt.grant_id,
|
||||
self.attempt.authorization_id,
|
||||
self.agent_journal_id,
|
||||
self.helper_journal_id,
|
||||
self.previous_decision_id,
|
||||
self.boot_id,
|
||||
self.owner_nonce,
|
||||
] {
|
||||
ensure!(!id.is_nil(), "HANDOFF_NIL_ID");
|
||||
}
|
||||
ensure!(
|
||||
self.attempt.enrollment_generation > 0
|
||||
&& self.attempt.assignment_version > 0
|
||||
&& self.connection_generation > 0,
|
||||
"HANDOFF_GENERATION"
|
||||
);
|
||||
for hash in [
|
||||
&self.attempt.plan_sha256,
|
||||
&self.attempt.job_payload_sha256,
|
||||
&self.attempt.original_request_sha256,
|
||||
&self.attempt.original_start_witness_sha256,
|
||||
&self.updater_sha256,
|
||||
&self.updater_policy_sha256,
|
||||
&self.predecessor_record_sha256,
|
||||
&self.retained_state_sha256,
|
||||
&self.ledger_identity_sha256,
|
||||
&self.staged_files_sha256,
|
||||
&self.pin_transition_sha256,
|
||||
] {
|
||||
digest(hash)?;
|
||||
}
|
||||
for pair in [&self.predecessor, &self.target] {
|
||||
for hash in [
|
||||
&pair.manifest_sha256,
|
||||
&pair.agent_sha256,
|
||||
&pair.helper_sha256,
|
||||
&pair.pin_sha256,
|
||||
] {
|
||||
digest(hash)?;
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
self.predecessor.manifest_sha256 != self.target.manifest_sha256,
|
||||
"HANDOFF_SAME_RELEASE"
|
||||
);
|
||||
ensure!(
|
||||
self.consumed_at > 0
|
||||
&& self.finish_before > self.consumed_at
|
||||
&& self.finish_before - self.consumed_at <= 600,
|
||||
"HANDOFF_DEADLINE"
|
||||
);
|
||||
let roles: Vec<_> = self.files.iter().map(|file| file.role).collect();
|
||||
let expected_roles = match self.pin_transition {
|
||||
PinTransition::UnchangedLinuxGeneralV1 => {
|
||||
vec![FileRole::AgentBinary, FileRole::HelperBinary]
|
||||
}
|
||||
PinTransition::LinuxGeneralFullV1 => vec![
|
||||
FileRole::AgentBinary,
|
||||
FileRole::HelperBinary,
|
||||
FileRole::LinuxFullConfig,
|
||||
FileRole::LinuxFullPin,
|
||||
],
|
||||
PinTransition::WindowsCodePairV1 => vec![
|
||||
FileRole::AgentBinary,
|
||||
FileRole::HelperBinary,
|
||||
FileRole::WindowsSettings,
|
||||
FileRole::WindowsPin,
|
||||
],
|
||||
};
|
||||
ensure!(roles == expected_roles, "HANDOFF_FILE_SET");
|
||||
for file in &self.files {
|
||||
digest(&file.old_sha256)?;
|
||||
digest(&file.new_sha256)?;
|
||||
}
|
||||
ensure!(
|
||||
self.files[0].old_sha256 == self.predecessor.agent_sha256
|
||||
&& self.files[0].new_sha256 == self.target.agent_sha256
|
||||
&& self.files[1].old_sha256 == self.predecessor.helper_sha256
|
||||
&& self.files[1].new_sha256 == self.target.helper_sha256,
|
||||
"HANDOFF_FILE_IMAGE_BINDING"
|
||||
);
|
||||
if self.files.len() == 4 {
|
||||
ensure!(
|
||||
self.files[3].old_sha256 == self.predecessor.pin_sha256
|
||||
&& self.files[3].new_sha256 == self.target.pin_sha256,
|
||||
"HANDOFF_FILE_PIN_BINDING"
|
||||
);
|
||||
}
|
||||
match self.pin_transition {
|
||||
PinTransition::UnchangedLinuxGeneralV1 => {
|
||||
ensure!(
|
||||
self.stop_set == [Service::LinuxAgent, Service::LinuxGeneralHelper]
|
||||
|| self.stop_set
|
||||
== [
|
||||
Service::LinuxAgent,
|
||||
Service::LinuxGeneralHelper,
|
||||
Service::LinuxAptHelper
|
||||
],
|
||||
"HANDOFF_UNSUPPORTED_SERVICE_SET"
|
||||
);
|
||||
ensure!(
|
||||
self.predecessor.pin_sha256 == self.target.pin_sha256,
|
||||
"HANDOFF_LINUX_PIN_CHANGED"
|
||||
);
|
||||
}
|
||||
PinTransition::LinuxGeneralFullV1 => ensure!(
|
||||
self.stop_set
|
||||
== [
|
||||
Service::LinuxAgent,
|
||||
Service::LinuxGeneralHelper,
|
||||
Service::LinuxFullHelper
|
||||
]
|
||||
|| self.stop_set
|
||||
== [
|
||||
Service::LinuxAgent,
|
||||
Service::LinuxGeneralHelper,
|
||||
Service::LinuxFullHelper,
|
||||
Service::LinuxAptHelper
|
||||
],
|
||||
"HANDOFF_UNSUPPORTED_SERVICE_SET"
|
||||
),
|
||||
PinTransition::WindowsCodePairV1 => ensure!(
|
||||
self.stop_set == [Service::WindowsAgent, Service::WindowsHelper],
|
||||
"HANDOFF_UNSUPPORTED_SERVICE_SET"
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn bytes(&self) -> Result<Vec<u8>> {
|
||||
self.validate()?;
|
||||
let bytes = serde_json::to_vec(self)?;
|
||||
ensure!(bytes.len() <= MAX_RECORD_BYTES, "HANDOFF_TOO_LARGE");
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Concrete process birth, not an unqualified PID or a service's Running flag.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Process {
|
||||
pub pid: u32,
|
||||
pub birth: u64,
|
||||
pub image_sha256: String,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
fn validate(&self, expected_image: &str) -> Result<()> {
|
||||
ensure!(
|
||||
self.pid > 0 && self.birth > 0 && self.image_sha256 == expected_image,
|
||||
"HANDOFF_PROCESS_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct StartedService {
|
||||
pub service: Service,
|
||||
pub process: Process,
|
||||
}
|
||||
|
||||
/// The server signs evidence only. `ready` MUST be false while the original
|
||||
/// handoff remains inflight; this receipt is never an ExecutionPermit.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HealthReceipt {
|
||||
pub schema_version: u32,
|
||||
pub handoff_sha256: String,
|
||||
pub owner_nonce: Uuid,
|
||||
pub boot_id: Uuid,
|
||||
pub helper_journal_id: Uuid,
|
||||
pub agent_journal_id: Uuid,
|
||||
pub connection_generation: u64,
|
||||
pub service_processes: Vec<StartedService>,
|
||||
pub ledger_identity_sha256: String,
|
||||
pub signed_sync_decision_id: Uuid,
|
||||
pub signed_sync_request_sha256: String,
|
||||
pub signed_sync_response_sha256: String,
|
||||
pub signed_sync_applied_at: u64,
|
||||
pub ready: bool,
|
||||
pub inventory_message_id: Uuid,
|
||||
pub inventory_received_at: u64,
|
||||
pub inventory_ack_sha256: String,
|
||||
pub issued_at: u64,
|
||||
pub valid_until: u64,
|
||||
}
|
||||
|
||||
/// Already decoded, bounded input; a network adapter must also bound encoding.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SignedHealth {
|
||||
pub payload: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "phase", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Evidence {
|
||||
StopIntent,
|
||||
AllStopped {
|
||||
observation_sha256: String,
|
||||
},
|
||||
UpdaterOwnsLedger {
|
||||
process: Process,
|
||||
ledger_identity_sha256: String,
|
||||
},
|
||||
ReplaceIntent {
|
||||
role: FileRole,
|
||||
},
|
||||
Replaced {
|
||||
role: FileRole,
|
||||
observed_sha256: String,
|
||||
},
|
||||
PairVerified {
|
||||
pair: CodePair,
|
||||
retained_state_sha256: String,
|
||||
},
|
||||
/// This append must be flushed under the updater guard; the guard is then
|
||||
/// dropped BEFORE starting the new helper, which reacquires the SAME lock.
|
||||
LedgerReturnIntent,
|
||||
ServicesStarted {
|
||||
services: Vec<StartedService>,
|
||||
ledger_identity_sha256: String,
|
||||
observation_sha256: String,
|
||||
},
|
||||
HealthVerified {
|
||||
receipt: SignedHealth,
|
||||
},
|
||||
/// Only the new helper's existing outcome-CAS may persist this outcome.
|
||||
/// It must still reject any pre-existing definitive Unknown/outcome.
|
||||
OutcomePersisted {
|
||||
outcome_sha256: String,
|
||||
},
|
||||
Unknown {
|
||||
reason: UnknownReason,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UnknownReason {
|
||||
OwnerLost,
|
||||
BootChanged,
|
||||
DeadlineExpired,
|
||||
StopUncertain,
|
||||
ReplaceUncertain,
|
||||
StartUncertain,
|
||||
StateChanged,
|
||||
HealthUnproven,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Event {
|
||||
pub schema_version: u32,
|
||||
pub handoff_sha256: String,
|
||||
pub sequence: u32,
|
||||
pub previous_sha256: String,
|
||||
pub observed_at: u64,
|
||||
pub boot_id: Uuid,
|
||||
pub evidence: Evidence,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
HandoffConsumed,
|
||||
StopIntent,
|
||||
AllStopped,
|
||||
UpdaterOwnsLedger,
|
||||
ReplaceIntent,
|
||||
Replaced,
|
||||
PairVerified,
|
||||
LedgerReturnIntent,
|
||||
ServicesStarted,
|
||||
HealthVerified,
|
||||
OutcomePersisted,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Retained journal view. No method returns a start grant, ready flag, retry,
|
||||
/// rollback or instruction to perform a service/file operation after a crash.
|
||||
pub struct Journal {
|
||||
handoff: Handoff,
|
||||
handoff_hash: String,
|
||||
head_hash: String,
|
||||
count: u32,
|
||||
phase: Phase,
|
||||
replaced: usize,
|
||||
observed_at: u64,
|
||||
started: Option<(Vec<StartedService>, u64)>,
|
||||
health_key: VerifyingKey,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
/// The caller independently verifies this record against the ORIGINAL
|
||||
/// consumed row/start witness, participant policy and retained state.
|
||||
pub fn open(record: &[u8], health_public_key: [u8; 32]) -> Result<Self> {
|
||||
let handoff: Handoff = canonical(record, MAX_RECORD_BYTES)?;
|
||||
handoff.validate()?;
|
||||
let health_key = VerifyingKey::from_bytes(&health_public_key)?;
|
||||
ensure!(!health_key.is_weak(), "HANDOFF_WEAK_HEALTH_KEY");
|
||||
let handoff_hash = sha256(record);
|
||||
Ok(Self {
|
||||
observed_at: handoff.consumed_at,
|
||||
handoff,
|
||||
head_hash: handoff_hash.clone(),
|
||||
handoff_hash,
|
||||
count: 0,
|
||||
phase: Phase::HandoffConsumed,
|
||||
replaced: 0,
|
||||
started: None,
|
||||
health_key,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn phase(&self) -> Phase {
|
||||
self.phase
|
||||
}
|
||||
pub fn head_sha256(&self) -> &str {
|
||||
&self.head_hash
|
||||
}
|
||||
pub fn handoff_sha256(&self) -> &str {
|
||||
&self.handoff_hash
|
||||
}
|
||||
|
||||
/// Prepare exact bytes for a bounded append-only CAS transaction against
|
||||
/// `head_sha256`. Returning bytes is NOT proof that this transaction ran.
|
||||
pub fn prepare(&self, observed_at: u64, evidence: Evidence) -> Result<Vec<u8>> {
|
||||
let event = Event {
|
||||
schema_version: 1,
|
||||
handoff_sha256: self.handoff_hash.clone(),
|
||||
sequence: self.count + 1,
|
||||
previous_sha256: self.head_hash.clone(),
|
||||
observed_at,
|
||||
boot_id: self.handoff.boot_id,
|
||||
evidence,
|
||||
};
|
||||
self.validate_event(&event)?;
|
||||
let bytes = serde_json::to_vec(&event)?;
|
||||
ensure!(bytes.len() <= MAX_EVENT_BYTES, "HANDOFF_EVENT_TOO_LARGE");
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Strict historical replay. The platform must check durable head/rowcount,
|
||||
/// inode/FileID and original ledger lineage to detect omitted suffixes.
|
||||
pub fn replay(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
let event: Event = canonical(bytes, MAX_EVENT_BYTES)?;
|
||||
let next = self.validate_event(&event)?;
|
||||
if matches!(event.evidence, Evidence::Replaced { .. }) {
|
||||
self.replaced += 1;
|
||||
}
|
||||
if let Evidence::ServicesStarted { services, .. } = event.evidence {
|
||||
self.started = Some((services, event.observed_at));
|
||||
}
|
||||
self.phase = next;
|
||||
self.observed_at = event.observed_at;
|
||||
self.count = event.sequence;
|
||||
self.head_hash = sha256(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_event(&self, event: &Event) -> Result<Phase> {
|
||||
ensure!(
|
||||
event.schema_version == 1
|
||||
&& event.handoff_sha256 == self.handoff_hash
|
||||
&& event.sequence == self.count + 1
|
||||
&& (event.sequence as usize) <= MAX_EVENTS
|
||||
&& event.previous_sha256 == self.head_hash,
|
||||
"HANDOFF_EVENT_CHAIN"
|
||||
);
|
||||
ensure!(
|
||||
!matches!(self.phase, Phase::Unknown | Phase::OutcomePersisted),
|
||||
"HANDOFF_TERMINAL"
|
||||
);
|
||||
ensure!(
|
||||
event.boot_id == self.handoff.boot_id && event.observed_at >= self.observed_at,
|
||||
"HANDOFF_BOOT_OR_CLOCK"
|
||||
);
|
||||
if matches!(event.evidence, Evidence::Unknown { .. }) {
|
||||
return Ok(Phase::Unknown);
|
||||
}
|
||||
ensure!(
|
||||
event.observed_at < self.handoff.finish_before,
|
||||
"HANDOFF_EXPIRED"
|
||||
);
|
||||
let next = match (&self.phase, &event.evidence) {
|
||||
(Phase::HandoffConsumed, Evidence::StopIntent) => Phase::StopIntent,
|
||||
(Phase::StopIntent, Evidence::AllStopped { observation_sha256 }) => {
|
||||
digest(observation_sha256)?;
|
||||
Phase::AllStopped
|
||||
}
|
||||
(
|
||||
Phase::AllStopped,
|
||||
Evidence::UpdaterOwnsLedger {
|
||||
process,
|
||||
ledger_identity_sha256,
|
||||
},
|
||||
) => {
|
||||
process.validate(&self.handoff.updater_sha256)?;
|
||||
ensure!(
|
||||
ledger_identity_sha256 == &self.handoff.ledger_identity_sha256,
|
||||
"HANDOFF_LEDGER_IDENTITY_CHANGED"
|
||||
);
|
||||
Phase::UpdaterOwnsLedger
|
||||
}
|
||||
(Phase::UpdaterOwnsLedger | Phase::Replaced, Evidence::ReplaceIntent { role }) => {
|
||||
ensure!(
|
||||
self.handoff
|
||||
.files
|
||||
.get(self.replaced)
|
||||
.is_some_and(|file| file.role == *role),
|
||||
"HANDOFF_REPLACE_ORDER"
|
||||
);
|
||||
Phase::ReplaceIntent
|
||||
}
|
||||
(
|
||||
Phase::ReplaceIntent,
|
||||
Evidence::Replaced {
|
||||
role,
|
||||
observed_sha256,
|
||||
},
|
||||
) => {
|
||||
ensure!(
|
||||
self.handoff.files.get(self.replaced).is_some_and(
|
||||
|file| file.role == *role && file.new_sha256 == *observed_sha256
|
||||
),
|
||||
"HANDOFF_REPLACEMENT_BINDING"
|
||||
);
|
||||
Phase::Replaced
|
||||
}
|
||||
(
|
||||
Phase::Replaced,
|
||||
Evidence::PairVerified {
|
||||
pair,
|
||||
retained_state_sha256,
|
||||
},
|
||||
) => {
|
||||
ensure!(
|
||||
self.replaced == self.handoff.files.len(),
|
||||
"HANDOFF_PAIR_INCOMPLETE"
|
||||
);
|
||||
ensure!(
|
||||
pair == &self.handoff.target
|
||||
&& retained_state_sha256 == &self.handoff.retained_state_sha256,
|
||||
"HANDOFF_PAIR_OR_STATE_CHANGED"
|
||||
);
|
||||
Phase::PairVerified
|
||||
}
|
||||
(Phase::PairVerified, Evidence::LedgerReturnIntent) => Phase::LedgerReturnIntent,
|
||||
(
|
||||
Phase::LedgerReturnIntent,
|
||||
Evidence::ServicesStarted {
|
||||
services,
|
||||
ledger_identity_sha256,
|
||||
observation_sha256,
|
||||
},
|
||||
) => {
|
||||
ensure!(
|
||||
ledger_identity_sha256 == &self.handoff.ledger_identity_sha256,
|
||||
"HANDOFF_LEDGER_IDENTITY_CHANGED"
|
||||
);
|
||||
let expected: Vec<_> = self
|
||||
.handoff
|
||||
.stop_set
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|service| *service != Service::LinuxAptHelper)
|
||||
.collect();
|
||||
ensure!(
|
||||
services.len() == expected.len(),
|
||||
"HANDOFF_STARTED_SERVICE_SET"
|
||||
);
|
||||
for (index, service) in services.iter().enumerate() {
|
||||
ensure!(
|
||||
service.service == expected[index],
|
||||
"HANDOFF_STARTED_SERVICE_SET"
|
||||
);
|
||||
let image =
|
||||
if matches!(service.service, Service::LinuxAgent | Service::WindowsAgent) {
|
||||
&self.handoff.target.agent_sha256
|
||||
} else {
|
||||
&self.handoff.target.helper_sha256
|
||||
};
|
||||
service.process.validate(image)?;
|
||||
ensure!(
|
||||
!services[..index]
|
||||
.iter()
|
||||
.any(|prior| prior.process.pid == service.process.pid),
|
||||
"HANDOFF_PROCESS_REUSE"
|
||||
);
|
||||
}
|
||||
digest(observation_sha256)?;
|
||||
Phase::ServicesStarted
|
||||
}
|
||||
(Phase::ServicesStarted, Evidence::HealthVerified { receipt }) => {
|
||||
self.verify_health(receipt, event.observed_at)?;
|
||||
Phase::HealthVerified
|
||||
}
|
||||
(Phase::HealthVerified, Evidence::OutcomePersisted { outcome_sha256 }) => {
|
||||
digest(outcome_sha256)?;
|
||||
Phase::OutcomePersisted
|
||||
}
|
||||
_ => anyhow::bail!("HANDOFF_PHASE_ORDER"),
|
||||
};
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
fn verify_health(&self, signed: &SignedHealth, at: u64) -> Result<()> {
|
||||
let receipt: HealthReceipt = canonical(&signed.payload, 4096)?;
|
||||
let signature =
|
||||
Signature::from_slice(&signed.signature).context("HANDOFF_HEALTH_SIGNATURE_LENGTH")?;
|
||||
let mut message = HEALTH_DOMAIN.to_vec();
|
||||
message.extend_from_slice(&signed.payload);
|
||||
self.health_key
|
||||
.verify_strict(&message, &signature)
|
||||
.context("HANDOFF_HEALTH_SIGNATURE")?;
|
||||
let (services, started_at) = self.started.as_ref().context("HANDOFF_START_MISSING")?;
|
||||
ensure!(
|
||||
receipt.schema_version == 1
|
||||
&& receipt.handoff_sha256 == self.handoff_hash
|
||||
&& receipt.owner_nonce == self.handoff.owner_nonce
|
||||
&& receipt.boot_id == self.handoff.boot_id
|
||||
&& receipt.helper_journal_id == self.handoff.helper_journal_id
|
||||
&& receipt.agent_journal_id == self.handoff.agent_journal_id
|
||||
&& receipt.connection_generation > self.handoff.connection_generation
|
||||
&& receipt.service_processes == *services
|
||||
&& receipt.ledger_identity_sha256 == self.handoff.ledger_identity_sha256
|
||||
&& !receipt.ready,
|
||||
"HANDOFF_HEALTH_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
!receipt.signed_sync_decision_id.is_nil() && !receipt.inventory_message_id.is_nil(),
|
||||
"HANDOFF_HEALTH_ID"
|
||||
);
|
||||
for hash in [
|
||||
&receipt.signed_sync_request_sha256,
|
||||
&receipt.signed_sync_response_sha256,
|
||||
&receipt.inventory_ack_sha256,
|
||||
] {
|
||||
digest(hash)?;
|
||||
}
|
||||
ensure!(
|
||||
receipt.signed_sync_applied_at >= *started_at
|
||||
&& receipt.inventory_received_at >= *started_at
|
||||
&& receipt.issued_at >= receipt.signed_sync_applied_at
|
||||
&& receipt.issued_at >= receipt.inventory_received_at
|
||||
&& receipt.issued_at <= at
|
||||
&& at < receipt.valid_until
|
||||
&& receipt.valid_until <= self.handoff.finish_before
|
||||
&& at.checked_sub(*started_at).is_some_and(|age| age < 180),
|
||||
"HANDOFF_HEALTH_NOT_FRESH"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sha256(bytes: &[u8]) -> String {
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn digest(hash: &str) -> Result<()> {
|
||||
ensure!(
|
||||
hash.len() == 64
|
||||
&& hash
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
||||
"HANDOFF_DIGEST"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonical<T: DeserializeOwned + Serialize>(bytes: &[u8], limit: usize) -> Result<T> {
|
||||
ensure!(
|
||||
!bytes.is_empty() && bytes.len() <= limit,
|
||||
"HANDOFF_BYTE_LIMIT"
|
||||
);
|
||||
let value = serde_json::from_slice::<T>(bytes)?;
|
||||
ensure!(serde_json::to_vec(&value)? == bytes, "HANDOFF_NONCANONICAL");
|
||||
Ok(value)
|
||||
}
|
||||
Reference in New Issue
Block a user