749 lines
26 KiB
Rust
749 lines
26 KiB
Rust
//! 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());
|
|
}
|
|
}
|