feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,748 @@
|
||||
//! Technical OS adapters only. These do not authorize jobs and are not exposed
|
||||
//! over a network. The eventual helper MUST verify/consume a plan-bound start
|
||||
//! grant and hold durable per-attempt/resource locks before calling these APIs.
|
||||
use crate::process;
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
io::Write,
|
||||
os::unix::fs::OpenOptionsExt,
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub use crate::process::Output as ScriptOutput;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Interpreter {
|
||||
PosixSh,
|
||||
Bash,
|
||||
}
|
||||
impl Interpreter {
|
||||
pub fn path(self) -> &'static str {
|
||||
match self {
|
||||
Self::PosixSh => "/bin/sh",
|
||||
Self::Bash => "/bin/bash",
|
||||
}
|
||||
}
|
||||
pub fn available(self) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::metadata(self.path()).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScriptRequest {
|
||||
bytes: Vec<u8>,
|
||||
interpreter: Interpreter,
|
||||
arguments: Vec<String>,
|
||||
timeout: Duration,
|
||||
max_output_bytes: usize,
|
||||
}
|
||||
impl ScriptRequest {
|
||||
/// Bytes are kept verbatim, including encoding/BOM/line endings. Hash and
|
||||
/// execution identity must be checked by the helper, not inferred here.
|
||||
pub fn new(
|
||||
bytes: Vec<u8>,
|
||||
interpreter: Interpreter,
|
||||
arguments: Vec<String>,
|
||||
timeout: Duration,
|
||||
max_output_bytes: usize,
|
||||
) -> Result<Self> {
|
||||
ensure!(
|
||||
!bytes.is_empty() && bytes.len() <= 32 * 1024,
|
||||
"script size out of bounds"
|
||||
);
|
||||
ensure!(
|
||||
!timeout.is_zero() && timeout <= Duration::from_secs(3600),
|
||||
"invalid script timeout"
|
||||
);
|
||||
ensure!(
|
||||
(1..=512 * 1024).contains(&max_output_bytes),
|
||||
"invalid output cap"
|
||||
);
|
||||
ensure!(
|
||||
arguments.len() <= 128
|
||||
&& arguments
|
||||
.iter()
|
||||
.all(|a| a.len() <= 4096 && !a.contains('\0')),
|
||||
"invalid script arguments"
|
||||
);
|
||||
Ok(Self {
|
||||
bytes,
|
||||
interpreter,
|
||||
arguments,
|
||||
timeout,
|
||||
max_output_bytes,
|
||||
})
|
||||
}
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
pub fn interpreter(&self) -> Interpreter {
|
||||
self.interpreter
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_script(request: &ScriptRequest) -> Result<ScriptOutput> {
|
||||
ensure!(
|
||||
request.interpreter.available(),
|
||||
"UNSUPPORTED_CAPABILITY: interpreter unavailable"
|
||||
);
|
||||
// create_new + private directory prevent cross-user symlink substitution.
|
||||
// Same-UID compromise is outside this adapter's isolation boundary.
|
||||
let dir = std::env::temp_dir().join(format!("rmm-script-{}", uuid::Uuid::new_v4()));
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
fs::DirBuilder::new().mode(0o700).create(&dir)?;
|
||||
struct Cleanup(PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(dir.clone());
|
||||
let path = dir.join("script");
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)?;
|
||||
file.write_all(&request.bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
let mut args = vec![
|
||||
"--".into(),
|
||||
path.to_str().context("non-UTF8 temp path")?.to_owned(),
|
||||
];
|
||||
args.extend(request.arguments.clone());
|
||||
process::run(
|
||||
request.interpreter.path(),
|
||||
&args,
|
||||
request.timeout,
|
||||
request.max_output_bytes,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ServiceUnit(String);
|
||||
impl ServiceUnit {
|
||||
pub fn new(value: &str) -> Result<Self> {
|
||||
ensure!(
|
||||
value.len() <= 255 && value.ends_with(".service"),
|
||||
"expected exact .service unit"
|
||||
);
|
||||
ensure!(
|
||||
!value.starts_with(['-', '.']) && value.len() > 8,
|
||||
"invalid unit"
|
||||
);
|
||||
ensure!(
|
||||
value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_.@:-".contains(&b)),
|
||||
"unit aliases/globs/paths/escapes unsupported"
|
||||
);
|
||||
ensure!(
|
||||
!value.contains("@.service"),
|
||||
"template requires an exact instance"
|
||||
);
|
||||
Ok(Self(value.to_owned()))
|
||||
}
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DesiredServiceState {
|
||||
Running,
|
||||
Stopped,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServiceRequest {
|
||||
pub unit: ServiceUnit,
|
||||
pub desired: DesiredServiceState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ExactPackage {
|
||||
name: String,
|
||||
version: String,
|
||||
architecture: String,
|
||||
}
|
||||
impl ExactPackage {
|
||||
pub fn new(name: &str, version: &str, architecture: &str) -> Result<Self> {
|
||||
ensure!(
|
||||
name.len() >= 2 && name.len() <= 128 && name.as_bytes()[0].is_ascii_lowercase(),
|
||||
"invalid Debian package name"
|
||||
);
|
||||
ensure!(
|
||||
name.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"+.-".contains(&b)),
|
||||
"invalid Debian package name"
|
||||
);
|
||||
ensure!(
|
||||
!version.is_empty() && version.len() <= 128 && version.as_bytes()[0].is_ascii_digit(),
|
||||
"version must be exact"
|
||||
);
|
||||
ensure!(
|
||||
version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b".+:~-'".contains(&b))
|
||||
&& !version.contains('\''),
|
||||
"invalid Debian version"
|
||||
);
|
||||
ensure!(
|
||||
!architecture.is_empty()
|
||||
&& architecture.len() <= 32
|
||||
&& architecture
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
&& !architecture.starts_with('-'),
|
||||
"invalid architecture"
|
||||
);
|
||||
Ok(Self {
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
architecture: architecture.into(),
|
||||
})
|
||||
}
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
pub fn version(&self) -> &str {
|
||||
&self.version
|
||||
}
|
||||
pub fn architecture(&self) -> &str {
|
||||
&self.architecture
|
||||
}
|
||||
pub fn apt_argument(&self) -> String {
|
||||
format!("{}:{}={}", self.name, self.architecture, self.version)
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PackageRequest {
|
||||
packages: Vec<ExactPackage>,
|
||||
}
|
||||
impl PackageRequest {
|
||||
/// The allowlist must come from the immutable, approved recipe, never from
|
||||
/// mutable APT candidates at execution time. All dependencies need inclusion.
|
||||
pub fn new(packages: Vec<ExactPackage>, approved_allowlist: &[ExactPackage]) -> Result<Self> {
|
||||
ensure!(
|
||||
!packages.is_empty() && packages.len() <= 128,
|
||||
"invalid package count"
|
||||
);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for p in &packages {
|
||||
ensure!(
|
||||
approved_allowlist.contains(p),
|
||||
"package/version/architecture not approved"
|
||||
);
|
||||
ensure!(
|
||||
seen.insert((&p.name, &p.architecture)),
|
||||
"duplicate package target"
|
||||
);
|
||||
}
|
||||
Ok(Self { packages })
|
||||
}
|
||||
pub fn packages(&self) -> &[ExactPackage] {
|
||||
&self.packages
|
||||
}
|
||||
}
|
||||
|
||||
/// No generic command/shell variant. This is the mockable typed OS boundary.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ProviderCommand {
|
||||
ReadService(ServiceUnit),
|
||||
SetService(ServiceRequest),
|
||||
ReadPackage(ExactPackage),
|
||||
SimulatePackages(PackageRequest),
|
||||
InstallPackages(PackageRequest),
|
||||
RequestReboot,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CommandEvidence {
|
||||
pub code: Option<i32>,
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub truncated: bool,
|
||||
pub timed_out: bool,
|
||||
}
|
||||
impl CommandEvidence {
|
||||
fn success(&self) -> bool {
|
||||
self.code == Some(0) && !self.timed_out && !self.truncated
|
||||
}
|
||||
}
|
||||
/// A runner error must mean proven non-start. Once a process might have started,
|
||||
/// return evidence with `timed_out=true`/`code=None`, not an error: callers must
|
||||
/// retain an unknown effect and must never blindly replay the action. Package
|
||||
/// mutation implementations additionally must own OS package locks across exact
|
||||
/// dependency re-resolution and enforce the approved no-reboot recipe boundary.
|
||||
pub trait CommandRunner {
|
||||
fn run(&mut self, command: &ProviderCommand) -> Result<CommandEvidence>;
|
||||
}
|
||||
|
||||
/// Native package mutation deliberately fails closed until an isolated package
|
||||
/// helper can suppress service/maintainer-script reboot side effects and retain
|
||||
/// package locks across resolution/execution. No unsafe `apt-get -y` shortcut.
|
||||
#[derive(Default)]
|
||||
pub struct NativeCommandRunner;
|
||||
impl CommandRunner for NativeCommandRunner {
|
||||
fn run(&mut self, command: &ProviderCommand) -> Result<CommandEvidence> {
|
||||
let (program, args, timeout) = match command {
|
||||
ProviderCommand::ReadService(unit) => {
|
||||
ensure!(
|
||||
Path::new("/run/systemd/system").is_dir(),
|
||||
"UNSUPPORTED_CAPABILITY: systemd unavailable"
|
||||
);
|
||||
(
|
||||
"/usr/bin/systemctl",
|
||||
vec![
|
||||
"show".into(),
|
||||
"--no-pager".into(),
|
||||
"--property=Id,LoadState,ActiveState,SubState,UnitFileState".into(),
|
||||
"--".into(),
|
||||
unit.0.clone(),
|
||||
],
|
||||
15,
|
||||
)
|
||||
}
|
||||
ProviderCommand::SetService(request) => {
|
||||
ensure!(
|
||||
Path::new("/run/systemd/system").is_dir(),
|
||||
"UNSUPPORTED_CAPABILITY: systemd unavailable"
|
||||
);
|
||||
(
|
||||
"/usr/bin/systemctl",
|
||||
vec![
|
||||
match request.desired {
|
||||
DesiredServiceState::Running => "start",
|
||||
DesiredServiceState::Stopped => "stop",
|
||||
}
|
||||
.into(),
|
||||
"--".into(),
|
||||
request.unit.0.clone(),
|
||||
],
|
||||
120,
|
||||
)
|
||||
}
|
||||
ProviderCommand::ReadPackage(p) => (
|
||||
"/usr/bin/dpkg-query",
|
||||
vec![
|
||||
"--show".into(),
|
||||
"--showformat=${db:Status-Status}\t${Package}\t${Version}\t${Architecture}\\n"
|
||||
.into(),
|
||||
"--".into(),
|
||||
format!("{}:{}", p.name, p.architecture),
|
||||
],
|
||||
15,
|
||||
),
|
||||
ProviderCommand::SimulatePackages(request) => {
|
||||
let mut args = vec![
|
||||
"--simulate".into(),
|
||||
"--no-remove".into(),
|
||||
"--no-install-recommends".into(),
|
||||
"install".into(),
|
||||
"--".into(),
|
||||
];
|
||||
args.extend(request.packages.iter().map(ExactPackage::apt_argument));
|
||||
("/usr/bin/apt-get", args, 30)
|
||||
}
|
||||
ProviderCommand::InstallPackages(_) => bail!(
|
||||
"UNSUPPORTED_CAPABILITY: isolated no-reboot package helper not integrated; no mutation performed"
|
||||
),
|
||||
ProviderCommand::RequestReboot => {
|
||||
ensure!(
|
||||
Path::new("/run/systemd/system").is_dir(),
|
||||
"UNSUPPORTED_CAPABILITY: systemd unavailable"
|
||||
);
|
||||
("/usr/bin/systemctl", vec!["reboot".into()], 15)
|
||||
}
|
||||
};
|
||||
let output = match process::run(program, &args, Duration::from_secs(timeout), 512 * 1024) {
|
||||
Ok(output) => output,
|
||||
// Conservatively retain unknown effect. An OS transport error is
|
||||
// not proof that a process never started, even after group cleanup.
|
||||
Err(_) => {
|
||||
return Ok(CommandEvidence {
|
||||
code: None,
|
||||
stdout: vec![],
|
||||
stderr: b"OS_TRANSPORT_ERROR_EFFECT_UNKNOWN".to_vec(),
|
||||
truncated: false,
|
||||
timed_out: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
Ok(CommandEvidence {
|
||||
code: output.code,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
truncated: output.truncated,
|
||||
timed_out: output.timed_out,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ActionState {
|
||||
Verified,
|
||||
Failed,
|
||||
Unknown,
|
||||
AwaitingReboot,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ActionResult {
|
||||
pub state: ActionState,
|
||||
pub evidence: Vec<CommandEvidence>,
|
||||
pub reboot_required: Option<bool>,
|
||||
}
|
||||
pub struct OsActionProvider<R> {
|
||||
runner: R,
|
||||
}
|
||||
impl<R: CommandRunner> OsActionProvider<R> {
|
||||
pub fn new(runner: R) -> Self {
|
||||
Self { runner }
|
||||
}
|
||||
pub fn read_service(&mut self, unit: &ServiceUnit) -> Result<CommandEvidence> {
|
||||
self.runner.run(&ProviderCommand::ReadService(unit.clone()))
|
||||
}
|
||||
pub fn read_package(&mut self, package: &ExactPackage) -> Result<CommandEvidence> {
|
||||
self.runner
|
||||
.run(&ProviderCommand::ReadPackage(package.clone()))
|
||||
}
|
||||
pub fn set_service_state(&mut self, request: &ServiceRequest) -> Result<ActionResult> {
|
||||
let before = self.read_service(&request.unit)?;
|
||||
let text = std::str::from_utf8(&before.stdout)?;
|
||||
ensure!(
|
||||
before.success()
|
||||
&& text.lines().any(|l| l == format!("Id={}", request.unit.0))
|
||||
&& text.lines().any(|l| l == "LoadState=loaded"),
|
||||
"service must resolve to exact loaded unit (no alias)"
|
||||
);
|
||||
let effect = self
|
||||
.runner
|
||||
.run(&ProviderCommand::SetService(request.clone()))?;
|
||||
let mut result = ActionResult {
|
||||
state: ActionState::Unknown,
|
||||
evidence: vec![before, effect],
|
||||
reboot_required: Some(false),
|
||||
};
|
||||
if !result.evidence[1].success() {
|
||||
return Ok(result);
|
||||
}
|
||||
let after = self.read_service(&request.unit)?;
|
||||
let expected = match request.desired {
|
||||
DesiredServiceState::Running => "ActiveState=active",
|
||||
DesiredServiceState::Stopped => "ActiveState=inactive",
|
||||
};
|
||||
result.state = if after.success()
|
||||
&& std::str::from_utf8(&after.stdout)?
|
||||
.lines()
|
||||
.any(|l| l == expected)
|
||||
{
|
||||
ActionState::Verified
|
||||
} else {
|
||||
ActionState::Unknown
|
||||
};
|
||||
result.evidence.push(after);
|
||||
Ok(result)
|
||||
}
|
||||
pub fn ensure_package(&mut self, request: &PackageRequest) -> Result<ActionResult> {
|
||||
self.packages(request)
|
||||
}
|
||||
pub fn apply_updates(
|
||||
&mut self,
|
||||
exact_resolved_updates: &PackageRequest,
|
||||
) -> Result<ActionResult> {
|
||||
self.packages(exact_resolved_updates)
|
||||
}
|
||||
fn packages(&mut self, request: &PackageRequest) -> Result<ActionResult> {
|
||||
let mut evidence = vec![];
|
||||
let mut already_installed = true;
|
||||
for package in &request.packages {
|
||||
let observed = self.read_package(package)?;
|
||||
already_installed &= package_matches(package, &observed);
|
||||
evidence.push(observed);
|
||||
}
|
||||
if already_installed {
|
||||
return Ok(ActionResult {
|
||||
state: ActionState::Verified,
|
||||
evidence,
|
||||
reboot_required: reboot_required(),
|
||||
});
|
||||
}
|
||||
let simulation = self
|
||||
.runner
|
||||
.run(&ProviderCommand::SimulatePackages(request.clone()))?;
|
||||
ensure!(
|
||||
simulation.success(),
|
||||
"package resolution unavailable/incomplete"
|
||||
);
|
||||
validate_apt_simulation(request, &simulation.stdout)?;
|
||||
evidence.push(simulation);
|
||||
// Implementations of CommandRunner must atomically recheck this exact
|
||||
// transaction under OS package locks and forbid unapproved dependencies.
|
||||
let effect = self
|
||||
.runner
|
||||
.run(&ProviderCommand::InstallPackages(request.clone()))?;
|
||||
let uncertain = !effect.success();
|
||||
evidence.push(effect);
|
||||
let mut verified = true;
|
||||
for package in &request.packages {
|
||||
let observed = self.read_package(package)?;
|
||||
verified &= package_matches(package, &observed);
|
||||
evidence.push(observed);
|
||||
}
|
||||
Ok(ActionResult {
|
||||
state: if verified && !uncertain {
|
||||
ActionState::Verified
|
||||
} else {
|
||||
ActionState::Unknown
|
||||
},
|
||||
evidence,
|
||||
reboot_required: reboot_required(),
|
||||
})
|
||||
}
|
||||
pub fn reboot(&mut self, request: &RebootRequest) -> Result<ActionResult> {
|
||||
ensure!(
|
||||
crate::boot_id()? == request.previous_boot_id,
|
||||
"boot changed before reboot request; reconcile, do not repeat"
|
||||
);
|
||||
let evidence = self.runner.run(&ProviderCommand::RequestReboot)?;
|
||||
Ok(ActionResult {
|
||||
state: if evidence.success() {
|
||||
ActionState::AwaitingReboot
|
||||
} else {
|
||||
ActionState::Unknown
|
||||
},
|
||||
evidence: vec![evidence],
|
||||
reboot_required: Some(true),
|
||||
})
|
||||
}
|
||||
}
|
||||
fn package_matches(p: &ExactPackage, output: &CommandEvidence) -> bool {
|
||||
output.success()
|
||||
&& std::str::from_utf8(&output.stdout).is_ok_and(|text| {
|
||||
text.trim_end() == format!("installed\t{}\t{}\t{}", p.name, p.version, p.architecture)
|
||||
})
|
||||
}
|
||||
pub fn reboot_required() -> Option<bool> {
|
||||
match fs::metadata("/var/run/reboot-required") {
|
||||
Ok(_) => Some(true),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
/// Parse C-locale APT simulation; fail closed on removals or unresolved changes.
|
||||
pub fn validate_apt_simulation(request: &PackageRequest, bytes: &[u8]) -> Result<()> {
|
||||
let text = std::str::from_utf8(bytes)?;
|
||||
for line in text.lines() {
|
||||
ensure!(!line.starts_with("Remv "), "unapproved removal");
|
||||
if let Some(rest) = line.strip_prefix("Inst ") {
|
||||
let name = rest
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.context("missing apt package")?;
|
||||
let version = rest
|
||||
.split_once('(')
|
||||
.context("missing apt version")?
|
||||
.1
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.context("missing version")?;
|
||||
// Require explicit architecture in the simulation. Never guess host
|
||||
// architecture for multiarch dependencies.
|
||||
let arch = rest
|
||||
.rsplit_once('[')
|
||||
.context("missing apt architecture")?
|
||||
.1
|
||||
.split(']')
|
||||
.next()
|
||||
.context("missing architecture")?;
|
||||
ensure!(
|
||||
request.packages.iter().any(|p| (name == p.name
|
||||
|| name == format!("{}:{}", p.name, p.architecture))
|
||||
&& p.version == version
|
||||
&& p.architecture == arch),
|
||||
"unapproved apt dependency/version/architecture"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RebootRequest {
|
||||
previous_boot_id: String,
|
||||
}
|
||||
impl RebootRequest {
|
||||
pub fn new(previous_boot_id: &str) -> Result<Self> {
|
||||
Ok(Self {
|
||||
previous_boot_id: uuid::Uuid::parse_str(previous_boot_id)?.to_string(),
|
||||
})
|
||||
}
|
||||
/// Caller must separately prove authenticated re-enrollment/contact and run
|
||||
/// approved postconditions. A changed boot ID alone is NOT job success.
|
||||
pub fn boot_changed(&self, observed_boot_id: &str) -> Result<bool> {
|
||||
Ok(uuid::Uuid::parse_str(observed_boot_id)?.to_string() != self.previous_boot_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn temp_script_permissions_arguments_and_combined_cap() {
|
||||
let bytes = b"stat -c '%a' -- \"$0\"; printf '%s' \"$1\"".to_vec();
|
||||
let request = ScriptRequest::new(
|
||||
bytes.clone(),
|
||||
Interpreter::PosixSh,
|
||||
vec!["literal;$(false)".into()],
|
||||
Duration::from_secs(2),
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(request.bytes(), bytes);
|
||||
let output = run_script(&request).unwrap();
|
||||
assert_eq!(output.code, Some(0));
|
||||
assert_eq!(output.stdout, b"600\nliteral;$(false)");
|
||||
let request = ScriptRequest::new(
|
||||
b"while :; do printf 'abcdef'; printf 'ghijkl' >&2; done".to_vec(),
|
||||
Interpreter::PosixSh,
|
||||
vec![],
|
||||
Duration::from_millis(50),
|
||||
17,
|
||||
)
|
||||
.unwrap();
|
||||
let output = run_script(&request).unwrap();
|
||||
assert!(output.truncated && output.timed_out);
|
||||
assert!(output.stdout.len() + output.stderr.len() <= 17);
|
||||
}
|
||||
#[test]
|
||||
fn native_package_mutation_fails_closed_before_execution() {
|
||||
let package = ExactPackage::new("hello", "2.10-3", "amd64").unwrap();
|
||||
let request = PackageRequest::new(vec![package.clone()], &[package]).unwrap();
|
||||
let error = NativeCommandRunner
|
||||
.run(&ProviderCommand::InstallPackages(request))
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("no mutation performed"));
|
||||
}
|
||||
#[test]
|
||||
fn exact_identifiers_reject_injection() {
|
||||
for unit in [
|
||||
"--help.service",
|
||||
"*.service",
|
||||
"a/b.service",
|
||||
"foo@.service",
|
||||
"foo.service;id",
|
||||
"foo\\x20.service",
|
||||
] {
|
||||
assert!(ServiceUnit::new(unit).is_err());
|
||||
}
|
||||
assert!(ServiceUnit::new("sshd.service").is_ok());
|
||||
for name in ["-qq", "x;id", "foo/bar", "foo:*", "foo bar"] {
|
||||
assert!(ExactPackage::new(name, "1.0", "amd64").is_err());
|
||||
}
|
||||
assert!(ExactPackage::new("hello", "1.0*", "amd64").is_err());
|
||||
let p = ExactPackage::new("hello", "2.10-3", "amd64").unwrap();
|
||||
assert!(PackageRequest::new(vec![p.clone()], &[]).is_err());
|
||||
let request = PackageRequest::new(vec![p.clone()], &[p]).unwrap();
|
||||
assert!(validate_apt_simulation(&request, b"Inst hello (2.10-3 repo [amd64])\n").is_ok());
|
||||
assert!(validate_apt_simulation(&request, b"Inst evil (1 repo [amd64])\n").is_err());
|
||||
assert!(validate_apt_simulation(&request, b"Remv hello [2.10-3]\n").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn harmless_script_raw_output_and_limits() {
|
||||
let request = |bytes: &[u8], timeout, cap| {
|
||||
ScriptRequest::new(bytes.to_vec(), Interpreter::PosixSh, vec![], timeout, cap).unwrap()
|
||||
};
|
||||
let hello = run_script(&request(
|
||||
b"printf 'Hello World\\n'",
|
||||
Duration::from_secs(2),
|
||||
100,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(hello.code, Some(0));
|
||||
assert_eq!(hello.stdout, b"Hello World\n");
|
||||
let capped = run_script(&request(
|
||||
b"while :; do printf '0123456789'; done",
|
||||
Duration::from_millis(60),
|
||||
21,
|
||||
))
|
||||
.unwrap();
|
||||
assert!(capped.timed_out && capped.truncated);
|
||||
assert!(capped.stdout.len() + capped.stderr.len() <= 21);
|
||||
let timeout =
|
||||
run_script(&request(b"sleep 5 & wait", Duration::from_millis(50), 100)).unwrap();
|
||||
assert!(timeout.timed_out);
|
||||
}
|
||||
struct Mock {
|
||||
commands: Vec<ProviderCommand>,
|
||||
replies: std::collections::VecDeque<CommandEvidence>,
|
||||
}
|
||||
impl CommandRunner for Mock {
|
||||
fn run(&mut self, c: &ProviderCommand) -> Result<CommandEvidence> {
|
||||
self.commands.push(c.clone());
|
||||
self.replies.pop_front().context("unexpected command")
|
||||
}
|
||||
}
|
||||
fn ok(text: &str) -> CommandEvidence {
|
||||
CommandEvidence {
|
||||
code: Some(0),
|
||||
stdout: text.as_bytes().to_vec(),
|
||||
stderr: vec![],
|
||||
truncated: false,
|
||||
timed_out: false,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn service_requires_independent_verification() {
|
||||
let mock = Mock {
|
||||
commands: vec![],
|
||||
replies: [
|
||||
ok("Id=demo.service\nLoadState=loaded\nActiveState=inactive\n"),
|
||||
ok(""),
|
||||
ok("Id=demo.service\nLoadState=loaded\nActiveState=active\n"),
|
||||
]
|
||||
.into(),
|
||||
};
|
||||
let mut provider = OsActionProvider::new(mock);
|
||||
let result = provider
|
||||
.set_service_state(&ServiceRequest {
|
||||
unit: ServiceUnit::new("demo.service").unwrap(),
|
||||
desired: DesiredServiceState::Running,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(result.state, ActionState::Verified);
|
||||
assert_eq!(provider.runner.commands.len(), 3);
|
||||
}
|
||||
#[test]
|
||||
fn package_mock_and_reboot_never_claim_exit_only_success() {
|
||||
let p = ExactPackage::new("hello", "2.10-3", "amd64").unwrap();
|
||||
let request = PackageRequest::new(vec![p.clone()], &[p]).unwrap();
|
||||
let mock = Mock {
|
||||
commands: vec![],
|
||||
replies: [
|
||||
ok("installed\thello\told\tamd64\n"),
|
||||
ok("Inst hello (2.10-3 repo [amd64])\n"),
|
||||
ok(""),
|
||||
ok("installed\thello\told\tamd64\n"),
|
||||
]
|
||||
.into(),
|
||||
};
|
||||
let mut provider = OsActionProvider::new(mock);
|
||||
assert_eq!(
|
||||
provider.ensure_package(&request).unwrap().state,
|
||||
ActionState::Unknown
|
||||
);
|
||||
let mock = Mock {
|
||||
commands: vec![],
|
||||
replies: [ok("")].into(),
|
||||
};
|
||||
let mut provider = OsActionProvider::new(mock);
|
||||
let request = RebootRequest::new(&crate::boot_id().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
provider.reboot(&request).unwrap().state,
|
||||
ActionState::AwaitingReboot
|
||||
);
|
||||
assert!(!request.boot_changed(&crate::boot_id().unwrap()).unwrap());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::Inventory;
|
||||
use std::{ffi::CString, fs, mem::MaybeUninit};
|
||||
|
||||
pub mod actions;
|
||||
pub mod inventory;
|
||||
mod process;
|
||||
pub mod wire;
|
||||
|
||||
/// Fixed helper metadata program only. Bounded and killable because this mode
|
||||
/// cannot launch APT or cause package effects; never use for transaction drivers.
|
||||
pub fn apt_planning_metadata() -> Result<Vec<u8>> {
|
||||
let output = process::run(
|
||||
"/usr/bin/python3",
|
||||
&[
|
||||
"-I".into(),
|
||||
"/usr/lib/rmm-apt-transaction/apt_transaction.py".into(),
|
||||
"planning-status".into(),
|
||||
],
|
||||
std::time::Duration::from_secs(4),
|
||||
32768,
|
||||
)?;
|
||||
ensure!(
|
||||
output.code == Some(0) && !output.timed_out && !output.truncated,
|
||||
"APT_PLANNING_UNAVAILABLE"
|
||||
);
|
||||
Ok(output.stdout)
|
||||
}
|
||||
|
||||
/// Read-only local collection. No shell, package manager or hypervisor access.
|
||||
pub fn collect() -> Result<Inventory> {
|
||||
let os = fs::read_to_string("/etc/os-release").context("read OS release")?;
|
||||
let hostname = fs::read_to_string("/proc/sys/kernel/hostname")?;
|
||||
let path = CString::new("/")?;
|
||||
let mut stat = MaybeUninit::<libc::statvfs>::uninit();
|
||||
// SAFETY: path is NUL terminated; stat points to writable, aligned storage.
|
||||
ensure!(
|
||||
unsafe { libc::statvfs(path.as_ptr(), stat.as_mut_ptr()) } == 0,
|
||||
"statvfs failed"
|
||||
);
|
||||
// SAFETY: successful statvfs initialized the structure.
|
||||
let stat = unsafe { stat.assume_init() };
|
||||
let inventory = Inventory {
|
||||
os,
|
||||
hostname: hostname.trim().to_owned(),
|
||||
architecture: std::env::consts::ARCH.to_owned(),
|
||||
root_total_bytes: stat
|
||||
.f_blocks
|
||||
.checked_mul(stat.f_frsize)
|
||||
.context("disk size overflow")?,
|
||||
root_available_bytes: stat
|
||||
.f_bavail
|
||||
.checked_mul(stat.f_frsize)
|
||||
.context("disk free overflow")?,
|
||||
root_available_inodes: stat.f_favail,
|
||||
};
|
||||
ensure!(inventory.validate(), "invalid local inventory");
|
||||
Ok(inventory)
|
||||
}
|
||||
pub fn boot_id() -> Result<String> {
|
||||
let id = fs::read_to_string("/proc/sys/kernel/random/boot_id")?;
|
||||
Ok(uuid::Uuid::parse_str(id.trim())?.to_string())
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn native_linux_inventory() {
|
||||
let i = super::collect().unwrap();
|
||||
assert!(i.validate());
|
||||
assert!(!super::boot_id().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Internal bounded argv-only subprocess transport; never a public command API.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use std::{
|
||||
io::Read,
|
||||
os::{fd::AsRawFd, unix::process::CommandExt},
|
||||
process::{Command, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Output {
|
||||
pub code: Option<i32>,
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub truncated: bool,
|
||||
pub timed_out: bool,
|
||||
}
|
||||
|
||||
// Nonblocking pipes avoid both unbounded output and reader threads held open by
|
||||
// grandchildren. The child has a separate process group, cleaned even on success.
|
||||
pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize) -> Result<Output> {
|
||||
ensure!(!timeout.is_zero() && cap > 0, "invalid process limits");
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
|
||||
.env("LC_ALL", "C")
|
||||
.env("LANG", "C")
|
||||
.env("DEBIAN_FRONTEND", "noninteractive")
|
||||
.env("SYSTEMD_PAGER", "")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.process_group(0);
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("spawn {program}"))?;
|
||||
struct Group(u32);
|
||||
impl Drop for Group {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: negative PID addresses only the group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(self.0 as i32), libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
let group = Group(child.id());
|
||||
let mut stdout = child.stdout.take().context("missing stdout")?;
|
||||
let mut stderr = child.stderr.take().context("missing stderr")?;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
// SAFETY: these are live owned pipe descriptors; flags are not pointers.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
}
|
||||
fn drain(
|
||||
pipe: &mut impl Read,
|
||||
target: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<bool> {
|
||||
let mut bytes = [0; 4096];
|
||||
// Bound each pass too: a continuously writing child cannot starve timeout.
|
||||
for _ in 0..16 {
|
||||
match pipe.read(&mut bytes) {
|
||||
Ok(0) => return Ok(true),
|
||||
Ok(n) => {
|
||||
let keep = n.min(*remaining);
|
||||
target.extend_from_slice(&bytes[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < n;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut result = Output {
|
||||
code: None,
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
truncated: false,
|
||||
timed_out: false,
|
||||
};
|
||||
let mut remaining = cap;
|
||||
let status = loop {
|
||||
let drained = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)
|
||||
.and_then(|_| {
|
||||
drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)
|
||||
});
|
||||
if let Err(e) = drained {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e);
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
if started.elapsed() >= timeout {
|
||||
result.timed_out = true;
|
||||
// SAFETY: this is the dedicated group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as i32), libc::SIGKILL);
|
||||
}
|
||||
break child.wait()?;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
let pgid = child.id();
|
||||
drop(group);
|
||||
// SIGKILL delivery is asynchronous. A single WouldBlock is not EOF and
|
||||
// does not prove that descendants have stopped. Bound both cleanup waiting
|
||||
// and output draining, and withhold a successful exit code if unconfirmed.
|
||||
let cleanup_started = Instant::now();
|
||||
loop {
|
||||
let stdout_closed = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let stderr_closed = drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
// SAFETY: signal zero only probes the dedicated process group.
|
||||
let absent = unsafe { libc::kill(-(pgid as i32), 0) } == -1
|
||||
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
|
||||
if stdout_closed && stderr_closed && absent {
|
||||
result.code = status.code();
|
||||
break;
|
||||
}
|
||||
if cleanup_started.elapsed() >= Duration::from_millis(250) {
|
||||
result.truncated |= !stdout_closed || !stderr_closed;
|
||||
// None explicitly means no confirmed successful completion. This
|
||||
// can also occur for lingering zombies: never guess their state.
|
||||
result.code = None;
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn exited_leader_does_not_leave_background_effects_or_open_pipes() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("rmm-group-test-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let marker = directory.join("unexpected-effect");
|
||||
// The background shell inherits stdout/stderr. The leader exits without
|
||||
// waiting; a missing group cleanup would allow the delayed write.
|
||||
let script = "(sleep 0.6; printf late; printf effect > \"$1\") & printf leader; exit 0";
|
||||
let started = Instant::now();
|
||||
let output = run(
|
||||
"/bin/sh",
|
||||
&[
|
||||
"-c".into(),
|
||||
script.into(),
|
||||
"rmm-test".into(),
|
||||
marker.to_str().unwrap().into(),
|
||||
],
|
||||
Duration::from_secs(2),
|
||||
128,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
assert!(output.stdout.starts_with(b"leader"));
|
||||
assert!(!output.stdout.windows(4).any(|s| s == b"late"));
|
||||
thread::sleep(Duration::from_millis(750));
|
||||
assert!(
|
||||
!marker.exists(),
|
||||
"background child caused an effect after return"
|
||||
);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Additive JSON observation mapping inside the existing snapshot payload. This
|
||||
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
|
||||
use anyhow::Result;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<Value>> {
|
||||
let value = serde_json::to_value(inventory)?;
|
||||
let mut result = Vec::new();
|
||||
for (name, observation) in value
|
||||
.as_object()
|
||||
.ok_or_else(|| anyhow::anyhow!("inventory object"))?
|
||||
{
|
||||
let mut observation = observation.clone();
|
||||
observation["scope"] = json!(format!("linux.{name}"));
|
||||
// Bound each scope independently. Never drop unsupported/error metadata
|
||||
// or imply that absent/truncated rows were deleted from a device.
|
||||
while serde_json::to_vec(&observation)?.len() > 32768 {
|
||||
observation["truncated"] = json!(true);
|
||||
observation["completeness"] = json!("partial");
|
||||
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
|
||||
if let Some(rows) = observation["data"].as_array_mut().filter(|v| !v.is_empty()) {
|
||||
rows.truncate(rows.len() / 2);
|
||||
} else {
|
||||
observation["data"] = Value::Null;
|
||||
observation["quality"] = json!("unknown");
|
||||
break;
|
||||
}
|
||||
}
|
||||
result.push(observation);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
pub fn snapshot(extended: bool) -> Result<Value> {
|
||||
let started = chrono::Utc::now();
|
||||
let mut base = serde_json::to_value(crate::collect()?)?;
|
||||
if extended {
|
||||
base["observations"] =
|
||||
serde_json::to_value(observations(&crate::inventory::collect_native())?)?;
|
||||
base["collection_started_at"] = json!(started);
|
||||
base["collection_completed_at"] = json!(chrono::Utc::now());
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
|
||||
let native = crate::inventory::collect_native();
|
||||
let mapped = observations(&native).unwrap();
|
||||
assert_eq!(mapped.len(), 11);
|
||||
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
|
||||
assert_eq!(smart["quality"], "unsupported");
|
||||
assert!(smart["data"].is_null());
|
||||
assert_eq!(smart["completeness"], "unknown");
|
||||
for observation in &mapped {
|
||||
assert!(
|
||||
chrono::DateTime::parse_from_rfc3339(observation["observed_at"].as_str().unwrap())
|
||||
.is_ok()
|
||||
);
|
||||
assert!(!observation["source_id"].as_str().unwrap().is_empty());
|
||||
assert!(observation.get("received_at").is_none());
|
||||
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
|
||||
}
|
||||
let base = snapshot(false).unwrap();
|
||||
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn scope_limit_retains_error_metadata_and_marks_partial() {
|
||||
let mut native = crate::inventory::collect_native();
|
||||
native.software.data = Some(
|
||||
(0..2000)
|
||||
.map(|_| crate::inventory::SoftwarePackage {
|
||||
name: "x".repeat(128),
|
||||
version: "1.0".into(),
|
||||
architecture: "amd64".into(),
|
||||
status: "installed".into(),
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let mapped = observations(&native).unwrap();
|
||||
let software = mapped
|
||||
.iter()
|
||||
.find(|v| v["scope"] == "linux.software")
|
||||
.unwrap();
|
||||
assert_eq!(software["truncated"], true);
|
||||
assert_eq!(software["completeness"], "partial");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user