Some checks are pending
ci / test (push) Waiting to run
- Mango + DankMaterialShell desktop option (desktop.profile = "mango") through the GURU overlay with scoped ~amd64 keywords, a sealed session entry point and a dwl fallback session (ADR 0009). - Coherent rollback/recovery: coordinated @ + @var snapshots, fstab and BLS root-subvolume rewriting, matching-kernel selection, snapshot recovery entry, retention/space gates and sys undo (ADR 0007). - Installed assistant (sys ask) with an OS-level systemd sandbox boundary and fail-closed typed plans; resolved package effects bound to approval. - Nix build isolation enforced (sandbox, no fallback) plus lifecycle/cleanup. - Desktop helpers (menu/lock/idle), transaction log, release gates with atomic publish and signing helpers, and a Debian-Live appliance VM harness.
555 lines
20 KiB
Rust
555 lines
20 KiB
Rust
//! Typed system actions.
|
|
//!
|
|
//! This is the schema the AI (or a deterministic front-end) may emit. There is
|
|
//! deliberately no `run_shell`/`run_command` action: privileged work is
|
|
//! expressed as closed, validated verbs that a policy engine can classify,
|
|
//! preview and (after approval) execute. Unknown actions fail closed.
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum ActionError {
|
|
#[error("invalid action JSON: {0}")]
|
|
Json(#[from] serde_json::Error),
|
|
#[error("invalid action: {0}")]
|
|
Invalid(String),
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Risk {
|
|
Low,
|
|
Medium,
|
|
High,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
|
|
pub enum SystemAction {
|
|
InspectService {
|
|
name: String,
|
|
},
|
|
EnableService {
|
|
name: String,
|
|
},
|
|
DisableService {
|
|
name: String,
|
|
},
|
|
InspectPackage {
|
|
atom: String,
|
|
},
|
|
InstallPackage {
|
|
atom: String,
|
|
},
|
|
RemovePackage {
|
|
atom: String,
|
|
},
|
|
SearchPackages {
|
|
query: String,
|
|
},
|
|
/// Install a sandboxed Flatpak application from flathub.
|
|
FlatpakInstall {
|
|
app_id: String,
|
|
},
|
|
FlatpakRemove {
|
|
app_id: String,
|
|
},
|
|
FlatpakList,
|
|
/// Realise bounded nixpkgs development packages into the Nix store.
|
|
NixPrepare {
|
|
packages: Vec<String>,
|
|
},
|
|
CreateSnapshot {
|
|
operation: String,
|
|
},
|
|
/// Restore a committed snapshot as the next boot root. `snapshot` selects a
|
|
/// specific id; unset means the newest committed snapshot.
|
|
Undo {
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
snapshot: Option<String>,
|
|
},
|
|
/// Report the rollback state (no mutation).
|
|
RollbackStatus,
|
|
History,
|
|
UpdateSystem,
|
|
PrepareUpdates,
|
|
InspectUpdates,
|
|
}
|
|
|
|
impl SystemAction {
|
|
pub fn describe(&self) -> String {
|
|
match self {
|
|
SystemAction::InspectService { name } => format!("inspect service {name}"),
|
|
SystemAction::EnableService { name } => format!("enable service {name} at boot"),
|
|
SystemAction::DisableService { name } => {
|
|
format!("disable service {name} at boot")
|
|
}
|
|
SystemAction::InspectPackage { atom } => format!("inspect package {atom}"),
|
|
SystemAction::InstallPackage { atom } => format!("install package {atom}"),
|
|
SystemAction::RemovePackage { atom } => format!("remove package {atom}"),
|
|
SystemAction::SearchPackages { query } => {
|
|
format!("search packages for `{query}`")
|
|
}
|
|
SystemAction::FlatpakInstall { app_id } => {
|
|
format!("install Flatpak app {app_id} from flathub")
|
|
}
|
|
SystemAction::FlatpakRemove { app_id } => format!("remove Flatpak app {app_id}"),
|
|
SystemAction::FlatpakList => "list installed Flatpak apps".to_string(),
|
|
SystemAction::NixPrepare { packages } => {
|
|
format!("realise Nix development packages: {}", packages.join(", "))
|
|
}
|
|
SystemAction::CreateSnapshot { operation } => {
|
|
format!("create a Btrfs snapshot before: {operation}")
|
|
}
|
|
SystemAction::Undo { snapshot } => match snapshot {
|
|
Some(id) => format!("roll back to snapshot {id} (restore as next boot root)"),
|
|
None => "roll back to the newest committed snapshot".to_string(),
|
|
},
|
|
SystemAction::RollbackStatus => "show the rollback state".to_string(),
|
|
SystemAction::History => "show system transaction history".to_string(),
|
|
SystemAction::PrepareUpdates => {
|
|
"prepare background updates (fetch + build binary packages, do not activate)"
|
|
.to_string()
|
|
}
|
|
SystemAction::InspectUpdates => "show background update preparation status".to_string(),
|
|
SystemAction::UpdateSystem => "update the system".to_string(),
|
|
}
|
|
}
|
|
|
|
/// Risk classification used by the policy engine to decide whether a
|
|
/// snapshot and/or stronger confirmation is required.
|
|
pub fn risk(&self) -> Risk {
|
|
match self {
|
|
SystemAction::InspectService { .. }
|
|
| SystemAction::InspectPackage { .. }
|
|
| SystemAction::SearchPackages { .. } => Risk::Low,
|
|
SystemAction::History => Risk::Low,
|
|
SystemAction::InspectUpdates => Risk::Low,
|
|
SystemAction::RollbackStatus => Risk::Low,
|
|
SystemAction::FlatpakList => Risk::Low,
|
|
SystemAction::PrepareUpdates => Risk::Medium,
|
|
SystemAction::EnableService { .. }
|
|
| SystemAction::DisableService { .. }
|
|
| SystemAction::CreateSnapshot { .. }
|
|
| SystemAction::FlatpakInstall { .. }
|
|
| SystemAction::FlatpakRemove { .. }
|
|
| SystemAction::NixPrepare { .. } => Risk::Medium,
|
|
SystemAction::InstallPackage { .. }
|
|
| SystemAction::RemovePackage { .. }
|
|
| SystemAction::UpdateSystem
|
|
| SystemAction::Undo { .. } => Risk::High,
|
|
}
|
|
}
|
|
|
|
/// Whether this action modifies the system (and therefore needs
|
|
/// authorization and, for High risk, a snapshot).
|
|
pub fn is_mutating(&self) -> bool {
|
|
!matches!(
|
|
self,
|
|
SystemAction::InspectService { .. }
|
|
| SystemAction::InspectPackage { .. }
|
|
| SystemAction::SearchPackages { .. }
|
|
| SystemAction::History
|
|
| SystemAction::InspectUpdates
|
|
| SystemAction::RollbackStatus
|
|
| SystemAction::FlatpakList
|
|
)
|
|
}
|
|
|
|
pub fn validate(&self) -> Result<(), String> {
|
|
let valid_token = |s: &str| {
|
|
!s.is_empty()
|
|
&& s.len() <= 128
|
|
&& s.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c))
|
|
};
|
|
match self {
|
|
SystemAction::InspectService { name }
|
|
| SystemAction::EnableService { name }
|
|
| SystemAction::DisableService { name } => {
|
|
if valid_token(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid service name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::InspectPackage { atom }
|
|
| SystemAction::InstallPackage { atom }
|
|
| SystemAction::RemovePackage { atom } => {
|
|
if valid_package_spec(atom) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid package name: {atom}"))
|
|
}
|
|
}
|
|
SystemAction::SearchPackages { query } => {
|
|
if valid_search_query(query) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid search query: {query}"))
|
|
}
|
|
}
|
|
SystemAction::FlatpakInstall { app_id } | SystemAction::FlatpakRemove { app_id } => {
|
|
if valid_flatpak_app_id(app_id) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid Flatpak application id: {app_id}"))
|
|
}
|
|
}
|
|
SystemAction::FlatpakList => Ok(()),
|
|
SystemAction::NixPrepare { packages } => {
|
|
if packages.is_empty() {
|
|
return Err("nix prepare requires at least one package".into());
|
|
}
|
|
if packages.len() > 32 {
|
|
return Err("too many Nix packages (max 32)".into());
|
|
}
|
|
for package in packages {
|
|
if !valid_nix_attribute(package) {
|
|
return Err(format!("invalid nixpkgs attribute: {package}"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::CreateSnapshot { operation } => {
|
|
if operation.is_empty() {
|
|
Err("snapshot operation must not be empty".into())
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
SystemAction::Undo { snapshot } => match snapshot {
|
|
Some(id) if !valid_token(id) => Err(format!("invalid snapshot id: {id}")),
|
|
_ => Ok(()),
|
|
},
|
|
SystemAction::History
|
|
| SystemAction::UpdateSystem
|
|
| SystemAction::PrepareUpdates
|
|
| SystemAction::InspectUpdates
|
|
| SystemAction::RollbackStatus => Ok(()),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn is_atom_char(c: char) -> bool {
|
|
c.is_ascii_alphanumeric() || "+._@-".contains(c)
|
|
}
|
|
|
|
/// 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.
|
|
pub fn valid_package_spec(spec: &str) -> bool {
|
|
if spec.is_empty() || spec.len() > 128 {
|
|
return false;
|
|
}
|
|
let mut parts = spec.split('/');
|
|
let Some(first) = parts.next() else {
|
|
return false;
|
|
};
|
|
if first.is_empty() || !first.chars().all(is_atom_char) {
|
|
return false;
|
|
}
|
|
match parts.next() {
|
|
None => true,
|
|
Some(second) => {
|
|
!second.is_empty() && second.chars().all(is_atom_char) && parts.next().is_none()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A bounded search query (letters, digits and a few punctuation characters).
|
|
pub fn valid_search_query(query: &str) -> bool {
|
|
!query.is_empty()
|
|
&& query.len() <= 128
|
|
&& query
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || " ._+@/-".contains(c))
|
|
}
|
|
|
|
/// A Flatpak application id: reverse-DNS, e.g. `org.chromium.Chromium`. No
|
|
/// slashes, spaces, or shell metacharacters.
|
|
pub fn valid_flatpak_app_id(app_id: &str) -> bool {
|
|
!app_id.is_empty()
|
|
&& app_id.len() <= 128
|
|
&& app_id.contains('.')
|
|
&& !app_id.starts_with('.')
|
|
&& !app_id.ends_with('.')
|
|
&& app_id
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c))
|
|
}
|
|
|
|
/// A bounded nixpkgs attribute name (`nodejs`, `python312`). No slashes, URLs,
|
|
/// or flake references, so the assistant cannot make Nix evaluate arbitrary
|
|
/// remote inputs.
|
|
pub fn valid_nix_attribute(value: &str) -> bool {
|
|
!value.is_empty()
|
|
&& value.len() <= 64
|
|
&& value
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "+-._".contains(c))
|
|
&& !value.contains('/')
|
|
&& !value.contains(':')
|
|
}
|
|
|
|
/// A small deterministic parser for common `sys` phrases.
|
|
///
|
|
/// Free-form requests that do not match are left to the AI path
|
|
/// (`--action-file`), which still produces the same typed schema.
|
|
pub fn parse_natural(text: &str) -> Option<SystemAction> {
|
|
// Snapshot ids are case-sensitive (`@-20260101T000000-...`), so parse the
|
|
// undo form from the original text before the general lowercasing.
|
|
let raw = text.trim();
|
|
let raw_lower = raw.to_ascii_lowercase();
|
|
for prefix in ["undo ", "rollback "] {
|
|
if raw_lower.starts_with(prefix) {
|
|
let id = raw[prefix.len()..].trim();
|
|
if id.eq_ignore_ascii_case("status") {
|
|
return Some(SystemAction::RollbackStatus);
|
|
}
|
|
if !id.is_empty() {
|
|
return Some(SystemAction::Undo {
|
|
snapshot: Some(id.to_string()),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
let t = text.trim().to_lowercase();
|
|
let rest = |prefix: &str| t.strip_prefix(prefix).map(|r| r.trim().to_string());
|
|
|
|
// Explicit commands first, so a search/install query cannot be mistaken for
|
|
// one of the heuristic phrases below.
|
|
if let Some(name) = rest("enable ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::EnableService { name });
|
|
}
|
|
}
|
|
if let Some(name) = rest("disable ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::DisableService { name });
|
|
}
|
|
}
|
|
if let Some(atom) = rest("install ").or_else(|| rest("add ")) {
|
|
if !atom.is_empty() {
|
|
return Some(SystemAction::InstallPackage { atom });
|
|
}
|
|
}
|
|
if let Some(atom) = rest("remove ")
|
|
.or_else(|| rest("uninstall "))
|
|
.or_else(|| rest("delete "))
|
|
{
|
|
if !atom.is_empty() {
|
|
return Some(SystemAction::RemovePackage { atom });
|
|
}
|
|
}
|
|
if let Some(query) = rest("search ").or_else(|| rest("find ")) {
|
|
if !query.is_empty() {
|
|
return Some(SystemAction::SearchPackages { query });
|
|
}
|
|
}
|
|
if let Some(name) = rest("inspect ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::InspectService { name });
|
|
}
|
|
}
|
|
if let Some(id) = rest("undo ").or_else(|| rest("rollback ")) {
|
|
if id == "status" {
|
|
return Some(SystemAction::RollbackStatus);
|
|
}
|
|
if !id.is_empty() {
|
|
return Some(SystemAction::Undo { snapshot: Some(id) });
|
|
}
|
|
}
|
|
if t == "undo" || t == "rollback" {
|
|
return Some(SystemAction::Undo { snapshot: None });
|
|
}
|
|
if t.contains("rollback status") || t.contains("undo status") {
|
|
return Some(SystemAction::RollbackStatus);
|
|
}
|
|
|
|
if t == "history" || t.starts_with("history ") {
|
|
return Some(SystemAction::History);
|
|
}
|
|
if t == "update" || t == "update system" || t == "sys update" {
|
|
return Some(SystemAction::UpdateSystem);
|
|
}
|
|
if t.contains("prepare") && t.contains("update") {
|
|
return Some(SystemAction::PrepareUpdates);
|
|
}
|
|
if t.contains("what are you compiling") || t.contains("update status") {
|
|
return Some(SystemAction::InspectUpdates);
|
|
}
|
|
None
|
|
}
|
|
|
|
pub fn parse_action(json: &str) -> Result<SystemAction, ActionError> {
|
|
let action: SystemAction = serde_json::from_str(json)?;
|
|
action.validate().map_err(ActionError::Invalid)?;
|
|
Ok(action)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parses_typed_actions() {
|
|
let a = parse_action(r#"{"action":"enable_service","name":"sshd"}"#).unwrap();
|
|
assert_eq!(
|
|
a,
|
|
SystemAction::EnableService {
|
|
name: "sshd".into()
|
|
}
|
|
);
|
|
assert!(a.is_mutating());
|
|
assert_eq!(a.risk(), Risk::Medium);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_shell_action() {
|
|
let err = parse_action(r#"{"action":"run_shell","command":"rm -rf /"}"#);
|
|
assert!(err.is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_unknown_fields_and_bad_values() {
|
|
assert!(parse_action(r#"{"action":"install_package","atom":"vim","extra":1}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"install_package","atom":"bad atom"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"install_package","atom":"a/b/c"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"enable_service","name":"bad name"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"search_packages","query":""}"#).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_bare_package_names() {
|
|
assert_eq!(
|
|
parse_action(r#"{"action":"install_package","atom":"vim"}"#).unwrap(),
|
|
SystemAction::InstallPackage { atom: "vim".into() }
|
|
);
|
|
let remove =
|
|
parse_action(r#"{"action":"remove_package","atom":"app-editors/vim"}"#).unwrap();
|
|
assert_eq!(remove.risk(), Risk::High);
|
|
assert!(remove.is_mutating());
|
|
let search = parse_action(r#"{"action":"search_packages","query":"firefox"}"#).unwrap();
|
|
assert!(!search.is_mutating());
|
|
assert_eq!(search.risk(), Risk::Low);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_language_maps_to_typed_actions() {
|
|
assert_eq!(
|
|
parse_natural("enable sshd"),
|
|
Some(SystemAction::EnableService {
|
|
name: "sshd".into()
|
|
})
|
|
);
|
|
assert_eq!(parse_natural("history"), Some(SystemAction::History));
|
|
assert_eq!(
|
|
parse_natural("install app-editors/vim"),
|
|
Some(SystemAction::InstallPackage {
|
|
atom: "app-editors/vim".into()
|
|
})
|
|
);
|
|
// The friendly, apt-like forms resolve to Portage operations.
|
|
assert_eq!(
|
|
parse_natural("install vim"),
|
|
Some(SystemAction::InstallPackage { atom: "vim".into() })
|
|
);
|
|
assert_eq!(
|
|
parse_natural("remove vim"),
|
|
Some(SystemAction::RemovePackage { atom: "vim".into() })
|
|
);
|
|
assert_eq!(
|
|
parse_natural("uninstall vim"),
|
|
Some(SystemAction::RemovePackage { atom: "vim".into() })
|
|
);
|
|
assert_eq!(
|
|
parse_natural("search firefox"),
|
|
Some(SystemAction::SearchPackages {
|
|
query: "firefox".into()
|
|
})
|
|
);
|
|
assert_eq!(parse_natural("why is my audio broken"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn risk_levels() {
|
|
assert_eq!(
|
|
parse_action(r#"{"action":"history"}"#).unwrap().risk(),
|
|
Risk::Low
|
|
);
|
|
assert_eq!(
|
|
parse_action(r#"{"action":"update_system"}"#)
|
|
.unwrap()
|
|
.risk(),
|
|
Risk::High
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn undo_is_high_risk_and_mutating() {
|
|
let undo = parse_action(r#"{"action":"undo"}"#).unwrap();
|
|
assert_eq!(undo.risk(), Risk::High);
|
|
assert!(undo.is_mutating());
|
|
assert_eq!(undo, SystemAction::Undo { snapshot: None });
|
|
let specific =
|
|
parse_action(r#"{"action":"undo","snapshot":"@-20260101T000000-sys-update"}"#).unwrap();
|
|
assert_eq!(
|
|
specific,
|
|
SystemAction::Undo {
|
|
snapshot: Some("@-20260101T000000-sys-update".into())
|
|
}
|
|
);
|
|
// Unknown fields and bad ids fail closed.
|
|
assert!(parse_action(r#"{"action":"undo","shell":"sh"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"undo","snapshot":"bad id"}"#).is_err());
|
|
let status = parse_action(r#"{"action":"rollback_status"}"#).unwrap();
|
|
assert!(!status.is_mutating());
|
|
assert_eq!(status.risk(), Risk::Low);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_undo_phrases() {
|
|
assert_eq!(
|
|
parse_natural("undo"),
|
|
Some(SystemAction::Undo { snapshot: None })
|
|
);
|
|
assert_eq!(
|
|
parse_natural("undo status"),
|
|
Some(SystemAction::RollbackStatus)
|
|
);
|
|
assert_eq!(
|
|
parse_natural("undo @-20260101T000000-sys-update"),
|
|
Some(SystemAction::Undo {
|
|
snapshot: Some("@-20260101T000000-sys-update".into())
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn flatpak_and_nix_actions_are_bounded() {
|
|
let install =
|
|
parse_action(r#"{"action":"flatpak_install","app_id":"org.chromium.Chromium"}"#)
|
|
.unwrap();
|
|
assert_eq!(install.risk(), Risk::Medium);
|
|
assert!(install.is_mutating());
|
|
assert!(parse_action(r#"{"action":"flatpak_install","app_id":"bad id"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"flatpak_install","app_id":"nodots"}"#).is_err());
|
|
|
|
let list = parse_action(r#"{"action":"flatpak_list"}"#).unwrap();
|
|
assert!(!list.is_mutating());
|
|
|
|
let nix =
|
|
parse_action(r#"{"action":"nix_prepare","packages":["nodejs","python312"]}"#).unwrap();
|
|
assert_eq!(nix.risk(), Risk::Medium);
|
|
assert!(nix.is_mutating());
|
|
assert!(parse_action(r#"{"action":"nix_prepare","packages":[]}"#).is_err());
|
|
assert!(
|
|
parse_action(r#"{"action":"nix_prepare","packages":["github:evil/repo"]}"#).is_err()
|
|
);
|
|
assert!(valid_nix_attribute("python312"));
|
|
assert!(!valid_nix_attribute("nixpkgs#x/y"));
|
|
assert!(valid_flatpak_app_id("com.spotify.Client"));
|
|
assert!(!valid_flatpak_app_id("com/spotify"));
|
|
}
|
|
}
|