1808 lines
67 KiB
Rust
1808 lines
67 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};
|
|
|
|
use crate::selection::{Backend, PackageKind};
|
|
|
|
#[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,
|
|
},
|
|
/// Start a service now (runtime, not boot persistence).
|
|
StartService {
|
|
name: String,
|
|
},
|
|
/// Stop a running service now.
|
|
StopService {
|
|
name: String,
|
|
},
|
|
/// Restart a running service now.
|
|
RestartService {
|
|
name: String,
|
|
},
|
|
InspectPackage {
|
|
atom: String,
|
|
},
|
|
InstallPackage {
|
|
atom: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
binary: Option<bool>,
|
|
},
|
|
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,
|
|
|
|
// ------------------------------------------------------------------
|
|
// Shared, hardware-aware package selection (read-only decision).
|
|
// ------------------------------------------------------------------
|
|
/// Show which backend/lane should satisfy a request, with the evidence and
|
|
/// the alternatives rejected. Never installs anything.
|
|
ChoosePackage {
|
|
name: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
kind: Option<PackageKind>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
backend: Option<Backend>,
|
|
#[serde(default)]
|
|
gui: bool,
|
|
#[serde(default)]
|
|
requires_sandbox: bool,
|
|
},
|
|
|
|
/// Persist (or clear) an explicit backend preference for an application.
|
|
/// The deterministic selector and the assistant both honour it. Personal
|
|
/// preferences need no privilege; `system_wide` changes the root-owned
|
|
/// default and is only applied through the authenticated broker.
|
|
SetPackagePreference {
|
|
name: String,
|
|
/// `None` clears the preference and returns to automatic selection.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
backend: Option<Backend>,
|
|
/// Change the system-wide default rather than the user's own choice.
|
|
#[serde(default)]
|
|
system_wide: bool,
|
|
},
|
|
|
|
// ------------------------------------------------------------------
|
|
// Bounded, read-only investigation used by the AI installation workflow.
|
|
// These return evidence only; they never mutate the system.
|
|
// ------------------------------------------------------------------
|
|
/// Discover the real candidates for an application across the available
|
|
/// lanes (Portage, Nix, Flatpak, Snap, AppImage, the Phoebus overlay).
|
|
DiscoverCandidates {
|
|
query: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
kind: Option<PackageKind>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
backend: Option<Backend>,
|
|
#[serde(default)]
|
|
gui: bool,
|
|
#[serde(default)]
|
|
requires_sandbox: bool,
|
|
},
|
|
/// Inspect one resolved candidate's metadata (version, source, sizes,
|
|
/// dependencies, permissions, confinement, update behaviour).
|
|
InspectCandidate {
|
|
backend: Backend,
|
|
id: String,
|
|
},
|
|
/// Report whether a lane is installed and ready, including daemon state and
|
|
/// confinement where relevant.
|
|
CheckBackend {
|
|
backend: Backend,
|
|
},
|
|
/// Report existing installations of an application and any duplication.
|
|
InspectInstallation {
|
|
application: String,
|
|
},
|
|
|
|
// ------------------------------------------------------------------
|
|
// Snap lane.
|
|
// ------------------------------------------------------------------
|
|
SnapFind {
|
|
query: String,
|
|
},
|
|
SnapInfo {
|
|
name: String,
|
|
},
|
|
SnapInstall {
|
|
name: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
channel: Option<String>,
|
|
/// Classic confinement is a security downgrade and must be explicit.
|
|
#[serde(default)]
|
|
classic: bool,
|
|
},
|
|
SnapRemove {
|
|
name: String,
|
|
},
|
|
SnapList,
|
|
SnapRefresh {
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
name: Option<String>,
|
|
},
|
|
/// Show the connections (permissions) a snap currently holds or requests.
|
|
SnapConnections {
|
|
name: String,
|
|
},
|
|
|
|
// ------------------------------------------------------------------
|
|
// AppImage lane.
|
|
// ------------------------------------------------------------------
|
|
/// Adopt a local AppImage under Phoebus management (hash recorded).
|
|
#[serde(rename = "appimage_import")]
|
|
AppImageImport {
|
|
path: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
name: Option<String>,
|
|
},
|
|
/// Download and adopt an AppImage with a pinned SHA-256.
|
|
#[serde(rename = "appimage_acquire")]
|
|
AppImageAcquire {
|
|
name: String,
|
|
url: String,
|
|
sha256: String,
|
|
},
|
|
/// Re-acquire a newer AppImage from a pinned URL + SHA-256.
|
|
#[serde(rename = "appimage_update")]
|
|
AppImageUpdate {
|
|
name: String,
|
|
url: String,
|
|
sha256: String,
|
|
},
|
|
#[serde(rename = "appimage_remove")]
|
|
AppImageRemove {
|
|
name: String,
|
|
/// Remove the application's user data too (default: preserve it).
|
|
#[serde(default)]
|
|
purge_data: bool,
|
|
},
|
|
#[serde(rename = "appimage_info")]
|
|
AppImageInfo {
|
|
name: String,
|
|
},
|
|
#[serde(rename = "appimage_list")]
|
|
AppImageList,
|
|
|
|
// ------------------------------------------------------------------
|
|
// Phoebus-managed custom ebuild lane.
|
|
// ------------------------------------------------------------------
|
|
/// Stage a reviewed custom ebuild in the Phoebus overlay. Writes the
|
|
/// artifact but does not build or install it.
|
|
CustomEbuildPrepare {
|
|
atom: String,
|
|
version: String,
|
|
rationale: String,
|
|
/// The full ebuild text. Treated as untrusted, executable content.
|
|
ebuild: String,
|
|
},
|
|
/// Build and install a staged ebuild whose content still matches `digest`.
|
|
CustomEbuildInstall {
|
|
atom: String,
|
|
version: String,
|
|
digest: String,
|
|
},
|
|
CustomEbuildRemove {
|
|
atom: String,
|
|
},
|
|
CustomEbuildList,
|
|
}
|
|
|
|
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::StartService { name } => format!("start service {name}"),
|
|
SystemAction::StopService { name } => format!("stop service {name}"),
|
|
SystemAction::RestartService { name } => format!("restart service {name}"),
|
|
SystemAction::InspectPackage { atom } => format!("inspect package {atom}"),
|
|
SystemAction::InstallPackage { atom, binary } => {
|
|
if *binary == Some(true) {
|
|
format!("install binary package {atom}")
|
|
} else {
|
|
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(),
|
|
SystemAction::ChoosePackage {
|
|
name,
|
|
kind,
|
|
backend,
|
|
..
|
|
} => {
|
|
let mut s = format!("choose the best source for {name}");
|
|
if let Some(kind) = kind {
|
|
s.push_str(&format!(" ({})", kind.as_str()));
|
|
}
|
|
if let Some(backend) = backend {
|
|
s.push_str(&format!(", preferring {}", backend.as_str()));
|
|
}
|
|
s
|
|
}
|
|
SystemAction::SetPackagePreference {
|
|
name,
|
|
backend,
|
|
system_wide,
|
|
} => {
|
|
let scope = if *system_wide { " (system-wide)" } else { "" };
|
|
match backend {
|
|
Some(backend) => {
|
|
format!("prefer {} for {name}{scope}", backend.as_str())
|
|
}
|
|
None => format!("clear the backend preference for {name}{scope}"),
|
|
}
|
|
}
|
|
SystemAction::DiscoverCandidates { query, .. } => {
|
|
format!("discover installation candidates for `{query}`")
|
|
}
|
|
SystemAction::InspectCandidate { backend, id } => {
|
|
format!("inspect the {} candidate {id}", backend.as_str())
|
|
}
|
|
SystemAction::CheckBackend { backend } => {
|
|
format!("check whether the {} lane is ready", backend.as_str())
|
|
}
|
|
SystemAction::InspectInstallation { application } => {
|
|
format!("inspect existing installations of {application}")
|
|
}
|
|
SystemAction::SnapFind { query } => format!("search the Snap store for `{query}`"),
|
|
SystemAction::SnapInfo { name } => format!("inspect snap {name}"),
|
|
SystemAction::SnapInstall {
|
|
name,
|
|
channel,
|
|
classic,
|
|
} => {
|
|
let mut s = format!("install snap {name}");
|
|
if let Some(channel) = channel {
|
|
s.push_str(&format!(" from channel {channel}"));
|
|
}
|
|
if *classic {
|
|
s.push_str(" with classic (unconfined) confinement");
|
|
}
|
|
s
|
|
}
|
|
SystemAction::SnapRemove { name } => format!("remove snap {name}"),
|
|
SystemAction::SnapList => "list installed snaps".to_string(),
|
|
SystemAction::SnapRefresh { name } => match name {
|
|
Some(name) => format!("refresh snap {name}"),
|
|
None => "refresh all snaps".to_string(),
|
|
},
|
|
SystemAction::SnapConnections { name } => format!("show snap {name} connections"),
|
|
SystemAction::AppImageImport { path, name } => format!(
|
|
"import AppImage {path}{}",
|
|
name.as_deref()
|
|
.map(|n| format!(" as {n}"))
|
|
.unwrap_or_default()
|
|
),
|
|
SystemAction::AppImageAcquire { name, url, .. } => {
|
|
format!("download and manage AppImage {name} from {url}")
|
|
}
|
|
SystemAction::AppImageUpdate { name, url, .. } => {
|
|
format!("update managed AppImage {name} from {url}")
|
|
}
|
|
SystemAction::AppImageRemove { name, purge_data } => {
|
|
if *purge_data {
|
|
format!("remove AppImage {name} and its user data")
|
|
} else {
|
|
format!("remove AppImage {name} (preserving user data)")
|
|
}
|
|
}
|
|
SystemAction::AppImageInfo { name } => format!("inspect managed AppImage {name}"),
|
|
SystemAction::AppImageList => "list managed AppImages".to_string(),
|
|
SystemAction::CustomEbuildPrepare { atom, version, .. } => {
|
|
format!("stage a custom ebuild for {atom}-{version} (not installed)")
|
|
}
|
|
SystemAction::CustomEbuildInstall { atom, version, .. } => {
|
|
format!("build and install custom ebuild {atom}-{version}")
|
|
}
|
|
SystemAction::CustomEbuildRemove { atom } => {
|
|
format!("remove the custom ebuild package {atom}")
|
|
}
|
|
SystemAction::CustomEbuildList => "list Phoebus-managed custom ebuilds".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::ChoosePackage { .. }
|
|
| SystemAction::SnapFind { .. }
|
|
| SystemAction::SnapInfo { .. }
|
|
| SystemAction::SnapList
|
|
| SystemAction::SnapConnections { .. }
|
|
| SystemAction::AppImageInfo { .. }
|
|
| SystemAction::AppImageList
|
|
| SystemAction::DiscoverCandidates { .. }
|
|
| SystemAction::InspectCandidate { .. }
|
|
| SystemAction::CheckBackend { .. }
|
|
| SystemAction::InspectInstallation { .. }
|
|
| SystemAction::CustomEbuildList => Risk::Low,
|
|
SystemAction::PrepareUpdates => Risk::Medium,
|
|
SystemAction::EnableService { .. }
|
|
| SystemAction::DisableService { .. }
|
|
| SystemAction::StartService { .. }
|
|
| SystemAction::StopService { .. }
|
|
| SystemAction::RestartService { .. }
|
|
| SystemAction::CreateSnapshot { .. }
|
|
| SystemAction::FlatpakInstall { .. }
|
|
| SystemAction::FlatpakRemove { .. }
|
|
| SystemAction::NixPrepare { .. }
|
|
| SystemAction::SetPackagePreference { .. }
|
|
| SystemAction::SnapInstall { .. }
|
|
| SystemAction::SnapRemove { .. }
|
|
| SystemAction::SnapRefresh { .. }
|
|
| SystemAction::AppImageImport { .. }
|
|
| SystemAction::AppImageAcquire { .. }
|
|
| SystemAction::AppImageUpdate { .. }
|
|
| SystemAction::AppImageRemove { .. }
|
|
| SystemAction::CustomEbuildPrepare { .. } => Risk::Medium,
|
|
SystemAction::InstallPackage { .. }
|
|
| SystemAction::RemovePackage { .. }
|
|
| SystemAction::UpdateSystem
|
|
| SystemAction::Undo { .. }
|
|
| SystemAction::CustomEbuildInstall { .. }
|
|
| SystemAction::CustomEbuildRemove { .. } => 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
|
|
| SystemAction::ChoosePackage { .. }
|
|
| SystemAction::SnapFind { .. }
|
|
| SystemAction::SnapInfo { .. }
|
|
| SystemAction::SnapList
|
|
| SystemAction::SnapConnections { .. }
|
|
| SystemAction::AppImageInfo { .. }
|
|
| SystemAction::AppImageList
|
|
| SystemAction::DiscoverCandidates { .. }
|
|
| SystemAction::InspectCandidate { .. }
|
|
| SystemAction::CheckBackend { .. }
|
|
| SystemAction::InspectInstallation { .. }
|
|
| SystemAction::CustomEbuildList
|
|
)
|
|
}
|
|
|
|
/// Whether this action requires root. A personal package preference is
|
|
/// mutable user state, not a privileged system change, so a normal desktop
|
|
/// account may set it; a system-wide preference still requires the broker.
|
|
pub fn requires_root(&self) -> bool {
|
|
match self {
|
|
SystemAction::SetPackagePreference { system_wide, .. } => *system_wide,
|
|
other => other.is_mutating(),
|
|
}
|
|
}
|
|
|
|
pub fn validate(&self) -> Result<(), String> {
|
|
let valid_token = |s: &str| {
|
|
!s.is_empty()
|
|
&& s.len() <= 128
|
|
// A leading dash would be parsed by the target command as an
|
|
// option, so it is never a service/unit name.
|
|
&& !s.starts_with('-')
|
|
&& s.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "@._+-".contains(c))
|
|
};
|
|
match self {
|
|
SystemAction::InspectService { name }
|
|
| SystemAction::EnableService { name }
|
|
| SystemAction::DisableService { name }
|
|
| SystemAction::StartService { name }
|
|
| SystemAction::StopService { name }
|
|
| SystemAction::RestartService { 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(()),
|
|
SystemAction::ChoosePackage { name, .. } => {
|
|
if valid_package_spec(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid package name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::SetPackagePreference { name, .. } => {
|
|
if valid_package_spec(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid package name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::DiscoverCandidates { query, .. } => {
|
|
if valid_search_query(query) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid application query: {query}"))
|
|
}
|
|
}
|
|
SystemAction::InspectCandidate { backend, id } => {
|
|
if valid_candidate_id(*backend, id) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid {} candidate id: {id}", backend.as_str()))
|
|
}
|
|
}
|
|
SystemAction::CheckBackend { .. } => Ok(()),
|
|
SystemAction::InspectInstallation { application } => {
|
|
if valid_application_name(application) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid application name: {application}"))
|
|
}
|
|
}
|
|
SystemAction::SnapFind { query } => {
|
|
if valid_search_query(query) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid Snap search query: {query}"))
|
|
}
|
|
}
|
|
SystemAction::SnapInfo { name }
|
|
| SystemAction::SnapRemove { name }
|
|
| SystemAction::SnapConnections { name } => {
|
|
if valid_snap_name(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid snap name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::SnapInstall { name, channel, .. } => {
|
|
if !valid_snap_name(name) {
|
|
return Err(format!("invalid snap name: {name}"));
|
|
}
|
|
if let Some(channel) = channel {
|
|
if !valid_snap_channel(channel) {
|
|
return Err(format!("invalid snap channel: {channel}"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::SnapList => Ok(()),
|
|
SystemAction::SnapRefresh { name } => match name {
|
|
Some(name) if !valid_snap_name(name) => Err(format!("invalid snap name: {name}")),
|
|
_ => Ok(()),
|
|
},
|
|
SystemAction::AppImageImport { path, name } => {
|
|
if path.is_empty() || path.len() > 4096 || path.contains('\0') {
|
|
return Err("invalid AppImage path".into());
|
|
}
|
|
if let Some(name) = name {
|
|
if !valid_appimage_name(name) {
|
|
return Err(format!("invalid AppImage name: {name}"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::AppImageAcquire { name, url, sha256 }
|
|
| SystemAction::AppImageUpdate { name, url, sha256 } => {
|
|
if !valid_appimage_name(name) {
|
|
return Err(format!("invalid AppImage name: {name}"));
|
|
}
|
|
if !valid_http_url(url) {
|
|
return Err(format!("invalid AppImage URL: {url}"));
|
|
}
|
|
if !valid_sha256(sha256) {
|
|
return Err(
|
|
"AppImage SHA-256 must be 64 hex characters (not a placeholder)".into(),
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::AppImageRemove { name, .. } => {
|
|
if valid_appimage_name(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid AppImage name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::AppImageInfo { name } => {
|
|
if valid_appimage_name(name) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid AppImage name: {name}"))
|
|
}
|
|
}
|
|
SystemAction::AppImageList => Ok(()),
|
|
SystemAction::CustomEbuildPrepare {
|
|
atom,
|
|
version,
|
|
rationale,
|
|
ebuild,
|
|
} => {
|
|
if !valid_ebuild_atom(atom) {
|
|
return Err(format!("invalid ebuild atom: {atom}"));
|
|
}
|
|
if !valid_ebuild_version(version) {
|
|
return Err(format!("invalid ebuild version: {version}"));
|
|
}
|
|
if rationale.trim().is_empty() || rationale.len() > 4096 {
|
|
return Err("custom ebuild requires a bounded rationale".into());
|
|
}
|
|
if ebuild.trim().is_empty() {
|
|
return Err("custom ebuild content must not be empty".into());
|
|
}
|
|
if ebuild.len() > 256 * 1024 {
|
|
return Err("custom ebuild content is too large (max 256 KiB)".into());
|
|
}
|
|
if ebuild.contains('\0') {
|
|
return Err("custom ebuild content contains a NUL byte".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::CustomEbuildInstall {
|
|
atom,
|
|
version,
|
|
digest,
|
|
} => {
|
|
if !valid_ebuild_atom(atom) {
|
|
return Err(format!("invalid ebuild atom: {atom}"));
|
|
}
|
|
if !valid_ebuild_version(version) {
|
|
return Err(format!("invalid ebuild version: {version}"));
|
|
}
|
|
if !valid_sha256(digest) {
|
|
return Err("custom ebuild digest must be 64 hex characters".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
SystemAction::CustomEbuildRemove { atom } => {
|
|
if valid_ebuild_atom(atom) {
|
|
Ok(())
|
|
} else {
|
|
Err(format!("invalid ebuild atom: {atom}"))
|
|
}
|
|
}
|
|
SystemAction::CustomEbuildList => 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;
|
|
}
|
|
// 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('-') {
|
|
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.starts_with('-')
|
|
&& 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
|
|
// Reject a leading dash so a query cannot become an option.
|
|
&& !query.starts_with('-')
|
|
&& 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 snap name: lower-case letters, digits and single hyphens; must start and
|
|
/// end alphanumeric; at most 40 characters (snapd's own rule).
|
|
pub fn valid_snap_name(value: &str) -> bool {
|
|
if value.is_empty() || value.len() > 40 {
|
|
return false;
|
|
}
|
|
if value.starts_with('-') || value.ends_with('-') || value.contains("--") {
|
|
return false;
|
|
}
|
|
value
|
|
.chars()
|
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
|
}
|
|
|
|
/// A snap channel: `track/risk/branch` with the usual building blocks. No
|
|
/// spaces, slashes beyond the two separators, or shell metacharacters.
|
|
pub fn valid_snap_channel(value: &str) -> bool {
|
|
!value.is_empty()
|
|
&& value.len() <= 64
|
|
&& !value.starts_with('-')
|
|
&& value.split('/').count() <= 3
|
|
&& value
|
|
.chars()
|
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "-._".contains(c) || c == '/')
|
|
}
|
|
|
|
/// A managed AppImage name (a bounded, filesystem-safe identifier).
|
|
pub fn valid_appimage_name(value: &str) -> bool {
|
|
if value.is_empty() || value.len() > 64 {
|
|
return false;
|
|
}
|
|
if value.starts_with('.') || value.starts_with('-') {
|
|
return false;
|
|
}
|
|
value
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
|
|
&& !value.contains("..")
|
|
}
|
|
|
|
/// An `http`/`https` URL with no whitespace or control characters.
|
|
pub fn valid_http_url(value: &str) -> bool {
|
|
!value.is_empty()
|
|
&& value.len() <= 2048
|
|
&& (value.starts_with("https://") || value.starts_with("http://"))
|
|
&& !value.chars().any(|c| c.is_whitespace() || c.is_control())
|
|
}
|
|
|
|
/// A user-facing application name (`firefox`, `org.mozilla.firefox`,
|
|
/// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls.
|
|
pub fn valid_application_name(value: &str) -> bool {
|
|
!value.is_empty()
|
|
&& value.len() <= 128
|
|
&& !value.starts_with('-')
|
|
&& value
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "._+@/-".contains(c))
|
|
}
|
|
|
|
/// Validate a backend-native candidate identifier. Each lane has its own
|
|
/// identity grammar, so a Portage atom is checked as an atom and a Flatpak
|
|
/// application id as a reverse-DNS id; a mismatch fails closed.
|
|
pub fn valid_candidate_id(backend: Backend, id: &str) -> bool {
|
|
match backend {
|
|
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
|
|
valid_package_spec(id)
|
|
}
|
|
Backend::Nix => valid_nix_attribute(id),
|
|
Backend::Flatpak => valid_flatpak_app_id(id),
|
|
Backend::Snap => valid_snap_name(id),
|
|
Backend::AppImage => valid_appimage_name(id),
|
|
Backend::CustomEbuild => valid_ebuild_atom(id),
|
|
}
|
|
}
|
|
|
|
/// A real SHA-256: 64 hex characters and not the all-zero placeholder.
|
|
pub fn valid_sha256(value: &str) -> bool {
|
|
value.len() == 64
|
|
&& value.chars().all(|c| c.is_ascii_hexdigit())
|
|
&& value.chars().any(|c| c != '0')
|
|
}
|
|
|
|
/// A Gentoo `category/package` atom for the custom overlay. Version and slots
|
|
/// are not part of the atom, so `/` appears exactly once.
|
|
pub fn valid_ebuild_atom(value: &str) -> bool {
|
|
if value.is_empty() || value.len() > 128 {
|
|
return false;
|
|
}
|
|
let mut parts = value.split('/');
|
|
let (Some(category), Some(package), None) = (parts.next(), parts.next(), parts.next()) else {
|
|
return false;
|
|
};
|
|
let ok = |s: &str| {
|
|
!s.is_empty()
|
|
&& !s.starts_with('-')
|
|
&& s.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "+._-".contains(c))
|
|
};
|
|
ok(category) && ok(package)
|
|
}
|
|
|
|
/// A Gentoo version string (optionally with a `-rN` revision).
|
|
pub fn valid_ebuild_version(value: &str) -> bool {
|
|
if value.is_empty() || value.len() > 64 || value.starts_with('-') || value.contains('/') {
|
|
return false;
|
|
}
|
|
value
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "+._-".contains(c))
|
|
}
|
|
|
|
/// Strip a case-insensitive ASCII prefix, returning the remainder. Used where
|
|
/// the operand after the verb is case-sensitive (Flatpak app ids).
|
|
fn strip_prefix_ascii_ci<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
|
|
// `get` (not `split_at`) so a prefix length that lands inside a multibyte
|
|
// character is simply "no match" rather than a panic.
|
|
let head = text.get(..prefix.len())?;
|
|
head.eq_ignore_ascii_case(prefix)
|
|
.then(|| &text[prefix.len()..])
|
|
}
|
|
|
|
/// A small deterministic parser for common `sys` phrases.
|
|
///
|
|
/// The parser validates its own output, so the deterministic (manual) entry
|
|
/// path cannot emit an invalid action — exactly like the JSON and AI paths.
|
|
/// 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> {
|
|
let action = parse_natural_raw(text)?;
|
|
action.validate().ok()?;
|
|
Some(action)
|
|
}
|
|
|
|
fn parse_natural_raw(text: &str) -> Option<SystemAction> {
|
|
// Strip polite prefix like "please"
|
|
let mut raw = text.trim();
|
|
if let Some(stripped) = raw.strip_prefix("please ") {
|
|
raw = stripped.trim();
|
|
} else if let Some(stripped) = raw.strip_prefix("Please ") {
|
|
raw = stripped.trim();
|
|
}
|
|
|
|
// Snapshot ids are case-sensitive (`@-20260101T000000-...`), so parse the
|
|
// undo form from the original text before the general lowercasing.
|
|
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 = raw.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(name) = rest("start ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::StartService { name });
|
|
}
|
|
}
|
|
if let Some(name) = rest("stop ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::StopService { name });
|
|
}
|
|
}
|
|
if let Some(name) = rest("restart ") {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::RestartService { name });
|
|
}
|
|
}
|
|
if let Some(atom) = rest("install ").or_else(|| rest("add ")) {
|
|
if !atom.is_empty() {
|
|
return Some(SystemAction::InstallPackage { atom, binary: None });
|
|
}
|
|
}
|
|
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 });
|
|
}
|
|
}
|
|
|
|
// Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so
|
|
// the operands are read from the original text, not the lowercased copy.
|
|
if let Some(rest) = strip_prefix_ascii_ci(raw, "flatpak ") {
|
|
let rest = rest.trim();
|
|
if let Some(id) = strip_prefix_ascii_ci(rest, "install ") {
|
|
let id = id.trim();
|
|
if !id.is_empty() {
|
|
return Some(SystemAction::FlatpakInstall {
|
|
app_id: id.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if let Some(id) = strip_prefix_ascii_ci(rest, "remove ")
|
|
.or_else(|| strip_prefix_ascii_ci(rest, "uninstall "))
|
|
{
|
|
let id = id.trim();
|
|
if !id.is_empty() {
|
|
return Some(SystemAction::FlatpakRemove {
|
|
app_id: id.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if rest.eq_ignore_ascii_case("list") || rest.eq_ignore_ascii_case("apps") {
|
|
return Some(SystemAction::FlatpakList);
|
|
}
|
|
}
|
|
if t == "flatpaks" {
|
|
return Some(SystemAction::FlatpakList);
|
|
}
|
|
|
|
// Snap verbs. Snap names and channels are lower-case, so the lowercased
|
|
// copy is safe here.
|
|
if let Some(rest) = rest("snap ") {
|
|
if let Some(name) = rest.strip_prefix("install ").map(str::trim) {
|
|
let mut parts = name.split_whitespace();
|
|
let name = parts.next()?;
|
|
if !name.is_empty() {
|
|
let channel = parts.next().map(str::to_string);
|
|
return Some(SystemAction::SnapInstall {
|
|
name: name.to_string(),
|
|
channel,
|
|
classic: false,
|
|
});
|
|
}
|
|
}
|
|
if let Some(name) = rest
|
|
.strip_prefix("remove ")
|
|
.or_else(|| rest.strip_prefix("uninstall "))
|
|
.map(str::trim)
|
|
{
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::SnapRemove {
|
|
name: name.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if let Some(query) = rest
|
|
.strip_prefix("find ")
|
|
.or_else(|| rest.strip_prefix("search "))
|
|
.map(str::trim)
|
|
{
|
|
if !query.is_empty() {
|
|
return Some(SystemAction::SnapFind {
|
|
query: query.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if let Some(name) = rest.strip_prefix("info ").map(str::trim) {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::SnapInfo {
|
|
name: name.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if let Some(name) = rest.strip_prefix("connections ").map(str::trim) {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::SnapConnections {
|
|
name: name.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if rest == "refresh" {
|
|
return Some(SystemAction::SnapRefresh { name: None });
|
|
}
|
|
if let Some(name) = rest.strip_prefix("refresh ").map(str::trim) {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::SnapRefresh {
|
|
name: Some(name.to_string()),
|
|
});
|
|
}
|
|
}
|
|
if rest == "list" || rest == "snaps" {
|
|
return Some(SystemAction::SnapList);
|
|
}
|
|
}
|
|
if t == "snaps" {
|
|
return Some(SystemAction::SnapList);
|
|
}
|
|
|
|
// AppImage verbs. Paths are case-sensitive, so read them from the original
|
|
// text.
|
|
if let Some(rest) = strip_prefix_ascii_ci(raw, "appimage ") {
|
|
let rest = rest.trim();
|
|
if let Some(path) = strip_prefix_ascii_ci(rest, "import ").map(str::trim) {
|
|
if !path.is_empty() {
|
|
return Some(SystemAction::AppImageImport {
|
|
path: path.to_string(),
|
|
name: None,
|
|
});
|
|
}
|
|
}
|
|
if let Some(name) = strip_prefix_ascii_ci(rest, "remove ").map(str::trim) {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::AppImageRemove {
|
|
name: name.to_string(),
|
|
purge_data: false,
|
|
});
|
|
}
|
|
}
|
|
if let Some(name) = strip_prefix_ascii_ci(rest, "info ").map(str::trim) {
|
|
if !name.is_empty() {
|
|
return Some(SystemAction::AppImageInfo {
|
|
name: name.to_string(),
|
|
});
|
|
}
|
|
}
|
|
if rest.eq_ignore_ascii_case("list") {
|
|
return Some(SystemAction::AppImageList);
|
|
}
|
|
}
|
|
|
|
// Custom ebuild inventory (staging/install are JSON/AI-only: they carry the
|
|
// full artifact and are too large and too sensitive for a one-line phrase).
|
|
if t == "ebuilds" || t == "custom ebuilds" || t == "custom-ebuilds" {
|
|
return Some(SystemAction::CustomEbuildList);
|
|
}
|
|
|
|
// Hardware-aware source choice: `choose firefox`, `choose firefox as a gui
|
|
// app`, `choose firefox via flatpak`.
|
|
if let Some(rest) = rest("choose ").or_else(|| rest("select source ")) {
|
|
let rest = rest.trim();
|
|
if !rest.is_empty() {
|
|
let mut words = rest.split_whitespace();
|
|
let name = words.next().unwrap_or("").to_string();
|
|
if !name.is_empty() {
|
|
let mut backend = None;
|
|
let mut gui = false;
|
|
let mut requires_sandbox = false;
|
|
let tokens: Vec<&str> = words.collect();
|
|
for (i, token) in tokens.iter().enumerate() {
|
|
match *token {
|
|
"via" | "with" | "using" => {
|
|
if let Some(b) = tokens.get(i + 1).and_then(|s| Backend::parse(s)) {
|
|
backend = Some(b);
|
|
}
|
|
}
|
|
"gui" | "desktop" => gui = true,
|
|
"sandboxed" | "sandbox" => requires_sandbox = true,
|
|
_ => {}
|
|
}
|
|
}
|
|
return Some(SystemAction::ChoosePackage {
|
|
name,
|
|
kind: None,
|
|
backend,
|
|
gui,
|
|
requires_sandbox,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Persisted backend preference: `prefer firefox via flatpak` / `prefer
|
|
// firefox auto`.
|
|
if let Some(rest) = rest("prefer ") {
|
|
let rest = rest.trim();
|
|
let tokens: Vec<&str> = rest.split_whitespace().collect();
|
|
if let Some(name) = tokens.first() {
|
|
if !name.is_empty() {
|
|
let backend = match (tokens.get(1), tokens.get(2)) {
|
|
(Some(&"auto"), _) | (Some(&"clear"), _) | (None, _) => None,
|
|
(Some(&"via" | &"with" | &"using"), Some(b)) => Backend::parse(b),
|
|
(Some(b), _) => Backend::parse(b),
|
|
};
|
|
return Some(SystemAction::SetPackagePreference {
|
|
name: name.to_string(),
|
|
backend,
|
|
system_wide: false,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Nix development packages.
|
|
if let Some(packages) = rest("nix prepare ").or_else(|| rest("nix realise ")) {
|
|
let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect();
|
|
if !packages.is_empty() {
|
|
return Some(SystemAction::NixPrepare { packages });
|
|
}
|
|
}
|
|
if let Some(packages) = rest("nix install ") {
|
|
let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect();
|
|
if !packages.is_empty() {
|
|
return Some(SystemAction::NixPrepare { packages });
|
|
}
|
|
}
|
|
|
|
// Protective snapshot.
|
|
if t == "snapshot" || t.starts_with("snapshot ") {
|
|
let operation = t.strip_prefix("snapshot").unwrap_or("").trim();
|
|
let operation = if operation.is_empty() {
|
|
"manual snapshot".to_string()
|
|
} else {
|
|
operation.to_string()
|
|
};
|
|
return Some(SystemAction::CreateSnapshot { operation });
|
|
}
|
|
|
|
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 value: serde_json::Value = serde_json::from_str(json)?;
|
|
let action: SystemAction = serde_json::from_value(value.clone())?;
|
|
// `deny_unknown_fields` does not reject extra keys on internally tagged
|
|
// *unit* variants (e.g. `{"action":"history","x":1}`), so compare the
|
|
// input keys against the canonical serialisation and fail closed.
|
|
if let (Some(input), Some(canonical)) = (
|
|
value.as_object(),
|
|
serde_json::to_value(&action)?.as_object(),
|
|
) {
|
|
for key in input.keys() {
|
|
if !canonical.contains_key(key) {
|
|
return Err(ActionError::Invalid(format!("unknown field `{key}`")));
|
|
}
|
|
}
|
|
}
|
|
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());
|
|
// Unit variants must reject unknown keys too (serde's
|
|
// deny_unknown_fields does not cover internally tagged unit variants).
|
|
assert!(parse_action(r#"{"action":"history","x":1}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"update_system","shell":"sh"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"snap_list","extra":true}"#).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_bare_package_names() {
|
|
assert_eq!(
|
|
parse_action(r#"{"action":"install_package","atom":"vim"}"#).unwrap(),
|
|
SystemAction::InstallPackage {
|
|
atom: "vim".into(),
|
|
binary: None,
|
|
}
|
|
);
|
|
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(),
|
|
binary: None,
|
|
})
|
|
);
|
|
// The friendly, apt-like forms resolve to Portage operations.
|
|
assert_eq!(
|
|
parse_natural("install vim"),
|
|
Some(SystemAction::InstallPackage {
|
|
atom: "vim".into(),
|
|
binary: None,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("please install vim"),
|
|
Some(SystemAction::InstallPackage {
|
|
atom: "vim".into(),
|
|
binary: None,
|
|
})
|
|
);
|
|
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"));
|
|
}
|
|
|
|
#[test]
|
|
fn service_lifecycle_actions_are_typed_and_medium_risk() {
|
|
for (json, expected) in [
|
|
(
|
|
r#"{"action":"start_service","name":"sshd"}"#,
|
|
SystemAction::StartService {
|
|
name: "sshd".into(),
|
|
},
|
|
),
|
|
(
|
|
r#"{"action":"stop_service","name":"sshd"}"#,
|
|
SystemAction::StopService {
|
|
name: "sshd".into(),
|
|
},
|
|
),
|
|
(
|
|
r#"{"action":"restart_service","name":"sshd.service"}"#,
|
|
SystemAction::RestartService {
|
|
name: "sshd.service".into(),
|
|
},
|
|
),
|
|
] {
|
|
let action = parse_action(json).unwrap();
|
|
assert_eq!(action, expected);
|
|
assert!(action.is_mutating());
|
|
assert_eq!(action.risk(), Risk::Medium);
|
|
}
|
|
assert!(parse_action(r#"{"action":"start_service","name":"--now"}"#).is_err());
|
|
assert_eq!(
|
|
parse_natural("restart sshd"),
|
|
Some(SystemAction::RestartService {
|
|
name: "sshd".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("stop bluetooth"),
|
|
Some(SystemAction::StopService {
|
|
name: "bluetooth".into()
|
|
})
|
|
);
|
|
}
|
|
|
|
/// The manual (natural), JSON and AI entry paths all reject an option-like
|
|
/// operand, so no entry path can smuggle an option into a command.
|
|
#[test]
|
|
fn option_like_operands_are_rejected_on_every_entry_path() {
|
|
// Manual path: the deterministic parser validates its own output.
|
|
assert_eq!(parse_natural("install --color=n"), None);
|
|
assert_eq!(parse_natural("enable --now"), None);
|
|
assert_eq!(parse_natural("search -C"), None);
|
|
assert_eq!(parse_natural("start --force"), None);
|
|
|
|
// JSON path.
|
|
assert!(parse_action(r#"{"action":"install_package","atom":"--color=n"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"enable_service","name":"--now"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"search_packages","query":"-C"}"#).is_err());
|
|
assert!(parse_action(r#"{"action":"install_package","atom":"app/--evil"}"#).is_err());
|
|
|
|
// The AI plan parser runs this same `validate` (covered in
|
|
// `phoebus-ai::assistant::tests`).
|
|
}
|
|
|
|
#[test]
|
|
fn case_insensitive_prefix_never_panics_on_multibyte() {
|
|
assert_eq!(
|
|
strip_prefix_ascii_ci("FLATPAK install x", "flatpak "),
|
|
Some("install x")
|
|
);
|
|
assert_eq!(strip_prefix_ascii_ci("notaflatpak", "flatpak "), None);
|
|
// The split point lands inside a multibyte character: no panic.
|
|
assert_eq!(strip_prefix_ascii_ci("aaa€€", "flatpak "), None);
|
|
assert_eq!(parse_natural("aaa€€ install x"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_flatpak_nix_and_snapshot_phrases() {
|
|
// Flatpak app ids are case-sensitive and must survive parsing.
|
|
assert_eq!(
|
|
parse_natural("flatpak install org.chromium.Chromium"),
|
|
Some(SystemAction::FlatpakInstall {
|
|
app_id: "org.chromium.Chromium".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("flatpak remove org.chromium.Chromium"),
|
|
Some(SystemAction::FlatpakRemove {
|
|
app_id: "org.chromium.Chromium".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("flatpak list"),
|
|
Some(SystemAction::FlatpakList)
|
|
);
|
|
assert_eq!(
|
|
parse_natural("nix prepare nodejs python312"),
|
|
Some(SystemAction::NixPrepare {
|
|
packages: vec!["nodejs".into(), "python312".into()]
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snapshot before update"),
|
|
Some(SystemAction::CreateSnapshot {
|
|
operation: "before update".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snapshot"),
|
|
Some(SystemAction::CreateSnapshot {
|
|
operation: "manual snapshot".into()
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_snap_phrases() {
|
|
assert_eq!(
|
|
parse_natural("snap install thunderbird"),
|
|
Some(SystemAction::SnapInstall {
|
|
name: "thunderbird".into(),
|
|
channel: None,
|
|
classic: false,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snap install code latest/stable"),
|
|
Some(SystemAction::SnapInstall {
|
|
name: "code".into(),
|
|
channel: Some("latest/stable".into()),
|
|
classic: false,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snap remove thunderbird"),
|
|
Some(SystemAction::SnapRemove {
|
|
name: "thunderbird".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snap find notes"),
|
|
Some(SystemAction::SnapFind {
|
|
query: "notes".into()
|
|
})
|
|
);
|
|
assert_eq!(parse_natural("snap list"), Some(SystemAction::SnapList));
|
|
assert_eq!(
|
|
parse_natural("snap refresh"),
|
|
Some(SystemAction::SnapRefresh { name: None })
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snap refresh thunderbird"),
|
|
Some(SystemAction::SnapRefresh {
|
|
name: Some("thunderbird".into())
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("snap connections thunderbird"),
|
|
Some(SystemAction::SnapConnections {
|
|
name: "thunderbird".into()
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_appimage_paths_keep_case() {
|
|
assert_eq!(
|
|
parse_natural("appimage import /home/u/MyTool.AppImage"),
|
|
Some(SystemAction::AppImageImport {
|
|
path: "/home/u/MyTool.AppImage".into(),
|
|
name: None,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("appimage list"),
|
|
Some(SystemAction::AppImageList)
|
|
);
|
|
assert_eq!(
|
|
parse_natural("appimage info mytool"),
|
|
Some(SystemAction::AppImageInfo {
|
|
name: "mytool".into()
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("appimage remove mytool"),
|
|
Some(SystemAction::AppImageRemove {
|
|
name: "mytool".into(),
|
|
purge_data: false,
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn natural_choose_phrase() {
|
|
assert_eq!(
|
|
parse_natural("choose firefox"),
|
|
Some(SystemAction::ChoosePackage {
|
|
name: "firefox".into(),
|
|
kind: None,
|
|
backend: None,
|
|
gui: false,
|
|
requires_sandbox: false,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("choose firefox via flatpak"),
|
|
Some(SystemAction::ChoosePackage {
|
|
name: "firefox".into(),
|
|
kind: None,
|
|
backend: Some(Backend::Flatpak),
|
|
gui: false,
|
|
requires_sandbox: false,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("choose spotify as a gui sandboxed app"),
|
|
Some(SystemAction::ChoosePackage {
|
|
name: "spotify".into(),
|
|
kind: None,
|
|
backend: None,
|
|
gui: true,
|
|
requires_sandbox: true,
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn new_actions_are_classified_and_validated() {
|
|
// Snap install is medium risk, mutating, and validates its operands.
|
|
let install = parse_action(
|
|
r#"{"action":"snap_install","name":"thunderbird","channel":"latest/stable"}"#,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(install.risk(), Risk::Medium);
|
|
assert!(install.is_mutating());
|
|
assert!(parse_action(r#"{"action":"snap_install","name":"Bad Name"}"#).is_err());
|
|
assert!(
|
|
parse_action(r#"{"action":"snap_install","name":"ok","channel":"--evil"}"#).is_err()
|
|
);
|
|
|
|
// AppImage acquisition requires a real pinned hash and an http(s) URL.
|
|
let acquire = parse_action(
|
|
r#"{"action":"appimage_acquire","name":"mytool","url":"https://example.org/mytool.AppImage","sha256":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}"#,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(acquire.risk(), Risk::Medium);
|
|
assert!(parse_action(
|
|
r#"{"action":"appimage_acquire","name":"mytool","url":"https://example.org/a","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}"#
|
|
)
|
|
.is_err());
|
|
assert!(parse_action(
|
|
r#"{"action":"appimage_acquire","name":"mytool","url":"ftp://x/a","sha256":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}"#
|
|
)
|
|
.is_err());
|
|
|
|
// Custom ebuild staging carries content and is a medium-risk mutation;
|
|
// installing it is high risk (it builds untrusted code).
|
|
let prepare = parse_action(
|
|
r#"{"action":"custom_ebuild_prepare","atom":"app-misc/example","version":"1.0","rationale":"no maintained package","ebuild":"EAPI=8\n"}"#,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(prepare.risk(), Risk::Medium);
|
|
let install = parse_action(
|
|
r#"{"action":"custom_ebuild_install","atom":"app-misc/example","version":"1.0","digest":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}"#,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(install.risk(), Risk::High);
|
|
assert!(install.is_mutating());
|
|
// Path traversal in an atom is refused.
|
|
assert!(parse_action(
|
|
r#"{"action":"custom_ebuild_prepare","atom":"../../etc/passwd","version":"1.0","rationale":"x","ebuild":"EAPI=8\n"}"#
|
|
)
|
|
.is_err());
|
|
|
|
// Read-only new actions.
|
|
for (json, expected) in [
|
|
(r#"{"action":"snap_list"}"#, SystemAction::SnapList),
|
|
(r#"{"action":"appimage_list"}"#, SystemAction::AppImageList),
|
|
(
|
|
r#"{"action":"custom_ebuild_list"}"#,
|
|
SystemAction::CustomEbuildList,
|
|
),
|
|
] {
|
|
let a = parse_action(json).unwrap();
|
|
assert_eq!(a, expected);
|
|
assert!(!a.is_mutating());
|
|
assert_eq!(a.risk(), Risk::Low);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn natural_preference_phrase() {
|
|
assert_eq!(
|
|
parse_natural("prefer firefox via flatpak"),
|
|
Some(SystemAction::SetPackagePreference {
|
|
name: "firefox".into(),
|
|
backend: Some(Backend::Flatpak),
|
|
system_wide: false,
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_natural("prefer firefox auto"),
|
|
Some(SystemAction::SetPackagePreference {
|
|
name: "firefox".into(),
|
|
backend: None,
|
|
system_wide: false,
|
|
})
|
|
);
|
|
let pref =
|
|
parse_action(r#"{"action":"set_package_preference","name":"firefox","backend":"nix"}"#)
|
|
.unwrap();
|
|
assert_eq!(pref.risk(), Risk::Medium);
|
|
assert!(pref.is_mutating());
|
|
// A personal preference needs no privilege; the system-wide variant does.
|
|
assert!(!pref.requires_root());
|
|
let system = parse_action(
|
|
r#"{"action":"set_package_preference","name":"firefox","backend":"nix","system_wide":true}"#,
|
|
)
|
|
.unwrap();
|
|
assert!(system.requires_root());
|
|
}
|
|
|
|
#[test]
|
|
fn selection_validators_are_strict() {
|
|
assert!(valid_snap_name("thunderbird"));
|
|
assert!(valid_snap_name("code-insiders"));
|
|
assert!(!valid_snap_name("Thunderbird"));
|
|
assert!(!valid_snap_name("-leading"));
|
|
assert!(!valid_snap_name("double--hyphen"));
|
|
assert!(!valid_snap_name(&"a".repeat(41)));
|
|
|
|
assert!(valid_snap_channel("latest/stable"));
|
|
assert!(valid_snap_channel("4.0/edge"));
|
|
assert!(!valid_snap_channel("--evil"));
|
|
|
|
assert!(valid_appimage_name("mytool"));
|
|
assert!(valid_appimage_name("My.Tool-2"));
|
|
assert!(!valid_appimage_name("../escape"));
|
|
assert!(!valid_appimage_name(".hidden"));
|
|
|
|
assert!(valid_http_url("https://example.org/a.AppImage"));
|
|
assert!(!valid_http_url("ftp://example.org/a"));
|
|
assert!(!valid_http_url("https://example.org/a b"));
|
|
|
|
assert!(valid_sha256(&"a".repeat(64)));
|
|
assert!(!valid_sha256(&"0".repeat(64)));
|
|
assert!(!valid_sha256("deadbeef"));
|
|
|
|
assert!(valid_ebuild_atom("app-misc/example"));
|
|
assert!(!valid_ebuild_atom("app-misc/example/extra"));
|
|
assert!(!valid_ebuild_atom("../etc/passwd"));
|
|
assert!(valid_ebuild_version("1.2.3-r1"));
|
|
assert!(!valid_ebuild_version("../1.0"));
|
|
}
|
|
}
|