Files
rust-discovery/crates/domain/src/agent_update.rs
T
kevin_janssen cafd13bca9
Rust development slice / linux (push) Failing after 7s
Deploy reviewed Windows sync alignment with schema 20 server
Bind the administrative connection-205 review to original signed history and preserve closed readiness. Include the qualified server dependency closure, UI review, native ARM64 build provenance, and guarded deployment evidence. Migration, API/gateway replacement and TLS checks passed with unchanged job authority, protected mounts and time/database services; native Windows receipt application remains separate.
2026-11-16 13:30:31 +01:00

943 lines
36 KiB
Rust

//! Fixed signed agent code-pair jobs. These decoded wire types validate shape
//! and exact bindings only: signature, trust, clock, policy, approval and local
//! observed predecessor remain independent admission requirements.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub const APPLY_CAPABILITY: &str = "agent.update.apply/1";
pub const CHECK_CAPABILITY: &str = "agent.update.check/1";
pub const MAX_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
/// Provisioning DTO only. The OS adapter must independently authenticate its
/// protected file, exact raw hash and generation; this type grants no trust.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdateKeyringFile {
pub schema_version: u32,
pub generation: u64,
pub keys: Vec<UpdateKeyringEntry>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdateKeyringEntry {
pub public_key_hex: String,
pub platform: Platform,
pub first_sequence: u64,
pub last_sequence: u64,
pub revoked: bool,
}
impl UpdateKeyringFile {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& self.generation > 0
&& !self.keys.is_empty()
&& self.keys.len() <= 16
&& self.keys.iter().all(|key| {
digest(&key.public_key_hex)
&& key.first_sequence > 0
&& key.last_sequence >= key.first_sequence
})
&& self.keys.iter().enumerate().all(|(i, key)| {
!self.keys[..i]
.iter()
.any(|prior| prior.public_key_hex == key.public_key_hex)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub enum Platform {
#[serde(rename = "x86_64-unknown-linux-gnu")]
LinuxX64,
#[serde(rename = "x86_64-pc-windows-msvc")]
WindowsX64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactRole {
Agent,
Helper,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ArtifactDescriptor {
pub role: ArtifactRole,
pub artifact_id: Uuid,
pub sha256: String,
pub bytes: u64,
}
/// Exact version1 field order shared with the frozen pure release verifier.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReleaseManifest {
pub schema_version: u32,
pub release_id: Uuid,
pub release_sequence: u64,
pub version: String,
pub platform: Platform,
pub published_at: u64,
pub expires_at: u64,
pub protocol_major: u32,
pub state_schema: u32,
pub minimum_updater_version: u32,
pub artifacts: [ArtifactDescriptor; 2],
}
impl ReleaseManifest {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& !self.release_id.is_nil()
&& self.release_sequence > 0
&& !self.version.is_empty()
&& self.version.len() <= 64
&& self
.version
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b))
&& self.expires_at > self.published_at
&& self.protocol_major > 0
&& self.state_schema > 0
&& self.minimum_updater_version > 0
&& self.artifacts[0].role == ArtifactRole::Agent
&& self.artifacts[1].role == ArtifactRole::Helper
&& self.artifacts[0].artifact_id != self.artifacts[1].artifact_id
&& self.artifacts.iter().all(|a| {
!a.artifact_id.is_nil()
&& digest(&a.sha256)
&& a.bytes > 0
&& a.bytes <= MAX_ARTIFACT_BYTES
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReleaseEnvelope {
pub schema_version: u32,
pub key_id: String,
/// Canonical Base64url, no padding; decoded payload at most16KiB.
pub payload_bytes: String,
/// Canonical Base64url of exactly64 signature bytes.
pub signature: String,
}
pub struct DecodedRelease {
pub payload_bytes: Vec<u8>,
pub signature: Vec<u8>,
pub manifest: ReleaseManifest,
}
/// Exact pre-existing helper Request field order. Shared read-only linkage for
/// authoritative server reconciliation, never an alternative execute request.
#[derive(Serialize)]
pub struct OriginalHelperRequest<'a> {
pub job_bytes: &'a [u8],
pub permit_bytes: &'a [u8],
pub signature: &'a [u8],
pub plan_hash: &'a str,
pub authorization_id: Uuid,
}
impl ReleaseEnvelope {
pub fn decode(&self) -> Result<DecodedRelease, &'static str> {
if self.schema_version != 1
|| !digest(&self.key_id)
|| self.payload_bytes.len() > 21846
|| self.signature.len() != 86
{
return Err("UPDATE_ENVELOPE_LIMIT");
}
let payload = URL_SAFE_NO_PAD
.decode(&self.payload_bytes)
.map_err(|_| "UPDATE_PAYLOAD_BASE64")?;
let signature = URL_SAFE_NO_PAD
.decode(&self.signature)
.map_err(|_| "UPDATE_SIGNATURE_BASE64")?;
if payload.is_empty()
|| payload.len() > 16384
|| signature.len() != 64
|| URL_SAFE_NO_PAD.encode(&payload) != self.payload_bytes
|| URL_SAFE_NO_PAD.encode(&signature) != self.signature
{
return Err("UPDATE_NONCANONICAL_BASE64");
}
let manifest: ReleaseManifest =
serde_json::from_slice(&payload).map_err(|_| "UPDATE_MANIFEST_SCHEMA")?;
if !manifest.validate()
|| serde_json::to_vec(&manifest).map_err(|_| "UPDATE_MANIFEST_CODEC")? != payload
{
return Err("UPDATE_MANIFEST_NONCANONICAL");
}
Ok(DecodedRelease {
payload_bytes: payload,
signature,
manifest,
})
}
pub fn sha256(&self) -> Result<String, serde_json::Error> {
serde_json::to_vec(self).map(|bytes| crate::jobs::hash(&bytes))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Predecessor {
pub release_id: Uuid,
pub release_sequence: u64,
pub manifest_sha256: String,
pub installed_record_sha256: String,
pub agent_sha256: String,
pub helper_sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdaterBinding {
pub binary_sha256: String,
pub policy_sha256: String,
pub keyring_generation: u64,
pub keyring_sha256: String,
pub health_public_key_hex: String,
pub health_key_pin_sha256: String,
}
/// Raw Config/Pin bytes reside in the protected fixed staging record. Their
/// exact hashes and effective provisioned key ID are bound BEFORE approval.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct LinuxFullTransition {
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,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WindowsTimeProfileTransition {
pub schema_version: u32,
pub old_time_profile_sha256: String,
pub new_time_profile_sha256: String,
pub agent_qualification_sha256: String,
pub helper_qualification_sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "profile", rename_all = "snake_case", deny_unknown_fields)]
pub enum PeerPinTransition {
UnchangedGeneralPinV1 {
general_pin_sha256: String,
},
LinuxGeneralFullV1 {
general_pin_sha256: String,
full: LinuxFullTransition,
},
WindowsCodePairV1 {
old_settings_sha256: String,
new_settings_sha256: String,
old_pin_sha256: String,
new_pin_sha256: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "strict_windows_time_profile"
)]
time_profile: Option<WindowsTimeProfileTransition>,
},
}
fn strict_windows_time_profile<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<WindowsTimeProfileTransition>, D::Error> {
WindowsTimeProfileTransition::deserialize(d).map(Some)
}
#[cfg(test)]
mod windows_time_transition_tests {
use super::*;
#[test]
fn optional_windows_clock_binding_is_additive_and_null_is_never_missing() {
let old = serde_json::json!({"profile":"windows_code_pair_v1","old_settings_sha256":"11".repeat(32),
"new_settings_sha256":"22".repeat(32),"old_pin_sha256":"33".repeat(32),"new_pin_sha256":"44".repeat(32)});
let decoded: PeerPinTransition = serde_json::from_value(old.clone()).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), old);
let mut invalid = old.clone();
invalid["time_profile"] = serde_json::Value::Null;
assert!(serde_json::from_value::<PeerPinTransition>(invalid).is_err());
let mut current = old;
current["time_profile"] = serde_json::json!({"schema_version":1,
"old_time_profile_sha256":"55".repeat(32),"new_time_profile_sha256":"66".repeat(32),
"agent_qualification_sha256":"77".repeat(32),"helper_qualification_sha256":"88".repeat(32)});
let decoded: PeerPinTransition = serde_json::from_value(current.clone()).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), current);
}
}
impl PeerPinTransition {
fn validate(&self, platform: Platform, predecessor: &Predecessor, target_helper: &str) -> bool {
match self {
Self::UnchangedGeneralPinV1 { general_pin_sha256 } => {
platform == Platform::LinuxX64 && digest(general_pin_sha256)
}
Self::LinuxGeneralFullV1 {
general_pin_sha256,
full,
} => {
platform == Platform::LinuxX64
&& digest(general_pin_sha256)
&& full.schema_version == 1
&& full.old_helper_sha256 == predecessor.helper_sha256
&& full.new_helper_sha256 == target_helper
&& [
&full.old_config_sha256,
&full.new_config_sha256,
&full.old_pin_sha256,
&full.new_pin_sha256,
&full.old_policy_sha256,
&full.new_policy_sha256,
&full.effective_signing_key_id,
]
.iter()
.all(|h| digest(h))
&& full.old_config_sha256 != full.new_config_sha256
&& full.old_pin_sha256 != full.new_pin_sha256
}
Self::WindowsCodePairV1 {
old_settings_sha256,
new_settings_sha256,
old_pin_sha256,
new_pin_sha256,
time_profile,
} => {
platform == Platform::WindowsX64
&& [
old_settings_sha256,
new_settings_sha256,
old_pin_sha256,
new_pin_sha256,
]
.iter()
.all(|h| digest(h))
&& old_settings_sha256 != new_settings_sha256
&& old_pin_sha256 != new_pin_sha256
&& time_profile.as_ref().is_none_or(|t| {
t.schema_version == 1
&& [
&t.old_time_profile_sha256,
&t.new_time_profile_sha256,
&t.agent_qualification_sha256,
&t.helper_qualification_sha256,
]
.iter()
.all(|h| digest(h))
&& t.old_time_profile_sha256 != t.new_time_profile_sha256
})
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub enum UpdateProfile {
#[serde(rename = "fixed_code_pair_v1")]
FixedCodePairV1,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub enum Recovery {
#[serde(rename = "restore_exact_predecessor_once")]
RestoreExactPredecessorOnce,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub enum HealthProfile {
#[serde(rename = "mtls_inventory_sync_v1")]
MtlsInventorySyncV1,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResolvedAgentUpdate {
pub schema_version: u32,
pub profile: UpdateProfile,
pub release_envelope: ReleaseEnvelope,
pub release_envelope_sha256: String,
pub manifest_sha256: String,
pub predecessor: Predecessor,
pub updater: UpdaterBinding,
pub peer_pin_transition: PeerPinTransition,
pub recovery: Recovery,
pub health_profile: HealthProfile,
pub health_timeout_seconds: u32,
pub no_reboot: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ObservationQuality {
Valid,
Unknown,
NotConfigured,
Error,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CandidatePreview {
pub release_id: Uuid,
pub manifest_sha256: String,
pub peer_pin_transition: PeerPinTransition,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ParticipantRole {
LinuxUpdater,
WindowsUpdater,
LinuxGeneralHelper,
LinuxFullHelper,
WindowsHelper,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ParticipantIdentity {
pub role: ParticipantRole,
pub pid: u32,
/// Exact native process creation identity, not a rounded wall clock/PID.
pub birth: u64,
pub image_sha256: String,
/// uid:0 on Linux, S-1-5-18 on Windows; local policy also pins service SID.
pub security_principal: String,
/// Protected service-unit/SCM/PID/image/creation observation hash.
pub service_instance_sha256: String,
}
impl ParticipantIdentity {
pub fn validate(&self) -> bool {
self.pid > 0
&& self.birth > 0
&& digest(&self.image_sha256)
&& digest(&self.service_instance_sha256)
&& self.security_principal
== match self.role {
ParticipantRole::LinuxUpdater
| ParticipantRole::LinuxGeneralHelper
| ParticipantRole::LinuxFullHelper => "uid:0",
ParticipantRole::WindowsUpdater | ParticipantRole::WindowsHelper => "S-1-5-18",
}
}
}
/// Explicit immutable runtime owner witness, atomically retained WITH the
/// existing original consumption/start/handoff before stopping any service.
/// Both identities come from authenticated local OS peers, never JSON claims.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdateDelegation {
pub schema_version: u32,
pub handoff_sha256: String,
pub owner_nonce: Uuid,
pub boot_id: Uuid,
pub prepared_at: chrono::DateTime<chrono::Utc>,
pub updater: ParticipantIdentity,
pub original_helper: ParticipantIdentity,
}
impl UpdateDelegation {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& digest(&self.handoff_sha256)
&& !self.owner_nonce.is_nil()
&& !self.boot_id.is_nil()
&& self.updater.validate()
&& self.original_helper.validate()
&& self.updater.pid != self.original_helper.pid
&& matches!(
(self.updater.role, self.original_helper.role),
(
ParticipantRole::LinuxUpdater,
ParticipantRole::LinuxGeneralHelper | ParticipantRole::LinuxFullHelper
) | (
ParticipantRole::WindowsUpdater,
ParticipantRole::WindowsHelper
)
)
}
}
/// A bounded exact retained journal prefix, never an outcome/start grant. All
/// binary fields are canonical Base64url to avoid nested JSON numeric arrays.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdateInflightProof {
pub schema_version: u32,
pub handoff_record: String,
pub delegation: UpdateDelegation,
pub events: Vec<String>,
pub head_sha256: String,
}
pub struct DecodedInflightProof {
pub handoff_record: Vec<u8>,
pub events: Vec<Vec<u8>>,
}
impl UpdateInflightProof {
pub fn from_raw(
record: &[u8],
delegation: UpdateDelegation,
events: &[Vec<u8>],
head: String,
) -> Result<Self, &'static str> {
let proof = Self {
schema_version: 1,
handoff_record: URL_SAFE_NO_PAD.encode(record),
delegation,
events: events
.iter()
.map(|bytes| URL_SAFE_NO_PAD.encode(bytes))
.collect(),
head_sha256: head,
};
proof.decode()?;
Ok(proof)
}
pub fn decode(&self) -> Result<DecodedInflightProof, &'static str> {
if self.schema_version != 1
|| !self.delegation.validate()
|| !digest(&self.head_sha256)
|| self.events.is_empty()
|| self.events.len() > rmm_updater_handoff::MAX_V2_EVENTS
|| self.handoff_record.len() > 21846
{
return Err("UPDATE_INFLIGHT_LIMIT");
}
fn bounded(value: &str) -> Result<Vec<u8>, &'static str> {
if value.is_empty() || value.len() > 21846 {
return Err("UPDATE_INFLIGHT_BYTE_LIMIT");
}
let raw = URL_SAFE_NO_PAD
.decode(value)
.map_err(|_| "UPDATE_INFLIGHT_BASE64")?;
if raw.is_empty() || raw.len() > 16384 || URL_SAFE_NO_PAD.encode(&raw) != value {
return Err("UPDATE_INFLIGHT_BASE64");
}
Ok(raw)
}
let handoff_record = bounded(&self.handoff_record)?;
if self.events.len() > rmm_updater_handoff::MAX_EVENTS {
let handoff: rmm_updater_handoff::Handoff = serde_json::from_slice(&handoff_record)
.map_err(|_| "UPDATE_INFLIGHT_WINDOWS_CLOCK_RECORD")?;
let limit = if handoff.schema_version == 2 {
rmm_updater_handoff::MAX_V2_EVENTS
} else if handoff.pin_transition
== rmm_updater_handoff::PinTransition::WindowsCodePairClockV1
{
rmm_updater_handoff::MAX_WINDOWS_CLOCK_EVENTS
} else {
rmm_updater_handoff::MAX_EVENTS
};
if self.events.len() > limit
|| handoff
.bytes()
.map_err(|_| "UPDATE_INFLIGHT_WINDOWS_CLOCK_RECORD")?
!= handoff_record
{
return Err("UPDATE_INFLIGHT_PROFILE_LIMIT");
}
}
Ok(DecodedInflightProof {
handoff_record,
events: self
.events
.iter()
.map(|event| bounded(event))
.collect::<Result<Vec<_>, _>>()?,
})
}
pub fn bytes(&self) -> Result<Vec<u8>, &'static str> {
self.decode()?;
let bytes = serde_json::to_vec(self).map_err(|_| "UPDATE_INFLIGHT_CODEC")?;
if bytes.len() > 384 * 1024 {
return Err("UPDATE_INFLIGHT_SIZE");
}
Ok(bytes)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
if bytes.len() > 384 * 1024 {
return Err("UPDATE_INFLIGHT_SIZE");
}
let proof: Self = serde_json::from_slice(bytes).map_err(|_| "UPDATE_INFLIGHT_SCHEMA")?;
if proof.bytes()? != bytes {
return Err("UPDATE_INFLIGHT_NONCANONICAL");
}
Ok(proof)
}
}
/// Evidence-only acknowledgement of the exact inflight prefix. It can appear
/// only with ready/helper_ready=false, no outcome and unlock=false.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct UpdateInflightDecision {
pub handoff_sha256: String,
pub delegation_sha256: String,
pub head_sha256: String,
pub owner_nonce: Uuid,
pub finish_before: u64,
}
/// Standard passive observation, not a user-triggered live query or approval.
/// A valid preview comes from the authenticated read-only privileged helper
/// after independent release/trust/floor/config/pin verification; no staging or
/// binary download. Device mTLS provides provenance, not hardware attestation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentUpdateObservation {
pub schema_version: u32,
pub platform: Platform,
pub observed_at: chrono::DateTime<chrono::Utc>,
pub quality: ObservationQuality,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub predecessor: Option<Predecessor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updater: Option<UpdaterBinding>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub activation_floor: Option<u64>,
pub rolled_back: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub helper_observation_sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed_sync_decision_id: Option<Uuid>,
pub candidate_previews: Vec<CandidatePreview>,
}
impl AgentUpdateObservation {
pub fn not_configured(platform: Platform, observed_at: chrono::DateTime<chrono::Utc>) -> Self {
// Passive envelope timestamps have millisecond precision. Keep the inner
// observation at that same measured precision, never after its envelope.
let observed_at = observed_at
- chrono::Duration::nanoseconds(i64::from(
observed_at.timestamp_subsec_nanos() % 1_000_000,
));
Self {
schema_version: 1,
platform,
observed_at,
quality: ObservationQuality::NotConfigured,
predecessor: None,
updater: None,
activation_floor: None,
rolled_back: false,
helper_observation_sha256: None,
signed_sync_decision_id: None,
candidate_previews: Vec::new(),
}
}
pub fn validate(&self) -> bool {
if self.schema_version != 1 || self.candidate_previews.len() > 1 {
return false;
}
if self.quality != ObservationQuality::Valid {
return self.predecessor.is_none()
&& self.updater.is_none()
&& self.activation_floor.is_none()
&& !self.rolled_back
&& self.helper_observation_sha256.is_none()
&& self.signed_sync_decision_id.is_none()
&& self.candidate_previews.is_empty();
}
let (Some(p), Some(u), Some(floor), Some(proof), Some(decision)) = (
&self.predecessor,
&self.updater,
self.activation_floor,
&self.helper_observation_sha256,
self.signed_sync_decision_id,
) else {
return false;
};
!p.release_id.is_nil()
&& p.release_sequence > 0
&& floor >= p.release_sequence
&& self.rolled_back == (floor > p.release_sequence)
&& digest(proof)
&& !decision.is_nil()
&& [
&p.manifest_sha256,
&p.installed_record_sha256,
&p.agent_sha256,
&p.helper_sha256,
&u.binary_sha256,
&u.policy_sha256,
&u.keyring_sha256,
&u.health_public_key_hex,
&u.health_key_pin_sha256,
]
.iter()
.all(|h| digest(h))
&& u.keyring_generation > 0
&& self.candidate_previews.iter().all(|c| {
!c.release_id.is_nil() && c.release_id != p.release_id && digest(&c.manifest_sha256)
})
}
}
impl ResolvedAgentUpdate {
pub fn manifest(&self) -> Result<ReleaseManifest, &'static str> {
self.release_envelope.decode().map(|d| d.manifest)
}
pub fn validate(&self) -> bool {
let Ok(decoded) = self.release_envelope.decode() else {
return false;
};
let m = decoded.manifest;
self.schema_version == 1
&& self.health_timeout_seconds == 180
&& self.no_reboot
&& self
.release_envelope
.sha256()
.is_ok_and(|hash| hash == self.release_envelope_sha256)
&& crate::jobs::hash(&decoded.payload_bytes) == self.manifest_sha256
&& !self.predecessor.release_id.is_nil()
&& self.predecessor.release_id != m.release_id
&& self.predecessor.release_sequence > 0
&& self.predecessor.release_sequence < m.release_sequence
&& [
&self.predecessor.manifest_sha256,
&self.predecessor.installed_record_sha256,
&self.predecessor.agent_sha256,
&self.predecessor.helper_sha256,
&self.updater.binary_sha256,
&self.updater.policy_sha256,
&self.updater.keyring_sha256,
&self.updater.health_public_key_hex,
&self.updater.health_key_pin_sha256,
]
.iter()
.all(|h| digest(h))
&& self.updater.keyring_generation > 0
&& self.peer_pin_transition.validate(
m.platform,
&self.predecessor,
&m.artifacts[1].sha256,
)
}
pub fn execution_identity(&self) -> Option<&'static str> {
self.manifest().ok().map(|m| match m.platform {
Platform::LinuxX64 => "root",
Platform::WindowsX64 => "system",
})
}
}
pub fn digest(hash: &str) -> bool {
hash.len() == 64
&& hash
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// Shared pure receipt/prefix validation. Does not authenticate OS observations,
/// establish a live owner, heal an Unknown or grant any start permission.
pub fn verify_inflight_proof(
proof: &UpdateInflightProof,
health_key: [u8; 32],
) -> Result<(rmm_updater_handoff::Handoff, rmm_updater_handoff::Journal), String> {
use rmm_updater_handoff::{Handoff, Journal, Phase};
let raw = proof.decode().map_err(str::to_string)?;
let mut journal = Journal::open(&raw.handoff_record, health_key).map_err(|e| e.to_string())?;
let handoff: Handoff =
serde_json::from_slice(&raw.handoff_record).map_err(|e| e.to_string())?;
if proof.delegation.handoff_sha256 != journal.handoff_sha256()
|| proof.delegation.owner_nonce != handoff.owner_nonce
|| proof.delegation.boot_id != handoff.boot_id
|| proof.delegation.updater.image_sha256 != handoff.updater_sha256
|| proof.delegation.original_helper.image_sha256 != handoff.predecessor.helper_sha256
|| u64::try_from(proof.delegation.prepared_at.timestamp()).ok() != Some(handoff.consumed_at)
{
return Err("UPDATE_INFLIGHT_DELEGATION_BINDING".into());
}
for event in raw.events {
journal.replay(&event).map_err(|e| e.to_string())?;
}
if journal.head_sha256() != proof.head_sha256
|| matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted)
{
return Err("UPDATE_INFLIGHT_TERMINAL_OR_HEAD".into());
}
Ok((handoff, journal))
}
pub fn inflight_decision(
proof: &UpdateInflightProof,
health_key: [u8; 32],
) -> Result<UpdateInflightDecision, String> {
let (handoff, _) = verify_inflight_proof(proof, health_key)?;
Ok(UpdateInflightDecision {
handoff_sha256: proof.delegation.handoff_sha256.clone(),
delegation_sha256: crate::jobs::hash(
&serde_json::to_vec(&proof.delegation).map_err(|e| e.to_string())?,
),
head_sha256: proof.head_sha256.clone(),
owner_nonce: handoff.owner_nonce,
finish_before: handoff.finish_before,
})
}
/// Exact immutable plan/job/release linkage, in addition to signature/prefix
/// verification. No current OS predecessor or permission is inferred here.
pub fn handoff_matches_job(
h: &rmm_updater_handoff::Handoff,
job: &crate::jobs::JobPayload,
) -> bool {
let crate::jobs::Action::UpdateAgent { update } = &job.action else {
return false;
};
let Ok(manifest) = update.manifest() else {
return false;
};
let Ok(job_bytes) = serde_json::to_vec(job) else {
return false;
};
let Ok(pin_bytes) = serde_json::to_vec(&update.peer_pin_transition) else {
return false;
};
let common = h.attempt.tenant_id == job.tenant_id
&& h.attempt.asset_id == job.asset_id
&& h.attempt.agent_id == job.agent_id
&& h.attempt.enrollment_generation == job.enrollment_generation
&& h.attempt.assignment_version == job.assignment_version
&& h.attempt.job_id == job.job_id
&& h.attempt.attempt_id == job.attempt_id
&& h.attempt.job_payload_sha256 == crate::jobs::hash(&job_bytes)
&& h.updater_sha256 == update.updater.binary_sha256
&& h.updater_policy_sha256 == update.updater.policy_sha256
&& h.predecessor_record_sha256 == update.predecessor.installed_record_sha256
&& h.predecessor.manifest_sha256 == update.predecessor.manifest_sha256
&& h.predecessor.agent_sha256 == update.predecessor.agent_sha256
&& h.predecessor.helper_sha256 == update.predecessor.helper_sha256
&& h.target.manifest_sha256 == update.manifest_sha256
&& h.target.agent_sha256 == manifest.artifacts[0].sha256
&& h.target.helper_sha256 == manifest.artifacts[1].sha256
&& h.pin_transition_sha256 == crate::jobs::hash(&pin_bytes);
if !common {
return false;
}
use rmm_updater_handoff::{FileRole, PinTransition};
match (&update.peer_pin_transition, h.pin_transition) {
(
PeerPinTransition::UnchangedGeneralPinV1 { general_pin_sha256 },
PinTransition::UnchangedLinuxGeneralV1,
) => {
h.predecessor.pin_sha256 == *general_pin_sha256
&& h.target.pin_sha256 == *general_pin_sha256
}
(PeerPinTransition::LinuxGeneralFullV1 { full, .. }, PinTransition::LinuxGeneralFullV1) => {
h.predecessor.pin_sha256 == full.old_pin_sha256
&& h.target.pin_sha256 == full.new_pin_sha256
&& h.files.get(2).is_some_and(|f| {
f.role == FileRole::LinuxFullConfig
&& f.old_sha256 == full.old_config_sha256
&& f.new_sha256 == full.new_config_sha256
})
}
(
PeerPinTransition::WindowsCodePairV1 {
old_settings_sha256,
new_settings_sha256,
old_pin_sha256,
new_pin_sha256,
time_profile: None,
},
PinTransition::WindowsCodePairV1,
) => {
h.predecessor.pin_sha256 == *old_pin_sha256
&& h.target.pin_sha256 == *new_pin_sha256
&& h.files.get(2).is_some_and(|f| {
f.role == FileRole::WindowsSettings
&& f.old_sha256 == *old_settings_sha256
&& f.new_sha256 == *new_settings_sha256
})
}
(
PeerPinTransition::WindowsCodePairV1 {
old_settings_sha256,
new_settings_sha256,
old_pin_sha256,
new_pin_sha256,
time_profile: Some(time),
},
PinTransition::WindowsCodePairClockV1,
) => {
h.predecessor.pin_sha256 == *old_pin_sha256
&& h.target.pin_sha256 == *new_pin_sha256
&& h.files.get(2).is_some_and(|f| {
f.role == FileRole::WindowsSettings
&& f.old_sha256 == *old_settings_sha256
&& f.new_sha256 == *new_settings_sha256
})
&& h.files.get(4).is_some_and(|f| {
f.role == FileRole::WindowsTimeProfile
&& f.old_sha256 == time.old_time_profile_sha256
&& f.new_sha256 == time.new_time_profile_sha256
})
}
_ => false,
}
}
/// The ORIGINAL signed update plan fixes a separately provisioned health key.
/// Parsing this public value alone does not provision local trust.
pub fn job_health_public_key(job: &crate::jobs::JobPayload) -> Result<[u8; 32], &'static str> {
let crate::jobs::Action::UpdateAgent { update } = &job.action else {
return Err("UPDATE_ACTION_REQUIRED");
};
if !update.validate() {
return Err("UPDATE_ACTION_INVALID");
}
hex::decode(&update.updater.health_public_key_hex)
.map_err(|_| "UPDATE_HEALTH_KEY")?
.try_into()
.map_err(|_| "UPDATE_HEALTH_KEY")
}
/// Diagnostic catalog metadata inside the existing linux.base observations
/// vector. This is never an AgentUpdateObservation/CandidatePreview or authority.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CatalogCheckStatus {
NotConfigured,
Unavailable,
Available,
Current,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CatalogCandidate {
pub release_id: Uuid,
pub release_sequence: u64,
pub version: String,
pub manifest_sha256: String,
pub keyring_generation: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CatalogCheckReport {
pub schema_version: u32,
pub source_id: String,
/// Actual authenticated check, not the later cache/inventory collection.
pub checked_at: chrono::DateTime<chrono::Utc>,
pub status: CatalogCheckStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub candidate: Option<CatalogCandidate>,
}
impl CatalogCheckReport {
pub fn validate(
&self,
collected_at: chrono::DateTime<chrono::Utc>,
now: chrono::DateTime<chrono::Utc>,
) -> bool {
self.schema_version == 1
&& self.source_id == "mtls:release-catalog-v1"
&& self.checked_at <= collected_at + chrono::Duration::seconds(1)
&& self.checked_at <= now + chrono::Duration::seconds(45)
&& self.checked_at >= now - chrono::Duration::hours(72)
&& match (&self.status, &self.candidate) {
(CatalogCheckStatus::Available | CatalogCheckStatus::Current, Some(candidate)) => {
!candidate.release_id.is_nil()
&& candidate.release_sequence > 0
&& candidate.keyring_generation > 0
&& digest(&candidate.manifest_sha256)
&& !candidate.version.is_empty()
&& candidate.version.len() <= 64
&& candidate
.version
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b))
}
(CatalogCheckStatus::NotConfigured | CatalogCheckStatus::Unavailable, None) => true,
_ => false,
}
}
}