Files
rust-discovery/crates/updater-handoff/src/linux_full.rs
T
kevin_janssen a2efb7990b
Rust development slice / linux (push) Failing after 6s
Add typed updater handoff and preserving Linux Full renderer
Keep release verifier and native drivers unchanged. Independently reviewed as an isolated contract after provisioned-file-key correction; eight local release contracts and format/clippy checks pass. Runtime persistence, approvals, service ownership, apply and rollback remain unimplemented.
2026-11-14 19:27:52 +01:00

310 lines
11 KiB
Rust

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