Add gated agent update planning, preserved handoff and Linux worker ports
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,782 @@
|
||||
//! 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(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,
|
||||
},
|
||||
}
|
||||
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,
|
||||
} => {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[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() > 16
|
||||
|| 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)
|
||||
}
|
||||
Ok(DecodedInflightProof {
|
||||
handoff_record: bounded(&self.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,
|
||||
},
|
||||
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
|
||||
})
|
||||
}
|
||||
_ => 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")
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Protected updater provisioning codecs only. Parsing is not authentication.
|
||||
//! Callers must authenticate original file bytes/owners, verify signatures and
|
||||
//! enforce retained history, current policy, revocation and monotonic floor.
|
||||
use crate::{
|
||||
agent_update::{Platform, ReleaseEnvelope, digest},
|
||||
jobs::hash,
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const BASELINE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-update-baseline.v1\0";
|
||||
pub const MAX_RECORD_BYTES: usize = 32 * 1024;
|
||||
pub const MAX_POLICY_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HealthKeyPin {
|
||||
pub schema_version: u32,
|
||||
pub key_id: String,
|
||||
pub public_key_hex: String,
|
||||
}
|
||||
impl HealthKeyPin {
|
||||
/// Shape/hash only; the independent crypto verifier must reject weak keys.
|
||||
pub fn public_key(&self) -> Result<[u8; 32], &'static str> {
|
||||
if self.schema_version != 1 || !digest(&self.public_key_hex) || !digest(&self.key_id) {
|
||||
return Err("UPDATE_HEALTH_PIN_SHAPE");
|
||||
}
|
||||
let raw: [u8; 32] = hex::decode(&self.public_key_hex)
|
||||
.map_err(|_| "UPDATE_HEALTH_PIN_KEY")?
|
||||
.try_into()
|
||||
.map_err(|_| "UPDATE_HEALTH_PIN_KEY")?;
|
||||
if hash(&raw) != self.key_id {
|
||||
return Err("UPDATE_HEALTH_PIN_ID");
|
||||
}
|
||||
Ok(raw)
|
||||
}
|
||||
pub fn validate(&self) -> bool {
|
||||
self.public_key().is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum ActivationEvidence {
|
||||
Bootstrap {
|
||||
qualification_receipt_sha256: String,
|
||||
},
|
||||
Updated {
|
||||
handoff_sha256: String,
|
||||
signed_health_sha256: String,
|
||||
},
|
||||
}
|
||||
impl ActivationEvidence {
|
||||
fn validate(&self) -> bool {
|
||||
match self {
|
||||
Self::Bootstrap {
|
||||
qualification_receipt_sha256,
|
||||
} => digest(qualification_receipt_sha256),
|
||||
Self::Updated {
|
||||
handoff_sha256,
|
||||
signed_health_sha256,
|
||||
} => digest(handoff_sha256) && digest(signed_health_sha256),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Current local record. A release signature authenticates its manifest, not
|
||||
/// these activation fields. The initial record additionally needs the separate
|
||||
/// baseline signature below; subsequent changes need the original guarded CAS
|
||||
/// and independently verified Health evidence. No floor may be inferred here.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct InstalledReleaseRecord {
|
||||
pub schema_version: u32,
|
||||
pub profile: String,
|
||||
pub platform: Platform,
|
||||
pub release_envelope: ReleaseEnvelope,
|
||||
pub manifest_sha256: String,
|
||||
pub activation_floor: u64,
|
||||
pub activated_at: u64,
|
||||
pub previous_record_sha256: Option<String>,
|
||||
pub activation_evidence: ActivationEvidence,
|
||||
pub rolled_back: bool,
|
||||
}
|
||||
impl InstalledReleaseRecord {
|
||||
pub fn validate(&self) -> bool {
|
||||
let Ok(release) = self.release_envelope.decode() else {
|
||||
return false;
|
||||
};
|
||||
if self.schema_version != 1
|
||||
|| self.profile != "decoder_compatible_handoff_v1"
|
||||
|| self.platform != release.manifest.platform
|
||||
|| self.manifest_sha256 != hash(&release.payload_bytes)
|
||||
|| self.activation_floor == 0
|
||||
|| self.activated_at == 0
|
||||
|| self
|
||||
.previous_record_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|v| !digest(v))
|
||||
|| !self.activation_evidence.validate()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match &self.activation_evidence {
|
||||
ActivationEvidence::Bootstrap { .. } => {
|
||||
self.previous_record_sha256.is_none()
|
||||
&& !self.rolled_back
|
||||
&& self.activation_floor == release.manifest.release_sequence
|
||||
}
|
||||
ActivationEvidence::Updated { .. } => {
|
||||
self.previous_record_sha256.is_some()
|
||||
&& if self.rolled_back {
|
||||
self.activation_floor >= release.manifest.release_sequence
|
||||
} else {
|
||||
self.activation_floor == release.manifest.release_sequence
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn bytes(&self) -> Result<Vec<u8>, &'static str> {
|
||||
if !self.validate() {
|
||||
return Err("UPDATE_INSTALLED_RECORD_SHAPE");
|
||||
}
|
||||
let raw = serde_json::to_vec(self).map_err(|_| "UPDATE_INSTALLED_RECORD_CODEC")?;
|
||||
if raw.len() > MAX_RECORD_BYTES {
|
||||
return Err("UPDATE_INSTALLED_RECORD_LIMIT");
|
||||
}
|
||||
Ok(raw)
|
||||
}
|
||||
pub fn from_bytes(raw: &[u8]) -> Result<Self, &'static str> {
|
||||
if raw.is_empty() || raw.len() > MAX_RECORD_BYTES {
|
||||
return Err("UPDATE_INSTALLED_RECORD_LIMIT");
|
||||
}
|
||||
let record: Self =
|
||||
serde_json::from_slice(raw).map_err(|_| "UPDATE_INSTALLED_RECORD_CODEC")?;
|
||||
if record.bytes()? != raw {
|
||||
return Err("UPDATE_INSTALLED_RECORD_NONCANONICAL");
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
}
|
||||
|
||||
/// Offline release-key signature over BASELINE_SIGNATURE_DOMAIN followed by the
|
||||
/// exact canonical initial InstalledReleaseRecord bytes. This codec checks no
|
||||
/// signature. The key must come from independently protected update trust.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SignedBaselineRecord {
|
||||
pub schema_version: u32,
|
||||
pub key_id: String,
|
||||
pub payload_bytes: String,
|
||||
pub signature: String,
|
||||
}
|
||||
pub struct DecodedBaselineRecord {
|
||||
pub payload_bytes: Vec<u8>,
|
||||
pub signature: [u8; 64],
|
||||
pub record: InstalledReleaseRecord,
|
||||
}
|
||||
impl SignedBaselineRecord {
|
||||
pub fn decode(&self) -> Result<DecodedBaselineRecord, &'static str> {
|
||||
if self.schema_version != 1
|
||||
|| !digest(&self.key_id)
|
||||
|| self.payload_bytes.is_empty()
|
||||
|| self.payload_bytes.len() > 4 * MAX_RECORD_BYTES.div_ceil(3)
|
||||
|| self.signature.len() != 86
|
||||
{
|
||||
return Err("UPDATE_BASELINE_LIMIT");
|
||||
}
|
||||
let raw = URL_SAFE_NO_PAD
|
||||
.decode(&self.payload_bytes)
|
||||
.map_err(|_| "UPDATE_BASELINE_CODEC")?;
|
||||
let signature = URL_SAFE_NO_PAD
|
||||
.decode(&self.signature)
|
||||
.map_err(|_| "UPDATE_BASELINE_SIGNATURE")?;
|
||||
if URL_SAFE_NO_PAD.encode(&raw) != self.payload_bytes
|
||||
|| URL_SAFE_NO_PAD.encode(&signature) != self.signature
|
||||
{
|
||||
return Err("UPDATE_BASELINE_NONCANONICAL");
|
||||
}
|
||||
let signature: [u8; 64] = signature
|
||||
.try_into()
|
||||
.map_err(|_| "UPDATE_BASELINE_SIGNATURE")?;
|
||||
let record = InstalledReleaseRecord::from_bytes(&raw)?;
|
||||
if !matches!(
|
||||
&record.activation_evidence,
|
||||
ActivationEvidence::Bootstrap { .. }
|
||||
) {
|
||||
return Err("UPDATE_INITIAL_BASELINE_REQUIRED");
|
||||
}
|
||||
Ok(DecodedBaselineRecord {
|
||||
payload_bytes: raw,
|
||||
signature,
|
||||
record,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LocalServicePin {
|
||||
pub unit: String,
|
||||
/// Same protected unit/drop-in composition digest as the native OS port;
|
||||
/// not merely the hash of the principal unit file.
|
||||
pub unit_sha256: String,
|
||||
}
|
||||
|
||||
/// Local-only protected policy. No member is copied from a model/job/request.
|
||||
/// Its OWN raw hash is external (UpdaterBinding.policy_sha256); storing that
|
||||
/// digest inside this document would create a circular hash dependency.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LocalUpdatePolicy {
|
||||
pub schema_version: u32,
|
||||
pub profile: String,
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub enrollment_generation: u64,
|
||||
pub assignment_version: u64,
|
||||
pub ledger_path: String,
|
||||
pub lock_path: String,
|
||||
pub installed_record_path: String,
|
||||
pub keyring_path: String,
|
||||
pub health_pin_path: String,
|
||||
pub services: Vec<LocalServicePin>,
|
||||
pub updater_service: LocalServicePin,
|
||||
pub updater_binary_sha256: String,
|
||||
pub initial_baseline: SignedBaselineRecord,
|
||||
pub initial_record_sha256: String,
|
||||
pub initial_manifest_sha256: String,
|
||||
pub initial_activation_floor: u64,
|
||||
}
|
||||
impl LocalUpdatePolicy {
|
||||
pub fn validate(&self) -> bool {
|
||||
const SERVICES: [&str; 3] = [
|
||||
"rmm-agent-remote.service",
|
||||
"rmm-helper-cloud.service",
|
||||
"rmm-full-maintenance-helper.service",
|
||||
];
|
||||
let Ok(baseline) = self.initial_baseline.decode() else {
|
||||
return false;
|
||||
};
|
||||
let names: Vec<_> = self.services.iter().map(|v| v.unit.as_str()).collect();
|
||||
self.schema_version == 1
|
||||
&& self.profile == "linux_general_full_v1"
|
||||
&& !self.tenant_id.is_nil()
|
||||
&& !self.asset_id.is_nil()
|
||||
&& !self.agent_id.is_nil()
|
||||
&& self.enrollment_generation > 0
|
||||
&& self.assignment_version > 0
|
||||
&& self.ledger_path == "/var/lib/rmm-helper/consumption.sqlite"
|
||||
&& self.lock_path == "/var/lib/rmm-helper/executor.lock"
|
||||
&& self.installed_record_path == "/var/lib/rmm-agent-updater/installed-record.json"
|
||||
&& self.keyring_path == "/etc/rmm-agent-updater/keyring.json"
|
||||
&& self.health_pin_path == "/etc/rmm-agent-updater/health-key.json"
|
||||
&& (names == SERVICES
|
||||
|| names
|
||||
== [
|
||||
SERVICES[0],
|
||||
SERVICES[1],
|
||||
SERVICES[2],
|
||||
"rmm-apt-helper.service",
|
||||
])
|
||||
&& self.services.iter().all(|v| digest(&v.unit_sha256))
|
||||
&& self.updater_service.unit == "rmm-agent-updater.service"
|
||||
&& digest(&self.updater_service.unit_sha256)
|
||||
&& digest(&self.updater_binary_sha256)
|
||||
&& baseline.record.platform == Platform::LinuxX64
|
||||
&& self.initial_record_sha256 == hash(&baseline.payload_bytes)
|
||||
&& self.initial_manifest_sha256 == baseline.record.manifest_sha256
|
||||
&& self.initial_activation_floor == baseline.record.activation_floor
|
||||
}
|
||||
/// Return the parsed policy AND its ORIGINAL raw hash. Config whitespace is
|
||||
/// not normalized into a different job pin. No authenticity is implied.
|
||||
pub fn from_bytes(raw: &[u8]) -> Result<(Self, String), &'static str> {
|
||||
if raw.is_empty() || raw.len() > MAX_POLICY_BYTES {
|
||||
return Err("UPDATE_LOCAL_POLICY_LIMIT");
|
||||
}
|
||||
let policy: Self = serde_json::from_slice(raw).map_err(|_| "UPDATE_LOCAL_POLICY_CODEC")?;
|
||||
if !policy.validate() {
|
||||
return Err("UPDATE_LOCAL_POLICY_SHAPE");
|
||||
}
|
||||
Ok((policy, hash(raw)))
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,25 @@ pub fn validate_for_scope(
|
||||
now: DateTime<Utc>,
|
||||
scope: &str,
|
||||
) -> Result<Value, &'static str> {
|
||||
if scope == "agent.update" {
|
||||
if bytes.len() > 65536 {
|
||||
return Err("AGENT_UPDATE_INVENTORY_SIZE");
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UpdateInventory {
|
||||
agent_update: crate::agent_update::AgentUpdateObservation,
|
||||
}
|
||||
let update: UpdateInventory =
|
||||
serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?;
|
||||
if !update.agent_update.validate()
|
||||
|| update.agent_update.observed_at - now > chrono::Duration::seconds(45)
|
||||
|| now - update.agent_update.observed_at > chrono::Duration::hours(72)
|
||||
{
|
||||
return Err("INVALID_AGENT_UPDATE_OBSERVATION");
|
||||
}
|
||||
return serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION");
|
||||
}
|
||||
let prefix = match scope {
|
||||
"linux.base" => "linux.",
|
||||
"windows.base" => "windows.",
|
||||
@@ -34,6 +53,31 @@ pub fn validate_for_scope(
|
||||
}
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| "INVALID_INVENTORY_JSON")?;
|
||||
let mut base = value.as_object().cloned().ok_or("INVENTORY_OBJECT")?;
|
||||
if let Some(update) = base.remove("agent_update") {
|
||||
// Decode the original bytes as well: Value alone would discard duplicate
|
||||
// fields before the strict new metadata DTO could reject them.
|
||||
#[derive(Deserialize)]
|
||||
struct UpdateField {
|
||||
agent_update: crate::agent_update::AgentUpdateObservation,
|
||||
}
|
||||
let typed: UpdateField =
|
||||
serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?;
|
||||
if serde_json::to_value(&typed.agent_update)
|
||||
.map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?
|
||||
!= update
|
||||
|| !typed.agent_update.validate()
|
||||
|| typed.agent_update.platform
|
||||
!= if scope == "linux.base" {
|
||||
crate::agent_update::Platform::LinuxX64
|
||||
} else {
|
||||
crate::agent_update::Platform::WindowsX64
|
||||
}
|
||||
|| typed.agent_update.observed_at - now > chrono::Duration::seconds(45)
|
||||
|| now - typed.agent_update.observed_at > chrono::Duration::hours(72)
|
||||
{
|
||||
return Err("INVALID_AGENT_UPDATE_OBSERVATION");
|
||||
}
|
||||
}
|
||||
let observations = base.remove("observations");
|
||||
let started = base.remove("collection_started_at");
|
||||
let completed = base.remove("collection_completed_at");
|
||||
@@ -231,3 +275,51 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod agent_update_tests {
|
||||
use super::*;
|
||||
use crate::agent_update::{AgentUpdateObservation, Platform};
|
||||
#[test]
|
||||
fn update_scope_is_separate_bounded_strict_and_never_restamps_base_inventory() {
|
||||
let now = Utc::now();
|
||||
let observation = AgentUpdateObservation::not_configured(Platform::LinuxX64, now);
|
||||
let value = serde_json::json!({"agent_update":observation});
|
||||
let bytes = serde_json::to_vec(&value).unwrap();
|
||||
assert_eq!(
|
||||
validate_for_scope(&bytes, now, "agent.update").unwrap(),
|
||||
value
|
||||
);
|
||||
assert!(validate_for_scope(&bytes, now, "linux.base").is_err());
|
||||
let object = serde_json::to_string(&observation).unwrap();
|
||||
let duplicate = format!("{{\"agent_update\":{object},\"agent_update\":{object}}}");
|
||||
assert!(validate_for_scope(duplicate.as_bytes(), now, "agent.update").is_err());
|
||||
let mut false_valid = value.clone();
|
||||
false_valid["agent_update"]["quality"] = serde_json::json!("valid");
|
||||
assert!(
|
||||
validate_for_scope(
|
||||
&serde_json::to_vec(&false_valid).unwrap(),
|
||||
now,
|
||||
"agent.update"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut mixed = value;
|
||||
mixed["hostname"] = serde_json::json!("pretend-new-base");
|
||||
assert!(
|
||||
validate_for_scope(&serde_json::to_vec(&mixed).unwrap(), now, "agent.update").is_err()
|
||||
);
|
||||
let future = AgentUpdateObservation::not_configured(
|
||||
Platform::LinuxX64,
|
||||
now + chrono::Duration::seconds(46),
|
||||
);
|
||||
assert!(
|
||||
validate_for_scope(
|
||||
&serde_json::to_vec(&serde_json::json!({"agent_update":future})).unwrap(),
|
||||
now,
|
||||
"agent.update"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,9 @@ pub enum Action {
|
||||
recipe_version: String,
|
||||
apt_manifest: crate::apt_transaction::AptExecutionManifest,
|
||||
},
|
||||
UpdateAgent {
|
||||
update: Box<crate::agent_update::ResolvedAgentUpdate>,
|
||||
},
|
||||
Reboot {
|
||||
reason: String,
|
||||
reconnect_timeout_seconds: u32,
|
||||
@@ -198,6 +201,7 @@ impl Action {
|
||||
Self::ApplyUpdates { .. } => "apply_updates",
|
||||
Self::AptNativeAcceptance { .. } => "apt_native_acceptance",
|
||||
Self::Reboot { .. } => "reboot",
|
||||
Self::UpdateAgent { .. } => "update_agent",
|
||||
}
|
||||
}
|
||||
pub fn validate(&self) -> bool {
|
||||
@@ -334,6 +338,7 @@ impl Action {
|
||||
&& recipe_id == &m.resolved_apt_transaction.recipe_id
|
||||
&& recipe_version == &m.resolved_apt_transaction.recipe_version
|
||||
}
|
||||
Self::UpdateAgent { update } => update.validate(),
|
||||
Self::Reboot {
|
||||
reason,
|
||||
reconnect_timeout_seconds,
|
||||
@@ -374,6 +379,9 @@ impl Action {
|
||||
)
|
||||
}
|
||||
pub fn valid_execution_identity(&self, identity: &str) -> bool {
|
||||
if let Self::UpdateAgent { update } = self {
|
||||
return update.execution_identity() == Some(identity);
|
||||
}
|
||||
!self.full_maintenance()
|
||||
|| matches!(
|
||||
(identity, self.script_platform()),
|
||||
@@ -387,6 +395,8 @@ impl Action {
|
||||
/// its inner Event Log calls retain their own cooperative <=5s deadline.
|
||||
pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool {
|
||||
(1..=3600).contains(&runtime_seconds)
|
||||
&& (!matches!(self, Self::UpdateAgent { .. })
|
||||
|| (runtime_seconds == 600 && output_bytes <= 65536))
|
||||
&& (!self.full_maintenance()
|
||||
|| (output_bytes <= 65536
|
||||
&& runtime_seconds
|
||||
@@ -417,7 +427,9 @@ impl Action {
|
||||
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
|
||||
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
|
||||
if !self.valid_execution_identity(identity)
|
||||
|| (identity == "system" && !self.valid_helper_denial_shape(identity))
|
||||
|| (identity == "system"
|
||||
&& !self.valid_helper_denial_shape(identity)
|
||||
&& !matches!(self, Self::UpdateAgent { .. }))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -436,6 +448,40 @@ impl Action {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
Self::UpdateAgent { update } => {
|
||||
let linux = update.execution_identity() == Some("root");
|
||||
update.validate()
|
||||
&& has(crate::agent_update::APPLY_CAPABILITY)
|
||||
&& has("rmm.sync.v1")
|
||||
&& has(if linux {
|
||||
"linux.base/1"
|
||||
} else {
|
||||
"windows.base/1"
|
||||
})
|
||||
&& !has(if linux {
|
||||
"windows.base/1"
|
||||
} else {
|
||||
"linux.base/1"
|
||||
})
|
||||
&& has(if linux {
|
||||
"helper.root.v1"
|
||||
} else {
|
||||
"helper.system.v1"
|
||||
})
|
||||
&& has(&format!("{}:update_agent", identity))
|
||||
&& has(&format!(
|
||||
"updater.binary.sha256:{}",
|
||||
update.updater.binary_sha256
|
||||
))
|
||||
&& has(&format!(
|
||||
"updater.policy.sha256:{}",
|
||||
update.updater.policy_sha256
|
||||
))
|
||||
&& has(&format!(
|
||||
"helper.binary.sha256:{}",
|
||||
update.predecessor.helper_sha256
|
||||
))
|
||||
}
|
||||
Self::RunScript {
|
||||
interpreter,
|
||||
windows_execution_profile,
|
||||
@@ -652,6 +698,10 @@ pub struct ExecutionPermitPayload {
|
||||
pub start_before: DateTime<Utc>,
|
||||
pub max_runtime_seconds: u32,
|
||||
pub key_id: String,
|
||||
/// Only update_agent needs its actual plan ID in the local durable handoff.
|
||||
/// Omitted on every legacy action, preserving original signed grant bytes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub agent_update_plan_id: Option<Uuid>,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -1190,6 +1240,7 @@ mod tests {
|
||||
let id = Uuid::nil();
|
||||
let epoch = DateTime::<Utc>::from_timestamp(0, 0).unwrap();
|
||||
let p = ExecutionPermitPayload {
|
||||
agent_update_plan_id: None,
|
||||
domain: "rmm.execution-permit".into(),
|
||||
schema_version: 1,
|
||||
grant_id: id,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
pub mod agent_update;
|
||||
pub mod agent_update_provisioning;
|
||||
pub mod apt_transaction;
|
||||
pub mod checkpoint_repair;
|
||||
pub mod inventory_document;
|
||||
|
||||
@@ -58,6 +58,8 @@ pub struct AttemptDecision {
|
||||
pub original_boot_id: Option<Uuid>,
|
||||
pub unlock: bool,
|
||||
pub reason: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub update_inflight: Option<crate::agent_update::UpdateInflightDecision>,
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -100,6 +102,21 @@ impl ReconcileDecisionPayload {
|
||||
&& self.attempts.len() <= 256
|
||||
&& self.acknowledged_message_ids.len() <= 256
|
||||
&& (!self.helper_ready || self.ready)
|
||||
&& self.attempts.iter().all(|attempt| {
|
||||
attempt.update_inflight.as_ref().is_none_or(|update| {
|
||||
!self.ready
|
||||
&& !self.helper_ready
|
||||
&& !attempt.unlock
|
||||
&& attempt.outcome_state == "running"
|
||||
&& attempt.outcome_bytes.is_empty()
|
||||
&& attempt.outcome_sha256.is_none()
|
||||
&& crate::agent_update::digest(&update.handoff_sha256)
|
||||
&& crate::agent_update::digest(&update.delegation_sha256)
|
||||
&& crate::agent_update::digest(&update.head_sha256)
|
||||
&& !update.owner_nonce.is_nil()
|
||||
&& update.finish_before > 0
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user