Files
rust-discovery/crates/domain/src/agent_update_provisioning.rs
T
2026-11-15 11:40:53 +01:00

291 lines
11 KiB
Rust

//! 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 registry_path: String,
pub reader_registry_sha256: 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"
&& self.registry_path == "/etc/rmm-agent-updater/reader-registry.json"
&& digest(&self.reader_registry_sha256)
&& (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)))
}
}