WP-10: contract and failing tests for OS and package inventory
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1
backend/Cargo.lock
generated
1
backend/Cargo.lock
generated
@ -989,6 +989,7 @@ dependencies = [
|
|||||||
"jsonwebtoken",
|
"jsonwebtoken",
|
||||||
"lettre",
|
"lettre",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"tokio",
|
"tokio",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
|||||||
58
backend/crates/api/tests/system.rs
Normal file
58
backend/crates/api/tests/system.rs
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
//! WP-10: /api/system/inventory
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use common::{get, post, test_app_with_admin};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
const ADMIN: &str = "admin@example.com";
|
||||||
|
const PW: &str = "admin-password-123";
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn inventory_is_empty_until_refreshed_and_then_lists_packages() {
|
||||||
|
let app = test_app_with_admin().await;
|
||||||
|
let token = common::login(&app, ADMIN, PW).await.access;
|
||||||
|
|
||||||
|
let res = get(&app, "/api/system/inventory", Some(&token)).await;
|
||||||
|
assert_eq!(res.status, StatusCode::OK);
|
||||||
|
assert!(res.json["refreshed_at"].is_null());
|
||||||
|
assert_eq!(res.json["packages"].as_array().unwrap().len(), 0);
|
||||||
|
|
||||||
|
let run = post(
|
||||||
|
&app,
|
||||||
|
"/api/jobs/run",
|
||||||
|
json!({"kind": "package_refresh"}),
|
||||||
|
Some(&token),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(run.status, StatusCode::ACCEPTED);
|
||||||
|
for _ in 0..50 {
|
||||||
|
let r = get(
|
||||||
|
&app,
|
||||||
|
&format!("/api/jobs/{}", run.json["id"].as_str().unwrap()),
|
||||||
|
Some(&token),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
if r.json["status"] != "running" {
|
||||||
|
assert_eq!(r.json["status"], "success", "{}", r.json["log"]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = get(&app, "/api/system/inventory", Some(&token)).await;
|
||||||
|
assert!(res.json["refreshed_at"].is_string());
|
||||||
|
assert_eq!(res.json["os"]["hostname"], "fake-host");
|
||||||
|
assert_eq!(res.json["os"]["reboot_required"], true);
|
||||||
|
let pkgs = res.json["packages"].as_array().unwrap();
|
||||||
|
assert!(pkgs.len() >= 5);
|
||||||
|
let openssl = pkgs.iter().find(|p| p["name"] == "openssl").unwrap();
|
||||||
|
assert_eq!(openssl["candidate"], "3.0.16-1~deb12u1");
|
||||||
|
assert_eq!(openssl["is_security"], true);
|
||||||
|
assert_eq!(res.json["summary"]["upgradable"], 3);
|
||||||
|
assert_eq!(res.json["summary"]["security"], 2);
|
||||||
|
assert_eq!(
|
||||||
|
get(&app, "/api/system/inventory", None).await.status,
|
||||||
|
StatusCode::UNAUTHORIZED
|
||||||
|
);
|
||||||
|
}
|
||||||
40
backend/crates/application/src/inventory_service.rs
Normal file
40
backend/crates/application/src/inventory_service.rs
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::host::Inventory;
|
||||||
|
use domain::ports::{HostInspector, InventoryRepository};
|
||||||
|
use domain::DomainError;
|
||||||
|
|
||||||
|
use crate::jobs::{JobHandler, JobLog};
|
||||||
|
|
||||||
|
pub struct InventoryService {
|
||||||
|
inspector: Arc<dyn HostInspector>,
|
||||||
|
repo: Arc<dyn InventoryRepository>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InventoryService {
|
||||||
|
pub fn new(inspector: Arc<dyn HostInspector>, repo: Arc<dyn InventoryRepository>) -> Self {
|
||||||
|
let _ = (&inspector, &repo);
|
||||||
|
Self { inspector, repo }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Query the host and persist a new snapshot.
|
||||||
|
pub async fn refresh(&self) -> Result<Inventory, DomainError> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Last persisted snapshot.
|
||||||
|
pub async fn current(&self) -> Result<Option<Inventory>, DomainError> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Job handler for `JobKind::PackageRefresh`.
|
||||||
|
pub struct PackageRefreshJob(pub Arc<InventoryService>);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl JobHandler for PackageRefreshJob {
|
||||||
|
async fn run(&self, _params: Option<String>, _log: &dyn JobLog) -> Result<(), String> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,11 +1,13 @@
|
|||||||
//! Application layer: use cases orchestrating the domain through its ports.
|
//! Application layer: use cases orchestrating the domain through its ports.
|
||||||
pub mod auth_service;
|
pub mod auth_service;
|
||||||
|
pub mod inventory_service;
|
||||||
pub mod jobs;
|
pub mod jobs;
|
||||||
pub mod scheduler;
|
pub mod scheduler;
|
||||||
pub mod settings_service;
|
pub mod settings_service;
|
||||||
pub mod user_service;
|
pub mod user_service;
|
||||||
|
|
||||||
pub use auth_service::AuthService;
|
pub use auth_service::AuthService;
|
||||||
|
pub use inventory_service::{InventoryService, PackageRefreshJob};
|
||||||
pub use jobs::{JobHandler, JobLog, JobRunner};
|
pub use jobs::{JobHandler, JobLog, JobRunner};
|
||||||
pub use settings_service::SettingsService;
|
pub use settings_service::SettingsService;
|
||||||
pub use user_service::UserService;
|
pub use user_service::UserService;
|
||||||
|
|||||||
@ -305,3 +305,66 @@ pub fn smtp() -> SmtpSettings {
|
|||||||
notify_to: vec!["ops@example.com".into()],
|
notify_to: vec!["ops@example.com".into()],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use domain::host::{Inventory, OsInfo, Package, PackageSource};
|
||||||
|
use domain::ports::{HostInspector, InventoryRepository};
|
||||||
|
|
||||||
|
pub struct FakeInspector {
|
||||||
|
pub fail: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl HostInspector for FakeInspector {
|
||||||
|
async fn os_info(&self) -> Result<OsInfo, DomainError> {
|
||||||
|
if self.fail {
|
||||||
|
return Err(DomainError::Unavailable("host down".into()));
|
||||||
|
}
|
||||||
|
Ok(OsInfo {
|
||||||
|
hostname: "srv".into(),
|
||||||
|
name: "Debian GNU/Linux 12 (bookworm)".into(),
|
||||||
|
version: "12".into(),
|
||||||
|
kernel: "6.1.0-42-amd64".into(),
|
||||||
|
uptime_secs: 3600,
|
||||||
|
reboot_required: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
async fn packages(&self) -> Result<Vec<Package>, DomainError> {
|
||||||
|
Ok(vec![
|
||||||
|
Package {
|
||||||
|
name: "bash".into(),
|
||||||
|
source: PackageSource::Apt,
|
||||||
|
installed: "5.2".into(),
|
||||||
|
candidate: None,
|
||||||
|
is_security: false,
|
||||||
|
},
|
||||||
|
Package {
|
||||||
|
name: "openssl".into(),
|
||||||
|
source: PackageSource::Apt,
|
||||||
|
installed: "3.0.1".into(),
|
||||||
|
candidate: Some("3.0.2".into()),
|
||||||
|
is_security: true,
|
||||||
|
},
|
||||||
|
Package {
|
||||||
|
name: "microk8s".into(),
|
||||||
|
source: PackageSource::Snap,
|
||||||
|
installed: "v1.32.13".into(),
|
||||||
|
candidate: None,
|
||||||
|
is_security: false,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct MemInventory(pub Mutex<Option<Inventory>>);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl InventoryRepository for MemInventory {
|
||||||
|
async fn save(&self, inventory: &Inventory) -> Result<(), DomainError> {
|
||||||
|
*self.0.lock().unwrap() = Some(inventory.clone());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn load(&self) -> Result<Option<Inventory>, DomainError> {
|
||||||
|
Ok(self.0.lock().unwrap().clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
67
backend/crates/application/src/tests/inventory_tests.rs
Normal file
67
backend/crates/application/src/tests/inventory_tests.rs
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::DomainError;
|
||||||
|
|
||||||
|
use crate::jobs::{JobHandler, JobLog};
|
||||||
|
use crate::test_fakes::{FakeInspector, MemInventory};
|
||||||
|
use crate::{InventoryService, PackageRefreshJob};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct VecLog(Mutex<Vec<String>>);
|
||||||
|
#[async_trait]
|
||||||
|
impl JobLog for VecLog {
|
||||||
|
async fn line(&self, text: &str) {
|
||||||
|
self.0.lock().unwrap().push(text.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn refresh_persists_snapshot_and_current_returns_it() {
|
||||||
|
let repo = Arc::new(MemInventory::default());
|
||||||
|
let svc = InventoryService::new(Arc::new(FakeInspector { fail: false }), repo.clone());
|
||||||
|
assert_eq!(svc.current().await.unwrap(), None);
|
||||||
|
let inv = svc.refresh().await.unwrap();
|
||||||
|
assert_eq!(inv.os.hostname, "srv");
|
||||||
|
assert_eq!(inv.packages.len(), 3);
|
||||||
|
assert_eq!(inv.upgradable(), 1);
|
||||||
|
assert_eq!(inv.security_upgrades(), 1);
|
||||||
|
assert_eq!(svc.current().await.unwrap(), Some(inv));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn refresh_failure_keeps_previous_snapshot() {
|
||||||
|
let repo = Arc::new(MemInventory::default());
|
||||||
|
let ok = InventoryService::new(Arc::new(FakeInspector { fail: false }), repo.clone());
|
||||||
|
let before = ok.refresh().await.unwrap();
|
||||||
|
let failing = InventoryService::new(Arc::new(FakeInspector { fail: true }), repo.clone());
|
||||||
|
assert!(matches!(
|
||||||
|
failing.refresh().await.unwrap_err(),
|
||||||
|
DomainError::Unavailable(_)
|
||||||
|
));
|
||||||
|
assert_eq!(failing.current().await.unwrap(), Some(before));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn job_handler_logs_summary_and_maps_errors() {
|
||||||
|
let repo = Arc::new(MemInventory::default());
|
||||||
|
let job = PackageRefreshJob(Arc::new(InventoryService::new(
|
||||||
|
Arc::new(FakeInspector { fail: false }),
|
||||||
|
repo.clone(),
|
||||||
|
)));
|
||||||
|
let log = VecLog::default();
|
||||||
|
job.run(None, &log).await.unwrap();
|
||||||
|
let lines = log.0.lock().unwrap().join("\n");
|
||||||
|
assert!(lines.contains("3 packages"), "{lines}");
|
||||||
|
assert!(lines.contains("1 upgradable"), "{lines}");
|
||||||
|
|
||||||
|
let job = PackageRefreshJob(Arc::new(InventoryService::new(
|
||||||
|
Arc::new(FakeInspector { fail: true }),
|
||||||
|
repo,
|
||||||
|
)));
|
||||||
|
assert!(job
|
||||||
|
.run(None, &VecLog::default())
|
||||||
|
.await
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("host down"));
|
||||||
|
}
|
||||||
@ -1,4 +1,5 @@
|
|||||||
mod auth_service_tests;
|
mod auth_service_tests;
|
||||||
|
mod inventory_tests;
|
||||||
mod jobs_tests;
|
mod jobs_tests;
|
||||||
mod scheduler_tests;
|
mod scheduler_tests;
|
||||||
mod settings_tests;
|
mod settings_tests;
|
||||||
|
|||||||
55
backend/crates/domain/src/host.rs
Normal file
55
backend/crates/domain/src/host.rs
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
//! Host inventory: operating system and installed packages.
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct OsInfo {
|
||||||
|
pub hostname: String,
|
||||||
|
pub name: String,
|
||||||
|
pub version: String,
|
||||||
|
pub kernel: String,
|
||||||
|
pub uptime_secs: u64,
|
||||||
|
pub reboot_required: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum PackageSource {
|
||||||
|
Apt,
|
||||||
|
Snap,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Package {
|
||||||
|
pub name: String,
|
||||||
|
pub source: PackageSource,
|
||||||
|
pub installed: String,
|
||||||
|
/// Newer version available, if any.
|
||||||
|
pub candidate: Option<String>,
|
||||||
|
pub is_security: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Package {
|
||||||
|
pub fn is_upgradable(&self) -> bool {
|
||||||
|
self.candidate.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Inventory {
|
||||||
|
pub os: OsInfo,
|
||||||
|
pub packages: Vec<Package>,
|
||||||
|
pub refreshed_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Inventory {
|
||||||
|
pub fn upgradable(&self) -> usize {
|
||||||
|
self.packages.iter().filter(|p| p.is_upgradable()).count()
|
||||||
|
}
|
||||||
|
pub fn security_upgrades(&self) -> usize {
|
||||||
|
self.packages
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.is_upgradable() && p.is_security)
|
||||||
|
.count()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,6 +2,7 @@
|
|||||||
//! layer depends on. No I/O here.
|
//! layer depends on. No I/O here.
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod host;
|
||||||
pub mod jobs;
|
pub mod jobs;
|
||||||
pub mod ports;
|
pub mod ports;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
|
|||||||
@ -3,6 +3,7 @@ use async_trait::async_trait;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::auth::{AccessClaims, AuthEvent, RefreshToken};
|
use crate::auth::{AccessClaims, AuthEvent, RefreshToken};
|
||||||
|
use crate::host::{Inventory, OsInfo, Package};
|
||||||
use crate::jobs::{JobKind, JobRun, JobStatus};
|
use crate::jobs::{JobKind, JobRun, JobStatus};
|
||||||
use crate::settings::SmtpSettings;
|
use crate::settings::SmtpSettings;
|
||||||
use crate::user::{User, UserUpdate};
|
use crate::user::{User, UserUpdate};
|
||||||
@ -76,3 +77,16 @@ pub trait JobRunRepository: Send + Sync {
|
|||||||
async fn find_running(&self, kind: JobKind) -> Result<Option<JobRun>, DomainError>;
|
async fn find_running(&self, kind: JobKind) -> Result<Option<JobRun>, DomainError>;
|
||||||
async fn last_finished(&self, kind: JobKind) -> Result<Option<JobRun>, DomainError>;
|
async fn last_finished(&self, kind: JobKind) -> Result<Option<JobRun>, DomainError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads the state of the Debian host.
|
||||||
|
#[async_trait]
|
||||||
|
pub trait HostInspector: Send + Sync {
|
||||||
|
async fn os_info(&self) -> Result<OsInfo, DomainError>;
|
||||||
|
async fn packages(&self) -> Result<Vec<Package>, DomainError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait InventoryRepository: Send + Sync {
|
||||||
|
async fn save(&self, inventory: &Inventory) -> Result<(), DomainError>;
|
||||||
|
async fn load(&self) -> Result<Option<Inventory>, DomainError>;
|
||||||
|
}
|
||||||
|
|||||||
@ -15,6 +15,8 @@ chrono.workspace = true
|
|||||||
jsonwebtoken.workspace = true
|
jsonwebtoken.workspace = true
|
||||||
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls", "hostname"] }
|
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls", "hostname"] }
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
sqlx.workspace = true
|
sqlx.workspace = true
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
|
|
||||||
|
|||||||
@ -0,0 +1,4 @@
|
|||||||
|
CREATE TABLE inventory (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
json TEXT NOT NULL
|
||||||
|
);
|
||||||
43
backend/crates/infrastructure/src/host/command.rs
Normal file
43
backend/crates/infrastructure/src/host/command.rs
Normal 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}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
165
backend/crates/infrastructure/src/host/debian.rs
Normal file
165
backend/crates/infrastructure/src/host/debian.rs
Normal 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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
68
backend/crates/infrastructure/src/host/fake.rs
Normal file
68
backend/crates/infrastructure/src/host/fake.rs
Normal 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,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
8
backend/crates/infrastructure/src/host/mod.rs
Normal file
8
backend/crates/infrastructure/src/host/mod.rs
Normal 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;
|
||||||
@ -1,6 +1,7 @@
|
|||||||
//! Infrastructure layer: SQLite repositories, Argon2 hashing, JWT issuing.
|
//! Infrastructure layer: SQLite repositories, Argon2 hashing, JWT issuing.
|
||||||
pub mod cipher;
|
pub mod cipher;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
|
pub mod host;
|
||||||
pub mod mail;
|
pub mod mail;
|
||||||
pub mod password;
|
pub mod password;
|
||||||
pub mod sqlite;
|
pub mod sqlite;
|
||||||
@ -8,7 +9,9 @@ pub mod token;
|
|||||||
|
|
||||||
pub use cipher::AesGcmCipher;
|
pub use cipher::AesGcmCipher;
|
||||||
pub use db::{connect, DbPool};
|
pub use db::{connect, DbPool};
|
||||||
|
pub use host::{DebianInspector, FakeHostInspector, SystemCommandRunner};
|
||||||
pub use mail::LettreMailer;
|
pub use mail::LettreMailer;
|
||||||
pub use password::Argon2Hasher;
|
pub use password::Argon2Hasher;
|
||||||
|
pub use sqlite::SqliteInventory;
|
||||||
pub use sqlite::{SqliteAuditLog, SqliteJobRuns, SqliteRefreshTokens, SqliteSettings, SqliteUsers};
|
pub use sqlite::{SqliteAuditLog, SqliteJobRuns, SqliteRefreshTokens, SqliteSettings, SqliteUsers};
|
||||||
pub use token::JwtIssuer;
|
pub use token::JwtIssuer;
|
||||||
|
|||||||
@ -461,3 +461,27 @@ mod job_tests {
|
|||||||
assert_eq!(repo.list(10).await.unwrap().len(), 1);
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
18
frontend/e2e/updates.spec.ts
Normal file
18
frontend/e2e/updates.spec.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { test, expect } from '@playwright/test'
|
||||||
|
|
||||||
|
test('updates page shows OS info and packages after a refresh', async ({ page }) => {
|
||||||
|
await page.goto('/login')
|
||||||
|
await page.getByLabel('Email').fill('admin@example.com')
|
||||||
|
await page.getByLabel('Password').fill('admin-password-123')
|
||||||
|
await page.getByRole('button', { name: 'Sign in' }).click()
|
||||||
|
await page.getByRole('link', { name: 'Updates' }).click()
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'Refresh inventory' }).click()
|
||||||
|
await expect(page.getByTestId('os-name')).toContainText('Debian', { timeout: 15_000 })
|
||||||
|
await expect(page.getByText('Reboot required')).toBeVisible()
|
||||||
|
await expect(page.getByTestId('summary-upgradable')).toContainText('3')
|
||||||
|
|
||||||
|
await page.getByLabel('Upgradable only').check()
|
||||||
|
await expect(page.getByRole('row', { name: /openssl/ })).toBeVisible()
|
||||||
|
await expect(page.getByRole('row', { name: /bash/ })).toHaveCount(0)
|
||||||
|
})
|
||||||
@ -67,3 +67,27 @@ export interface JobRun {
|
|||||||
log: string
|
log: string
|
||||||
triggered_by: string
|
triggered_by: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface OsInfo {
|
||||||
|
hostname: string
|
||||||
|
name: string
|
||||||
|
version: string
|
||||||
|
kernel: string
|
||||||
|
uptime_secs: number
|
||||||
|
reboot_required: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Package {
|
||||||
|
name: string
|
||||||
|
source: 'apt' | 'snap'
|
||||||
|
installed: string
|
||||||
|
candidate: string | null
|
||||||
|
is_security: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InventoryResponse {
|
||||||
|
refreshed_at: string | null
|
||||||
|
os: OsInfo | null
|
||||||
|
packages: Package[]
|
||||||
|
summary: { total: number; upgradable: number; security: number }
|
||||||
|
}
|
||||||
|
|||||||
37
frontend/src/components/PackageTable.test.ts
Normal file
37
frontend/src/components/PackageTable.test.ts
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import PackageTable from './PackageTable.vue'
|
||||||
|
import type { Package } from '../api/types'
|
||||||
|
|
||||||
|
const pkgs: Package[] = [
|
||||||
|
{ name: 'bash', source: 'apt', installed: '5.2', candidate: null, is_security: false },
|
||||||
|
{ name: 'openssl', source: 'apt', installed: '3.0.1', candidate: '3.0.2', is_security: true },
|
||||||
|
{ name: 'curl', source: 'apt', installed: '7.88', candidate: '7.89', is_security: false },
|
||||||
|
{ name: 'microk8s', source: 'snap', installed: 'v1.32', candidate: null, is_security: false },
|
||||||
|
]
|
||||||
|
|
||||||
|
const rows = (w: ReturnType<typeof mount>) => w.findAll('tbody tr').map((r) => r.text())
|
||||||
|
|
||||||
|
describe('PackageTable', () => {
|
||||||
|
it('lists all packages and marks upgradable ones', () => {
|
||||||
|
const w = mount(PackageTable, { props: { packages: pkgs } })
|
||||||
|
expect(rows(w)).toHaveLength(4)
|
||||||
|
expect(rows(w)[1]).toContain('3.0.2')
|
||||||
|
expect(rows(w)[1]).toContain('security')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters by search text and upgradable flag', async () => {
|
||||||
|
const w = mount(PackageTable, { props: { packages: pkgs } })
|
||||||
|
await w.find('input[name=search]').setValue('ssl')
|
||||||
|
expect(rows(w)).toHaveLength(1)
|
||||||
|
await w.find('input[name=search]').setValue('')
|
||||||
|
await w.find('input[name=upgradable]').setValue(true)
|
||||||
|
expect(rows(w).map((r) => r.split(' ')[0])).toEqual(['openssl', 'curl'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters by source', async () => {
|
||||||
|
const w = mount(PackageTable, { props: { packages: pkgs } })
|
||||||
|
await w.find('select[name=source]').setValue('snap')
|
||||||
|
expect(rows(w)).toHaveLength(1)
|
||||||
|
expect(rows(w)[0]).toContain('microk8s')
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user