diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d0ac7a3..4051b92 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,39 @@ this file is the curated, human-readable summary. ## Unreleased — Fast defaults with user-controlled source builds +- **`sys` adversarial input battery + hardening (2026-09-28).** New host-level + `tests/sys_adversarial.rs` (54 cases across 11 attack categories: shell + injection in every operand type, empty/NUL inputs, extreme lengths, Unicode + and homoglyphs, path traversal, option injection, malformed/nested JSON, CLI + flag conflicts, natural-language edge cases, boundary values, and privilege + gates) run against both the `phoebus-core` validators directly and the `sys` + binary as an isolated subprocess (`PATH=/nonexistent`, no AI provider). The + battery found and fixed five real validation gaps, each now regression-tested + in `phoebus-core` and the executor: `valid_file_path` now rejects shell + metacharacters and `..` components (its documented contract, previously + unimplemented); `valid_application_name` refuses `..`/empty path components + and a leading slash; `valid_ebuild_atom` refuses `.`-leading + (`.`, `..`) category/package components, closing a real overlay path + traversal (`../pkg` previously escaped `var/db/repos/phoebus`), with + `ebuild::package_dir` re-validating as defence in depth; + `valid_flatpak_app_id` refuses an empty reverse-DNS element (`org..test`); + and `valid_nix_attribute` refuses a leading dash (`--impure`). All gates + green: `cargo fmt`, `clippy --workspace --all-targets -- -D warnings`, + `cargo test --workspace` 828 passed, 0 failed. +- **`sys` flaw-fix battery (2026-09-28).** Six static-analysis flaws fixed and + regression-tested: `valid_package_spec` now accepts Gentoo version operators, + slots/subslots, repository specifiers, USE-dependency flags and wildcard + versions (`=app-editors/vim-9.0.2167`, `dev-lang/python:3.11`, + `sys-apps/portage::gentoo`) while still refusing leading dashes, whitespace + and shell metacharacters; the legacy phrase parser accepts quoted multi-word + application names (`sys install "visual studio code" --legacy --flatpak`); + `vdb_has_atom` (executor and kernel) normalizes through + `portage::normalize_dep_atom` so versioned post-install checks resolve; + `FlatpakInstall`/`FlatpakRemove` add `--system --noninteractive`; `who owns + usr/bin/vim` is normalized to an absolute path. New host-level battery + `tests/sys_flaws.rs` (9 cases) and `sys-acceptance.sh` service-lifecycle + + versioned-atom + path-normalization cases. All gates green: `cargo fmt`, + `clippy --workspace --all-targets`, `cargo test --workspace` 773 passed. - **Pristine reinstall + full boot acceptance (Run 15, 2026-09-28).** Rebuilt static binaries from HEAD and reinstalled clean on a fresh disposable 80 GiB VM: `INSTALL-RC=0`, no secret leak, 347/347 desktop diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 76efeb0..f614143 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,31 @@ Rolling note between work sessions. **Update this file before you finish**, then commit it. It should be short and current; use `git log` for detail. +- **`sys` adversarial battery + hardening (2026-09-28, IMPLEMENTED + + UNIT-TESTED, VM NOT RUN):** new `installer-rs/crates/phoebus-installer/tests/ + sys_adversarial.rs` (54 cases: shell injection per operand, empty/NUL, + lengths, Unicode/homoglyphs, traversal, option injection, malformed/nested + JSON, CLI flag conflicts, natural-language edges, boundaries, privilege + gates) exercising the `phoebus-core` validators and the `sys` binary under + `PATH=/nonexistent`. Found and fixed 5 real gaps, each regression-tested: + `valid_file_path` shell metacharacters + `..` (doc contract previously + unimplemented); `valid_application_name` `..`/empty components + leading + slash; `valid_ebuild_atom` `.`-leading components, closing a real overlay + path traversal (`../pkg`), plus `ebuild::package_dir` re-validation; + `valid_flatpak_app_id` empty reverse-DNS element; `valid_nix_attribute` + leading dash. Gates: `cargo fmt --all -- --check` clean, `clippy + --workspace --all-targets -- -D warnings` clean, `cargo test --workspace` + 828 passed / 0 failed. VM rerun of the acceptance matrix remains NotRun. +- **`sys` flaw-fix battery (2026-09-28, IMPLEMENTED + UNIT-TESTED, VM NOT RUN):** + fixed 6 audited flaws: versioned/slotted/repo atoms now validate + (`valid_package_spec`), quoted multi-word app names parse in legacy + install/remove, `vdb_has_atom` normalizes (executor + kernel), Flatpak + install/remove pin `--system --noninteractive`, and `who owns ` + is normalized. Added host battery `installer-rs/crates/phoebus-installer/tests/ + sys_flaws.rs` (9 tests) and `sys-acceptance.sh` service-lifecycle / versioned- + atom / who-owns cases. Gates: `cargo fmt --all -- --check`, `clippy + --workspace --all-targets`, `cargo test --workspace` 773 passed, `bash -n` + + `shellcheck` clean. VM rerun of the expanded acceptance matrix is NotRun. - **Headless stabilization run (SELF-HEALING LOOP ACTIVE, run 10 IN FLIGHT):** Failures so far, each fixed + committed + verified green (761 tests) + rerun: 1. Brave overlay pin missing → recorded reviewed pin `d3a97f22…` (`0aa31a3`). diff --git a/docs/STATUS.md b/docs/STATUS.md index 695beab..95d7a7f 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -106,7 +106,8 @@ Booting that recovery entry offline remains a manual gate. | Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | yes (installed VM: saved to user config, exit 0) | no | | Personal write ownership (elevated chown, symlink refusal, cross-uid refusal) | yes | yes (ownership-fixer seam + CLI refusal) | no | no | | Personal preference does not need the root-owned system transaction log | yes | yes (CLI regression: read-only transaction dir) | yes (installed VM acceptance) | n/a | -| Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=40 FAIL=0`, catalogue + regression group) | no | +| Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=40 FAIL=0`, catalogue + regression group; **plus service-lifecycle, versioned-atom and path-normalization cases added 2026-09-28 — host-level `tests/sys_flaws.rs` 9/9 PASS, VM rerun pending**) | no | +| `sys` adversarial input battery (injection/traversal/boundaries) | yes | yes (54-case `tests/sys_adversarial.rs`; five validation gaps fixed: file-path metacharacters + `..`, application-name traversal, ebuild `..` category (real overlay escape), Flatpak empty element, Nix option prefix) | no | no | | Portage config readable for non-root queries (`normalize_config_permissions`) | yes | yes (modes + keyring exclusion) | yes (fresh VM install: 0755/0644 out of the box; non-root `search` returns 3 results, `updates` reports 10) | no | | Privileged catalogue mutations (install/remove/depclean/cache/apply updates, alternate-root) | yes | yes (unit) | yes (fresh installed VM via root: 7/7 PASS) | no | | Rollback acceptance (snapshot -> change -> `sys undo` -> detached verify) | yes | yes | yes (`serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0 on a fresh disposable clone: package DB changed then restored, root marker gone, `/home` survives, boot running, no secret leak) | no | diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs index ee506c2..bfeb214 100644 --- a/installer-rs/crates/phoebus-core/src/action.rs +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -959,29 +959,100 @@ fn is_atom_char(c: char) -> bool { } /// A package may be a bare name (`vim`) so `emerge vim` resolves it, or a full -/// atom (`app-editors/vim`). Both are accepted; anything else is refused. +/// atom (`app-editors/vim`). Gentoo version operators, slots/subslots, repository +/// specifiers, USE-dependency flags and wildcard versions are accepted, because +/// those are exactly the atoms `emerge` understands. Anything containing shell +/// metacharacters, whitespace or control characters is refused, as is a leading +/// dash (which `emerge` would consume as an option). pub fn valid_package_spec(spec: &str) -> bool { - if spec.is_empty() || spec.len() > 128 { + let s = spec; + if s.is_empty() || s.len() > 256 { return false; } // A leading dash would be consumed by `emerge` as an option (e.g. // `--color=n` or `-C`), so it is rejected before any command is built. - if spec.starts_with('-') { + if s.starts_with('-') { return false; } - let mut parts = spec.split('/'); + // Reject whitespace, control characters and shell metacharacters. The base + // grammar below already excludes most of these, but this makes the security + // invariant explicit and independent of the parser. + if s.chars() + .any(|c| c.is_whitespace() || c.is_control() || ";&|$`\"'\\(){}".contains(c)) + { + return false; + } + let mut rest = s; + // Strip a version operator prefix (`>=`, `<=`, `=`, `>`, `<`, `~`). + for op in [">=", "<=", "=", ">", "<", "~"] { + if let Some(stripped) = rest.strip_prefix(op) { + rest = stripped; + break; + } + } + if rest.is_empty() || rest.starts_with('-') { + return false; + } + // Strip an optional repository specifier (`::repo`). + if let Some((base, repo)) = rest.split_once("::") { + if repo.is_empty() + || !repo + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_-".contains(c)) + { + return false; + } + rest = base; + } + // Strip optional USE-dependency flags (`[flag1,-flag2]`). + if let Some(open) = rest.find('[') { + if !rest.ends_with(']') { + return false; + } + let flags = &rest[open + 1..rest.len() - 1]; + if flags.is_empty() + || !flags + .chars() + .all(|c| c.is_ascii_alphanumeric() || "+._-,!*=?".contains(c)) + { + return false; + } + rest = &rest[..open]; + } + // Strip an optional slot/subslot specifier (`:slot`, `:slot/subslot`, `:=`, + // `:*`). + if let Some((base, slot)) = rest.split_once(':') { + if slot.is_empty() { + return false; + } + let valid_slot = slot == "=" + || slot == "*" + || slot + .chars() + .all(|c| c.is_ascii_alphanumeric() || "+._-=/".contains(c)); + if !valid_slot { + return false; + } + rest = base; + } + // Base atom: a bare name (`vim`) or `category/package` (`app-editors/vim-9.0*`). + // A `.`/`..` component is never a Gentoo atom and could traverse a path, so + // it is refused before the base grammar is considered. + let not_dot = |s: &str| s != "." && s != ".."; + let mut parts = rest.split('/'); let Some(first) = parts.next() else { return false; }; - if first.is_empty() || !first.chars().all(is_atom_char) { + if first.is_empty() || !not_dot(first) || !first.chars().all(is_atom_char) { return false; } match parts.next() { None => true, Some(second) => { !second.is_empty() + && not_dot(second) && !second.starts_with('-') - && second.chars().all(is_atom_char) + && second.chars().all(|c| is_atom_char(c) || c == '*') && parts.next().is_none() } } @@ -1006,6 +1077,9 @@ pub fn valid_flatpak_app_id(app_id: &str) -> bool { && app_id.contains('.') && !app_id.starts_with('.') && !app_id.ends_with('.') + // Double dots create an empty reverse-DNS element, which Flatpak's own + // id grammar rejects. + && !app_id.contains("..") && app_id .chars() .all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c)) @@ -1017,6 +1091,8 @@ pub fn valid_flatpak_app_id(app_id: &str) -> bool { pub fn valid_nix_attribute(value: &str) -> bool { !value.is_empty() && value.len() <= 64 + // A leading dash would be consumed by `nix` as an option. + && !value.starts_with('-') && value .chars() .all(|c| c.is_ascii_alphanumeric() || "+-._".contains(c)) @@ -1073,7 +1149,8 @@ pub fn valid_http_url(value: &str) -> bool { } /// An absolute file path for an ownership query: bounded, no NUL or control -/// characters, no shell metacharacters that a backend could misread. +/// characters, no shell metacharacters that a backend could misread, and no +/// `..` component that could escape the queried location. pub fn valid_file_path(value: &str) -> bool { !value.is_empty() && value.len() <= 4096 @@ -1081,14 +1158,22 @@ pub fn valid_file_path(value: &str) -> bool { && !value.starts_with('-') && !value.contains('\0') && !value.chars().any(|c| c.is_control()) + && !value.chars().any(|c| ";&|$`\"'\\(){}<>".contains(c)) + && !value.split('/').any(|c| c == "..") } /// A user-facing application name (`firefox`, `org.mozilla.firefox`, -/// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls. +/// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls, +/// and not a path: a leading slash, an empty element or a `.`/`..` component +/// could otherwise escape a managed directory when a record is resolved. pub fn valid_application_name(value: &str) -> bool { !value.is_empty() && value.len() <= 128 && !value.starts_with('-') + && !value.starts_with('/') + && !value + .split('/') + .any(|c| c.is_empty() || c == "." || c == "..") && value .chars() .all(|c| c.is_ascii_alphanumeric() || "._+@/-".contains(c)) @@ -1130,6 +1215,9 @@ pub fn valid_ebuild_atom(value: &str) -> bool { let ok = |s: &str| { !s.is_empty() && !s.starts_with('-') + // A leading dot admits `.` and `..`, which would traverse the + // overlay when the category/package directories are joined. + && !s.starts_with('.') && s.chars() .all(|c| c.is_ascii_alphanumeric() || "+._-".contains(c)) }; @@ -1325,7 +1413,15 @@ fn parse_natural_raw(text: &str) -> Option { } } if let Some(path) = rest("owners ").or_else(|| rest("who owns ")) { + let path = path.trim(); if !path.is_empty() { + // Normalize a relative path (`usr/bin/vim`) to an absolute one so a + // natural query is not rejected by the absolute-path validator. + let path = if path.starts_with('/') { + path.to_string() + } else { + format!("/{path}") + }; return Some(SystemAction::PackageOwners { path }); } } @@ -1812,6 +1908,29 @@ mod tests { assert!(!valid_flatpak_app_id("com/spotify")); } + #[test] + fn adversarial_operands_are_refused() { + // Path traversal in an application name or an ownership query path. + assert!(!valid_application_name("../../etc/passwd")); + assert!(!valid_application_name("/etc/passwd")); + assert!(!valid_application_name("a//b")); + assert!(!valid_application_name("a/./b")); + assert!(valid_application_name("app-editors/vim")); + assert!(!valid_file_path("/etc/../../../root/.ssh/id_rsa")); + assert!(!valid_file_path("/usr/bin/vim;id")); + assert!(!valid_file_path("/tmp/$(id)")); + assert!(valid_file_path("/usr/bin/vim")); + // Option injection into a native tool. + assert!(!valid_nix_attribute("--impure")); + assert!(!valid_package_spec("-C")); + assert!(!valid_package_spec("cat/..")); + // Reverse-DNS holes and ebuild category traversal. + assert!(!valid_flatpak_app_id("org..test")); + assert!(!valid_ebuild_atom("../pkg")); + assert!(!valid_ebuild_atom("app-misc/..")); + assert!(!valid_ebuild_atom(".hidden/pkg")); + } + #[test] fn service_lifecycle_actions_are_typed_and_medium_risk() { for (json, expected) in [ diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index de6aa64..ed81b2a 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -217,7 +217,11 @@ fn pretend_args(action: &SystemAction) -> Option> { /// Whether a Portage atom has a VDB record under `root` (installed). fn vdb_has_atom(root: &Path, atom: &str) -> bool { - let (category, package) = match atom.split_once('/') { + // Normalize first: a versioned/slotted atom (`=app-editors/vim-9.0.2167`, + // `dev-libs/openssl:0/1.1`) must resolve to the same `category/name` VDB + // directory as the bare atom. + let normalized = portage::normalize_dep_atom(atom); + let (category, package) = match normalized.split_once('/') { Some((c, p)) => (c, p), None => return false, }; @@ -1373,6 +1377,8 @@ pub fn execute_inner( "flatpak", &[ "install".into(), + "--system".into(), + "--noninteractive".into(), "-y".into(), "--".into(), "flathub".into(), @@ -1388,7 +1394,14 @@ pub fn execute_inner( "sys", "remove flatpak", "flatpak", - &["uninstall".into(), "-y".into(), "--".into(), app_id.clone()], + &[ + "uninstall".into(), + "--system".into(), + "--noninteractive".into(), + "-y".into(), + "--".into(), + app_id.clone(), + ], )?; format!("removed Flatpak app {app_id}") } diff --git a/installer-rs/crates/phoebus-executor/src/ebuild.rs b/installer-rs/crates/phoebus-executor/src/ebuild.rs index 7234afe..5ee2e1d 100644 --- a/installer-rs/crates/phoebus-executor/src/ebuild.rs +++ b/installer-rs/crates/phoebus-executor/src/ebuild.rs @@ -58,6 +58,15 @@ fn overlay_dir(root: &Path) -> PathBuf { } fn package_dir(root: &Path, atom: &str) -> Result { + // The path constructor is the last line of defence: never join an atom + // that is not a strict `category/package` with safe components. + if !phoebus_core::action::valid_ebuild_atom(atom) { + return Err(ExecError::operation( + "ebuild", + "resolve overlay path", + "atom must be category/package", + )); + } let (category, package) = atom.split_once('/').ok_or_else(|| { ExecError::operation( "ebuild", @@ -65,13 +74,6 @@ fn package_dir(root: &Path, atom: &str) -> Result { "atom must be category/package", ) })?; - if category.is_empty() || package.is_empty() { - return Err(ExecError::operation( - "ebuild", - "resolve overlay path", - "atom must be category/package", - )); - } Ok(overlay_dir(root).join(category).join(package)) } @@ -534,7 +536,15 @@ SLOT=\"0\" fn weird_atoms_cannot_escape_the_overlay() { let exec = make_exec(RecordingRunner::new(), false); let root = tempfile::tempdir().unwrap(); - for atom in ["../../etc/passwd", "a/b/c", "/bin/sh", "a//b"] { + for atom in [ + "../../etc/passwd", + "a/b/c", + "/bin/sh", + "a//b", + "../pkg", + "app-misc/..", + ".hidden/pkg", + ] { assert!( prepare(&exec, root.path(), atom, "1.0", "r", SAMPLE).is_err(), "atom {atom} must be refused" diff --git a/installer-rs/crates/phoebus-executor/src/kernel.rs b/installer-rs/crates/phoebus-executor/src/kernel.rs index 22ec10a..f9d8c08 100644 --- a/installer-rs/crates/phoebus-executor/src/kernel.rs +++ b/installer-rs/crates/phoebus-executor/src/kernel.rs @@ -175,7 +175,9 @@ fn tuned_kernel_fragment() -> String { /// Whether a VDB record exists for `atom` under `root`. fn vdb_has_atom(root: &Path, atom: &str) -> bool { - let (category, package) = match atom.split_once('/') { + // Normalize versioned/slotted atoms to `category/name` before the lookup. + let normalized = portage::normalize_dep_atom(atom); + let (category, package) = match normalized.split_once('/') { Some((c, p)) => (c, p), None => return false, }; diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index 55579a8..fb61cb2 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -570,8 +570,13 @@ fn parse_install_text(text: &str) -> Option { let lower = trimmed.to_ascii_lowercase(); for prefix in ["install ", "add "] { if lower.starts_with(prefix) { - let app = trimmed[prefix.len()..].trim(); - if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { + // Strip surrounding quotes so a multi-word app name ("visual + // studio code") is treated as one operand. + let app = trimmed[prefix.len()..] + .trim() + .trim_matches(['"', '\'']) + .trim(); + if !app.is_empty() && !app.starts_with('-') && !app.chars().any(char::is_control) { return Some(app.to_string()); } } @@ -591,8 +596,13 @@ fn parse_removal_text(text: &str) -> Option { let lower = trimmed.to_ascii_lowercase(); for prefix in ["remove ", "uninstall ", "delete "] { if lower.starts_with(prefix) { - let app = trimmed[prefix.len()..].trim(); - if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { + // Strip surrounding quotes so a multi-word app name ("Google + // Chrome") is treated as one operand. + let app = trimmed[prefix.len()..] + .trim() + .trim_matches(['"', '\'']) + .trim(); + if !app.is_empty() && !app.starts_with('-') && !app.chars().any(char::is_control) { return Some(app.to_string()); } } diff --git a/installer-rs/crates/phoebus-installer/tests/sys_adversarial.rs b/installer-rs/crates/phoebus-installer/tests/sys_adversarial.rs new file mode 100644 index 0000000..d8546c1 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/tests/sys_adversarial.rs @@ -0,0 +1,955 @@ +//! Adversarial stress battery for `sys`. +//! +//! This file systematically tries to break every input surface of `sys` with +//! hostile, malformed and boundary inputs. It is deliberately conservative in +//! its expectations: a test asserts a *security invariant* (never crash, never +//! execute unvalidated input, reject a malformed operand) rather than an +//! incidental output string. +//! +//! Two layers are exercised: +//! +//! * the validators and parsers in `phoebus-core::action` directly (fast and +//! deterministic), and +//! * the `sys` binary itself as a subprocess, isolated with an empty `PATH` and +//! no AI provider so nothing on the host is touched or contacted. +//! +//! When a case fails it reveals a real gap in validation or routing. Fix the +//! underlying code, not the assertion. + +use phoebus_core::action::{ + parse_action, parse_natural, valid_appimage_name, valid_application_name, valid_ebuild_atom, + valid_ebuild_version, valid_flatpak_app_id, valid_http_url, valid_nix_attribute, + valid_package_spec, valid_search_query, valid_sha256, valid_snap_channel, valid_snap_name, +}; +use std::process::{Command, Output}; + +fn sys() -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_sys")); + // Isolate from the host: an empty PATH prevents any real tool from being + // found, and an unconfigured provider prevents any network call. The + // `effective_uid` probe fails closed to a non-root sentinel, so privilege + // gates are exercised deterministically. + cmd.env("PATH", "/nonexistent") + .env("PHOEBUS_AI_PROVIDER", "") + .env("PHOEBUS_AI_API_KEY_FILE", "") + .env("PHOEBUS_AI_BACKEND", "direct"); + cmd +} + +fn action(json: &str) -> Output { + sys() + .args(["--legacy", "--action", json]) + .output() + .expect("run sys") +} + +fn run_legacy(args: &[&str]) -> Output { + let root = tempfile::tempdir().expect("temp root"); + sys() + .arg("--root") + .arg(root.path()) + .args(["--legacy"]) + .args(args) + .output() + .expect("run sys") +} + +/// On Unix a signal death (segfault, abort, stack overflow) leaves `code()` +/// unset. A panic in `sys` must never happen on any input. +fn assert_no_crash(out: &Output, context: &str) { + if out.status.code().is_none() { + panic!( + "sys CRASHED (signal death) on: {context}\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + } +} + +/// The input must be refused: no crash, non-zero exit. +fn assert_rejected(out: &Output, context: &str) { + assert_no_crash(out, context); + assert!( + !out.status.success(), + "sys accepted a hostile input that must be refused: {context}\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); +} + +fn accepted(json: &str) -> bool { + parse_action(json).is_ok() +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 1 — shell injection through every field type +// ═══════════════════════════════════════════════════════════════════════════ + +/// Payloads that must never survive into any command. Appended to a benign +/// operand so a version-operator prefix cannot accidentally make it valid. +const INJECTIONS: &[&str] = &[ + ";id", "&&id", "||id", "|id", "$(id)", "`id`", "\nid", ">out", " = (0..40).map(|i| format!("\"pkg{i}\"")).collect(); + let json = format!( + r#"{{"action":"nix_prepare","packages":[{}]}}"#, + packages.join(",") + ); + assert!( + !accepted(&json), + "more than 32 Nix packages must be refused" + ); +} + +#[test] +fn extremely_long_natural_phrase_does_not_crash() { + let phrase = format!("install {}", "a".repeat(10_000)); + let out = run_legacy(&[&phrase]); + assert_no_crash(&out, "10K natural phrase"); +} + +#[test] +fn many_positional_arguments_do_not_crash() { + let words: Vec = (0..1_000).map(|_| "word".to_string()).collect(); + let refs: Vec<&str> = words.iter().map(String::as_str).collect(); + let out = run_legacy(&refs); + assert_no_crash(&out, "1000 positional arguments"); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 4 — Unicode, homoglyphs and invisible characters +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn unicode_package_atoms_are_refused() { + for atom in [ + "app-misc/héllo", + "app-misc/hello™", + "app-misc/hello🔥", + "категория/пакет", + "app-misc/hello\u{200B}evil", // zero-width space + "app-misc/hello\u{FEFF}evil", // BOM + "app-misc/hello\u{202E}evil", // RTL override + "app-misc/hello\u{0301}", // combining accent + ] { + assert!(!valid_package_spec(atom), "atom must be refused: {atom:?}"); + } +} + +#[test] +fn homoglyph_package_atom_is_refused() { + // Cyrillic 'а' (U+0430) is visually identical to Latin 'a'. + assert!(!valid_package_spec("\u{0430}pp-misc/hello")); +} + +#[test] +fn unicode_natural_language_does_not_crash() { + for phrase in [ + "install 🔥🔥🔥", + "search категория", + "who owns /tmp/héllo", + "enable sshd™", + "install app-misc/héllo", + ] { + let out = run_legacy(&[phrase]); + assert_no_crash(&out, &format!("unicode natural phrase: {phrase:?}")); + } +} + +#[test] +fn unicode_in_each_typed_operand_is_refused() { + let cases = [ + r#"{"action":"search_packages","query":"fïrefox"}"#, + r#"{"action":"flatpak_install","app_id":"org.mözilla.Firefox"}"#, + r#"{"action":"snap_install","name":"hellö"}"#, + r#"{"action":"enable_service","name":"sshð"}"#, + r#"{"action":"nix_prepare","packages":["héllo"]}"#, + ]; + for json in cases { + assert!(!accepted(json), "unicode operand must be refused: {json}"); + } +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 5 — path traversal +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn path_traversal_package_atoms_are_refused() { + for atom in [ + "../etc/passwd", + "../../root/.ssh/id_rsa", + "app-misc/../../../etc/shadow", + "./relative/path", + "cat/pkg/../../../etc/shadow", + "cat/pkg/..", + "cat/../pkg", + ] { + assert!(!valid_package_spec(atom), "atom must be refused: {atom:?}"); + } + assert!(valid_package_spec("app-editors/vim")); +} + +#[test] +fn path_traversal_in_ebuild_atoms_is_refused() { + for atom in ["../../etc/passwd", "a/b/c", "/bin/sh", "a//b", "../pkg"] { + assert!( + !valid_ebuild_atom(atom), + "ebuild atom must be refused: {atom:?}" + ); + } +} + +#[test] +fn path_traversal_in_application_names_is_refused() { + // An application name is not a path: `..` components and a leading slash + // could otherwise escape a managed directory when a record is resolved. + for name in [ + "../../etc/passwd", + "/etc/passwd", + "a/../../etc", + "foo/..", + "foo/./bar", + "a//b", + ] { + assert!( + !valid_application_name(name), + "application name must be refused: {name:?}" + ); + } + assert!(valid_application_name("firefox")); + assert!(valid_application_name("org.mozilla.firefox")); + assert!(valid_application_name("app-editors/vim")); +} + +#[test] +fn path_traversal_in_file_paths_is_refused() { + for path in ["/etc/../../../root/.ssh/id_rsa", "/tmp/../../etc/shadow"] { + let json = format!(r#"{{"action":"package_owners","path":"{path}"}}"#); + assert!(!accepted(&json), "traversal path must be refused: {path:?}"); + } +} + +#[test] +fn path_traversal_in_appimage_names_is_refused() { + for name in ["../evil", "../../root", ".hidden", "a/../../etc", ".."] { + assert!( + !valid_appimage_name(name), + "AppImage name must be refused: {name:?}" + ); + } +} + +#[test] +fn path_traversal_in_custom_ebuild_json_is_refused() { + let json = r#"{"action":"custom_ebuild_prepare","atom":"../../etc/passwd","version":"1","rationale":"test","ebuild":"EAPI=8"}"#; + assert!(!accepted(json), "traversal ebuild atom must be refused"); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 6 — option / flag injection +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn leading_dash_operands_are_refused() { + let cases = [ + (r#"{"action":"install_package","atom":"-C"}"#, "atom"), + ( + r#"{"action":"install_package","atom":"--config"}"#, + "atom-long", + ), + (r#"{"action":"remove_package","atom":"-rf"}"#, "remove"), + (r#"{"action":"flatpak_install","app_id":"-y"}"#, "flatpak"), + (r#"{"action":"nix_prepare","packages":["--impure"]}"#, "nix"), + (r#"{"action":"snap_install","name":"--dangerous"}"#, "snap"), + (r#"{"action":"enable_service","name":"--user"}"#, "service"), + (r#"{"action":"search_packages","query":"--help"}"#, "search"), + (r#"{"action":"package_info","package":"--exec"}"#, "info"), + ( + r#"{"action":"package_dependencies","package":"-R"}"#, + "deps", + ), + (r#"{"action":"appimage_info","name":"-x"}"#, "appimage"), + ]; + for (json, ctx) in cases { + assert!( + !accepted(json), + "option injection ({ctx}) must be refused: {json}" + ); + } +} + +#[test] +fn search_query_allows_only_safe_punctuation() { + for query in [ + "firefox", + "google-chrome", + "visual studio code", + "org.mozilla.firefox", + "python@3.11", + "app-arch/p7zip", + ] { + assert!(valid_search_query(query), "safe query rejected: {query:?}"); + } +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 7 — malformed JSON actions +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn malformed_json_is_refused_without_crashing() { + let cases = [ + "", + "not json at all", + "{", + "{}", + "[]", + "null", + "42", + "true", + r#"{"action":null}"#, + r#"{"action":42}"#, + r#"{"action":""}"#, + r#"{"action":"install_package"}"#, + r#"{"action":"install_package","atom":42}"#, + r#"{"action":"install_package","atom":"vim","extra":"field"}"#, + r#"{"action":"history","x":1}"#, + r#"{"action":"run_shell","command":"rm -rf /"}"#, + ]; + for json in cases { + assert!( + !accepted(json), + "malformed action must be refused: {json:?}" + ); + assert_rejected( + &action(json), + &format!("malformed JSON via binary: {json:?}"), + ); + } +} + +#[test] +fn deeply_nested_json_does_not_crash() { + let mut json = String::from(r#"{"action":"install_package","atom":"#); + for _ in 0..400 { + json.push_str(r#"{"n":"#); + } + json.push_str(r#""leaf""#); + for _ in 0..400 { + json.push('}'); + } + json.push('}'); + assert!(!accepted(&json), "deeply nested JSON must be refused"); + assert_no_crash(&action(&json), "deeply nested JSON"); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 8 — CLI flag combinations and routing +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn conflicting_backend_flags_are_refused() { + let flags = [ + "--portage", + "--flatpak", + "--nix", + "--snap", + "--appimage", + "--ebuild", + ]; + for (i, a) in flags.iter().enumerate() { + for b in &flags[i + 1..] { + let out = sys() + .args(["install", "firefox", a, b]) + .output() + .expect("run sys"); + assert_rejected(&out, &format!("conflicting backends {a} {b}")); + } + } +} + +#[test] +fn all_backend_flags_at_once_are_refused() { + let out = sys() + .args([ + "install", + "firefox", + "--portage", + "--flatpak", + "--nix", + "--snap", + "--appimage", + "--ebuild", + ]) + .output() + .expect("run sys"); + assert_rejected(&out, "all backends at once"); +} + +#[test] +fn backend_flag_without_a_verb_is_refused() { + for flag in [ + "--portage", + "--flatpak", + "--nix", + "--snap", + "--appimage", + "--ebuild", + ] { + let out = run_legacy(&["history", flag]); + assert_rejected(&out, &format!("backend flag without a verb: {flag}")); + } +} + +#[test] +fn typed_action_requires_legacy_or_broker() { + let out = sys() + .args(["--action", r#"{"action":"history"}"#]) + .output() + .expect("run sys"); + assert_rejected(&out, "--action without --legacy/--broker"); +} + +#[test] +fn repeated_legacy_flag_does_not_crash() { + let out = run_legacy(&["--legacy", "history"]); + // `--legacy` is forwarded here as a second occurrence via args; clap may + // accept or refuse it, but it must not crash either way. + assert_no_crash(&out, "double --legacy"); +} + +#[test] +fn version_with_extra_arguments_does_not_crash() { + let out = sys() + .args(["--version", "extra", "args"]) + .output() + .expect("run sys"); + assert_no_crash(&out, "--version with extra args"); +} + +#[test] +fn execute_plan_without_broker_is_refused() { + let out = sys() + .args(["--execute-plan", "plan-inst-deadbeef"]) + .output() + .expect("run sys"); + assert_rejected(&out, "--execute-plan without --broker"); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 9 — natural-language edge cases +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn natural_language_variants_do_not_crash() { + let phrases = [ + "INSTALL FIREFOX", + "Install Firefox", + "iNsTaLl FiReFoX", + "HISTORY", + " install firefox ", + "install\tfirefox", + "search \t firefox", + " history ", + "who owns /usr/bin/bash", + "please install firefox", + "Please please install firefox", + "can you install firefox", + "I want to install firefox", + "could you please install firefox for me", + ]; + for phrase in phrases { + let out = run_legacy(&[phrase]); + assert_no_crash(&out, &format!("natural phrase: {phrase:?}")); + } +} + +#[test] +fn ambiguous_verbs_do_not_crash_and_do_not_invent_actions() { + for phrase in [ + "install", "remove", "search", "enable", "who owns", "info", "undo", + ] { + let out = run_legacy(&[phrase]); + assert_no_crash(&out, &format!("ambiguous verb: {phrase:?}")); + } +} + +#[test] +fn typo_phrases_do_not_crash() { + for phrase in [ + "instal firefox", + "instll firefox", + "remov firefox", + "serach firefox", + "histroy", + "updte", + "enble sshd", + ] { + let out = run_legacy(&[phrase]); + assert_no_crash(&out, &format!("typo phrase: {phrase:?}")); + } +} + +#[test] +fn natural_parser_is_case_insensitive_and_trims() { + use phoebus_core::action::SystemAction; + assert_eq!( + parse_natural("HISTORY"), + Some(SystemAction::History), + "case must be folded" + ); + assert_eq!( + parse_natural(" install vim "), + Some(SystemAction::InstallPackage { + atom: "vim".into(), + binary: None, + }) + ); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 10 — boundary values +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn snap_name_boundaries() { + assert!(valid_snap_name("a")); + assert!(valid_snap_name(&"a".repeat(40))); + assert!(!valid_snap_name(&"a".repeat(41))); + assert!(valid_snap_name("a-b")); + assert!(!valid_snap_name("a--b")); + assert!(!valid_snap_name("-leading")); + assert!(!valid_snap_name("trailing-")); + assert!(!valid_snap_name("Uppercase")); + assert!(!valid_snap_name("")); +} + +#[test] +fn sha256_boundaries() { + assert!(valid_sha256(&"a".repeat(64))); + assert!(!valid_sha256(&"a".repeat(63))); + assert!(!valid_sha256(&"a".repeat(65))); + assert!(!valid_sha256(&"0".repeat(64))); + // Uppercase hex is still valid hex; the digest is compared as given. + assert!(valid_sha256(&"A".repeat(64))); + assert!(!valid_sha256(&"g".repeat(64))); + assert!(!valid_sha256("")); +} + +#[test] +fn service_name_boundaries() { + let cases = [ + "sshd", + "sshd.service", + "user@1000.service", + "dbus-org.freedesktop.NetworkManager.service", + "a", + ]; + for unit in cases { + assert!( + accepted(&format!( + r#"{{"action":"inspect_service","name":"{unit}"}}"# + )), + "valid service name rejected: {unit:?}" + ); + } + // The shared token validator caps a service name at 128 characters. + assert!( + !accepted(&format!( + r#"{{"action":"inspect_service","name":"{}"}}"#, + "a".repeat(257) + )), + "over-long service name must be refused" + ); + // A path-like unit is refused. + assert!(!accepted( + r#"{"action":"enable_service","name":"../etc/shadow"}"# + )); +} + +#[test] +fn flatpak_id_boundaries() { + assert!(valid_flatpak_app_id("org.mozilla.Firefox")); + assert!(valid_flatpak_app_id("com.google.Chrome")); + assert!(!valid_flatpak_app_id("nodots")); + assert!(!valid_flatpak_app_id("org.")); + assert!(!valid_flatpak_app_id(".org.test")); + assert!(!valid_flatpak_app_id("org..test")); + assert!(!valid_flatpak_app_id(&format!("org.{}", "a".repeat(260)))); + assert!(!valid_flatpak_app_id("")); +} + +#[test] +fn nix_attribute_boundaries() { + assert!(valid_nix_attribute("nixpkgs.hello")); + assert!(valid_nix_attribute("python311")); + assert!(valid_nix_attribute("hello")); + assert!(valid_nix_attribute("python311Packages.requests")); + assert!(!valid_nix_attribute("")); + assert!(!valid_nix_attribute("github:owner/repo")); + assert!(!valid_nix_attribute("nixpkgs#x/y")); + assert!(!valid_nix_attribute(&"a".repeat(129))); + assert!(!valid_nix_attribute("--impure")); +} + +#[test] +fn snap_channel_boundaries() { + assert!(valid_snap_channel("stable")); + assert!(valid_snap_channel("latest/stable")); + assert!(valid_snap_channel("latest/stable/hotfix-1")); + assert!(!valid_snap_channel("latest/stable/edge/extra")); + assert!(!valid_snap_channel("-edge")); + assert!(!valid_snap_channel("Stable")); + assert!(!valid_snap_channel("")); +} + +#[test] +fn ebuild_atom_and_version_boundaries() { + assert!(valid_ebuild_atom("app-misc/hello")); + assert!(!valid_ebuild_atom("hello")); + assert!(!valid_ebuild_atom("a/b/c")); + assert!(!valid_ebuild_atom("-bad/pkg")); + assert!(!valid_ebuild_atom("app-misc/")); + assert!(valid_ebuild_version("1.2.3")); + assert!(valid_ebuild_version("1.2.3-r1")); + assert!(!valid_ebuild_version("")); + assert!(!valid_ebuild_version("1/2")); + assert!(!valid_ebuild_version("-1")); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Category 11 — privilege and state edge cases +// ═══════════════════════════════════════════════════════════════════════════ + +/// The isolated `sys` always sees a non-root effective uid, so every mutating +/// action must be refused before any effect is resolved. +#[test] +fn mutating_actions_require_root() { + let actions = [ + r#"{"action":"install_package","atom":"app-misc/hello"}"#, + r#"{"action":"remove_package","atom":"app-misc/hello"}"#, + r#"{"action":"flatpak_install","app_id":"org.test.Test"}"#, + r#"{"action":"flatpak_remove","app_id":"org.test.Test"}"#, + r#"{"action":"nix_prepare","packages":["hello"]}"#, + r#"{"action":"snap_install","name":"hello"}"#, + r#"{"action":"snap_remove","name":"hello"}"#, + r#"{"action":"enable_service","name":"sshd"}"#, + r#"{"action":"disable_service","name":"sshd"}"#, + r#"{"action":"start_service","name":"sshd"}"#, + r#"{"action":"stop_service","name":"sshd"}"#, + r#"{"action":"restart_service","name":"sshd"}"#, + r#"{"action":"apply_updates"}"#, + r#"{"action":"depclean"}"#, + r#"{"action":"clean_cache"}"#, + r#"{"action":"undo"}"#, + r#"{"action":"convert_to_source","app":"firefox"}"#, + r#"{"action":"build_tuned_kernel","make_default":false}"#, + ]; + for json in actions { + let out = action(json); + assert_rejected(&out, &format!("non-root mutation must be refused: {json}")); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("require root"), + "refusal must name root for {json}: {stderr}" + ); + } +} + +#[test] +fn read_only_actions_are_not_refused_as_mutations() { + let actions = [ + r#"{"action":"history"}"#, + r#"{"action":"rollback_status"}"#, + r#"{"action":"appimage_list"}"#, + r#"{"action":"custom_ebuild_list"}"#, + r#"{"action":"flatpak_list"}"#, + r#"{"action":"snap_list"}"#, + r#"{"action":"list_packages"}"#, + r#"{"action":"check_updates"}"#, + ]; + for json in actions { + let out = action(json); + assert_no_crash(&out, &format!("read-only action: {json}")); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + !stderr.contains("mutating actions require root"), + "read-only action wrongly gated as a mutation: {json}: {stderr}" + ); + } +} + +#[test] +fn unusual_root_paths_do_not_crash() { + // A non-existent root. + let out = sys() + .args([ + "--root", + "/nonexistent/path/that/does/not/exist", + "--legacy", + "history", + ]) + .output() + .expect("run sys"); + assert_no_crash(&out, "non-existent root"); + + // A file used as a root. + let out = sys() + .args(["--root", "/etc/passwd", "--legacy", "history"]) + .output() + .expect("run sys"); + assert_no_crash(&out, "file as root"); + + // A symlink used as a root. + let dir = tempfile::tempdir().expect("temp dir"); + let link = dir.path().join("link"); + std::os::unix::fs::symlink("/tmp", &link).expect("symlink"); + let out = sys() + .arg("--root") + .arg(link.to_str().expect("utf-8 path")) + .args(["--legacy", "list"]) + .output() + .expect("run sys"); + assert_no_crash(&out, "symlink as root"); +} + +#[test] +fn adding_root_to_a_mutating_action_does_not_weaken_the_gate() { + // Even with an explicit `--root`, the privileged gate is tied to the + // effective uid, not to a caller-supplied path. + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .arg("--root") + .arg(root.path()) + .args([ + "--legacy", + "--action", + r#"{"action":"install_package","atom":"app-misc/hello"}"#, + ]) + .output() + .expect("run sys"); + assert_rejected(&out, "mutating action with a caller root"); + assert!( + String::from_utf8_lossy(&out.stderr).contains("require root"), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); +} diff --git a/installer-rs/crates/phoebus-installer/tests/sys_flaws.rs b/installer-rs/crates/phoebus-installer/tests/sys_flaws.rs new file mode 100644 index 0000000..091cf6c --- /dev/null +++ b/installer-rs/crates/phoebus-installer/tests/sys_flaws.rs @@ -0,0 +1,197 @@ +//! Regression battery for the six `sys` flaws found during the audit. +//! +//! Validation-level cases call `phoebus-core` directly (fast, deterministic); +//! the binary-private phrase parsers and privilege gates run the `sys` binary. + +use phoebus_core::action::{parse_action, parse_natural, valid_package_spec, SystemAction}; +use std::process::Command; + +fn sys() -> Command { + Command::new(env!("CARGO_BIN_EXE_sys")) +} + +fn effective_uid_is_root() -> bool { + Command::new("id") + .arg("-u") + .output() + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0") + .unwrap_or(false) +} + +// ── Flaw 1: versioned atoms, slots, wildcards, repositories ──────────────── + +#[test] +fn versioned_slotted_and_repo_atoms_validate() { + for atom in [ + "vim", + "app-editors/vim", + "=app-editors/vim-9.0.2167", + "~net-misc/curl-8.5.0", + ">=dev-lang/rust-1.75.0", + "dev-lang/python:3.11", + "dev-libs/openssl:0/1.1", + "sys-devel/llvm:17", + "=app-editors/vim-9.0*", + "sys-apps/portage::gentoo", + "app-editors/vim[python]", + "dev-libs/openssl:0[ssl]", + ] { + assert!(valid_package_spec(atom), "atom {atom:?} should be valid"); + } +} + +#[test] +fn dangerous_specs_are_still_rejected() { + for spec in [ + "-C", + "--color=n", + "cat/pkg;rm -rf /", + "cat/pkg&echo pwned", + "cat/pkg|cat /etc/shadow", + "cat/pkg$(id)", + "cat/pkg`id`", + "../etc/passwd", + "a/b/c", + "app/--evil", + "cat/pkg::", + "cat/pkg:", + "cat/pkg[flag", + "", + " ", + " vim", + "vim ", + "app-editors/vim ", + ] { + assert!(!valid_package_spec(spec), "spec {spec:?} must be rejected"); + } +} + +#[test] +fn versioned_atoms_pass_the_json_action_validation_gate() { + for atom in [ + "=app-editors/vim-9.0.2167", + "dev-lang/python:3.11", + "sys-apps/portage::gentoo", + "=app-editors/vim-9.0*", + ] { + let json = format!(r#"{{"action":"inspect_package","atom":"{atom}"}}"#); + assert!( + parse_action(&json).is_ok(), + "JSON validation wrongly rejected {atom:?}" + ); + } +} + +// ── Flaw 2: quoted multi-word application names ───────────────────────────── + +#[test] +fn quoted_multi_word_install_parses_in_legacy_mode() { + let root = tempfile::tempdir().expect("temp root"); + let empty = tempfile::tempdir().expect("empty PATH"); + let out = sys() + .env("PATH", empty.path()) + .arg("--root") + .arg(root.path()) + .args(["install", "\"visual studio code\"", "--legacy", "--flatpak"]) + .output() + .expect("run sys"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + !stderr.contains("could not parse"), + "quoted multi-word install was not parsed: {stderr}" + ); +} + +#[test] +fn quoted_multi_word_remove_parses_in_legacy_mode() { + let root = tempfile::tempdir().expect("temp root"); + let empty = tempfile::tempdir().expect("empty PATH"); + let out = sys() + .env("PATH", empty.path()) + .arg("--root") + .arg(root.path()) + .args(["remove", "\"Google Chrome\"", "--legacy"]) + .output() + .expect("run sys"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + !stderr.contains("could not parse"), + "quoted multi-word remove was not parsed: {stderr}" + ); +} + +// ── Flaw 5: path normalization in `who owns` ──────────────────────────────── + +#[test] +fn who_owns_normalizes_a_missing_leading_slash() { + match parse_natural("who owns usr/bin/vim") { + Some(SystemAction::PackageOwners { path }) => assert_eq!(path, "/usr/bin/vim"), + other => panic!("expected a normalized PackageOwners, got {other:?}"), + } + match parse_natural("who owns /usr/bin/vim") { + Some(SystemAction::PackageOwners { path }) => assert_eq!(path, "/usr/bin/vim"), + other => panic!("expected PackageOwners, got {other:?}"), + } + // A relative path is still refused by the JSON contract: normalization is a + // natural-language convenience, not a weaker validation rule. + assert!(parse_action(r#"{"action":"package_owners","path":"relative"}"#).is_err()); +} + +#[test] +fn who_owns_relative_path_runs_without_a_parse_failure() { + let empty = tempfile::tempdir().expect("empty PATH"); + let out = sys() + .env("PATH", empty.path()) + .args(["who", "owns", "usr/bin/bash", "--legacy"]) + .output() + .expect("run sys"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + !stderr.contains("invalid file path"), + "relative path was not normalized: {stderr}" + ); +} + +// ── Flaw 6: service lifecycle privilege gates ────────────────────────────── + +#[test] +fn service_mutations_require_root() { + if effective_uid_is_root() { + return; + } + for verb in ["enable", "disable", "start", "stop", "restart"] { + let out = sys() + .args([verb, "sshd", "--legacy"]) + .output() + .expect("run sys"); + assert!(!out.status.success(), "{verb} should require root"); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + combined.contains("root"), + "{verb} refusal must mention root: {combined}" + ); + } +} + +#[test] +fn service_inspect_is_not_a_privileged_mutation() { + // `inspect` must parse and must not be refused as a mutating action. With an + // empty PATH the read-only probe cannot run, but the refusal (if any) is + // never the root gate and never a parse failure. + let empty = tempfile::tempdir().expect("empty PATH"); + let out = sys() + .env("PATH", empty.path()) + .args(["inspect", "sshd", "--legacy"]) + .output() + .expect("run sys"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + !stderr.contains("mutating actions require root") && !stderr.contains("could not parse"), + "inspect was wrongly refused: {stderr}" + ); +} diff --git a/installer/tests/vm/sys-acceptance.sh b/installer/tests/vm/sys-acceptance.sh index ce0dcf2..a3f6652 100755 --- a/installer/tests/vm/sys-acceptance.sh +++ b/installer/tests/vm/sys-acceptance.sh @@ -234,6 +234,33 @@ if [[ "$(id -u)" -eq 0 ]]; then json_nonzero source-unknown "no supported source build" '{"action":"convert_to_source","app":"definitely-not-an-app-xyz"}' fi +# --- Service lifecycle (read-only + non-root gates) ----------------------- +run_expect_zero inspect-service-legacy --legacy inspect sshd +if [[ "$(id -u)" -ne 0 ]]; then + run_expect_nonzero nonroot-enable "root" --legacy enable sshd + run_expect_nonzero nonroot-disable "root" --legacy disable sshd + run_expect_nonzero nonroot-start "root" --legacy start sshd + run_expect_nonzero nonroot-stop "root" --legacy stop sshd + run_expect_nonzero nonroot-restart "root" --legacy restart sshd +fi + +# --- Versioned atom validation (Flaw 1 regression) ------------------------ +# Versioned/slotted atoms must pass the validator and reach the tool. +run_expect_zero versioned-atom-inspect --legacy --action \ + '{"action":"inspect_package","atom":"=app-misc/hello-2.10"}' +run_expect_zero slot-atom-inspect --legacy --action \ + '{"action":"inspect_package","atom":"dev-lang/python:3.12"}' + +# --- Path normalization (Flaw 5 regression) ------------------------------- +# A relative path in "who owns" must be normalized, never rejected as an +# invalid file path. (The ownership tool itself may be absent.) +"$SYS" who owns usr/bin/bash --legacy >"$WORK/who.out" 2>"$WORK/who.err" +if ! grep -qi "invalid file path\|could not parse" "$WORK/who.err" "$WORK/who.out"; then + report who-owns-relative PASS "$(head -c 140 "$WORK/who.out" | tr '\n' ' ')" +else + report who-owns-relative FAIL "$(head -c 200 "$WORK/who.err" | tr '\n' ' ')" +fi + # --- Optional mutating group (disposable VM only) ------------------------- if [[ "$MUTATE" == "1" ]]; then PKG="${SYS_ACCEPTANCE_PACKAGE:-app-misc/hello}"