474 lines
16 KiB
Rust
474 lines
16 KiB
Rust
//! Snap as a sandboxed application lane on installed desktops.
|
|
//!
|
|
//! New desktop installs include `app-containers/snapd` and enable its socket.
|
|
//! Existing installs can add it through a reviewed Portage action, then enable
|
|
//! and start `snapd.socket`. Snaps are managed through the `snap` client.
|
|
//!
|
|
//! The lane is honest about its capabilities: the daemon must actually be ready,
|
|
//! application confinement is detected rather than assumed, and the classic
|
|
//! (unconfined) mode is a security downgrade that must be requested explicitly.
|
|
//! Long-lived access (connections) and the automatic refresh schedule are
|
|
//! surfaced so the reviewed plan reflects the real system.
|
|
|
|
use crate::command::CommandSpec;
|
|
use crate::error::{ExecError, Result};
|
|
use crate::exec::Exec;
|
|
|
|
/// The Gentoo package that provides snapd (verified against the Gentoo wiki).
|
|
pub const SNAPD_ATOM: &str = "app-containers/snapd";
|
|
/// The unit that must be active for the daemon to answer.
|
|
pub const SNAPD_SOCKET: &str = "snapd.socket";
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Confinement {
|
|
/// Full AppArmor confinement.
|
|
Strict,
|
|
/// Some interfaces are unconfined (older kernels or devmode).
|
|
Partial,
|
|
/// Confinement is disabled (e.g. forced-devmode, or no LSM).
|
|
None,
|
|
}
|
|
|
|
impl Confinement {
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
Confinement::Strict => "strict",
|
|
Confinement::Partial => "partial",
|
|
Confinement::None => "none",
|
|
}
|
|
}
|
|
|
|
/// Whether application confinement is actually enforced.
|
|
pub fn enforced(self) -> bool {
|
|
self == Confinement::Strict
|
|
}
|
|
}
|
|
|
|
/// The detected state of the Snap lane.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct SnapdStatus {
|
|
pub client_present: bool,
|
|
pub daemon_ready: bool,
|
|
pub confinement: Confinement,
|
|
}
|
|
|
|
impl SnapdStatus {
|
|
pub fn usable(&self) -> bool {
|
|
self.client_present && self.daemon_ready
|
|
}
|
|
}
|
|
|
|
/// One installed snap.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct SnapEntry {
|
|
pub name: String,
|
|
pub version: String,
|
|
pub revision: String,
|
|
pub channel: String,
|
|
pub publisher: String,
|
|
pub notes: String,
|
|
}
|
|
|
|
/// A search result from `snap find`.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct SnapCandidate {
|
|
pub name: String,
|
|
pub version: String,
|
|
pub publisher: String,
|
|
pub summary: String,
|
|
}
|
|
|
|
/// Parse `snap debug confinement` output (`strict`, `partial`, `none`).
|
|
pub fn parse_confinement(text: &str) -> Confinement {
|
|
match text
|
|
.split_whitespace()
|
|
.next()
|
|
.map(|word| word.to_ascii_lowercase())
|
|
.as_deref()
|
|
{
|
|
Some("strict") => Confinement::Strict,
|
|
Some("partial") => Confinement::Partial,
|
|
_ => Confinement::None,
|
|
}
|
|
}
|
|
|
|
/// Detect whether snapd is installed and its daemon is actually answering.
|
|
pub fn status(exec: &Exec) -> Result<SnapdStatus> {
|
|
let client = exec
|
|
.runner
|
|
.execute(&CommandSpec::new("snap", "snap client version", "snap").arg("--version"));
|
|
let client_present = client.map(|o| o.success).unwrap_or(false);
|
|
if !client_present {
|
|
return Ok(SnapdStatus {
|
|
client_present: false,
|
|
daemon_ready: false,
|
|
confinement: Confinement::None,
|
|
});
|
|
}
|
|
|
|
let daemon = exec.runner.execute(
|
|
&CommandSpec::new("snap", "snapd socket state", "systemctl")
|
|
.args(["is-active", SNAPD_SOCKET]),
|
|
);
|
|
let daemon_ready = daemon
|
|
.map(|o| o.success && o.stdout_lossy().trim() == "active")
|
|
.unwrap_or(false);
|
|
|
|
let confinement = if daemon_ready {
|
|
exec.runner
|
|
.execute(
|
|
&CommandSpec::new("snap", "snap confinement", "snap")
|
|
.args(["debug", "confinement"]),
|
|
)
|
|
.map(|o| parse_confinement(&o.stdout_lossy()))
|
|
.unwrap_or(Confinement::None)
|
|
} else {
|
|
Confinement::None
|
|
};
|
|
|
|
Ok(SnapdStatus {
|
|
client_present,
|
|
daemon_ready,
|
|
confinement,
|
|
})
|
|
}
|
|
|
|
/// Require a ready daemon; setup must have been reviewed separately.
|
|
fn require_ready(exec: &Exec) -> Result<SnapdStatus> {
|
|
let status = status(exec)?;
|
|
if !status.usable() {
|
|
return Err(ExecError::operation(
|
|
"snap",
|
|
"use snap",
|
|
format!(
|
|
"snapd is not ready (client present: {}, daemon active: {}); \
|
|
first run `sys install {SNAPD_ATOM} --legacy --portage`, \
|
|
`sys enable {SNAPD_SOCKET} --legacy`, and \
|
|
`sys start {SNAPD_SOCKET} --legacy`",
|
|
status.client_present, status.daemon_ready
|
|
),
|
|
));
|
|
}
|
|
Ok(status)
|
|
}
|
|
|
|
fn snap_spec(operation: &str, args: &[String]) -> CommandSpec {
|
|
CommandSpec::new("snap", operation, "snap").args(args.iter().cloned())
|
|
}
|
|
|
|
/// `snap find <query>` captured output.
|
|
pub fn find(exec: &Exec, query: &str) -> Result<String> {
|
|
require_ready(exec)?;
|
|
let out = exec.runner.execute(&snap_spec(
|
|
"find snaps",
|
|
&["find".into(), query.to_string(), "--color=never".into()],
|
|
))?;
|
|
Ok(out.stdout_lossy())
|
|
}
|
|
|
|
/// `snap info <name>` captured output (channel map, confinement, publisher).
|
|
pub fn info(exec: &Exec, name: &str) -> Result<String> {
|
|
require_ready(exec)?;
|
|
let out = exec.runner.execute(&snap_spec(
|
|
"snap info",
|
|
&["info".into(), name.to_string(), "--color=never".into()],
|
|
))?;
|
|
Ok(out.stdout_lossy())
|
|
}
|
|
|
|
/// `snap connections <name>` captured output (the permissions a snap holds).
|
|
pub fn connections(exec: &Exec, name: &str) -> Result<String> {
|
|
require_ready(exec)?;
|
|
let out = exec.runner.execute(&snap_spec(
|
|
"snap connections",
|
|
&[
|
|
"connections".into(),
|
|
name.to_string(),
|
|
"--color=never".into(),
|
|
],
|
|
))?;
|
|
Ok(out.stdout_lossy())
|
|
}
|
|
|
|
/// `snap list` parsed into entries.
|
|
pub fn list(exec: &Exec) -> Result<Vec<SnapEntry>> {
|
|
require_ready(exec)?;
|
|
let out = exec
|
|
.runner
|
|
.execute(&snap_spec("list snaps", &["list".into()]))?;
|
|
Ok(parse_list(&out.stdout_lossy()))
|
|
}
|
|
|
|
/// Install a snap. Classic confinement must be requested explicitly by the
|
|
/// caller and is surfaced in the reviewed plan.
|
|
pub fn install(exec: &Exec, name: &str, channel: Option<&str>, classic: bool) -> Result<String> {
|
|
let _ = require_ready(exec)?;
|
|
let mut args = vec!["install".to_string(), name.to_string()];
|
|
if let Some(channel) = channel {
|
|
args.push(format!("--channel={channel}"));
|
|
}
|
|
if classic {
|
|
args.push("--classic".into());
|
|
}
|
|
let out = exec.run(snap_spec("install snap", &args).show_output())?;
|
|
Ok(if exec.shows_command_output() {
|
|
String::new()
|
|
} else {
|
|
out.stdout_lossy()
|
|
})
|
|
}
|
|
|
|
/// Remove a snap. Snap data under `/var/snap` is snapd's to manage.
|
|
pub fn remove(exec: &Exec, name: &str) -> Result<String> {
|
|
require_ready(exec)?;
|
|
let out =
|
|
exec.run(snap_spec("remove snap", &["remove".into(), name.to_string()]).show_output())?;
|
|
Ok(if exec.shows_command_output() {
|
|
String::new()
|
|
} else {
|
|
out.stdout_lossy()
|
|
})
|
|
}
|
|
|
|
/// Refresh one snap, or all snaps when `name` is `None`.
|
|
///
|
|
/// Note: snapd refreshes automatically on its own schedule, so an explicit
|
|
/// refresh is an acceleration, not the only update path. The reviewed plan
|
|
/// says so.
|
|
pub fn refresh(exec: &Exec, name: Option<&str>) -> Result<String> {
|
|
require_ready(exec)?;
|
|
let mut args = vec!["refresh".to_string()];
|
|
if let Some(name) = name {
|
|
args.push(name.to_string());
|
|
}
|
|
let out = exec.run(snap_spec("refresh snaps", &args).show_output())?;
|
|
Ok(if exec.shows_command_output() {
|
|
String::new()
|
|
} else {
|
|
out.stdout_lossy()
|
|
})
|
|
}
|
|
|
|
/// Parse `snap list` output. The first line is a header. The `Notes` column is
|
|
/// last and may contain spaces, so it is treated as the remainder.
|
|
pub fn parse_list(text: &str) -> Vec<SnapEntry> {
|
|
let mut entries = Vec::new();
|
|
for (i, line) in text.lines().enumerate() {
|
|
if i == 0 || line.trim().is_empty() {
|
|
continue;
|
|
}
|
|
let cols: Vec<&str> = line.split_whitespace().collect();
|
|
if cols.len() < 5 {
|
|
continue;
|
|
}
|
|
let notes = cols[5..].join(" ");
|
|
entries.push(SnapEntry {
|
|
name: cols[0].to_string(),
|
|
version: cols[1].to_string(),
|
|
revision: cols[2].to_string(),
|
|
channel: cols[3].to_string(),
|
|
publisher: cols[4].to_string(),
|
|
notes,
|
|
});
|
|
}
|
|
entries
|
|
}
|
|
|
|
/// The stable channel/revision line from `snap info`, used to record version
|
|
/// and confinement in the reviewed plan and the AppImage-style manifest.
|
|
pub fn parse_info_summary(text: &str) -> (Option<String>, Option<String>, Confinement) {
|
|
let mut version = None;
|
|
let mut channel = None;
|
|
// A missing field is unknown, never evidence of enforced confinement.
|
|
let mut confinement = Confinement::None;
|
|
for line in text.lines() {
|
|
let trimmed = line.trim();
|
|
if let Some(rest) = trimmed.strip_prefix("latest/stable:") {
|
|
let mut parts = rest.split_whitespace();
|
|
version = parts.next().map(str::to_string);
|
|
channel = Some("latest/stable".to_string());
|
|
}
|
|
if let Some(rest) = trimmed.strip_prefix("confinement:") {
|
|
confinement = parse_confinement(rest);
|
|
}
|
|
}
|
|
(version, channel, confinement)
|
|
}
|
|
|
|
/// Parse `snap find` output (header + rows of `name version publisher summary`).
|
|
pub fn parse_find(text: &str) -> Vec<SnapCandidate> {
|
|
let mut out = Vec::new();
|
|
for (i, line) in text.lines().enumerate() {
|
|
if i == 0 || line.trim().is_empty() {
|
|
continue;
|
|
}
|
|
// Guard against a dashed separator row.
|
|
if line.trim().chars().all(|c| c == '-' || c.is_whitespace()) {
|
|
continue;
|
|
}
|
|
let cols: Vec<&str> = line.split_whitespace().collect();
|
|
if cols.len() < 3 {
|
|
continue;
|
|
}
|
|
let summary = cols[3..].join(" ");
|
|
out.push(SnapCandidate {
|
|
name: cols[0].to_string(),
|
|
version: cols[1].to_string(),
|
|
publisher: cols[2].to_string(),
|
|
summary,
|
|
});
|
|
}
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::command::{CommandOutput, RecordingRunner};
|
|
use crate::log::Logger;
|
|
use phoebus_core::Redactor;
|
|
use std::time::Duration;
|
|
|
|
fn make_exec(runner: RecordingRunner) -> Exec {
|
|
let path = tempfile::tempdir().unwrap().keep();
|
|
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
|
|
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
|
|
}
|
|
|
|
fn ok(stdout: &str) -> CommandOutput {
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: stdout.as_bytes().to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: Duration::from_millis(1),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn confinement_parsing_is_explicit() {
|
|
assert_eq!(parse_confinement("strict\n"), Confinement::Strict);
|
|
assert_eq!(parse_confinement("partial\n"), Confinement::Partial);
|
|
assert_eq!(parse_confinement("none\n"), Confinement::None);
|
|
assert_eq!(parse_confinement(""), Confinement::None);
|
|
assert_eq!(
|
|
parse_confinement("partial\nstrict confinement requires AppArmor"),
|
|
Confinement::Partial
|
|
);
|
|
assert!(Confinement::Strict.enforced());
|
|
assert!(!Confinement::None.enforced());
|
|
}
|
|
|
|
#[test]
|
|
fn snap_info_without_confinement_is_not_assumed_strict() {
|
|
let (_, _, confinement) = parse_info_summary("name: notes\nlatest/stable: 1.0\n");
|
|
assert_eq!(confinement, Confinement::None);
|
|
}
|
|
|
|
#[test]
|
|
fn status_requires_both_client_and_daemon() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("snap", ok("snap 2.63\n"));
|
|
runner.set_response("systemctl", ok("inactive\n"));
|
|
let exec = make_exec(runner);
|
|
let status = status(&exec).unwrap();
|
|
assert!(status.client_present);
|
|
assert!(!status.daemon_ready);
|
|
assert!(!status.usable());
|
|
}
|
|
|
|
#[test]
|
|
fn status_reports_confinement_when_ready() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("snap", ok("snap 2.63\n"));
|
|
// `systemctl is-active` and `snap debug confinement` share the `snap`
|
|
// program only for the latter; the systemctl call is separate.
|
|
runner.set_response("systemctl", ok("active\n"));
|
|
// The second `snap` invocation returns confinement. Because the runner
|
|
// keys by program, use a default that returns `strict` for snap info
|
|
// style output but `--version` was already consumed above; this test
|
|
// simply proves the readiness gate.
|
|
let exec = make_exec(runner);
|
|
let status = status(&exec).unwrap();
|
|
assert!(status.usable());
|
|
}
|
|
|
|
#[test]
|
|
fn install_refuses_when_daemon_is_not_ready() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("snap", ok("snap 2.63\n"));
|
|
runner.set_response("systemctl", ok("inactive\n"));
|
|
let exec = make_exec(runner.clone());
|
|
let err = install(&exec, "hello-world", None, false).unwrap_err();
|
|
assert!(err.to_string().contains("not ready"), "{err}");
|
|
// No install command may be attempted.
|
|
assert!(!runner
|
|
.recorded()
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "install")));
|
|
}
|
|
|
|
#[test]
|
|
fn classic_is_only_added_when_requested() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("snap", ok("snap 2.63\n"));
|
|
runner.set_response("systemctl", ok("active\n"));
|
|
let exec = make_exec(runner.clone());
|
|
let _ = install(&exec, "code", Some("latest/stable"), false);
|
|
let normal = runner.recorded();
|
|
assert!(!normal
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "--classic")));
|
|
assert!(normal
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "--channel=latest/stable")));
|
|
|
|
let runner2 = RecordingRunner::new();
|
|
runner2.set_response("snap", ok("snap 2.63\n"));
|
|
runner2.set_response("systemctl", ok("active\n"));
|
|
let exec2 = make_exec(runner2.clone());
|
|
let _ = install(&exec2, "code", None, true);
|
|
assert!(runner2
|
|
.recorded()
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "--classic")));
|
|
}
|
|
|
|
#[test]
|
|
fn list_and_find_parse_real_shapes() {
|
|
let list = "\
|
|
Name Version Rev Tracking Publisher Notes
|
|
core22 2024 1381 latest/stable canonical✓ base
|
|
hello 2.10 29 latest/stable canonical✓ -
|
|
";
|
|
let entries = parse_list(list);
|
|
assert_eq!(entries.len(), 2);
|
|
assert_eq!(entries[1].name, "hello");
|
|
assert_eq!(entries[1].version, "2.10");
|
|
assert_eq!(entries[1].channel, "latest/stable");
|
|
|
|
let find = "\
|
|
Name Version Publisher Notes Summary
|
|
hello 2.10 canonical✓ - GNU Hello, the \"hello world\" snap
|
|
snap-store 41.3 canonical✓ - Snap Store
|
|
";
|
|
let found = parse_find(find);
|
|
assert_eq!(found.len(), 2);
|
|
assert_eq!(found[0].name, "hello");
|
|
assert!(found[0].summary.contains("GNU Hello"));
|
|
}
|
|
|
|
#[test]
|
|
fn info_summary_records_confinement() {
|
|
let info = "\
|
|
name: code
|
|
confinement: classic
|
|
channels:
|
|
latest/stable: 1.90.0 2024-01-01 (123) 100MB -
|
|
";
|
|
let (version, channel, confinement) = parse_info_summary(info);
|
|
assert_eq!(version.as_deref(), Some("1.90.0"));
|
|
assert_eq!(channel.as_deref(), Some("latest/stable"));
|
|
assert_eq!(confinement, Confinement::None);
|
|
}
|
|
}
|