Files
rust-discovery/crates/domain/src/agent_update_provisioning.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

364 lines
15 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();
let linux = self.schema_version == 1
&& self.profile == "linux_general_full_v1"
&& 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"
&& (names == SERVICES
|| names
== [
SERVICES[0],
SERVICES[1],
SERVICES[2],
"rmm-apt-helper.service",
])
&& self.updater_service.unit == "rmm-agent-updater.service"
&& baseline.record.platform == Platform::LinuxX64;
let windows = self.schema_version == 2
&& self.profile == "windows_code_pair_clock_v1"
&& self.ledger_path == r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite"
&& self.lock_path == r"C:\ProgramData\RustDiscoverySystem\state\executor.lock"
&& self.installed_record_path
== r"C:\ProgramData\RustDiscoveryUpdater\installed-record.json"
&& self.keyring_path == r"C:\ProgramData\RustDiscoveryUpdater\keyring.json"
&& self.health_pin_path == r"C:\ProgramData\RustDiscoveryUpdater\health-key.json"
&& self.registry_path == r"C:\ProgramData\RustDiscoveryUpdater\reader-registry.json"
&& names == ["RmmDiscoveryWindows", "RmmDiscoverySystemHelper"]
&& self.updater_service.unit == "RmmDiscoveryUpdater"
&& baseline.record.platform == Platform::WindowsX64;
(linux || windows)
&& !self.tenant_id.is_nil()
&& !self.asset_id.is_nil()
&& !self.agent_id.is_nil()
&& self.enrollment_generation > 0
&& self.assignment_version > 0
&& digest(&self.reader_registry_sha256)
&& self.services.iter().all(|v| digest(&v.unit_sha256))
&& digest(&self.updater_service.unit_sha256)
&& digest(&self.updater_binary_sha256)
&& 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)))
}
}
/// Deterministic PUBLIC record metadata only. This does not authenticate an
/// original, a release, Health or policy, and grants no namespace/ledger access.
/// Each native private BuiltRecord constructor must first verify its actual
/// Original and signed Health independently, then retain its own effect guard.
pub fn assemble_updated_record(
update: &crate::agent_update::ResolvedAgentUpdate,
prior_raw: &[u8],
handoff_sha256: &str,
signed: &rmm_updater_handoff::SignedHealth,
receipt: &rmm_updater_handoff::HealthReceipt,
) -> Result<InstalledReleaseRecord, &'static str> {
if !update.validate()
|| !digest(handoff_sha256)
|| receipt.handoff_sha256 != handoff_sha256
|| receipt.ready
|| signed.signature.len() != 64
|| serde_json::to_vec(receipt).map_err(|_| "UPDATE_RECORD_RECEIPT_CODEC")? != signed.payload
{
return Err("UPDATE_RECORD_INPUT");
}
let prior = InstalledReleaseRecord::from_bytes(prior_raw)?;
let parent = prior.release_envelope.decode()?;
let target = update.manifest()?;
let old_sha256 = hash(prior_raw);
if prior.rolled_back
|| old_sha256 != update.predecessor.installed_record_sha256
|| prior.manifest_sha256 != update.predecessor.manifest_sha256
|| parent.manifest.release_id != update.predecessor.release_id
|| parent.manifest.release_sequence != update.predecessor.release_sequence
|| parent.manifest.artifacts[0].sha256 != update.predecessor.agent_sha256
|| parent.manifest.artifacts[1].sha256 != update.predecessor.helper_sha256
|| prior.platform != target.platform
|| target.release_sequence <= prior.activation_floor
|| receipt.issued_at < prior.activated_at
{
return Err("UPDATE_RECORD_PREDECESSOR_OR_FLOOR");
}
let record = InstalledReleaseRecord {
schema_version: 1,
profile: "decoder_compatible_handoff_v1".into(),
platform: target.platform,
release_envelope: update.release_envelope.clone(),
manifest_sha256: update.manifest_sha256.clone(),
activation_floor: target.release_sequence,
activated_at: receipt.issued_at,
previous_record_sha256: Some(old_sha256.clone()),
activation_evidence: ActivationEvidence::Updated {
handoff_sha256: handoff_sha256.into(),
signed_health_sha256: hash(
&serde_json::to_vec(signed).map_err(|_| "UPDATE_RECORD_HEALTH_CODEC")?,
),
},
rolled_back: false,
};
if hash(&record.bytes()?) == old_sha256 {
return Err("UPDATE_RECORD_SAME_BYTES");
}
Ok(record)
}