Add typed updater handoff and preserving Linux Full renderer
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:
2026-11-14 19:27:52 +01:00
parent 3543e07779
commit a2efb7990b
8 changed files with 1888 additions and 1 deletions
+713
View File
@@ -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)
}
+309
View File
@@ -0,0 +1,309 @@
//! Closed renderer for the existing Linux Full helper Config -> Policy ->
//! GeneralPin schema2. Definitions are deliberately a versioned snapshot until
//! integration can use the reviewed runtime types. No arbitrary JSON patch,
//! paths, key loading, permission migration, service operation or publication.
use crate::{digest, sha256};
use anyhow::{Result, ensure};
use ed25519_dalek::VerifyingKey;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Binding {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
enrollment_generation: u64,
assignment_version: u64,
public_key_hex: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Identity {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
enrollment_generation: u64,
assignment_version: u64,
signing_key_id: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum FullProfile {
#[serde(rename = "full_maintenance_v1")]
FullMaintenanceV1,
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct Config {
profile: FullProfile,
binding: Binding,
#[serde(default)]
signing_key_file: Option<String>,
agent_uid: u32,
socket_gid: u32,
socket: String,
state: String,
allowed_services: Vec<String>,
allow_reboot: bool,
allow_root_scripts: bool,
allowed_script_profiles: Vec<FullProfile>,
helper_binary_sha256: String,
/// Full Config forbids an APT provider; any non-null value is rejected.
#[serde(default)]
apt_provider: Option<()>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u32,
profile: FullProfile,
identity: Identity,
allowed_services: Vec<String>,
allow_root_scripts: bool,
allow_reboot: bool,
allowed_script_profiles: Vec<FullProfile>,
helper_binary_sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Pin {
schema_version: u32,
profile: FullProfile,
identity: Identity,
policy_sha256: String,
helper_binary_sha256: String,
}
/// Only value spans of these named TOP-LEVEL fields are selected. Full typed
/// decoding first rejects unknown/duplicate fields, including nested objects.
#[derive(Deserialize)]
struct ConfigSpans<'a> {
#[serde(borrow)]
helper_binary_sha256: &'a RawValue,
}
#[derive(Deserialize)]
struct PinSpans<'a> {
#[serde(borrow)]
policy_sha256: &'a RawValue,
#[serde(borrow)]
helper_binary_sha256: &'a RawValue,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct LinuxFullTransitionProof {
pub schema_version: u32,
pub old_config_sha256: String,
pub new_config_sha256: String,
pub old_pin_sha256: String,
pub new_pin_sha256: String,
pub old_policy_sha256: String,
pub new_policy_sha256: String,
pub old_helper_sha256: String,
pub new_helper_sha256: String,
pub effective_signing_key_id: String,
}
/// Private construction preserves correspondence between rendered bytes and
/// their fixed proof. Wire proof fields remain untrusted once transported.
pub struct LinuxFullTransition {
proof: LinuxFullTransitionProof,
new_config: Vec<u8>,
new_pin: Vec<u8>,
}
impl LinuxFullTransition {
pub fn proof(&self) -> &LinuxFullTransitionProof {
&self.proof
}
pub fn new_config_bytes(&self) -> &[u8] {
&self.new_config
}
pub fn new_pin_bytes(&self) -> &[u8] {
&self.new_pin
}
pub fn sha256(&self) -> Result<String> {
Ok(sha256(&serde_json::to_vec(&self.proof)?))
}
}
/// The adapter must compare old bytes to the exact protected deployed files,
/// bind BOTH returned raw-file hashes in the immutable job before approval,
/// and independently recheck the same closed transition before/after swap.
/// General/APT bytes and central rights/scopes are never rendered or changed.
/// `provisioned_signing_key` must be independently authenticated from the
/// already provisioned public-key record/pinned identity by the adapter.
/// Parsing a VerifyingKey alone does NOT authenticate its provisioning.
/// This pure function never opens `signing_key_file` or modifies inline keys.
pub fn render_linux_full(
config_bytes: &[u8],
pin_bytes: &[u8],
target_helper: &str,
provisioned_signing_key: &VerifyingKey,
) -> Result<LinuxFullTransition> {
ensure!(
!config_bytes.is_empty()
&& config_bytes.len() <= 16384
&& !pin_bytes.is_empty()
&& pin_bytes.len() <= 8192,
"FULL_RENDER_LIMIT"
);
digest(target_helper)?;
let config: Config = serde_json::from_slice(config_bytes)?;
let pin: Pin = serde_json::from_slice(pin_bytes)?;
digest(&config.helper_binary_sha256)?;
ensure!(
!provisioned_signing_key.is_weak(),
"FULL_RENDER_WEAK_SIGNING_KEY"
);
let effective_public_key = hex::encode(provisioned_signing_key.as_bytes());
if let Some(path) = &config.signing_key_file {
ensure!(path.starts_with('/'), "FULL_RENDER_KEY_PATH_ABSOLUTE");
ensure!(
config.binding.public_key_hex.is_empty()
|| config.binding.public_key_hex == effective_public_key,
"FULL_RENDER_PROVISIONED_KEY_MISMATCH"
);
} else {
ensure!(
config.binding.public_key_hex == effective_public_key,
"FULL_RENDER_INLINE_KEY_REQUIRED"
);
}
ensure!(
config.helper_binary_sha256 != target_helper,
"FULL_RENDER_SAME_IMAGE"
);
ensure!(
!config.binding.tenant_id.is_nil()
&& !config.binding.asset_id.is_nil()
&& !config.binding.agent_id.is_nil()
&& config.binding.enrollment_generation > 0
&& config.binding.assignment_version > 0,
"FULL_RENDER_IDENTITY"
);
ensure!(
config.allowed_services.is_empty()
&& !config.allow_reboot
&& config.allow_root_scripts
&& config.allowed_script_profiles == [FullProfile::FullMaintenanceV1]
&& config.apt_provider.is_none()
&& config.state == "/var/lib/rmm-helper"
&& config.socket.starts_with('/')
&& config.socket != "/run/rmm-apt-helper/helper.sock"
&& config.agent_uid > 0
&& config.socket_gid > 0,
"FULL_RENDER_PROFILE"
);
let identity = Identity {
tenant_id: config.binding.tenant_id,
asset_id: config.binding.asset_id,
agent_id: config.binding.agent_id,
enrollment_generation: config.binding.enrollment_generation,
assignment_version: config.binding.assignment_version,
signing_key_id: sha256(provisioned_signing_key.as_bytes()),
};
let mut policy = Policy {
schema_version: 2,
profile: FullProfile::FullMaintenanceV1,
identity,
allowed_services: config.allowed_services.clone(),
allow_root_scripts: config.allow_root_scripts,
allow_reboot: config.allow_reboot,
allowed_script_profiles: config.allowed_script_profiles.clone(),
helper_binary_sha256: config.helper_binary_sha256.clone(),
};
let old_policy_sha256 = sha256(&serde_json::to_vec(&policy)?);
ensure!(
pin.schema_version == 2
&& pin.identity == policy.identity
&& pin.helper_binary_sha256 == config.helper_binary_sha256
&& pin.policy_sha256 == old_policy_sha256,
"FULL_RENDER_PIN_BINDING"
);
policy.helper_binary_sha256 = target_helper.into();
let new_policy_sha256 = sha256(&serde_json::to_vec(&policy)?);
let config_spans: ConfigSpans<'_> = serde_json::from_slice(config_bytes)?;
let pin_spans: PinSpans<'_> = serde_json::from_slice(pin_bytes)?;
let new_config = replace_spans(
config_bytes,
vec![(config_spans.helper_binary_sha256, target_helper)],
)?;
let new_pin = replace_spans(
pin_bytes,
vec![
(pin_spans.helper_binary_sha256, target_helper),
(pin_spans.policy_sha256, &new_policy_sha256),
],
)?;
let rendered_config: Config = serde_json::from_slice(&new_config)?;
let rendered_pin: Pin = serde_json::from_slice(&new_pin)?;
let mut expected_config = config.clone();
expected_config.helper_binary_sha256 = target_helper.into();
let mut expected_pin = pin;
expected_pin.helper_binary_sha256 = target_helper.into();
expected_pin.policy_sha256.clone_from(&new_policy_sha256);
ensure!(
rendered_config == expected_config && rendered_pin == expected_pin,
"FULL_RENDER_UNEXPECTED_CHANGE"
);
Ok(LinuxFullTransition {
proof: LinuxFullTransitionProof {
schema_version: 1,
old_config_sha256: sha256(config_bytes),
new_config_sha256: sha256(&new_config),
old_pin_sha256: sha256(pin_bytes),
new_pin_sha256: sha256(&new_pin),
old_policy_sha256,
new_policy_sha256,
old_helper_sha256: config.helper_binary_sha256,
new_helper_sha256: target_helper.into(),
effective_signing_key_id: sha256(provisioned_signing_key.as_bytes()),
},
new_config,
new_pin,
})
}
fn replace_spans(bytes: &[u8], values: Vec<(&RawValue, &str)>) -> Result<Vec<u8>> {
let mut spans = Vec::new();
for (raw, replacement) in values {
let raw = raw.get();
let start = (raw.as_ptr() as usize)
.checked_sub(bytes.as_ptr() as usize)
.ok_or_else(|| anyhow::anyhow!("FULL_RENDER_SPAN"))?;
let end = start
.checked_add(raw.len())
.ok_or_else(|| anyhow::anyhow!("FULL_RENDER_SPAN"))?;
ensure!(
bytes.get(start..end) == Some(raw.as_bytes())
&& raw.len() == 66
&& raw.starts_with('"')
&& raw.ends_with('"'),
"FULL_RENDER_HASH_ENCODING"
);
digest(&raw[1..65])?;
spans.push((start, end, format!("\"{replacement}\"")));
}
spans.sort_by_key(|span| span.0);
ensure!(
spans.windows(2).all(|p| p[0].1 <= p[1].0),
"FULL_RENDER_SPAN_OVERLAP"
);
let mut rendered = Vec::with_capacity(bytes.len());
let mut cursor = 0;
for (start, end, replacement) in spans {
rendered.extend_from_slice(&bytes[cursor..start]);
rendered.extend_from_slice(replacement.as_bytes());
cursor = end;
}
rendered.extend_from_slice(&bytes[cursor..]);
Ok(rendered)
}