WP-10: contract and failing tests for OS and package inventory
Some checks failed
CI / backend (push) Has been cancelled
CI / frontend (push) Has been cancelled
CI / ui (push) Has been cancelled

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Dennis Nemec
2026-09-02 22:19:25 +02:00
parent b6c3ddf040
commit 7b6d242988
21 changed files with 698 additions and 0 deletions

View File

@ -15,6 +15,8 @@ chrono.workspace = true
jsonwebtoken.workspace = true
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls", "hostname"] }
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
sqlx.workspace = true
uuid.workspace = true

View File

@ -0,0 +1,4 @@
CREATE TABLE inventory (
id INTEGER PRIMARY KEY CHECK (id = 1),
json TEXT NOT NULL
);

View File

@ -0,0 +1,43 @@
use async_trait::async_trait;
use domain::DomainError;
#[derive(Clone, Debug, Default)]
pub struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
#[async_trait]
pub trait CommandRunner: Send + Sync {
async fn run(&self, program: &str, args: &[&str]) -> Result<Output, DomainError>;
async fn read_file(&self, path: &str) -> Result<Option<String>, DomainError>;
}
pub struct SystemCommandRunner;
#[async_trait]
impl CommandRunner for SystemCommandRunner {
async fn run(&self, program: &str, args: &[&str]) -> Result<Output, DomainError> {
let out = tokio::process::Command::new(program)
.args(args)
.env("DEBIAN_FRONTEND", "noninteractive")
.env("LC_ALL", "C")
.output()
.await
.map_err(|e| DomainError::Unavailable(format!("{program}: {e}")))?;
Ok(Output {
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
success: out.status.success(),
})
}
async fn read_file(&self, path: &str) -> Result<Option<String>, DomainError> {
match tokio::fs::read_to_string(path).await {
Ok(s) => Ok(Some(s)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(DomainError::Unavailable(format!("{path}: {e}"))),
}
}
}

View File

@ -0,0 +1,165 @@
//! Inspector for Debian hosts using dpkg, apt-get and snap.
use std::sync::Arc;
use async_trait::async_trait;
use domain::host::{OsInfo, Package};
use domain::ports::HostInspector;
use domain::DomainError;
use super::command::CommandRunner;
pub struct DebianInspector {
runner: Arc<dyn CommandRunner>,
}
impl DebianInspector {
pub fn new(runner: Arc<dyn CommandRunner>) -> Self {
Self { runner }
}
}
#[async_trait]
impl HostInspector for DebianInspector {
async fn os_info(&self) -> Result<OsInfo, DomainError> {
todo!()
}
async fn packages(&self) -> Result<Vec<Package>, DomainError> {
todo!()
}
}
/// `dpkg-query -W -f '${Package}\t${Version}\t${Status}\n'` → (name, version) of installed packages.
pub fn parse_dpkg(_out: &str) -> Vec<(String, String)> {
todo!()
}
/// `apt-get -s upgrade` → (name, candidate version, is_security) for lines starting with `Inst`.
pub fn parse_apt_simulation(_out: &str) -> Vec<(String, String, bool)> {
todo!()
}
/// `snap list` → (name, version) skipping the header.
pub fn parse_snap_list(_out: &str) -> Vec<(String, String)> {
todo!()
}
/// `/etc/os-release` → (PRETTY_NAME, VERSION_ID).
pub fn parse_os_release(_content: &str) -> (String, String) {
todo!()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dpkg_keeps_only_installed() {
let out = "bash\t5.2.15-2+b7\tinstall ok installed\nold\t1.0\tdeinstall ok config-files\nzlib1g\t1:1.2.13.dfsg-1\tinstall ok installed\n";
assert_eq!(
parse_dpkg(out),
vec![
("bash".to_string(), "5.2.15-2+b7".to_string()),
("zlib1g".to_string(), "1:1.2.13.dfsg-1".to_string())
]
);
}
#[test]
fn apt_simulation_extracts_candidates_and_security_flag() {
let out = "Reading package lists...\nBuilding dependency tree...\n\
Inst openssl [3.0.15-1~deb12u1] (3.0.16-1~deb12u1 Debian-Security:12/stable-security [amd64])\n\
Inst curl [7.88.1-10+deb12u8] (7.88.1-10+deb12u12 Debian:12.9/stable [amd64]) []\n\
Conf openssl (3.0.16-1~deb12u1 Debian-Security:12/stable-security [amd64])\n";
assert_eq!(
parse_apt_simulation(out),
vec![
("openssl".to_string(), "3.0.16-1~deb12u1".to_string(), true),
("curl".to_string(), "7.88.1-10+deb12u12".to_string(), false)
]
);
}
#[test]
fn snap_list_skips_header() {
let out = "Name Version Rev Tracking Publisher Notes\ncore20 20260410 2866 latest/stable canonical** base\nmicrok8s v1.32.13 8702 1.32/stable canonical** classic\n";
assert_eq!(
parse_snap_list(out),
vec![
("core20".to_string(), "20260410".to_string()),
("microk8s".to_string(), "v1.32.13".to_string())
]
);
}
#[test]
fn os_release_strips_quotes() {
let c = "PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\nNAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12\"\n";
assert_eq!(
parse_os_release(c),
(
"Debian GNU/Linux 12 (bookworm)".to_string(),
"12".to_string()
)
);
}
struct Canned;
#[async_trait]
impl CommandRunner for Canned {
async fn run(
&self,
program: &str,
args: &[&str],
) -> Result<super::super::Output, DomainError> {
let stdout = match (program, args.first().copied()) {
("dpkg-query", _) => "bash\t5.2\tinstall ok installed\nopenssl\t3.0.15\tinstall ok installed\n",
("apt-get", Some("-s")) => "Inst openssl [3.0.15] (3.0.16 Debian-Security:12/stable-security [amd64])\n",
("apt-get", _) => "",
("snap", _) => "Name Version Rev Tracking Publisher Notes\nmicrok8s v1.32.13 8702 1.32/stable canonical** classic\n",
("uname", _) => "6.1.0-42-amd64\n",
("hostname", _) => "srv\n",
_ => "",
};
Ok(super::super::Output {
stdout: stdout.into(),
stderr: String::new(),
success: true,
})
}
async fn read_file(&self, path: &str) -> Result<Option<String>, DomainError> {
Ok(match path {
"/etc/os-release" => Some(
"PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\nVERSION_ID=\"12\"\n".into(),
),
"/proc/uptime" => Some("12345.67 40000.00\n".into()),
"/var/run/reboot-required" => Some(String::new()),
_ => None,
})
}
}
#[tokio::test]
async fn inspector_combines_sources() {
let i = DebianInspector::new(Arc::new(Canned));
let os = i.os_info().await.unwrap();
assert_eq!(os.hostname, "srv");
assert_eq!(os.version, "12");
assert_eq!(os.kernel, "6.1.0-42-amd64");
assert_eq!(os.uptime_secs, 12345);
assert!(os.reboot_required);
let pkgs = i.packages().await.unwrap();
assert_eq!(pkgs.len(), 3);
let openssl = pkgs.iter().find(|p| p.name == "openssl").unwrap();
assert_eq!(openssl.candidate.as_deref(), Some("3.0.16"));
assert!(openssl.is_security);
assert_eq!(
pkgs.iter().find(|p| p.name == "bash").unwrap().candidate,
None
);
assert_eq!(
pkgs.iter().find(|p| p.name == "microk8s").unwrap().source,
domain::host::PackageSource::Snap
);
}
}

View File

@ -0,0 +1,68 @@
//! Sample data for development machines without apt (FAKE_HOST=true).
use async_trait::async_trait;
use domain::host::{OsInfo, Package, PackageSource};
use domain::ports::HostInspector;
use domain::DomainError;
pub struct FakeHostInspector;
#[async_trait]
impl HostInspector for FakeHostInspector {
async fn os_info(&self) -> Result<OsInfo, DomainError> {
Ok(OsInfo {
hostname: "fake-host".into(),
name: "Debian GNU/Linux 12 (bookworm)".into(),
version: "12".into(),
kernel: "6.1.0-42-amd64".into(),
uptime_secs: 86400 * 3 + 3600,
reboot_required: true,
})
}
async fn packages(&self) -> Result<Vec<Package>, DomainError> {
let apt = |n: &str, i: &str, c: Option<&str>, s: bool| Package {
name: n.into(),
source: PackageSource::Apt,
installed: i.into(),
candidate: c.map(String::from),
is_security: s,
};
Ok(vec![
apt("bash", "5.2.15-2+b7", None, false),
apt(
"openssl",
"3.0.15-1~deb12u1",
Some("3.0.16-1~deb12u1"),
true,
),
apt(
"curl",
"7.88.1-10+deb12u8",
Some("7.88.1-10+deb12u12"),
false,
),
apt(
"libssl3",
"3.0.15-1~deb12u1",
Some("3.0.16-1~deb12u1"),
true,
),
apt("systemd", "252.36-1~deb12u1", None, false),
apt("openssh-server", "1:9.2p1-2+deb12u5", None, false),
Package {
name: "microk8s".into(),
source: PackageSource::Snap,
installed: "v1.32.13".into(),
candidate: None,
is_security: false,
},
Package {
name: "core20".into(),
source: PackageSource::Snap,
installed: "20260410".into(),
candidate: None,
is_security: false,
},
])
}
}

View File

@ -0,0 +1,8 @@
//! Host adapters: command execution, Debian inspector, fake inspector.
pub mod command;
pub mod debian;
pub mod fake;
pub use command::{CommandRunner, Output, SystemCommandRunner};
pub use debian::DebianInspector;
pub use fake::FakeHostInspector;

View File

@ -1,6 +1,7 @@
//! Infrastructure layer: SQLite repositories, Argon2 hashing, JWT issuing.
pub mod cipher;
pub mod db;
pub mod host;
pub mod mail;
pub mod password;
pub mod sqlite;
@ -8,7 +9,9 @@ pub mod token;
pub use cipher::AesGcmCipher;
pub use db::{connect, DbPool};
pub use host::{DebianInspector, FakeHostInspector, SystemCommandRunner};
pub use mail::LettreMailer;
pub use password::Argon2Hasher;
pub use sqlite::SqliteInventory;
pub use sqlite::{SqliteAuditLog, SqliteJobRuns, SqliteRefreshTokens, SqliteSettings, SqliteUsers};
pub use token::JwtIssuer;

View File

@ -461,3 +461,27 @@ mod job_tests {
assert_eq!(repo.list(10).await.unwrap().len(), 1);
}
}
pub struct SqliteInventory(pub DbPool);
#[async_trait]
impl domain::ports::InventoryRepository for SqliteInventory {
async fn save(&self, inventory: &domain::host::Inventory) -> Result<(), DomainError> {
let json =
serde_json::to_string(inventory).map_err(|e| DomainError::Storage(e.to_string()))?;
sqlx::query("INSERT INTO inventory (id, json) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json")
.bind(json)
.execute(&self.0)
.await
.map(|_| ())
.map_err(storage)
}
async fn load(&self) -> Result<Option<domain::host::Inventory>, DomainError> {
let json: Option<String> = sqlx::query_scalar("SELECT json FROM inventory WHERE id = 1")
.fetch_optional(&self.0)
.await
.map_err(storage)?;
json.map(|j| serde_json::from_str(&j).map_err(|e| DomainError::Storage(e.to_string())))
.transpose()
}
}