Compare commits

..
Author SHA1 Message Date
kevin_janssen 6792b0dd11 Verify signed OPNsense kernel probes on the service account and retain exactly-once evidence
Rust development slice / linux (push) Waiting to run
2026-11-19 20:55:29 +01:00
kevin_janssen 2e060e9507 Plan an exact service-account OPNsense kernel probe through normal approval 2026-11-19 20:48:41 +01:00
kevin_janssen 71adc2adf6 Record live OPNsense enrollment, WireGuard handshakes and remaining job parity
Rust development slice / linux (push) Failing after 14s
2026-11-19 20:14:34 +01:00
kevin_janssen 8acbee6a60 Qualify FreeBSD kernel time and supervise bounded POSIX process groups natively 2026-11-19 20:14:34 +01:00
kevin_janssen 6bf6e2539c Exercise appliance secret projection, truncation and device-only UI states
Rust development slice / linux (push) Failing after 12s
2026-11-19 20:10:36 +01:00
kevin_janssen 50b1fa4033 Run bounded OPNsense inventory and durable mTLS heartbeats as separate FreeBSD services
Rust development slice / linux (push) Failing after 11s
2026-11-19 20:07:49 +01:00
kevin_janssen b7d9046996 Project native FreeBSD packages, interfaces, hardware and login observations 2026-11-19 20:06:56 +01:00
kevin_janssen d05caf6fd3 Allow OPNsense snapshots in the tenant-bound observations table 2026-11-19 19:54:55 +01:00
kevin_janssen 89a58c609c Accept separate OPNsense inventory and show VPN and PF observations in device details
Rust development slice / linux (push) Failing after 13s
2026-11-19 19:53:51 +01:00
kevin_janssen ac6f940e2e Record public RAM bar verification
Rust development slice / linux (push) Failing after 12s
2026-11-19 19:38:18 +01:00
kevin_janssen 577a6eea75 Clarify the free and used RAM bar in device inventory
Rust development slice / linux (push) Failing after 12s
2026-11-19 19:37:41 +01:00
kevin_janssen 58236bc8f0 Record public rollout of device purpose
Rust development slice / linux (push) Failing after 13s
2026-11-19 15:11:58 +01:00
kevin_janssen 2070ae95e7 Add editable purpose to device inventory
Rust development slice / linux (push) Failing after 13s
2026-11-19 15:07:26 +01:00
51 changed files with 2246 additions and 470 deletions
Generated
+20
View File
@@ -2187,6 +2187,7 @@ dependencies = [
"chrono",
"ed25519-dalek",
"hex",
"libc",
"openssl",
"prost",
"reqwest",
@@ -2285,6 +2286,25 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rmm-opnsense-jobs"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"ed25519-dalek",
"hex",
"libc",
"prost",
"rmm-agent-core",
"rmm-agent-linux",
"rmm-domain",
"rmm-protocol",
"rusqlite",
"serde_json",
"uuid",
]
[[package]]
name = "rmm-persistence"
version = "0.1.0"
+1 -1
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "2"
exclude = ["crates/oidc-auth"]
members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/update-history", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"]
members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/agent-opnsense-jobs", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/update-history", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"]
[workspace.package]
version = "0.1.0"
+5 -1
View File
@@ -12,7 +12,7 @@ Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` be
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät.
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Wie beim Speicherplatz zeigt ein Balken den belegten Anteil. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Im RAM-Balken ist der verfügbare Anteil (links) grün und der belegte Anteil grau. Die sichtbare Prozentangabe benennt den verfügbaren Anteil. Ohne gültiges Wertepaar erscheint kein Balken. Der Laufwerksbalken hebt weiterhin den belegten Anteil hervor. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Mit der ersten gültigen Inventarmeldung der authentisierten neuen Kopplung schließt der Server den Wechsel automatisch ab. Er sperrt die bisherige Geräteidentität und schaltet den Bestand in derselben Transaktion auf den Zielkunden um. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung.
@@ -20,8 +20,12 @@ Eine ausgeschiedene Installation kann nach Widerruf und persönlicher Bestätigu
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
Die Spalte **Zweck** und das Gerätedetail zeigen optionalen Freitext. Unter **Zweck bearbeiten** können Betreiber mit Inventarlese- und Geräteverwaltungsrecht für den betreffenden Kunden bis zu 500 Zeichen speichern oder den Text entfernen. Der Zweck gehört zum Gerät beim bisherigen Kunden und wird beim Kundenwechsel nicht übernommen. Die Änderung wird ohne den Text auditiert und erzeugt keinen Geräteauftrag.
## Vom Skript zum Ergebnis
**OPNsense-Testprofil:** Das Gerätegateway akzeptiert `opnsense.base/1` als eigene Inventarplattform. Im Gerätedetail erscheinen aktive PF-Filterregeln sowie getrennte Listen für konfigurierte VPNs und native Laufzeitbefunde. Fehlende Berechtigung bzw. ausgefallene Quellen sind kein Nachweis einer leeren Liste. Nur mit ausdrücklich eingerichteter Capability `opnsense.uname/1`, `run_script` und signiertem Abgleich kann die feste POSIX-Kernelabfrage auf dem Dienstkonto angefordert werden. Sie nutzt die reguläre persönliche Genehmigung und genau einen gebundenen Versuch. [OPNsense-Betrieb](deploy/opnsense/README.md)
| Schritt | Verhalten |
| --- | --- |
| Skript veröffentlichen | In der Bibliothek eines Kunden erhält ein Skript einen Namen, einen Interpreter, einen Standard-Ausführungskontext und eine unveränderliche Version. Eine Bearbeitung veröffentlicht eine weitere Version. |
+3
View File
@@ -31,3 +31,6 @@ openssl = { workspace = true, optional = true }
[target.'cfg(unix)'.dev-dependencies]
openssl.workspace = true
[target.'cfg(target_os = "freebsd")'.dependencies]
libc = "0.2"
+81
View File
@@ -0,0 +1,81 @@
//! Read-only FreeBSD kernel discipline for the signed reconciliation clock.
//! Never adjust the guest clock. No cached qualification across a failed read.
use crate::reconcile::{ClockReading, SyncClock};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, TimeDelta, Utc};
use std::{mem::MaybeUninit, time::Instant};
pub struct NativeClock {
origin: DateTime<Utc>,
monotonic: Instant,
}
impl Default for NativeClock {
fn default() -> Self {
Self {
origin: Utc::now(),
monotonic: Instant::now(),
}
}
}
impl NativeClock {
fn observation(&self) -> Result<(DateTime<Utc>, TimeDelta)> {
let start = Instant::now();
let mut raw = MaybeUninit::<libc::ntptimeval>::zeroed();
// SAFETY: the read-only syscall writes the platform's ntptimeval.
let result = unsafe { libc::ntp_gettime(raw.as_mut_ptr()) };
ensure!(result == libc::TIME_OK, "FREEBSD_CLOCK_UNQUALIFIED");
let sample = unsafe { raw.assume_init() };
let wall =
DateTime::from_timestamp(sample.time.tv_sec, u32::try_from(sample.time.tv_nsec)?)
.context("FREEBSD_CLOCK_INVALID")?;
let duration = TimeDelta::from_std(start.elapsed())?;
ensure!(
sample.time_state == libc::TIME_OK
&& (0..=5_000_000).contains(&sample.maxerror)
&& (0..=sample.maxerror).contains(&sample.esterror)
&& sample.time.tv_nsec < 1_000_000_000
&& duration <= TimeDelta::milliseconds(100)
&& ((wall - self.origin) - TimeDelta::from_std(self.monotonic.elapsed())?)
.num_milliseconds()
.unsigned_abs()
<= 5000,
"FREEBSD_CLOCK_UNQUALIFIED"
);
Ok((wall, TimeDelta::microseconds(sample.maxerror) + duration))
}
}
impl SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
Ok(self.observation()?.0)
}
fn reading(&self) -> Result<ClockReading> {
let (wall, error) = self.observation()?;
Ok(ClockReading {
own_wall: wall,
upper: wall + error,
})
}
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let (wall, error) = self.observation()?;
Ok((wall - error, wall + error))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore = "requires a FreeBSD guest synchronized by ntpd"]
fn native_bounds_and_monotonic_fence() -> Result<()> {
let mut clock = NativeClock::default();
let (low, high) = clock.bounds()?;
ensure!(low <= high && high - low <= TimeDelta::milliseconds(10200));
clock.origin += TimeDelta::minutes(1);
ensure!(clock.bounds().is_err());
Ok(())
}
}
+27 -53
View File
@@ -205,7 +205,6 @@ pub struct HelperSync<V = DefaultVerifier> {
born: DateTime<Utc>,
capture: Option<Capture>,
lease: Option<Lease>,
integrity: Option<crate::ledger::IntegrityMonitor>,
}
impl HelperSync<DefaultVerifier> {
/// No persisted ready bit can open a newly started helper.
@@ -223,7 +222,6 @@ impl<V: Ed25519Verifier> HelperSync<V> {
born: clock.now()?,
capture: None,
lease: None,
integrity: None,
})
}
/// Select exactly one protected helper execution identity, closing leases.
@@ -232,12 +230,6 @@ impl<V: Ed25519Verifier> HelperSync<V> {
self.identity = identity;
self
}
/// Use with one protected SQLite connection retained for this instance.
/// The native owner must run a full check before any new host effect.
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
self
}
pub fn close(&mut self) {
self.lease = None;
self.capture = None;
@@ -296,8 +288,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
ledger_fingerprint: lease.fingerprint.clone(),
captured_at: capture.captured_at,
};
let audit_history = self.integrity.is_none();
self.verify_no_start_anchor(db, guard, &anchor, clock, boot, audit_history)?;
self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?;
Ok(anchor)
}
/// Consume exactly the approved update attempt and delegate its ORIGINAL
@@ -398,9 +389,9 @@ impl<V: Ed25519Verifier> HelperSync<V> {
tx.commit()?;
return Ok(outcome);
}
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
let observation = guard.verify_no_dispatch(request, anchor)?;
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
ensure!(
!observation.intent_id.is_nil()
&& digest(&observation.intent_sha256)
@@ -430,7 +421,6 @@ impl<V: Ed25519Verifier> HelperSync<V> {
anchor: &NoStartAnchor,
clock: &impl Clock,
boot: &impl BootSource,
audit_history: bool,
) -> Result<DateTime<Utc>> {
guard.check(db)?;
let now = clock.now()?;
@@ -455,18 +445,15 @@ impl<V: Ed25519Verifier> HelperSync<V> {
&& ledger_fingerprint(db)? == anchor.ledger_fingerprint,
"DENIAL_HELPER_LINEAGE_CHANGED"
);
// Idle anchor capture checks the current signed head. The native
// executor audits the full history before execution, and abandonment
// always audits it under the same transaction before recording evidence.
if audit_history {
verify_checkpoint_repair_history_with(
db,
&self.binding,
None,
self.identity,
&self.verifier,
)?;
}
// Exact equality is deliberate: a first implementation refuses even
// legitimate intervening progress rather than inventing lineage links.
verify_checkpoint_repair_history_with(
db,
&self.binding,
None,
self.identity,
&self.verifier,
)?;
let (response, raw): (Vec<u8>, Vec<u8>) = db.query_row(
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
[anchor.decision_id.to_string()],
@@ -496,12 +483,8 @@ impl<V: Ed25519Verifier> HelperSync<V> {
&& decision.helper_journal_id == Some(anchor.journal_id)
&& decision.helper_checkpoint == anchor.checkpoint
&& decision.connection_generation == anchor.connection_generation
&& decision.request_hash == anchor.sync_request_sha256
&& capture.journal_id == anchor.journal_id
&& capture.checkpoint == anchor.checkpoint
&& capture.captured_at == anchor.captured_at
&& capture.boot_id == anchor.boot_id
&& capture.captured_at <= decision.issued_at
&& capture.captured_at <= now,
"DENIAL_CONFIRMED_READY_REQUIRED"
);
@@ -540,12 +523,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
);
let boot_id = boot.current_boot()?;
ensure!(!boot_id.is_nil(), "BOOT_ID_REQUIRED");
if let Some(integrity) = &mut self.integrity {
integrity.check(db, false, "ROOT_LEDGER_INTEGRITY")?;
initialize_schema(db, &self.binding)?;
} else {
initialize(db, &self.binding)?;
}
initialize(db, &self.binding)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let meta = metadata(&tx)?;
ensure!(meta.fault.is_none(), "HELPER_MANUAL_RECOVERY_REQUIRED");
@@ -1053,17 +1031,13 @@ struct Meta {
agent_checkpoint: u64,
}
fn initialize(db: &Connection, binding: &Binding) -> Result<()> {
crate::ledger::check_integrity(db, "ROOT_LEDGER_INTEGRITY")?;
initialize_schema(db, binding)
}
fn initialize_schema(db: &Connection, binding: &Binding) -> Result<()> {
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "ROOT_LEDGER_INTEGRITY");
db.execute_batch("PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS helper_sync_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,binding_sha256 TEXT NOT NULL,last_decision TEXT,fault TEXT,agent_journal_id TEXT,agent_checkpoint INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,fingerprint TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS helper_sync_captures(checkpoint INTEGER PRIMARY KEY,snapshot BLOB NOT NULL,fingerprint TEXT NOT NULL,captured_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS helper_sync_decisions_checkpoint ON helper_sync_decisions(checkpoint);")?;
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);")?;
let legacy_captures: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='helper_sync_captures')",
[], |row| row.get(0),
@@ -1201,23 +1175,23 @@ pub fn verify_checkpoint_repair_history_with(
) -> Result<()> {
let meta = metadata(db)?;
validate_history(db, binding, &meta, meta.generation, verifier)?;
let entry_count: u64 = db.query_row(
"SELECT count(*) FROM helper_sync_decisions",
[],
|row| row.get(0),
)?;
ensure!(entry_count <= 100000, "REPAIR_HISTORY_LIMIT");
let mut statement = db.prepare(
"SELECT response,request,checkpoint FROM helper_sync_decisions ORDER BY checkpoint",
)?;
let mut entries = statement.query([])?;
let entries = statement
.query_map([], |r| {
Ok((
r.get::<_, Vec<u8>>(0)?,
r.get::<_, Vec<u8>>(1)?,
r.get::<_, u64>(2)?,
))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
ensure!(entries.len() <= 100000, "REPAIR_HISTORY_LIMIT");
let mut previous = None;
let mut previous_checkpoint = 0;
let mut previous_agent_checkpoint = 0;
while let Some(entry) = entries.next()? {
let signed: Vec<u8> = entry.get(0)?;
let raw: Vec<u8> = entry.get(1)?;
let checkpoint: u64 = entry.get(2)?;
for (signed, raw, checkpoint) in entries {
let response: SignedResponse = serde_json::from_slice(&signed)?;
let parsed: ReconcileDecisionPayload = serde_json::from_slice(&response.decision_bytes)?;
let decision = verify(verifier, binding, &response, parsed.issued_at)?;
+3 -72
View File
@@ -7,8 +7,7 @@ use rmm_domain::{
jobs::hash,
reconciliation::{ReconciledOutcome, canonical_outcome_bytes},
};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use std::time::{Duration, Instant};
use rusqlite::{OptionalExtension, TransactionBehavior, params};
use uuid::Uuid;
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
@@ -30,48 +29,11 @@ pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
check_integrity(db, "JOURNAL_INTEGRITY")
}
pub fn check_integrity(db: &Connection, error_code: &'static str) -> Result<()> {
let check: String = db.query_row("PRAGMA integrity_check", [], |row| row.get(0))?;
ensure!(check == "ok", "{error_code}");
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
Ok(())
}
/// Full integrity scans for an owner holding one protected, long-lived SQLite
/// connection. External commits and schema changes require another scan even
/// when the interval has not elapsed. No cached result authorizes an effect.
#[derive(Default)]
pub(crate) struct IntegrityMonitor {
checked: Option<(u64, u64, Instant)>,
}
impl IntegrityMonitor {
pub(crate) fn check(
&mut self,
db: &Connection,
required: bool,
error_code: &'static str,
) -> Result<()> {
let data: u64 = db.query_row("PRAGMA data_version", [], |row| row.get(0))?;
let schema: u64 = db.query_row("PRAGMA schema_version", [], |row| row.get(0))?;
if !required
&& self.checked.is_some_and(|(previous_data, previous_schema, checked)| {
data == previous_data
&& schema == previous_schema
&& checked.elapsed() < Duration::from_secs(300)
})
{
return Ok(());
}
self.checked = None;
check_integrity(db, error_code)?;
self.checked = Some((data, schema, Instant::now()));
Ok(())
}
}
/// Before a human WebUI closure replaces the unresolved local outcome, keep the
/// exact original outcome bytes once. A differing second copy fails closed.
pub(crate) fn retain_closure_original(
@@ -417,34 +379,3 @@ pub fn start_witness_bytes(
"reauthentication_required":true,"postconditions_passed":false});
Ok(serde_json::to_vec(&evidence)?)
}
#[cfg(test)]
mod integrity_tests {
use super::*;
#[test]
fn idle_integrity_reuses_the_check_but_reaudits_external_changes_and_expiry() {
let path = std::env::temp_dir().join(format!("rmm-integrity-{}.sqlite", Uuid::new_v4()));
{
let db = Connection::open(&path).unwrap();
db.execute_batch("CREATE TABLE sample(id INTEGER PRIMARY KEY);").unwrap();
let mut monitor = IntegrityMonitor::default();
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
let first = monitor.checked.unwrap();
db.execute("INSERT INTO sample VALUES (1)", []).unwrap();
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
assert_eq!(monitor.checked, Some(first));
let peer = Connection::open(&path).unwrap();
peer.execute("INSERT INTO sample VALUES (2)", []).unwrap();
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
let changed = monitor.checked.unwrap();
assert_ne!(changed.0, first.0);
monitor.checked = Some((changed.0, changed.1, changed.2 - Duration::from_secs(300)));
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
assert!(monitor.checked.unwrap().2 >= changed.2);
}
std::fs::remove_file(path).unwrap();
}
}
+2
View File
@@ -5,6 +5,8 @@
pub mod auth;
pub mod customer_transfer;
pub mod crypto;
#[cfg(target_os = "freebsd")]
pub mod freebsd_clock;
pub mod helper_reconcile;
pub mod jobs;
pub mod ledger;
+3 -23
View File
@@ -101,7 +101,6 @@ pub struct ClientSync<V = DefaultVerifier> {
verifier: V,
helper_identity: HelperIdentity,
pending: Option<PreparedSync>,
integrity: Option<crate::ledger::IntegrityMonitor>,
channel: Option<Channel>,
gate: Option<Gate>,
}
@@ -118,7 +117,6 @@ impl<V: Ed25519Verifier> ClientSync<V> {
verifier,
helper_identity: HelperIdentity::Root,
pending: None,
integrity: None,
channel: None,
gate: None,
}
@@ -129,11 +127,6 @@ impl<V: Ed25519Verifier> ClientSync<V> {
self.helper_identity = identity;
self
}
/// Use with one protected SQLite connection retained for this instance.
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
self
}
/// Invoke on every authenticated/fenced ServerHello or transport loss.
pub fn close(&mut self) {
self.gate = None;
@@ -613,17 +606,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
"UNAUTHENTICATED_CHANNEL"
);
if let Some(integrity) = &mut self.integrity {
let work_pending: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))",
[],
|row| row.get(0),
)?;
integrity.check(db, work_pending, "JOURNAL_INTEGRITY")?;
initialize_schema(db)?;
} else {
initialize(db)?;
}
initialize(db)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let meta = metadata(&tx)?;
ensure!(meta.fault.is_none(), "SYNC_MANUAL_RECOVERY_REQUIRED");
@@ -1164,11 +1147,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
}
pub fn initialize(db: &Connection) -> Result<()> {
crate::ledger::check_integrity(db, "JOURNAL_INTEGRITY")?;
initialize_schema(db)
}
fn initialize_schema(db: &Connection) -> Result<()> {
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
db.execute_batch("PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS reconcile_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,high_sequence INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,last_decision TEXT,pending_request TEXT,helper_id TEXT,helper_checkpoint INTEGER NOT NULL DEFAULT 0,fault TEXT);
CREATE TABLE IF NOT EXISTS reconcile_requests(id TEXT PRIMARY KEY,request BLOB NOT NULL,envelope BLOB NOT NULL,generation INTEGER NOT NULL,response BLOB);
@@ -466,31 +466,6 @@ struct Fixture {
identity: HelperIdentity,
}
#[test]
fn idle_anchor_checks_the_head_but_abandonment_rejects_damaged_history() {
let (mut f, sync, _, request, mut guard) = denial_case();
let mut sync = sync.with_periodic_idle_integrity_checks();
f.clock.now += Duration::seconds(1);
let capture = f.snapshot(&mut sync, 7);
let raw = f.request(&capture);
let ready = f.decision(&capture, &raw, 7, true);
assert!(f.apply(&mut sync, &ready, &raw).unwrap().ready);
guard.intent_recorded_at = f.clock.now;
f.db.execute(
"UPDATE helper_sync_decisions SET response=X'00' WHERE checkpoint < ?1",
[capture.checkpoint],
).unwrap();
let anchor = sync.no_start_anchor(&f.db, &guard, 7, &f.clock, &f.boot).unwrap();
guard.anchor_sha256 = hash(&serde_json::to_vec(&anchor).unwrap());
let before = denial_ledger_bytes(&f.db);
assert!(
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.is_err()
);
assert_eq!(denial_ledger_bytes(&f.db), before);
}
#[test]
fn checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor() {
let mut f = Fixture::new();
+44 -1
View File
@@ -114,7 +114,7 @@ pub(crate) fn run_controlled(
let state = unsafe {
libc::waitid(
libc::P_PID,
child.id(),
child.id() as libc::id_t,
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
@@ -232,6 +232,7 @@ fn drain(
}
Ok(false)
}
#[cfg(not(target_os = "freebsd"))]
fn group_has_no_live_members(pgid: u32) -> bool {
let Ok(entries) = std::fs::read_dir("/proc") else {
return false;
@@ -265,6 +266,48 @@ fn group_has_no_live_members(pgid: u32) -> bool {
true
}
#[cfg(target_os = "freebsd")]
fn group_has_no_live_members(pgid: u32) -> bool {
// FreeBSD has no Linux /proc/<pid>/stat. Ask the kernel for this
// process group while its original leader's PID is still reserved.
use std::{mem, ptr};
let mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PGRP,
pgid as i32,
];
let mut size = 0;
let query = |out, n: &mut usize| unsafe {
libc::sysctl(mib.as_ptr(), mib.len() as _, out, n, ptr::null(), 0)
};
let unit = mem::size_of::<libc::kinfo_proc>();
if query(ptr::null_mut(), &mut size) != 0 || size == 0 || size > 16 * 1024 * 1024 {
return false;
}
let mut rows = vec![mem::MaybeUninit::<libc::kinfo_proc>::zeroed(); size.div_ceil(unit) + 1];
size = rows.len() * unit;
if query(rows.as_mut_ptr().cast(), &mut size) != 0
|| !size.is_multiple_of(unit)
|| size / unit > rows.len()
{
return false;
}
let mut leader = false;
for row in &rows[..size / unit] {
// A successful MIB read returned this complete aligned record.
let row = unsafe { row.assume_init_ref() };
if row.ki_structsize as usize != unit
|| row.ki_pgid != pgid as i32
|| row.ki_stat != libc::SZOMB
{
return false;
}
leader |= row.ki_pid == pgid as i32;
}
leader
}
#[cfg(test)]
mod tests {
use super::*;
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "rmm-opnsense-jobs"
version.workspace = true
edition.workspace = true
license.workspace = true
[target.'cfg(target_os = "freebsd")'.dependencies]
anyhow.workspace = true
chrono.workspace = true
hex.workspace = true
libc = "0.2"
prost.workspace = true
rmm-agent-core = { path = "../agent-core" }
rmm-agent-linux = { path = "../agent-linux" }
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
rusqlite.workspace = true
serde_json.workspace = true
uuid.workspace = true
[target.'cfg(target_os = "freebsd")'.dev-dependencies]
ed25519-dalek = "=2.2.0"
+11
View File
@@ -0,0 +1,11 @@
#[cfg(target_os = "freebsd")]
mod native;
#[cfg(target_os = "freebsd")]
fn main() -> anyhow::Result<()> {
native::main()
}
#[cfg(not(target_os = "freebsd"))]
fn main() {
eprintln!("FreeBSD required");
std::process::exit(1);
}
+398
View File
@@ -0,0 +1,398 @@
//! One worker per authenticated Python HTTPS channel, never a network listener.
//! Only the fixed unprivileged probe is executable. The shared Rust core owns
//! all approval/permit verification, receipt, consumption and sync transitions.
use anyhow::{Context, Result, bail, ensure};
use chrono::Utc;
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Outcome},
freebsd_clock::NativeClock,
jobs, ledger,
reconcile::{self, Channel, ClientSync, SyncClock},
};
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
use rmm_domain::jobs::{Action, JobPayload, hash};
use rmm_protocol::*;
use rusqlite::{Connection, params};
use std::{
env, fs,
io::{self, BufRead, Read, Write},
os::{
fd::AsRawFd,
unix::fs::{MetadataExt, OpenOptionsExt},
},
path::Path,
time::{Duration, Instant},
};
use uuid::Uuid;
#[cfg(test)]
mod tests;
fn supported(job: &JobPayload) -> bool {
job.execution_identity == "agent_service"
&& job.action.opnsense_kernel_probe()
&& job.max_runtime_seconds == 10
&& job.max_output_bytes == 1024
}
struct Worker {
binding: Binding,
channel: Channel,
sync: ClientSync,
clock: NativeClock,
db: Connection,
ledger: Connection,
sync_due: Instant,
permit_after: Instant,
}
impl Worker {
fn envelope(&self, payload: Payload) -> Result<Envelope> {
let seq = self.db.query_row(
"UPDATE counter SET seq=seq+1 WHERE id=1 RETURNING seq",
[],
|r| r.get(0),
)?;
Ok(Envelope {
protocol_major: 1,
message_id: Uuid::new_v4().to_string(),
agent_id: self.binding.agent_id.to_string(),
enrollment_generation: self.binding.enrollment_generation,
connection_generation: self.channel.connection_generation,
boot_id: self.channel.boot_id.to_string(),
sequence: seq,
observed_at: Utc::now().timestamp_millis(),
payload: Some(payload),
..Default::default()
})
}
fn result(&mut self, offer: &JobOffer, grant: &str, outcome: Outcome) -> Result<()> {
let mut e = self.envelope(Payload::JobResult(Default::default()))?;
let tx = self.db.transaction()?;
let rev = jobs::transition(&tx, offer, &outcome.state, grant)?;
e.payload = Some(Payload::JobResult(jobs::result(offer, rev, grant, outcome)));
jobs::event(&tx, &e)?;
tx.commit()?;
self.sync_due = Instant::now();
Ok(())
}
fn recover(&mut self) -> Result<()> {
for (offer, grant) in jobs::interrupted(&self.db, &self.ledger, &self.binding)? {
if grant.is_empty() {
jobs::interrupted_request(&self.db, &offer)?;
} else {
let saved =
jobs::recover_interrupted_outcome(&self.ledger, &self.binding, &offer, &grant)?;
self.result(
&offer,
&grant,
saved.unwrap_or_else(|| Outcome::unknown("AGENT_PROCESS_INTERRUPTED")),
)?;
}
}
Ok(())
}
fn next(&mut self) -> Result<Option<Envelope>> {
if let Some(mut e) = jobs::events(&self.db)?.into_iter().next() {
e.connection_generation = self.channel.connection_generation;
return Ok(Some(e));
}
// A refused or unqualified clock closes the effect gate, not telemetry.
if Instant::now() >= self.sync_due {
self.sync_due = Instant::now() + Duration::from_secs(40);
if self.clock.now().is_err() {
self.sync.close();
return Ok(None);
}
let p = self.sync.prepare(
&mut self.db,
&self.ledger,
self.channel.clone(),
None,
&self.clock,
)?;
return Ok(Some(p.envelope));
}
if self.sync.can_start(&self.channel, false, &self.clock)
&& Instant::now() >= self.permit_after
&& let Some(offer) = jobs::next(&self.db)?
{
let job = self.binding.job(&offer.payload_bytes)?;
if self.clock.now()? >= job.start_before {
self.result(
&offer,
"",
jobs::no_start("expired", "START_DEADLINE_EXPIRED"),
)?;
return self.next();
}
ensure!(supported(&job), "UNSUPPORTED_JOB");
jobs::reserve_request(&self.db, &offer)?;
return self
.envelope(Payload::ExecutionPermitRequest(ExecutionPermitRequest {
job_id: offer.job_id,
attempt_id: offer.attempt_id,
job_payload_hash: offer.job_payload_hash,
assignment_version: self.binding.assignment_version,
}))
.map(Some);
}
Ok(None)
}
fn receive(&mut self, e: Envelope) -> Result<()> {
ensure!(
valid_envelope(
&e,
&self.binding.agent_id.to_string(),
self.channel.connection_generation
) && e.enrollment_generation == self.binding.enrollment_generation,
"WRONG_CHANNEL"
);
match e.payload.context("EMPTY_REPLY")? {
Payload::Ack(a) => jobs::ack(&mut self.db, &a.message_id)?,
Payload::SyncResponse(s) => {
let applied = self.sync.apply(&mut self.db, &s, &self.clock)?;
ensure!(applied.helper_instruction.is_none(), "UNEXPECTED_HELPER");
self.sync.apply_consumption(&mut self.ledger, &self.clock)?;
}
Payload::JobOffer(o) => {
let receipt = self.envelope(Payload::JobAccepted(JobAccepted {
job_id: o.job_id.clone(),
attempt_id: o.attempt_id.clone(),
job_payload_hash: o.job_payload_hash.clone(),
journal_proof: hash(&o.encode_to_vec()),
}))?;
let tx = self.db.transaction()?;
let fresh = jobs::accept(&tx, &self.binding, &o, supported)?;
jobs::event(&tx, &receipt)?;
tx.commit()?;
if fresh {
self.sync_due = Instant::now();
}
}
Payload::ExecutionPermit(p) => self.permit(p)?,
Payload::CancelRequest(c) => {
let offer:Option<Vec<u8>>=rusqlite::OptionalExtension::optional(self.db.query_row(
"UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2 AND state='accepted' RETURNING offer",
params![c.job_id,c.attempt_id],|r|r.get(0)))?;
if let Some(bytes) = offer {
self.result(
&JobOffer::decode(bytes.as_slice())?,
"",
jobs::no_start("cancelled", "CANCELLED_BEFORE_START"),
)?;
}
}
_ => bail!("UNEXPECTED_JOB_MESSAGE"),
}
Ok(())
}
fn permit(&mut self, p: ExecutionPermit) -> Result<()> {
let offer = jobs::requesting(&self.db)?.context("UNSOLICITED_PERMIT")?;
if !p.denial_code.is_empty() {
jobs::denied_request(&self.db, &offer, &p)?;
self.sync.close();
self.sync_due = Instant::now();
self.permit_after = Instant::now() + Duration::from_secs(30);
return Ok(());
}
let req = jobs::permit_request(&offer, &p)?;
let verify = || -> Result<_> {
ensure!(
self.sync.can_start(&self.channel, false, &self.clock),
"SYNC_REQUIRED"
);
let (low, high) = self.clock.bounds()?;
self.binding.verify(&req, high)?;
self.binding.verify(&req, low)
};
// The signed not_before is the reservation instant. Wait within the
// qualified uncertainty interval before checking both ends at start.
let began = Instant::now();
let (job, grant) = loop {
match verify() {
Ok(x) => break x,
Err(err)
if err.to_string() == "PERMIT_TIME"
&& began.elapsed() < Duration::from_secs(6) =>
{
std::thread::sleep(Duration::from_millis(50));
}
Err(e) => return Err(e),
}
};
ensure!(supported(&job), "UNSUPPORTED_JOB");
let Action::RunScript { script_utf8, .. } = &job.action else {
bail!("SCRIPT_REQUIRED")
};
let script = ScriptRequest::new(
script_utf8.as_bytes().to_vec(),
Interpreter::PosixSh,
vec![],
Duration::from_secs(job.max_runtime_seconds.into()),
job.max_output_bytes as usize,
)?;
ledger::begin_execution(
&mut self.ledger,
&grant,
&req,
self.channel.boot_id,
self.clock.now()?,
)?;
let id = grant.grant_id.to_string();
let mut running = self.envelope(Payload::JobStateChanged(Default::default()))?;
let tx = self.db.transaction()?;
let revision = jobs::transition(&tx, &offer, "running", &id)?;
running.payload = Some(Payload::JobStateChanged(JobStateChanged {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
grant_id: id.clone(),
revision,
state: "running".into(),
}));
jobs::event(&tx, &running)?;
tx.commit()?;
let mut first = true;
let result = run_script_controlled(&script, || {
if first {
ensure!(
self.sync.can_start(&self.channel, false, &self.clock),
"SYNC_EXPIRED"
);
let (lo, hi) = self.clock.bounds()?;
self.binding.verify(&req, lo)?;
self.binding.verify(&req, hi)?;
first = false;
} else {
self.clock.now()?;
}
Ok(())
});
let outcome = match result {
Ok(o) => {
let ok = o.code == Some(0)
&& !o.timed_out
&& !o.interrupted
&& !o.truncated
&& o.stdout == b"FreeBSD\n";
Outcome {
state: if ok { "succeeded" } else { "failed" }.into(),
stdout: o.stdout,
stderr: o.stderr,
output_truncated: o.truncated,
reboot_required: false,
exit_code: o.code,
evidence: serde_json::json!({"postconditions_passed":ok,"effective_uid":unsafe{libc::geteuid()}}),
error_code: if ok { "" } else { "PROBE_POSTCONDITION_FAILED" }.into(),
}
}
Err(_) => Outcome::unknown("PROBE_EFFECT_UNCERTAIN"),
};
ledger::persist_outcome(&self.ledger, &grant, &outcome)?;
let saved = serde_json::to_vec(&outcome)?;
self.result(&offer, &id, outcome)?;
ledger::finish(&self.ledger, &grant, &serde_json::from_slice(&saved)?)?;
Ok(())
}
}
pub fn main() -> Result<()> {
let args = env::args().skip(1).collect::<Vec<_>>();
ensure!(args.len() == 4, "bound channel required");
let uid = unsafe { libc::geteuid() };
ensure!(
uid != 0 && uid == unsafe { libc::getuid() },
"SERVICE_ACCOUNT_REQUIRED"
);
unsafe { libc::umask(0o077) };
let state = Path::new("/var/db/discovery-agent");
let m = fs::symlink_metadata(state)?;
ensure!(
m.is_dir() && m.uid() == uid && m.mode() & 0o077 == 0,
"PRIVATE_STATE_REQUIRED"
);
let lock = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(state.join("job-worker.lock"))?;
ensure!(
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"ACTIVE_JOB_WORKER"
);
let config = Path::new("/usr/local/etc/discovery-agent/job-binding.json");
for path in [config.parent().unwrap(), config] {
let m = fs::symlink_metadata(path)?;
ensure!(
!m.is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0,
"PROTECTED_BINDING_REQUIRED"
);
}
let binding: Binding = serde_json::from_slice(&fs::read(config)?)?;
ensure!(
args[0] == binding.agent_id.to_string() && args[1] == binding.asset_id.to_string(),
"WRONG_DEVICE"
);
let channel = Channel {
boot_id: args[2].parse()?,
connection_generation: args[3].parse()?,
};
ensure!(
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
"CHANNEL_REQUIRED"
);
let db = Connection::open(state.join("channel.sqlite"))?;
ledger::bounded_journal_capacity(&db)?;
db.execute_batch("PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS counter(id INTEGER PRIMARY KEY CHECK(id=1),seq INTEGER NOT NULL);
INSERT OR IGNORE INTO counter SELECT id,n FROM sequence;
UPDATE counter SET seq=max(seq,(SELECT n FROM sequence WHERE id=1)) WHERE id=1;
CREATE TRIGGER IF NOT EXISTS telemetry_sequence AFTER UPDATE ON sequence WHEN NEW.n>(SELECT seq FROM counter WHERE id=1)
BEGIN UPDATE counter SET seq=NEW.n WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS job_sequence AFTER UPDATE ON counter WHEN NEW.seq>(SELECT n FROM sequence WHERE id=1)
BEGIN UPDATE sequence SET n=NEW.seq WHERE id=1; END;
CREATE TABLE IF NOT EXISTS job_attempts(job TEXT NOT NULL,attempt TEXT NOT NULL,offer BLOB NOT NULL,state TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,grant_id TEXT NOT NULL DEFAULT '',cancel_requested INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(job,attempt));
CREATE TABLE IF NOT EXISTS job_events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);")?;
reconcile::initialize(&db)?;
let ledger = Connection::open(state.join("consumption.sqlite"))?;
ledger::initialize_ledger(&ledger)?;
let mut w = Worker {
sync: ClientSync::new(binding.clone()),
binding,
db,
ledger,
channel,
clock: NativeClock::default(),
sync_due: Instant::now(),
permit_after: Instant::now(),
};
w.recover()?;
let mut input = io::stdin().lock();
println!("ready");
io::stdout().flush()?;
loop {
let mut line = String::new();
let n = (&mut input).take(2_100_000).read_line(&mut line)?;
if n == 0 {
return Ok(());
}
ensure!(line.ends_with('\n'), "FRAME_LIMIT");
let line = line.trim_end();
if line == "next" {
println!(
"{}",
w.next()?
.map(|e| hex::encode(e.encode_to_vec()))
.unwrap_or_default()
);
} else {
let data = hex::decode(line)?;
w.receive(Envelope::decode(data.as_slice())?)?;
println!("ok");
}
io::stdout().flush()?;
}
}
@@ -0,0 +1,139 @@
use super::*;
use chrono::TimeDelta;
use ed25519_dalek::{Signer, SigningKey};
use serde_json::json;
/// Completely isolated identity, signing key, journal and grant. Never contacts
/// the gateway or reads a device key; run the fixture under the guest service uid.
#[test]
fn native_probe_requires_signature_and_redelivery_does_not_rerun() -> Result<()> {
ensure!(
unsafe { libc::geteuid() } != 0,
"run as unprivileged test account"
);
let key = SigningKey::from_bytes(&[31; 32]);
let public = key.verifying_key().to_bytes();
let b = Binding {
tenant_id: Uuid::new_v4(),
asset_id: Uuid::new_v4(),
agent_id: Uuid::new_v4(),
assignment_version: 1,
enrollment_generation: 1,
public_key_hex: hex::encode(public),
};
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE counter(id INTEGER PRIMARY KEY,seq INTEGER);INSERT INTO counter VALUES(1,0);
CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,revision INTEGER DEFAULT 0,grant_id TEXT DEFAULT '',cancel_requested INTEGER DEFAULT 0,PRIMARY KEY(job,attempt));
CREATE TABLE job_events(id TEXT PRIMARY KEY,payload BLOB);")?;
reconcile::initialize(&db)?;
let ledger = Connection::open_in_memory()?;
ledger::initialize_ledger(&ledger)?;
let mut w = Worker {
channel: Channel {
boot_id: Uuid::new_v4(),
connection_generation: 2,
},
sync: ClientSync::new(b.clone()),
binding: b.clone(),
db,
ledger,
sync_due: Instant::now(),
permit_after: Instant::now(),
clock: NativeClock::default(),
};
let now = w.clock.now()?;
let job = JobPayload {
schema_version: 1,
tenant_id: b.tenant_id,
asset_id: b.asset_id,
agent_id: b.agent_id,
enrollment_generation: 1,
assignment_version: 1,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
execution_identity: "agent_service".into(),
max_runtime_seconds: 10,
max_output_bytes: 1024,
not_before: now - TimeDelta::minutes(1),
start_before: now + TimeDelta::minutes(2),
action: Action::RunScript {
script_utf8: "uname -s\n".into(),
expected_stdout: Some("FreeBSD\n".into()),
arguments: vec![],
interpreter: "posix_sh".into(),
windows_execution_profile: None,
privileged_script_profile: None,
},
};
let bytes = serde_json::to_vec(&job)?;
let offer = JobOffer {
job_id: job.job_id.to_string(),
attempt_id: job.attempt_id.to_string(),
plan_hash: hash(b"fixture"),
authorization_id: Uuid::new_v4().to_string(),
job_payload_hash: hash(&bytes),
payload_bytes: bytes,
};
w.receive(w.envelope(Payload::JobOffer(offer.clone()))?)?;
let event = w.next()?.unwrap();
ensure!(matches!(event.payload, Some(Payload::JobAccepted(_))));
jobs::ack(&mut w.db, &event.message_id)?;
let Some(Payload::SyncRequest(r)) = w.next()?.unwrap().payload else {
bail!("expected signed sync")
};
let decision = json!({"domain":"rmm.reconciliation-decision","schema_version":1,"decision_id":Uuid::new_v4(),
"request_id":r.request_id,"request_hash":hash(&r.encode_to_vec()),"tenant_id":b.tenant_id,
"asset_id":b.asset_id,"agent_id":b.agent_id,"enrollment_generation":1,"assignment_version":1,
"connection_generation":2,"boot_id":w.channel.boot_id,"journal_id":r.journal_id,"checkpoint":r.checkpoint,
"helper_journal_id":null,"helper_checkpoint":0,"issued_at":now-TimeDelta::seconds(1),"valid_until":now+TimeDelta::seconds(59),
"ready":true,"helper_ready":false,"reason":"CONSISTENT","key_id":hash(&public),"acknowledged_message_ids":[],
"attempts":[{"job_id":job.job_id,"attempt_id":job.attempt_id,"job_payload_hash":offer.job_payload_hash,
"action":"run_script","execution_identity":"agent_service","revision":0,"outcome_state":"accepted","outcome_bytes":[],
"unlock":false,"reason":"ACCEPTED_NOT_STARTED"}]});
let raw = serde_json::to_vec(&decision)?;
w.receive(w.envelope(Payload::SyncResponse(SyncResponse {
signature: key.sign(&raw).to_bytes().to_vec(),
decision_bytes: raw,
}))?)?;
ensure!(matches!(
w.next()?.unwrap().payload,
Some(Payload::ExecutionPermitRequest(_))
));
let raw = serde_json::to_vec(
&json!({"domain":"rmm.execution-permit","schema_version":1,"grant_id":Uuid::new_v4(),
"authorization_id":offer.authorization_id,"tenant_id":b.tenant_id,"asset_id":b.asset_id,"agent_id":b.agent_id,
"enrollment_generation":1,"assignment_version":1,"job_id":job.job_id,"attempt_id":job.attempt_id,
"plan_hash":offer.plan_hash,"job_payload_hash":offer.job_payload_hash,"action":"run_script",
"execution_identity":"agent_service","not_before":now-TimeDelta::seconds(6),"start_before":now+TimeDelta::seconds(50),
"max_runtime_seconds":10,"key_id":hash(&public)}),
)?;
let permit = ExecutionPermit {
signature: key.sign(&raw).to_bytes().to_vec(),
payload_bytes: raw,
..Default::default()
};
let mut invalid = permit.clone();
invalid.signature[0] ^= 1;
ensure!(w.permit(invalid).is_err());
let count =
|db: &Connection| db.query_row("SELECT count(*) FROM consumed", [], |r| r.get::<_, i64>(0));
ensure!(count(&w.ledger)? == 0);
w.permit(permit.clone())?;
w.receive(w.envelope(Payload::JobOffer(offer))?)?;
ensure!(w.permit(permit).is_err() && count(&w.ledger)? == 1);
let results = jobs::events(&w.db)?
.into_iter()
.filter_map(|e| match e.payload {
Some(Payload::JobResult(r)) => Some(r),
_ => None,
})
.collect::<Vec<_>>();
ensure!(
results.len() == 1
&& results[0].state == "succeeded"
&& results[0].exit_code == Some(0)
&& results[0].stdout == b"FreeBSD\n",
"native output mismatch"
);
Ok(())
}
+12 -23
View File
@@ -903,6 +903,9 @@ impl SystemHelper {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
let boot = WindowsBoot::capture()?;
let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock)
.ok()
.map(|s| s.with_helper_identity(HelperIdentity::System));
Ok(Self {
settings,
pin,
@@ -911,8 +914,7 @@ impl SystemHelper {
db,
clock,
boot,
// The initial connection creates the reconciler using its own qualified time.
sync: None,
sync,
last_diagnostic: None,
last_apply_diagnostic: None,
unsettled_msi: None,
@@ -1006,17 +1008,14 @@ impl SystemHelper {
}
fn sync(&mut self) -> Result<&mut HelperSync<DalekVerifier>> {
if self.sync.is_none() {
let sync = HelperSync::with_verifier(
self.settings.binding.clone(),
DalekVerifier,
&self.clock,
)?
.with_helper_identity(HelperIdentity::System);
self.sync = Some(if self.settings.managed_scripts() {
sync.with_periodic_idle_integrity_checks()
} else {
sync
});
self.sync = Some(
HelperSync::with_verifier(
self.settings.binding.clone(),
DalekVerifier,
&self.clock,
)?
.with_helper_identity(HelperIdentity::System),
);
}
self.sync.as_mut().context("SYSTEM_SYNC_CLOSED")
}
@@ -1291,16 +1290,6 @@ impl SystemHelper {
}
ensure!(self.settings.enable_effects, "SYSTEM_EFFECTS_DISABLED");
verified_window(&self.settings.binding, request, &self.clock)?;
if self.settings.managed_scripts() {
ledger::check_integrity(&self.db, "ROOT_LEDGER_INTEGRITY")?;
rmm_agent_core::helper_reconcile::verify_checkpoint_repair_history_with(
&self.db,
&self.settings.binding,
None,
HelperIdentity::System,
&DalekVerifier,
)?;
}
self.sync()?;
ensure!(
self.sync.as_ref().unwrap().can_start(
+6 -31
View File
@@ -1291,8 +1291,8 @@ impl Agent {
&& !self.helper_apply_unconfirmed
&& !self.prepared
&& self.running.is_none()
&& self.helper_probe_at.elapsed() >= Duration::from_secs(30)
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
&& self.helper_probe_at.elapsed() >= Duration::from_secs(30)
{
let agent = self.identity.agent_id.clone();
let asset = self.identity.asset_id.clone();
@@ -2663,9 +2663,8 @@ impl Agent {
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_secs(30);
let active_tick = Duration::from_millis(20);
let idle_tick = Duration::from_millis(250);
let mut next_tick = tokio::time::Instant::now();
let mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut readiness_at = Instant::now() - Duration::from_secs(5);
#[cfg(feature = "system-helper")]
let mut update_control_at = Instant::now() - Duration::from_secs(2);
@@ -2676,19 +2675,9 @@ impl Agent {
running.cancel.store(true, Ordering::SeqCst);
}
}
let control_pending = self.running.is_some()
|| self.prepared
|| self.deferred_sync.is_some()
|| self.deferred_permit.is_some()
|| self.helper_control_pending();
#[cfg(feature = "system-helper")]
let control_pending = control_pending || self.helper_probe.is_some();
let cadence = if control_pending { active_tick } else { idle_tick };
next_tick = next_tick.min(tokio::time::Instant::now() + cadence);
tokio::select! {
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
_=tokio::time::sleep_until(next_tick)=>{
next_tick = tokio::time::Instant::now() + cadence;
_=tick.tick()=>{
if !stop.load(Ordering::SeqCst) && self.poll_sync_apply(generation,true).is_err(){self.close_gate();needs_sync=true;}
#[cfg(feature = "system-helper")]
if !stop.load(Ordering::SeqCst) && self.poll_helper(&channel,generation).await.is_err() {self.close_gate();needs_sync=self.sync.is_some();}
@@ -2720,9 +2709,7 @@ impl Agent {
if self.sync.is_some() && !self.prepared && !self.helper_control_busy_for_sync() && rmm_agent_windows::job_readiness::refresh_due(needs_sync,sync_at.elapsed(),self.sync.as_ref().and_then(|s|s.validity_deadline()),self.clock.reading().ok().map(|r|r.upper)) {
if self.start_sync(&channel,generation).await.is_err(){self.close_gate();needs_sync=true;}else{needs_sync=false;}sync_at=Instant::now();
}
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.config.enable_jobs
&& self.journal.connection().prepare_cached("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state='accepted' AND cancel_requested=0)")?.query_row([], |row| row.get::<_, bool>(0))?
&& self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
// A transiently stale clock skips this tick; it must not end the session.
if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
@@ -3091,19 +3078,7 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
ensure!(rmm_agent_windows::echo_probe::protected_scope()? == *scope, "WINDOWS_ECHO_CONFIGURATION_CHANGED");
}
}
let sync = if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {
binding.clone().map(|binding| {
let sync = reconcile::ClientSync::new(binding)
.with_helper_identity(reconcile::HelperIdentity::System);
if config.localservice_time_policy.is_some() {
sync.with_periodic_idle_integrity_checks()
} else {
sync
}
})
} else {
None
};
let sync=if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
config,
+4
View File
@@ -1,4 +1,5 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
mod opnsense;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -64,6 +65,9 @@ pub fn validate_for_scope(
now: DateTime<Utc>,
scope: &str,
) -> Result<Value, &'static str> {
if scope == "opnsense.base" {
return opnsense::validate(bytes);
}
if scope == "agent.update" {
if bytes.len() > 65536 {
return Err("AGENT_UPDATE_INVENTORY_SIZE");
@@ -0,0 +1,107 @@
//! Allowlisted wire document. No appliance configuration or VPN secrets on the wire.
use serde::Deserialize;
use serde_json::Value;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Snapshot {
os: String,
hostname: String,
architecture: String,
root_total_bytes: u64,
root_available_bytes: u64,
cpu_model: String,
logical_processors: u32,
memory_total_bytes: u64,
firewall: Rows,
vpn_configured: Rows,
wireguard: Rows,
openvpn: Rows,
ipsec: Rows,
hardware: Option<Hardware>,
software: Option<Records<Software>>,
interfaces: Option<Records<Interface>>,
users: Option<Rows>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Hardware {
device_type: String,
booted_at: chrono::DateTime<chrono::Utc>,
manufacturer: Option<String>,
bios_serial_number: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Records<T> { status: String, entries: Vec<T> }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Software { name: String, version: String }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Interface { name: String, mac: Option<String>, addresses: Vec<String> }
impl<T> Records<T> {
fn valid(&self, limit: usize, check: impl Fn(&T) -> bool) -> bool {
matches!(self.status.as_str(),"ok"|"partial"|"unavailable")
&& (self.status != "unavailable" || self.entries.is_empty())
&& self.entries.len() <= limit && self.entries.iter().all(check)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Rows {
status: String,
entries: Vec<String>,
}
impl Rows {
fn valid(&self) -> bool {
matches!(self.status.as_str(), "ok" | "partial" | "unavailable")
&& (self.status != "unavailable" || self.entries.is_empty())
&& self.entries.len() <= 128
&& self.entries.iter().all(|s| clean(s, 512))
}
}
fn clean(s: &str, limit: usize) -> bool {
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
}
pub(super) fn validate(bytes: &[u8]) -> Result<Value, &'static str> {
let err = "INVALID_OPNSENSE_INVENTORY";
if bytes.len() > 384 * 1024 { return Err(err); }
let s: Snapshot = serde_json::from_slice(bytes).map_err(|_| err)?;
if !s.os.starts_with("OPNsense ") || !clean(&s.os, 128)
|| !clean(&s.hostname, 255) || s.architecture != "amd64"
|| s.root_total_bytes == 0 || s.root_available_bytes > s.root_total_bytes
|| !clean(&s.cpu_model, 256) || s.logical_processors == 0 || s.memory_total_bytes == 0
|| ![&s.firewall,&s.vpn_configured,&s.wireguard,&s.openvpn,&s.ipsec].iter().all(|r| r.valid())
|| s.users.is_some_and(|r| !r.valid())
|| s.hardware.is_some_and(|h| !matches!(h.device_type.as_str(),"physical"|"virtual")
|| h.booted_at.timestamp() < 0
|| [h.manufacturer,h.bios_serial_number].into_iter().flatten().any(|v| !clean(&v,256)))
|| s.software.is_some_and(|r| !r.valid(1024, |p| clean(&p.name,256) && clean(&p.version,256)))
|| s.interfaces.is_some_and(|r| !r.valid(128, |i| clean(&i.name,128)
&& i.mac.as_ref().is_none_or(|m| clean(m,64)) && i.addresses.len()<=256
&& i.addresses.iter().all(|s| clean(s,128))))
{ return Err(err); }
serde_json::from_slice(bytes).map_err(|_| err)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn no_config_blob_and_no_false_empty_on_error() {
let rows = json!({"status":"ok","entries":[]});
let mut doc = json!({"os":"OPNsense 26.7","hostname":"test","architecture":"amd64",
"root_total_bytes":20,"root_available_bytes":10,"cpu_model":"Test","logical_processors":2,
"memory_total_bytes":10,"firewall":rows,"vpn_configured":rows,"wireguard":rows,"ipsec":rows,"openvpn":rows});
assert!(validate(doc.to_string().as_bytes()).is_ok());
doc["wireguard"]["private_key"] = json!("not-permitted");
assert!(validate(doc.to_string().as_bytes()).is_err());
doc["wireguard"] = json!({"status":"unavailable","entries":["peer"]});
assert!(validate(doc.to_string().as_bytes()).is_err());
}
}
+31 -1
View File
@@ -480,7 +480,16 @@ impl Action {
_ => None,
}
}
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
/// The first FreeBSD profile is one exact POSIX script. It does not make
/// an appliance eligible for the Linux library, arbitrary scripts or root.
pub fn opnsense_kernel_probe(&self) -> bool {
matches!(self, Self::RunScript { interpreter, script_utf8, arguments,
expected_stdout: Some(expected), windows_execution_profile: None, privileged_script_profile: None }
if interpreter == "posix_sh" && script_utf8 == "uname -s\n"
&& arguments.is_empty() && expected == "FreeBSD\n")
}
/// Shared plan/revalidation/start gate. Passive inventory never implies job support.
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
if !self.valid_execution_identity(identity)
|| (identity == "system"
@@ -490,6 +499,11 @@ impl Action {
return false;
}
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
if has("opnsense.base/1") {
return identity == "agent_service" && has("run_script") && has("rmm.sync.v1")
&& has("opnsense.uname/1") && !has("windows.base/1") && !has("linux.base/1")
&& self.opnsense_kernel_probe();
}
if !has(self.name())
|| (self.full_maintenance()
&& !((has(FULL_MAINTENANCE_CAPABILITY)
@@ -828,6 +842,22 @@ impl JobState {
mod tests {
use super::*;
#[test]
fn appliance_kernel_probe_rejects_unbound_or_changed_profiles() {
let caps: Vec<String> = ["run_script","opnsense.base/1","rmm.sync.v1","opnsense.uname/1"].map(String::from).into();
let mut a = Action::RunScript { interpreter:"posix_sh".into(),script_utf8:"uname -s\n".into(),
arguments:vec![],expected_stdout:Some("FreeBSD\n".into()),windows_execution_profile:None,privileged_script_profile:None };
assert!(a.available_for("agent_service",&caps));
for excluded in &caps {
let fewer = caps.iter().filter(|v| *v!=excluded).cloned().collect::<Vec<_>>();
assert!(!a.available_for("agent_service",&fewer));
}
assert!(!a.available_for("root",&caps));
let mut mixed = caps.clone(); mixed.push("linux.base/1".into());
assert!(!a.available_for("agent_service",&mixed));
if let Action::RunScript { script_utf8,.. } = &mut a { script_utf8.push(' '); }
assert!(!a.available_for("agent_service",&caps));
}
#[test]
fn windows_update_final_report_and_policy_are_exact() {
assert_eq!(
windows_update_reboot_report(
+1 -1
View File
@@ -160,7 +160,7 @@ pub async fn ingest(
ensure!(
matches!(
s.scope.as_str(),
"linux.base" | "windows.base" | "agent.update"
"linux.base" | "windows.base" | "opnsense.base" | "agent.update"
) && s.schema_version == 1
&& s.chunk_count == 1
&& s.chunk_index == 0
+65 -1
View File
@@ -3,7 +3,7 @@ use axum::{
Json, Router,
extract::{Path, Query, State},
http::{HeaderMap, StatusCode},
routing::{delete, post},
routing::{delete, patch, post},
};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -34,6 +34,10 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
post(archive_device),
)
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/purpose",
patch(update_device_purpose),
)
.route(
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
post(revoke_plan),
@@ -132,6 +136,66 @@ async fn archive_device(
tx.commit().await?;
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Purpose {
purpose: String,
}
fn normalize_purpose(raw: &str) -> Result<Option<String>, Error> {
let normalized = raw.replace("\r\n", "\n");
let text = normalized.trim();
if text.chars().count() > 500
|| normalized
.chars()
.any(|c| c.is_control() && !matches!(c, '\n' | '\t'))
{
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
}
Ok((!text.is_empty()).then(|| text.to_owned()))
}
async fn update_device_purpose(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Json(input): Json<Purpose>,
) -> Result<Json<Value>, Error> {
const EVENT: &str = "device_purpose_updated";
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
let purpose = normalize_purpose(&input.purpose)?;
let current: Option<String> = sqlx::query_scalar(
"SELECT purpose FROM assets WHERE tenant_id=$1 AND asset_id=$2
AND EXISTS (SELECT 1 FROM agent_installations a WHERE a.tenant_id=$1 AND a.asset_id=$2
AND NOT a.customer_transfer_pending)
FOR UPDATE",
)
.bind(tenant)
.bind(asset)
.fetch_optional(&mut *tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
if current != purpose {
sqlx::query("UPDATE assets SET purpose=$3 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant)
.bind(asset)
.bind(&purpose)
.execute(&mut *tx)
.await?;
audit(
&mut tx,
&p,
EVENT,
json!({"asset_id":asset,"cleared":purpose.is_none()}),
)
.await?;
}
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"purpose":purpose})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pairing {
+2 -2
View File
@@ -3,7 +3,7 @@ WITH classified AS (
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
a.system_usage,a.system_usage_observed_at,
asset.archived_at,asset.hypervisor_asset_id,t.name AS customer_name,
asset.archived_at,asset.hypervisor_asset_id,asset.purpose,t.name AS customer_name,
CASE
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
WHEN asset.archived_at IS NOT NULL THEN 'archived'
@@ -34,7 +34,7 @@ SELECT c.*,o.observed_at,o.received_at,o.data,o.source_id FROM classified c
LEFT JOIN LATERAL (
SELECT observed_at,received_at,data,source_id FROM observations
WHERE tenant_id=c.tenant_id AND agent_id=c.agent_id AND received_at<=$2
AND source_id IN ('linux.base','windows.base')
AND source_id IN ('linux.base','windows.base','opnsense.base')
ORDER BY observed_at DESC,received_at DESC,sequence DESC LIMIT 1
) o ON true
WHERE ($6::text IS NULL OR (c.lifecycle='current')=($6='current'))
+7 -4
View File
@@ -321,6 +321,7 @@ fn device_type(hardware: &Value) -> Option<DeviceType> {
fn inventory_device_type(data: &Value) -> Option<DeviceType> {
device_type(observed(data, "linux.hardware"))
.or_else(|| device_type(observed(data, "windows.hardware")))
.or_else(|| device_type(&data["hardware"]))
}
fn hostname_filter(query: Option<&str>) -> Result<&str, Error> {
@@ -517,7 +518,8 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
let ram_total = usage["ram_total_bytes"]
.as_u64()
.or_else(|| linux_memory["total_bytes"].as_u64())
.or_else(|| windows["memory_total_bytes"].as_u64());
.or_else(|| windows["memory_total_bytes"].as_u64())
.or_else(|| data["memory_total_bytes"].as_u64());
let device_type = inventory_device_type(&data);
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
@@ -533,10 +535,11 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
"hostname":data["hostname"].as_str(),"device_type":device_type,"os":os_label(&data),
"hostname":data["hostname"].as_str(),"purpose":row.get::<Option<String>,_>("purpose"),
"device_type":device_type,"os":os_label(&data),
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()).or_else(||data["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()).or_else(||data["logical_processors"].as_u64()),
"cpu_usage_percent":cpu_usage,
"cpu_usage_observed_at":cpu_observed_at,
"ram_total_bytes":ram_total,
+10 -3
View File
@@ -292,7 +292,8 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
privileged_script_profile: None,
};
if v.encoding != "utf-8"
|| action.script_platform() != Some(v.os_family.as_str())
|| !(action.script_platform() == Some(v.os_family.as_str())
|| (v.os_family == "opnsense" && v.interpreter == "posix_sh"))
|| !action.validate()
{
return Err(fail("UNSUPPORTED_CAPABILITY"));
@@ -346,9 +347,11 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
let platform = match (
caps.iter().any(|c| c == "linux.base/1"),
caps.iter().any(|c| c == "windows.base/1"),
caps.iter().any(|c| c == "opnsense.base/1"),
) {
(true, false) => "linux",
(false, true) => "windows",
(true, false, false) => "linux",
(false, true, false) => "windows",
(false, false, true) => "opnsense",
_ => return Err(fail("UNSUPPORTED_CAPABILITY")),
};
let v = input
@@ -438,6 +441,10 @@ pub(crate) async fn plan_resolved(
let row = &rows[0];
let caps = capabilities(row.get("capabilities"))?;
let action = target_action(&input, &caps)?;
if caps.iter().any(|s| s=="opnsense.base/1") &&
(input.max_runtime_seconds != 10 || input.max_output_bytes != 1024) {
return Err(fail("UNSUPPORTED_CAPABILITY"));
}
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
return Err(fail("VALIDATION_ERROR"));
}
+29
View File
@@ -492,6 +492,8 @@ mod tests {
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
for request in [
client.get(format!("{base}/{b}/devices/{asset}")),
client.patch(format!("{base}/{b}/devices/{asset}/purpose"))
.json(&json!({"purpose":"foreign write"})),
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
client
.post(format!("{base}/{b}/operation-plans"))
@@ -530,6 +532,14 @@ mod tests {
.send().await.unwrap().json::<Value>().await.unwrap();
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
let csrf = session["csrf_token"].as_str().unwrap();
let detail = format!("{base}/{a}/devices/{asset}");
let purpose = format!("{detail}/purpose");
let update = |text: &str| client.patch(&purpose).header("origin", origin)
.header("cookie", cookie).json(&json!({"purpose":text}));
assert_eq!(client.patch(&purpose).bearer_auth(&token).json(&json!({"purpose":"token write"}))
.send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(update("reader denied").header("x-csrf-token", csrf)
.send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
@@ -537,6 +547,25 @@ mod tests {
.bind(a).bind(asset).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
assert_eq!(update("missing CSRF").send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(update(&"ü".repeat(501)).header("x-csrf-token", csrf)
.send().await.unwrap().status(), StatusCode::BAD_REQUEST);
let text = "Dateiserver für Nürnberg\nNur Entwicklung";
let saved: Value = update(" Dateiserver für Nürnberg\r\nNur Entwicklung ")
.header("x-csrf-token", csrf).send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
assert_eq!(saved["purpose"], text);
let device: Value = client.get(&detail).bearer_auth(&token)
.send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
assert_eq!(device["purpose"], text);
let other: Option<String> = sqlx::query_scalar("SELECT purpose FROM assets WHERE tenant_id=$1 AND asset_id=$2")
.bind(b).bind(asset).fetch_one(&admin).await.unwrap();
assert!(other.is_none());
let cleared: Value = update(" \n ").header("x-csrf-token", csrf)
.send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
assert_eq!(cleared["purpose"], Value::Null);
let events: Vec<Value> = sqlx::query_scalar("SELECT data->'decision' FROM audit_events WHERE tenant_id=$1 AND event_type='device_purpose_updated' ORDER BY created_at")
.bind(a).fetch_all(&admin).await.unwrap();
assert_eq!(events, [json!({"asset_id":asset,"cleared":false}), json!({"asset_id":asset,"cleared":true})]);
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
+22
View File
@@ -0,0 +1,22 @@
# OPNsense-Testclient
Test-VM `discovery-opnsense` auf `qemu:///system`, 2 vCPU, 1536 MiB RAM, 12 GiB virtuelle Platte. Basis: offizielles Nano-Image OPNsense 26.7 amd64; SHA-256 des komprimierten Images `28d5e2f37e40d87468a924e3006ef10e2ddc6de485b85333d9e3958c84d0cb9d`, gegen die Herstellerankündigung verglichen und die Signatur des entpackten Images geprüft. Start bei Bedarf: `virsh -c qemu:///system start discovery-opnsense`. Konsole: `virsh -c qemu:///system console discovery-opnsense`. Das LAN `192.168.247.0/24` ist eine isolierte libvirt-Bridge, das WAN `192.168.246.0/24` verwendet NAT. Management vom Notebook: `https://192.168.247.1`. Der Hostpin stammt aus der seriellen Konsole; Zugangswerte liegen ausschließlich im privaten Zugangsspeicher des ursprünglichen Checkouts.
## Quelle und Entwicklungsinstallation
Der OPNsense-eigene Python-Interpreter führt zwei Zipapps aus. Der lokale Collector läuft mit den für PF, VPN-Sockets und Konfiguration nötigen Rechten. Er veröffentlicht ausschließlich den ausgewählten Bestand atomar in `/var/db/discovery-observations/inventory.json`. Das Dienstkonto `discovery` kann die Datei lesen, aber weder Collector noch Cache verändern. Nur dieses Konto hält die Geräteidentität und nutzt den ausgehenden HTTPS-Kanal. Für die Erfassung wird keine eingehende Netzwerkverbindung benötigt.
1. In einer Build-venv `grpcio-tools==1.76.0` und `protobuf==6.33.5` installieren. `python deploy/opnsense/build.py ARTIFAKTORDNER` generiert die Protobuf-Bindung aus `proto/agent.proto` und packt die portable Python-Laufzeit mit ein. `python deploy/opnsense/test_agent.py ARTIFAKTORDNER/agent.pyz` prüft die Wiederholung einer nicht bestätigten Inventarmeldung mit unveränderter Nachrichtenidentität.
2. Über den gepinnten Entwicklungszugang `agent.pyz`, `collect.pyz`, `discovery_agent` und den **bestätigten öffentlichen CA-Anker des Gerätegateways** als `ca.pem` in einen privaten Stagingordner im Gast übertragen. `sh install-dev.sh STAGINGORDNER` auf dem Gast ausführen. Diese Strecke ist eine direkte Entwicklungsbereitstellung, kein signierter Releasekanal.
3. Bei einer frischen Installation in der Discovery-WebUI den Testkunden wählen und einen Einmalcode erzeugen. Den Code über geschützte Standardeingabe an `su -m discovery -c '/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/agent.pyz enroll'` übergeben. Danach `service discovery_agent start`. Bei vorhandener Identität nicht neu enrollen. Der Dienst verwaltet beide Prozesse; `rc.conf.local` aktiviert sie beim Start.
4. In **Geräte** den Hostnamen öffnen. Das Inventar wird ungefähr einmal pro Minute erhoben, der Heartbeat etwa alle 20 Sekunden gesendet. Das Betriebssystem liefert CPU-Zeitdifferenzen und eine RAM-Schätzung aus freien und inaktiven Seiten. Fehlgeschlagene Quellen erscheinen als „Nicht ermittelbar“, ein erfolgreicher leerer Befund gesondert. Pro Liste werden höchstens 128 Zeilen gemeldet; Auszüge sind gekennzeichnet.
**Systeminventar:** Kern-Bootzeit, VM-Erkennung, verfügbare SMBIOS-Daten, Netzwerkkarten mit MAC und IPs, angemeldete Benutzer und lokale FreeBSD-Pakete mit Version. Bei Software liegt die Obergrenze bei 1024 Paketen.
**VPN:** Beschreibungen und Aktivierung der OPNsense-Modelle für WireGuard-Instanzen/-Peers, OpenVPN-Instanzen und IPsec-Verbindungen. Separat: WireGuard-Handshakes (kein dauerhafter Online-Status), OpenVPN-Managementstatus und IKE-Sicherheitsassoziationen. Ohne erreichbaren IPsec-Dienst ist der Laufzeitstatus unbekannt. Keine privaten Schlüssel, PSKs, Zertifikate oder vollständige Gerätekonfiguration im Inventar.
**Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze.
**Profile:** Ohne Worker und Signaturbindung bleibt das Gerät passiv. Mit dem FreeBSD-Worker unterstützt `0.1.0-opnsense.5` genau die feste Kernelabfrage (`uname -s\n`, `posix_sh`, erwartete Ausgabe `FreeBSD\n`, keine Argumente, Dienstkonto, 10 s, 1024 Byte). Unter **Geräte → OPNsense-Kernelabfrage** lässt sie sich für diese Installation einreichen. Die persönliche WebUI-Genehmigung und der signierte Startgrant sind erforderlich. Root, beliebige Shell-/Bibliotheksskripte und signierte OPNsense-Releases bleiben offen. Das Gerät ist kein Linuxziel.
**Probe bereitstellen:** Im Gast steht die gepinnte Toolchain unter `/opt/discovery-rust`. `cargo build --locked -p rmm-opnsense-jobs` nativ bauen und `rmm-opnsense-jobs` root-eigen (0555) neben den Zipapps installieren. Auf der bereits aufgenommenen Testinstallation `python3 -I pin-probe.py TENANT ASSET AGENT ENROLLMENT_GENERATION ASSIGNMENT_VERSION` mit den bestätigten Kennungen aufrufen. Das Skript bezieht den öffentlichen Jobschlüssel über das bestehende Gerätezertifikat und überschreibt keine andere Bindung. Den Agentendienst anschließend neu starten. Der Worker nutzt bestehende Nachrichtenfolgen, den signierten Abgleich und getrennte dauerhafte Start-/Ergebnisjournale. Er läuft ohne Netzwerklistener als `discovery`. Der [native Integrationstest](../../crates/agent-opnsense-jobs/src/native/tests.rs) prüft mit eigener Testidentität und eigenem Schlüssel die Ablehnung einer defekten Signatur, erwartete Ausgabe, einen Verbrauch und keine zweite Ausführung bei Wiederzustellung. Das ist ein separater Beleg vom persönlich genehmigten Geräteauftrag.
+304
View File
@@ -0,0 +1,304 @@
"""Unprivileged OPNsense telemetry channel. Input never selects a local command."""
import hashlib
import contextlib
import fcntl
import http.client
import json
import os
from pathlib import Path
import re
import sqlite3
import ssl
import subprocess
import sys
import time
import uuid
import agent_pb2 as pb
STATE = Path('/var/db/discovery-agent')
CA = '/usr/local/etc/discovery-agent/ca.pem'
HOST = 'discovery.ease-technologies.de'
MEDIA = 'application/x-protobuf'
VERSION = '0.1.0-opnsense.5'
WORKER = Path('/usr/local/libexec/discovery-agent/rmm-opnsense-jobs')
BINDING = Path('/usr/local/etc/discovery-agent/job-binding.json')
def post(ctx, path, data, media):
conn = http.client.HTTPSConnection(HOST, context=ctx, timeout=15)
try:
conn.request('POST', '/agent/v1/'+path, data, {'Content-Type':media, 'Accept':media})
res = conn.getresponse()
if res.status != 200 or res.getheader('Content-Type', '').split(';')[0] != media:
raise ValueError(f'{path}: HTTP {res.status}')
body = res.read(1024*1024 + 1)
if len(body) > 1024*1024:
raise ValueError('response size')
return body
finally:
conn.close()
def context():
return ssl.create_default_context(cafile=CA)
def enroll():
# Existing keys are never overwritten, including after an ambiguous POST.
key = STATE/'device.key'
if key.exists() or (STATE/'identity.json').exists():
raise RuntimeError('installation already initialized')
token = sys.stdin.readline(128).strip()
if not re.fullmatch('[0-9a-f]{64}', token):
raise ValueError('invalid enrollment code')
csr = subprocess.check_output(['/usr/bin/openssl','req','-new','-newkey','ec','-pkeyopt',
'ec_paramgen_curve:P-256','-nodes','-subj','/CN=discovery-agent','-keyout',str(key)],
stderr=subprocess.DEVNULL)
result = json.loads(post(context(), 'enroll', json.dumps(dict(token=token, csr_pem=csr.decode())),
'application/json'))
for name in ('agent_id','asset_id'):
uuid.UUID(result[name])
(STATE/'device.pem').write_text(result.pop('certificate_pem'))
context().load_cert_chain(STATE/'device.pem', key)
(STATE/'identity.json').write_text(json.dumps(result))
def durable_write(path, data):
tmp = path.with_suffix('.new')
with tmp.open('wb') as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
fd = os.open(STATE, os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def renew(ctx, identity):
# Reuse a durable request after a lost reply; gateway renewal is idempotent
# for the same CSR. Keep the currently working certificate until key match.
cert, key, csr = (STATE/n for n in ('device.pem','device.key','renewal.csr'))
if not csr.exists():
check = subprocess.run(['/usr/bin/openssl','x509','-in',str(cert),'-noout','-checkend','604800'],
stdout=subprocess.DEVNULL, check=False)
if check.returncode == 0:
return False
durable_write(csr,subprocess.check_output(['/usr/bin/openssl','req','-new','-key',str(key),
'-subj','/CN=discovery-agent']))
result = json.loads(post(ctx,'certificates/renew',json.dumps({'csr_pem':csr.read_text()}),'application/json'))
if result['agent_id'] != identity['agent_id']:
raise ValueError('renewal identity mismatch')
candidate = STATE/'candidate.pem'
durable_write(candidate,result['certificate_pem'].encode())
context().load_cert_chain(candidate,key)
durable_write(cert,candidate.read_bytes())
candidate.unlink()
csr.unlink()
return True
def usage(previous):
def counters(*keys):
return [int(x) for x in subprocess.check_output(['/sbin/sysctl', '-n', *keys],timeout=3).split()]
ticks = counters('kern.cp_time')
free, inactive, page, total = counters('vm.stats.vm.v_free_count','vm.stats.vm.v_inactive_count',
'hw.pagesize','hw.physmem')
sample = pb.SystemUsage(ram_available_bytes=min((free+inactive)*page,total),ram_total_bytes=total)
if previous and len(previous) == len(ticks) and all(x >= y for x,y in zip(ticks,previous)):
delta = sum(ticks)-sum(previous)
if delta > 0:
sample.cpu_usage_basis_points = 10000*(delta-ticks[-1]+previous[-1])//delta
return sample,ticks
class Jobs:
"""Private pipe to the non-root worker. The mTLS agent owns the transport."""
def __init__(self, process):
self.process = process
def read(self):
line = self.process.stdout.readline(2_100_000)
if not line.endswith(b'\n'):
raise ValueError('job worker disconnected')
return line[:-1]
def call(self, line):
self.process.stdin.write(line+b'\n')
self.process.stdin.flush()
return self.read()
def received(self, envelope):
if self.call(envelope.SerializeToString().hex().encode()) != b'ok':
raise ValueError('job response not committed')
def pump(self, ctx, agent, boot, generation):
for _ in range(12):
frame = self.call(b'next')
if not frame:
return
e = pb.Envelope.FromString(bytes.fromhex(frame.decode('ascii')))
kind = e.WhichOneof('payload')
if (e.protocol_major!=1 or e.agent_id!=agent or e.enrollment_generation!=1 or
e.connection_generation!=generation or kind not in (
'job_accepted','job_state_changed','job_result','sync_request','execution_permit_request')):
raise ValueError('invalid outbound job event')
batch = pb.MessageBatch(protocol_major=1,messages=[e])
reply = pb.MessageBatch.FromString(post(ctx,'messages',batch.SerializeToString(),MEDIA))
expected = {'sync_request':'sync_response','execution_permit_request':'execution_permit'}.get(kind,'ack')
check_reply(reply,e,expected)
for r in reply.messages:
self.received(r)
def check_reply(batch,e,expected):
if batch.protocol_major!=1 or not 1<=len(batch.messages)<=16:
raise ValueError('unexpected reply')
first = batch.messages[0]
generation = first.server_hello.connection_generation if expected=='server_hello' else e.connection_generation
for index,r in enumerate(batch.messages):
if (r.protocol_major,r.protocol_minor,r.agent_id,r.enrollment_generation,r.connection_generation,
r.boot_id,r.sequence)!=(1,0,e.agent_id,e.enrollment_generation,generation,e.boot_id,e.sequence):
raise ValueError('reply identity')
kind = r.WhichOneof('payload')
if (not index and kind!=expected) or (index and kind not in ('job_offer','cancel_request')):
raise ValueError('unexpected job reply')
if expected=='ack' and first.ack.message_id!=e.message_id:
raise ValueError('unconfirmed message')
return first
def session(db, identity, boot, instance):
with contextlib.ExitStack() as stack:
return run_channel(db, identity, boot, instance, stack)
def run_channel(db, identity, boot, instance, stack):
ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
generation = 0
jobs = None
enabled = BINDING.is_file() and WORKER.is_file()
def send(kind, payload, captured=None):
# A lost inventory ACK replays the exact durable envelope, including its
# original time, boot and sequence; only the connection fence changes.
with db:
pending = db.execute('SELECT envelope FROM pending WHERE id=1').fetchone() if kind=='inventory_snapshot' else None
if pending:
e = pb.Envelope.FromString(pending[0])
if e.agent_id != identity['agent_id']:
raise ValueError('pending snapshot identity')
e.connection_generation = generation
else:
seq = db.execute('UPDATE sequence SET n=n+1 RETURNING n').fetchone()[0]
e = pb.Envelope(protocol_major=1, message_id=str(uuid.uuid4()), agent_id=identity['agent_id'],
enrollment_generation=1, connection_generation=generation, boot_id=boot,
sequence=seq, observed_at=captured or time.time_ns()//1_000_000)
getattr(e, kind).CopyFrom(payload)
if kind == 'inventory_snapshot':
db.execute('INSERT INTO pending VALUES(1,?,?)',(e.SerializeToString(),e.observed_at))
batch = pb.MessageBatch(protocol_major=1, messages=[e])
reply = pb.MessageBatch.FromString(post(ctx, 'messages', batch.SerializeToString(), MEDIA))
r = check_reply(reply,e,'server_hello' if kind=='client_hello' else 'ack')
if len(reply.messages)>1 and jobs is None:
raise ValueError('work outside established job session')
for extra in reply.messages[1:]:
jobs.received(extra)
if kind == 'client_hello':
if (r.WhichOneof('payload') != 'server_hello' or r.connection_generation == 0 or
r.connection_generation != r.server_hello.connection_generation or
r.server_hello.max_message_bytes != 1024*1024):
raise ValueError('invalid server hello')
return r.connection_generation
if (r.connection_generation != generation or r.WhichOneof('payload') != 'ack'
or r.ack.message_id != e.message_id):
raise ValueError('unconfirmed message')
if kind == 'inventory_snapshot':
with db:
db.execute('DELETE FROM pending WHERE id=1')
if renew(ctx, identity):
ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
caps = ['heartbeat/1','opnsense.base/1']
if enabled:
caps.extend(['rmm.sync.v1','run_script','opnsense.uname/1'])
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=caps))
if enabled:
p = subprocess.Popen([WORKER,identity['agent_id'],identity['asset_id'],boot,str(generation)],
stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True)
def close():
p.stdin.close()
try:
p.wait(timeout=15)
except subprocess.TimeoutExpired:
p.kill(); p.wait()
finally:
p.stdout.close()
stack.callback(close)
jobs = Jobs(p)
if jobs.read()!=b'ready':
raise ValueError('job worker unavailable')
last = None
previous = None
check_cert = time.monotonic()+12*3600
while True:
if time.monotonic() >= check_cert:
if renew(ctx, identity):
return
check_cert = time.monotonic()+12*3600
sample,previous = usage(previous)
send('heartbeat',pb.Heartbeat(instance_id=instance,uptime_seconds=int(time.clock_gettime(time.CLOCK_UPTIME)),
system_usage=sample))
with db:
# The ingestion contract accepts observations for 72 hours.
db.execute('DELETE FROM pending WHERE observed < ?', (time.time_ns()//1_000_000 - 72*3600*1000,))
if db.execute('SELECT 1 FROM pending').fetchone():
send('inventory_snapshot',None)
file = Path('/var/db/discovery-observations/inventory.json')
if file.exists():
with file.open('rb') as f:
stamp = os.fstat(f.fileno()).st_mtime_ns
if stamp != last and 0 <= time.time()-stamp/1e9 <= 120:
raw = f.read(384*1024+1)
if len(raw) > 384*1024:
raise ValueError('snapshot size')
send('inventory_snapshot',pb.InventorySnapshot(snapshot_id=str(uuid.uuid4()),
scope='opnsense.base',schema_version=1,chunk_count=1,data=raw,
sha256=hashlib.sha256(raw).digest(),completeness='partial'),stamp//1_000_000)
last = stamp
if jobs:
jobs.pump(ctx,identity['agent_id'],boot,generation)
time.sleep(20)
def main():
os.umask(0o077)
if sys.argv[1:] == ['enroll']:
return enroll()
# Never allow a second network actor to fence or race an in-flight worker.
lock = (STATE/'channel.lock').open('ab')
fcntl.flock(lock,fcntl.LOCK_EX | fcntl.LOCK_NB)
identity = json.loads((STATE/'identity.json').read_bytes())
db = sqlite3.connect(STATE/'channel.sqlite')
with db:
db.execute('CREATE TABLE IF NOT EXISTS sequence(id INTEGER PRIMARY KEY CHECK(id=1),n INTEGER NOT NULL)')
db.execute('CREATE TABLE IF NOT EXISTS pending(id INTEGER PRIMARY KEY CHECK(id=1),envelope BLOB NOT NULL,observed INTEGER NOT NULL)')
db.execute('INSERT OR IGNORE INTO sequence VALUES(1,0)')
started = subprocess.check_output(['/sbin/sysctl','-n','kern.boottime']).decode().split('}')[0]
boot = str(uuid.uuid5(uuid.UUID(identity['agent_id']),started))
instance = str(uuid.uuid4())
while True:
try:
session(db, identity, boot, instance)
except Exception as exc:
print('OPNsense channel:', type(exc).__name__, str(exc)[:160], flush=True)
time.sleep(30)
if __name__ == '__main__':
main()
+33
View File
@@ -0,0 +1,33 @@
"""Build two FreeBSD Python zipapps; use grpcio-tools 1.76.0 + protobuf 6.33.5."""
import importlib.metadata as metadata
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import zipapp
here = Path(__file__).resolve().parent
out = Path(sys.argv[1])
out.mkdir(exist_ok=True, parents=True)
if metadata.version('protobuf') != '6.33.5' or metadata.version('grpcio-tools') != '1.76.0':
sys.exit('Unexpected protocol builder dependencies')
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
proto = here.parents[1]/'proto'
subprocess.run([sys.executable,'-m','grpc_tools.protoc','-I'+str(proto),'--python_out='+tmp,
str(proto/'agent.proto')],check=True)
dist = metadata.distribution('protobuf')
for f in dist.files:
if str(f).startswith('google/protobuf/') and f.suffix == '.py':
dst = work/f
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(dist.locate_file(f), dst)
(work/'google/__init__.py').touch()
license_file = next(f for f in dist.files if f.name=='LICENSE' and '.dist-info/' in str(f))
shutil.copyfile(dist.locate_file(license_file),work/'LICENSE-protobuf')
shutil.copyfile(here/'agent.py',work/'__main__.py')
zipapp.create_archive(work,out/'agent.pyz',compressed=True)
with tempfile.TemporaryDirectory() as tmp:
shutil.copyfile(here/'collect.py',Path(tmp)/'__main__.py')
zipapp.create_archive(tmp,out/'collect.pyz',compressed=True)
+161
View File
@@ -0,0 +1,161 @@
"""Bounded local inventory projection. Runs independently of the network agent."""
import datetime
import json
import os
from pathlib import Path
import re
import resource
import socket
import subprocess
import tempfile
import time
import xml.etree.ElementTree as ET
CACHE = Path('/var/db/discovery-observations')
def run(*args):
# Appliance commands may produce much more than one snapshot. Cap the
# producer before reading its output, including on a misconfigured host.
def limits():
resource.setrlimit(resource.RLIMIT_FSIZE, (2**21, 2**21))
with tempfile.TemporaryFile() as out:
subprocess.run(args, stdout=out, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
check=True, timeout=10, preexec_fn=limits)
out.seek(0)
return out.read(2**21).decode('utf8', errors='replace').strip()
def sysctl(name):
return run('/sbin/sysctl', '-n', name)
def rows(provider):
entries = []
partial = False
try:
for text in provider():
if len(entries) == 128:
partial = True
break
text = ' '.join(text.split())
if len(text.encode()) > 512:
partial = True
text = text.encode()[:509].decode(errors='ignore') + '…'
if text:
entries.append(text)
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.SubprocessError):
return dict(status='partial' if entries else 'unavailable', entries=entries)
return dict(status='partial' if partial else 'ok', entries=entries)
def configured(config_path='/conf/config.xml'):
# Project only these model paths and display fields. Never serialize XML.
with open(config_path, 'rb') as f:
data = f.read(8 * 1024 * 1024 + 1)
if len(data) > 8 * 1024 * 1024:
raise ValueError('config size')
root = ET.fromstring(data)
for title, path, field in [
('WireGuard-Instanz', 'wireguard/server/servers/server', 'name'),
('WireGuard-Peer', 'wireguard/client/clients/client', 'name'),
('IPsec', 'Swanctl/Connections/Connection', 'description'),
('OpenVPN', 'OpenVPN/Instances/Instance', 'description'),
]:
for item in root.findall('OPNsense/' + path):
enabled = {'0': 'deaktiviert', '1': 'aktiviert'}.get(item.findtext('enabled'), 'Status unbekannt')
yield f"{title} · {item.findtext(field) or item.get('uuid') or '–'} · {enabled}"
def wireguard():
for line in run('/usr/bin/wg', 'show', 'all', 'latest-handshakes').splitlines():
interface, public_key, epoch = line.split()
stamp = datetime.datetime.fromtimestamp(int(epoch), datetime.timezone.utc).isoformat() if int(epoch) else 'nie'
yield f'{interface} · {public_key} · {stamp}'
def openvpn():
data = json.loads(run('/usr/local/opnsense/scripts/openvpn/ovpn_status.py', '--options', 'client,server'))
for role in ('server', 'client'):
for instance, status in data.get(role, {}).items():
yield f"{role} {instance} · {status.get('status', 'unbekannt')}"
for peer in status.get('client_list', []):
yield f"{instance} · {peer.get('common_name', '–')} · {peer.get('real_address', '–')}"
def ipsec():
# Only IKE summary lines, not CHILD_SA details or authentication settings.
for line in run('/usr/local/sbin/swanctl', '--list-sas').splitlines():
if re.match(r'^\S.*: #\d+, ', line):
yield line
def interfaces():
item = None
for line in run('/sbin/ifconfig','-f','inet:cidr,inet6:cidr','-a').splitlines():
if line and not line[0].isspace():
if item:
yield item
item = dict(name=line.split(':',1)[0],mac=None,addresses=[])
elif item:
fields = line.split()
if len(fields)>1 and fields[0]=='ether':
item['mac'] = fields[1]
elif len(fields)>1 and fields[0] in ('inet','inet6'):
item['addresses'].append(fields[1])
if item:
yield item
def packages():
for line in run('/usr/sbin/pkg','query','%n\t%v').splitlines():
name,version = line.split('\t',1)
yield dict(name=name,version=version)
def inventory_rows(fn, limit):
entries = []
try:
for item in fn():
if len(entries) >= limit:
return dict(status='partial',entries=entries)
entries.append(item)
return dict(status='ok',entries=entries)
except (OSError,ValueError,subprocess.SubprocessError):
return dict(status='partial' if entries else 'unavailable',entries=entries)
def snapshot():
disk = os.statvfs('/')
boot = int(re.search(r'sec = (\d+)',sysctl('kern.boottime'))[1])
hardware = {'device_type':'physical' if sysctl('kern.vm_guest')=='none' else 'virtual',
'booted_at':datetime.datetime.fromtimestamp(boot,datetime.timezone.utc).isoformat()}
for key,name in [('smbios.system.maker','manufacturer'),('smbios.system.serial','bios_serial_number')]:
try:
value = run('/bin/kenv',key)
if value and value.lower() not in ('none','unknown','not specified','default string'):
hardware[name]=value[:128]
except (OSError,subprocess.SubprocessError):
pass
return dict(os=run('/usr/local/sbin/opnsense-version'), hostname=socket.gethostname(),
architecture=os.uname().machine, root_total_bytes=disk.f_blocks*disk.f_frsize,
root_available_bytes=max(0,disk.f_bavail)*disk.f_frsize, cpu_model=sysctl('hw.model'),
logical_processors=int(sysctl('hw.ncpu')), memory_total_bytes=int(sysctl('hw.physmem')),
firewall=rows(lambda: run('/sbin/pfctl', '-sr').splitlines()), vpn_configured=rows(configured),
wireguard=rows(wireguard), openvpn=rows(openvpn), ipsec=rows(ipsec),
hardware=hardware, interfaces=inventory_rows(interfaces,128), software=inventory_rows(packages,1024),
users=rows(lambda:sorted(set(run('/usr/bin/users').split()))))
if __name__ == '__main__':
while True:
try:
with tempfile.NamedTemporaryFile(dir=CACHE, delete=False) as f:
f.write(json.dumps(snapshot(), ensure_ascii=False).encode())
os.fchmod(f.fileno(), 0o640)
os.replace(f.name, CACHE/'inventory.json')
except Exception as exc:
print('OPNsense collection:', type(exc).__name__, flush=True)
if 'f' in locals():
Path(f.name).unlink(missing_ok=True)
time.sleep(60)
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# PROVIDE: discovery_agent
# REQUIRE: NETWORKING
# KEYWORD: shutdown
. /etc/rc.subr
name=discovery_agent
rcvar=discovery_agent_enable
load_rc_config "$name"
: "${discovery_agent_enable:=NO}"
start_cmd=discovery_start
stop_cmd=discovery_stop
discovery_start() {
for part in collect agent; do
pid=/var/run/discovery-$part.pid
[ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue
user=root
[ "$part" != agent ] || user=discovery
/usr/sbin/daemon -f -r -R 10 -P "$pid" -u "$user" -S -T "discovery-$part" \
/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/"$part".pyz || return 1
done
}
discovery_stop() {
for part in agent collect; do
pid=$(check_pidfile "/var/run/discovery-$part.pid" /usr/sbin/daemon)
[ -z "$pid" ] || kill -TERM "$pid"
done
}
run_rc_command "$1"
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Direct artifact deployment in the test guest. Enrollment is a separate step.
set -eu
[ "$(id -u)" = 0 ] && [ "$(uname -s)" = FreeBSD ] && [ -x /usr/local/sbin/opnsense-version ]
[ "$#" = 1 ] || { echo 'Usage: install-dev.sh /path/to/staged-artifacts' >&2; exit 2; }
src=$1
for f in agent.pyz collect.pyz discovery_agent ca.pem; do [ -f "$src/$f" ]; done
/usr/bin/openssl x509 -in "$src/ca.pem" -noout -checkend 0 >/dev/null
pw groupshow discovery >/dev/null 2>&1 || pw groupadd discovery
pw usershow discovery >/dev/null 2>&1 || pw useradd discovery -g discovery -d /var/db/discovery-agent -s /usr/sbin/nologin
[ "$(id -gn discovery)" = discovery ] && [ "$(id -u discovery)" != 0 ]
app=/usr/local/libexec/discovery-agent
conf=/usr/local/etc/discovery-agent
rc=/usr/local/etc/rc.d/discovery_agent
install -d -o root -g wheel -m 0755 "$app" "$conf"
install -d -o discovery -g discovery -m 0700 /var/db/discovery-agent
install -d -o root -g discovery -m 2750 /var/db/discovery-observations
if [ -e "$conf/ca.pem" ]; then
cmp -s "$conf/ca.pem" "$src/ca.pem" || { echo 'Existing trust anchor differs' >&2; exit 1; }
fi
for part in collect agent; do
install -o root -g wheel -m 0444 "$src/$part.pyz" "$app/$part.next"
done
if [ -x "$rc" ]; then
"$rc" onestop
for _ in 1 2 3 4 5; do
[ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || break
sleep 1
done
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ]; then
echo 'Existing service still running' >&2; exit 1
fi
fi
for part in collect agent; do mv -f "$app/$part.next" "$app/$part.pyz"; done
install -o root -g wheel -m 0444 "$src/ca.pem" "$conf/ca.pem"
install -o root -g wheel -m 0555 "$src/discovery_agent" "$rc"
sysrc -f /etc/rc.conf.local discovery_agent_enable=YES >/dev/null
if [ -s /var/db/discovery-agent/identity.json ]; then
"$rc" start
else
echo 'Ready for enrollment under the discovery service account.'
fi
+53
View File
@@ -0,0 +1,53 @@
"""Provision the first service-account probe on an existing development installation.
Run as root in FreeBSD with the operator-confirmed tenant/asset/agent UUIDs and
enrollment/assignment generations. Fetch only the public signing pin as discovery.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import uuid
def main():
if os.geteuid() or len(sys.argv)!=6:
raise SystemExit('pin-probe.py TENANT ASSET AGENT ENROLLMENT_GENERATION ASSIGNMENT_VERSION')
tenant,asset,agent = (str(uuid.UUID(s)) for s in sys.argv[1:4])
enroll,assignment = map(int,sys.argv[4:])
if min(enroll,assignment)<1:
raise ValueError('invalid generation')
# Device-owned inputs are opened only after dropping privileges.
source = """
import hashlib,http.client,json,ssl
from pathlib import Path
p=Path('/var/db/discovery-agent')
i=json.loads((p/'identity.json').read_bytes())
ctx=ssl.create_default_context(cafile='/usr/local/etc/discovery-agent/ca.pem')
ctx.load_cert_chain(p/'device.pem',p/'device.key')
c=http.client.HTTPSConnection('discovery.ease-technologies.de',context=ctx,timeout=10)
c.request('GET','/api/v1/job-signing-key')
r=c.getresponse()
if r.status!=200:raise ValueError('device trust endpoint rejected')
print(json.dumps([i['agent_id'],i['asset_id'],json.loads(r.read(4097))]))
"""
current,bound_asset,k=json.loads(subprocess.check_output(
['su','-m','discovery','-c','/usr/local/bin/python3 -I -'],input=source.encode(),timeout=15))
key = k['public_key_hex']
if (current,bound_asset)!=(agent,asset) or not re.fullmatch('[a-f0-9]{64}',key) or (
k['algorithm'],k['schema_version'],k['key_id'])!=('Ed25519',1,hashlib.sha256(bytes.fromhex(key)).hexdigest()):
raise ValueError('conflicting device or signing key')
payload=dict(agent_id=agent,asset_id=asset,tenant_id=tenant,enrollment_generation=enroll,
assignment_version=assignment,public_key_hex=key)
p=Path('/usr/local/etc/discovery-agent/job-binding.json')
try:
with p.open('x') as f:
os.fchmod(f.fileno(),0o444); json.dump(payload,f); f.flush(); os.fsync(f.fileno())
except FileExistsError:
if p.is_symlink() or json.loads(p.read_bytes())!=payload: raise ValueError('existing binding differs')
if __name__=='__main__':
main()
+80
View File
@@ -0,0 +1,80 @@
"""Run from the protocol-builder venv: python test_agent.py <built agent.pyz>."""
import importlib.util
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
from unittest.mock import patch
import uuid
sys.path.insert(0,sys.argv.pop(1))
spec = importlib.util.spec_from_file_location('opn_channel', Path(__file__).with_name('agent.py'))
a = importlib.util.module_from_spec(spec)
spec.loader.exec_module(a)
class Reconnect(unittest.TestCase):
def test_piggybacked_work_requires_same_authenticated_channel_and_exact_receipt(self):
e=a.pb.Envelope(protocol_major=1,enrollment_generation=1,connection_generation=3,
agent_id=str(uuid.uuid4()),boot_id=str(uuid.uuid4()),sequence=42,message_id=str(uuid.uuid4()))
ack=a.pb.Envelope();ack.CopyFrom(e);ack.ack.message_id=e.message_id
offer=a.pb.Envelope();offer.CopyFrom(e);offer.job_offer.job_id=str(uuid.uuid4())
batch=a.pb.MessageBatch(protocol_major=1,messages=[ack,offer])
self.assertEqual(a.check_reply(batch,e,'ack'),ack)
batch.messages[1].connection_generation=2
with self.assertRaisesRegex(ValueError,'identity'): a.check_reply(batch,e,'ack')
del batch.messages[1:]
batch.messages[0].ack.message_id=str(uuid.uuid4())
with self.assertRaisesRegex(ValueError,'unconfirmed'): a.check_reply(batch,e,'ack')
def test_lost_ack_keeps_original_identity_after_restart(self):
with tempfile.TemporaryDirectory() as temp:
db = sqlite3.connect(':memory:')
db.executescript('CREATE TABLE sequence(id INTEGER PRIMARY KEY,n INTEGER);INSERT INTO sequence VALUES(1,0);'
'CREATE TABLE pending(id INTEGER PRIMARY KEY,envelope BLOB,observed INTEGER);')
cache = Path(temp)/'inventory.json'
cache.write_text('{}')
identity = {'agent_id':str(uuid.uuid4())}
instance = str(uuid.uuid4())
captures = []
generation = 0
def gateway(_ctx,path,data,media):
nonlocal generation
req = a.pb.MessageBatch.FromString(data).messages[0]
reply = a.pb.Envelope()
reply.CopyFrom(req)
kind = req.WhichOneof('payload')
if kind == 'client_hello':
generation += 1
reply.connection_generation = generation
reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=generation,max_message_bytes=1024*1024))
else:
if kind == 'inventory_snapshot':
captures.append(req)
if len(captures)==1: raise OSError('lost ACK')
reply.ack.CopyFrom(a.pb.Ack(message_id=req.message_id))
return a.pb.MessageBatch(protocol_major=1,messages=[reply]).SerializeToString()
with patch.object(a,'context'), patch.object(a,'renew',return_value=False), \
patch.object(a,'post',gateway), patch.object(a,'Path',return_value=cache), \
patch.object(a,'usage',return_value=(a.pb.SystemUsage(),[])), \
patch.object(a.time,'clock_gettime',return_value=100), \
patch.object(a.time,'CLOCK_UPTIME',1,create=True), patch.object(a.time,'sleep',side_effect=StopIteration):
with self.assertRaises(OSError):
a.session(db,identity,str(uuid.uuid4()),instance)
self.assertIsNotNone(db.execute('SELECT 1 FROM pending').fetchone())
os.unlink(cache)
with self.assertRaises(StopIteration):
a.session(db,identity,str(uuid.uuid4()),instance)
self.assertIsNone(db.execute('SELECT 1 FROM pending').fetchone())
self.assertEqual(len(captures),2)
self.assertNotEqual(captures[0].connection_generation,captures[1].connection_generation)
captures[0].connection_generation=captures[1].connection_generation
self.assertEqual(captures[0],captures[1])
if __name__=='__main__':
unittest.main()
+28
View File
@@ -0,0 +1,28 @@
import tempfile
import unittest
from pathlib import Path
import collect
class ApplianceProjection(unittest.TestCase):
def test_configured_disabled_is_not_a_connection_and_secrets_stay_local(self):
with tempfile.TemporaryDirectory() as root:
p = Path(root)/'config.xml'
p.write_text('<opnsense><OPNsense><wireguard><server><servers><server uuid="uuid">'
'<name>Test</name><enabled>0</enabled><privkey>do-not-export</privkey>'
'</server></servers></server></wireguard><OpenVPN><Instances><Instance>'
'<enabled>1</enabled><description>Lab</description><tlskey>do-not-export</tlskey>'
'</Instance></Instances></OpenVPN></OPNsense></opnsense>')
self.assertEqual(collect.rows(lambda:collect.configured(p)), {
'status':'ok','entries':['WireGuard-Instanz · Test · deaktiviert','OpenVPN · Lab · aktiviert']})
p.write_text('<broken')
self.assertEqual(collect.rows(lambda:collect.configured(p)),{'status':'unavailable','entries':[]})
def test_truncation_is_explicit_and_utf8_stays_within_the_wire_limit(self):
result = collect.rows(lambda:iter(['ü'*1000]*200))
self.assertEqual((result['status'],len(result['entries'])),('partial',128))
self.assertTrue(all(len(s.encode())<=512 for s in result['entries']))
if __name__=='__main__':
unittest.main()
@@ -0,0 +1,15 @@
{
"jobs": 0,
"state": "pending_approval",
"outbox": 0,
"script": "uname -s\n",
"target": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"attempt": "ea526a57-d3f0-4ae6-8d52-d6ffdf89dfa9",
"plan_id": "c3aa157c-4908-45c1-b7f4-0f588879d1af",
"plan_hash": "f615d46f5ac6e1a4e81eb498f29609da36c77613fe7d7ab55ccf0a395f368143",
"checked_at": "2026-11-19T19:53:19.073901+00:00",
"expires_at": "2026-11-20T19:52:59.134+00:00",
"uid_profile": "agent_service",
"operation_id": "67205987-0fda-4635-ae7a-4b7979c274dc",
"start_grants": 0
}
@@ -0,0 +1,40 @@
{
"rules": 91,
"source": "opnsense.base",
"tenant": "Ease Testserver - For development",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"asset_id": "1d0b9642-9f31-4fba-95f3-8cc15a11aa34",
"tenant_id": "9d730e0a-ba31-402c-8b82-8995c2585f59",
"transport": "https",
"cpu_reported": true,
"inventory_at": "2026-11-19T19:11:42.453+00:00",
"ram_reported": true,
"agent_version": "0.1.0-opnsense.4",
"last_contact_at": "2026-11-19T19:12:03.492329+00:00",
"wireguard_after_cleanup": 0,
"current_certificate_authenticated": true,
"vm": "discovery-opnsense",
"native_runtime_checks": {
"rust_freebsd_toolchain": "1.99.1",
"shared_contract_and_reconciliation_tests_passed": 71,
"qualified_clock_and_step_rejection": true,
"owned_process_group_tests_as_service_account_passed": 2,
"approved_rmm_script_executed": false,
"signed_agent_self_update_verified": false
},
"native_os": "OPNsense 26.7 (amd64), FreeBSD 15.1-RELEASE-p1",
"agent_sha256": "1e545467e0e96b87210aa39c4ab7e0f3e0ca5bf0bbbf3cb0140e2f229875e1a4",
"server_revision": "b7d9046996fdf4778d04b24a8ab2effd19647db7",
"public_browser": {
"rules_rendered": 91,
"wireguard_loopback_test_peer_handshakes_rendered": 2,
"test_interfaces_removed": true,
"vpn_section_rendered": true,
"native_interface_rendered": true,
"native_package_search_verified": true
},
"packages": 169,
"interfaces": 6,
"device_type": "virtual",
"collector_sha256": "6c4b2fd8a6d2bb9d435a00e40bca63bd53b6430006f044b3edac3655efad30db"
}
@@ -1,201 +0,0 @@
{
"native_method": "Three windows with process CPU and logical I/O counters from Win32_Process, plus existing readiness observations. Percentages use both Windows logical processors. I/O counts include cached reads. The data shows the combined effect of each release.",
"source_findings": {
"baseline_revision": "9e957e6d8d4254a01fe215b32ecd6bc8c31b6947",
"agent": "20 ms timer did journal queries and qualified clock reads even with no accepted attempt. Every sync prepared with a complete SQLite integrity scan.",
"helper": "Every snapshot ran a complete SQLite integrity scan. Every ready response rebuilt a denial anchor and revalidated the entire historical decision chain. ORDER BY checkpoint had no supporting index for that replay.",
"idle_runtime_tick_ms": 250,
"active_runtime_tick_ms": 20,
"idle_integrity_audit_interval_seconds": 300,
"full_audits_before_new_system_effect": true,
"full_lineage_audit_before_no_start_record": true
},
"local_sqlite_query_plan": {
"baseline": [
"SCAN helper_sync_decisions",
"USE TEMP B-TREE FOR ORDER BY"
],
"with_checkpoint_index": [
"SCAN helper_sync_decisions USING INDEX helper_sync_decisions_checkpoint"
]
},
"measurements": [
{
"start": "2026-11-19T09:05:49.2782989Z",
"end": "2026-11-19T09:07:20.7135402Z",
"version": "0.1.22",
"cpu_count": 2,
"duration_seconds": 91.127271,
"journal_bytes": 452415488,
"ledger_bytes": 335908864,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds": 0.03125,
"cpu_percent": 0.0171,
"read_mib_s": 0.0003,
"write_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 4700,
"cpu_seconds": 21.546875,
"cpu_percent": 11.8224,
"read_mib_s": 102.0242,
"write_mib_s": 34.4732
},
"rmm-agent-windows.exe": {
"pid": 1908,
"cpu_seconds": 5.75,
"cpu_percent": 3.1549,
"read_mib_s": 38.1056,
"write_mib_s": 0.0482
}
},
"idle_job_authorizations": 0,
"readiness_samples": 19,
"signed_decisions_observed": 6,
"ready_samples": 14
},
{
"start": "2026-11-19T09:13:22.8803140Z",
"end": "2026-11-19T09:14:54.0077643Z",
"version": "0.1.23",
"cpu_count": 2,
"duration_seconds": 90.93767,
"journal_bytes": 455192576,
"ledger_bytes": 337829888,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds": 0.015625,
"cpu_percent": 0.0086,
"read_mib_s": 0.0,
"write_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 8036,
"cpu_seconds": 10.015625,
"cpu_percent": 5.5069,
"read_mib_s": 63.7249,
"write_mib_s": 13.9068
},
"rmm-agent-windows.exe": {
"pid": 832,
"cpu_seconds": 2.640625,
"cpu_percent": 1.4519,
"read_mib_s": 26.3846,
"write_mib_s": 0.0204
}
},
"idle_job_authorizations": 0,
"readiness_samples": 18,
"signed_decisions_observed": 3,
"ready_samples": 10
},
{
"start": "2026-11-19T09:18:45.8146916Z",
"end": "2026-11-19T09:20:16.8017398Z",
"version": "0.1.24",
"cpu_count": 2,
"duration_seconds": 90.814144,
"journal_bytes": 456974336,
"ledger_bytes": 339193856,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds": 0.0,
"cpu_percent": 0.0,
"read_mib_s": 0.0,
"write_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 4168,
"cpu_seconds": 1.53125,
"cpu_percent": 0.8431,
"read_mib_s": 16.1736,
"write_mib_s": 0.0126
},
"rmm-agent-windows.exe": {
"pid": 404,
"cpu_seconds": 1.28125,
"cpu_percent": 0.7054,
"read_mib_s": 12.3686,
"write_mib_s": 0.0294
}
},
"idle_job_authorizations": 0,
"readiness_samples": 19,
"signed_decisions_observed": 4,
"ready_samples": 18
}
],
"candidate_0_1_23_revision": "478ee1fc1a8141845427011e566f5225eeebadd0",
"final_build_revision": "f01e81418e7b36a86bfb686542bd2f5380ecfe82",
"release": {
"release_id": "2032b236-4ab7-4dad-8e74-1144c5a5d165",
"version": "0.1.24",
"platform": "x86_64-pc-windows-gnu",
"manifest_sha256": "311e5df4979904907e54d5d1e08205decaf78fa3e3c6e34a68215f4873c2782d"
},
"activation": {
"method": "Signed automatic Windows GNU release pull in Development A",
"sequence": 25,
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
"services": [
{
"name": "RmmDiscoveryReleasePull",
"pid": 2384,
"state": "Running",
"sha256": "575ceb6a0b76c835d28646a498dfa73e88fb5de6343b77bf11d5eefea3fc68b1"
},
{
"name": "RmmDiscoverySystemHelper",
"pid": 4168,
"state": "Running",
"sha256": "bcff281db15549381f1fbe530af74ad4b44cefaa94a7c1c30e1f5a6a673ea556"
},
{
"name": "RmmDiscoveryWindows",
"pid": 404,
"state": "Running",
"sha256": "3c4727fd08ffecf3147221826087f125c6d835201b182b8ad1a4280c98ea0954"
}
],
"observed_at_utc": "2026-11-19T09:18:43.8141692Z",
"fresh_gateway_contact": "2026-11-19T09:18:40.275768+00:00"
},
"system_test": {
"operation_id": "e6d139c0-7f29-478d-87e8-38f466d8634f",
"job_id": "512f9311-4ace-4b64-9c60-24bb40719312",
"attempt_id": "d6e4a74a-4a56-4d95-b640-db4267c437eb",
"plan_hash": "7aeffea215d916810af3b7748fb3fb7bc715e5d9470d85e7f669bd20526ff2e7",
"stdout": "Windows-Konto S-1-5-18",
"exit_code": 0,
"state": "succeeded",
"observed_at": "2026-11-19T09:20:39.711Z",
"script_sha256": "8a0c76004a480aa11f6c768b2984e2cf2c01431009ccdbfb1607825133fcbc4f",
"approval": {
"principal": "simulated-testprincipal-a",
"approval_origin": "dev_test_browser_simulation",
"testsimulation": true,
"plan_hash": "7aeffea215d916810af3b7748fb3fb7bc715e5d9470d85e7f669bd20526ff2e7"
},
"preapproval": {
"jobs": 0,
"outbox": 0,
"grants": 0
},
"grants": 1
},
"final_health": {
"auth_contact": "2026-11-19T09:20:39.525258+00:00",
"contact": "2026-11-19T09:20:26.027274+00:00",
"generation": 80,
"active_jobs": 0,
"helper_ready": true,
"ready": true,
"system_run_script": true
},
"targeted_core_tests_passed": 70
}
+10 -1
View File
@@ -11,6 +11,15 @@
| Windows | `discwindowstest`, Windows 11 Pro x64, Agent `0.1.16` aus dem offiziellen GNU-Kanal |
| Quellstand mit Dokumentation | Gitea-Branch `main` |
## Ergänzungen zur Geräteansicht
- **OPNsense-Kernelabfrage, 19.11.2026:** Server/WebUI `2e060e9` und Client `0.1.0-opnsense.5` aktiv. Dieselbe Geräteidentität meldete einen angewendeten signierten Abgleich. Ein isolierter nativer Integrationstest auf dem Dienstkonto bestätigte `FreeBSD\n`/Exitcode 0 und genau eine Grant-Verwendung, auch nach doppelter Zustellung. Der getrennte, im öffentlichen Browser eingereichte [Geräteantrag](evidence/opnsense-probe-submission-20261119.json) hatte bei der Prüfung `pending_approval`, null Jobs, Outbox-Einträge und Startgrants. Für den fachlichen End-to-End-Nachweis fehlen persönliche Freigabe und das Ergebnis genau dieses Versuchs.
- **OPNsense-Testgerät:** OPNsense 26.7/FreeBSD 15.1 nativ in der Notebook-VM gestartet; Aufnahme per Kunden-Einmalcode, lokaler P-256-Schlüssel, ausgehendes mTLS. Die öffentliche Geräteansicht zeigte 91 aktive PF-Regeln und beide tatsächlichen Handshakes eines vorübergehenden lokalen WireGuard-Testpaars. Beide Testinterfaces wurden danach entfernt. OpenVPN ohne Verbindungen, IPsec-Dienst nicht erreichbar. Heartbeats, Inventar, CPU und RAM mit derselben Installation nach Agentwechsel geprüft. Version `0.1.0-opnsense.4` meldete Gerätetyp `virtual`, sechs Interfaces und 169 Pakete; Netzwerkkarte und Paketsuche wurden im öffentlichen Browser nachgelesen. Im Gast bestanden 71 Rust-Vertrags-/Abgleichtests, der Test der FreeBSD-Kerneluhr und zwei Prozessgruppenprüfungen als Dienstkonto. Noch offen: durchgängiger Skript-/Root-Jobpfad, signierter OPNsense-Releasekanal und öffentliche Erstinstallation. [Betrieb](../deploy/opnsense/README.md) · [Nachweis](evidence/opnsense-test-device-20261119.json)
- **RAM-Balken:** Der alte Balken hob bei „RAM frei / gesamt“ den belegten Anteil hervor. Der neue Balken färbt verfügbare Kapazität grün und belegte grau und beschriftet den freien Anteil direkt. Bei fehlenden oder ungültigen Werten wird kein Balken gezeichnet. Build, 80 Komponententests und sechs Browserprüfungen einschließlich 0 %, 75 % und 100 % frei bestanden. WebUI `577a6ee` am 19. November 2026 um 18:38 UTC ausgeliefert. Angemeldetes Chromium bestätigte für neun reale Geräte die gerenderten Segmentbreiten und Beschriftungen bei 1280, 900 und 390 px. API, Datenbank und Agenten mussten nicht geändert werden. [Browserregression](../tests/browser/customer-management.spec.ts)
- **Zweck je Gerät:** Optionale Spalte im Bestand und in der Historie, Freitextpflege im Gerätedetail. WebUI-Build, 80 Komponententests, fünf Browserprüfungen und HTTP-Rundlauf auf isoliertem PostgreSQL mit Schreib-, Lese- und Fremdkundenfällen bestanden. Am 19. November 2026 um 14:10 UTC wurde `2070ae9` mit [Migration 45](../migrations/0045_device_purpose.sql) aktiviert. API, öffentliche API und Gateway bestanden die TLS-Healthchecks; der öffentliche WebUI-Index entsprach dem Build. Angemeldetes Chromium zeigte die Zweck-Spalte für sechs Geräte, den Editor im Gerätedetail und die Spalte bei 390 px Breite. Bei der Live-Sichtprüfung wurde nichts gespeichert; kein Agentwechsel. [Bedienung](public-access.md#zweck-eines-geräts-pflegen) · [Browserregression](../tests/browser/device-purpose.spec.ts)
## Geräteaktionen über MCP
Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederanmeldung derselben Kopplung nach einem tatsächlichen Bootwechsel geprüft. Der Ping wurde jeweils erst nach dieser Wiederanmeldung eingereicht. Die Zeiten in der Tabelle sind UTC.
@@ -35,7 +44,7 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
| Von der Auswahl zur Ausgabe | Die WebUI bindet die ausgewählte Skriptversion, zeigt den Inhalt vor Genehmigung und verlinkt das Ergebnis je Gerät. Ein abgelehnter Antrag erzeugte null Jobs. [Auftragsablauf](evidence/webui-auftragsablauf-20261117.json) · [Ergebnislinks und Entscheidungen](evidence/webui-order-history-20261118.json) Auf OTRS ARM64 wurde der Root-Skript-Helper nachträglich mit dem HTTPS-Installer aktiviert. Die zentrale Geräteregel bindet das berechtigte WebUI-Konto an diese Installation und den signierten Helper. Die öffentliche WebUI-Vorschau akzeptierte Root für OTRS. Die Probe blieb bei einer Vorschau und erzeugte null Anträge, Jobs, Outbox-Einträge und Startgrants. [OTRS-Nachweis](evidence/linux-arm64-otrs-root-helper-20261118.json) |
| Frische Installation und periodisches Agentupdate | Beide VMs wurden über HTTPS aufgenommen und übernahmen anschließend ein signiertes Folgepaket mit derselben Geräteidentität. Auf Windows ist der öffentliche GNU-Kanal einschließlich Prüfung des offiziellen Schlüssels belegt. [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows GNU](evidence/windows-gnu-official-vm-20261118.json). ARM64 erweitert denselben HTTPS-Installer mit automatischer Architekturerkennung. Release `0.1.0-arm64.1` ist veröffentlicht und als Starter verfügbar. Auf Ubuntu 22.04.5 ARM64 wurden die öffentlichen Downloads, die Signaturprüfung, die Ablehnung einer veränderten Agentdatei und der native Start aller drei Dateien im Prüfmodus beobachtet. OTRS ist mit Gerätezertifikat aufgenommen und meldet authentisierte Heartbeats. Die erste Kontaktprüfung wartet seit der Korrektur auf das Zertifikat. Der öffentliche Installer lief auf OTRS erneut ohne Traceback und ohne neuen Einmalcode. Der ARM64-Katalogabruf ist bestätigt. Ein späterer Versionswechsel auf ARM64 steht aus. [ARM64-Release](evidence/linux-arm64-installer-20261118.json) · [Geräteaufnahme und Nachtest](evidence/linux-arm64-enrollment-heartbeat-20261118.json) |
| Betriebssystemupdate per PowerShell | Die Windows-Updatevorlage installierte KB890830 v5.147 als SYSTEM. Ergebnis und Windows-Ereignis 19 bestätigen die Installation. [Installationsbeleg](evidence/windows-update-installation-20261117.json) |
| Windows im Leerlauf | Windows GNU `0.1.20` aus `a4bcebf` aktualisiert den signierten Zeitbeleg des Helpers nach erfolgreicher Abfrage im Abstand von fünf Sekunden. Der Testgast übernahm das Paket mit derselben Geräteidentität. Im Leerlauf sank die CPU-Last des Agenten von 15,20 % auf 2,30 % und die des Helpers von 15,67 % auf 2,72 %. Der in der internen Entwicklungs-WebUI genehmigte PowerShell-Testauftrag meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. Beide Dienste blieben synchron. [Leerlaufmessung und SYSTEM-Test](evidence/windows-idle-cpu-20261118.json) Am 19.11. senkte `0.1.24` im jeweils 91 Sekunden langen Leerlauftest die Gast-CPU-Last von 3,15 % auf 0,71 % beim Agenten und von 11,82 % auf 0,84 % beim Helper. Die Lastspitzen fielen mit wiederholten Vollprüfungen großer SQLite-Dateien und der kompletten signierten Helperhistorie zusammen. Der Agent prüft im Leerlauf alle 250 ms auf Arbeit. Vollprüfungen bleiben für anstehende SYSTEM-Aufträge und den Nachweis unterbliebener Ausführung erhalten. Der Testgast übernahm das signierte Paket mit denselben Geräte- und Agentenkennungen. Der erneut in der Entwicklungs-WebUI genehmigte SYSTEM-Test meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. [Folgemessung und Abnahme](evidence/windows-idle-cpu-followup-20261119.json) |
| Windows im Leerlauf | Windows GNU `0.1.20` aus `a4bcebf` aktualisiert den signierten Zeitbeleg des Helpers nach erfolgreicher Abfrage im Abstand von fünf Sekunden. Der Testgast übernahm das Paket mit derselben Geräteidentität. Im Leerlauf sank die CPU-Last des Agenten von 15,20 % auf 2,30 % und die des Helpers von 15,67 % auf 2,72 %. Der in der internen Entwicklungs-WebUI genehmigte PowerShell-Testauftrag meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. Beide Dienste blieben synchron. [Leerlaufmessung und SYSTEM-Test](evidence/windows-idle-cpu-20261118.json) |
| Wiederanlauf | Nach einem Gatewaywechsel wurde der Windows-Agent ohne manuellen Dienstneustart wieder bereit. Der Helper glich seine bereits quittierte Ergebnismeldung ab. [Gatewaywechsel](evidence/windows-gateway-clock-recovery-20261117.json) · [Helper-Abgleich](evidence/windows-helper-result-recovery-20261118.json) |
| WebUI-Abschluss eines ungeklärten Versuchs | Auf OTRS ARM64 war derselbe Versuch zentral als `closed_unknown` abgeschlossen und lokal wegen unterschiedlicher Befunde noch blockiert. Der Agent hatte eine archivierte Unterbrechungsmeldung, beide Verbrauchsjournale hatten den ursprünglichen Start und kein Ergebnis. 71 Tests zu `915e126` prüfen den signierten Abschluss in Agent und Helper, den Erhalt der Originale und den Wiederanlauf nach unterbrochenen Journalaktualisierungen. Am 18. November um 18:05 UTC startete das bestehende Gerät einmal kontrolliert unter exklusiver Startsperre mit dem über mTLS abgerufenen signierten Paar `0.1.0-arm64.3`. Beide Verbrauchsjournale übernahmen den bereits vorhandenen WebUI-Abschluss. Die archivierte Originalmeldung, die Startbelege und die Geräteidentität waren unverändert nachweisbar. Der native Updater meldete `idle`, Agent und Helper waren nach dem Abgleich bereit und der reguläre Updatetimer war aktiv. Linux x64 übernahm `0.1.0-mvp.9` über den regulären Timer. [Geräteabgleich](../crates/agent-core/tests/reconcile.rs) |
+4
View File
@@ -8,6 +8,10 @@ Die öffentliche WebUI verwendet ein lokales Benutzerkonto mit Passwort und eine
Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1)
### Zweck eines Geräts pflegen
Unter **Geräte** den Hostnamen öffnen und im Abschnitt **Zweck** auf **Zweck bearbeiten** klicken. Der Freitext darf bis zu 500 Zeichen enthalten. Speichern übernimmt ihn auch in die Übersicht. Zum Entfernen das Feld leeren und erneut speichern. Das Bearbeiten erfordert `inventory:read` und `devices:revoke` im betreffenden Kunden.
### Hypervisor einer VM zuordnen
Eine VM unter **Geräte** öffnen und unter **Gerät verwalten → Hypervisor zuordnen** einen Host aus demselben Kundenbestand auswählen. Die Zuordnung speichern. Der Hostname erscheint unter dem VM-Namen in der Übersicht und öffnet die Details des Hypervisors. **Kein konkreter Hypervisor** entfernt die gespeicherte Zuordnung.
+3
View File
@@ -0,0 +1,3 @@
-- Operator metadata belongs to the asset, not the installation or its inventory.
ALTER TABLE assets ADD COLUMN purpose text CHECK (char_length(purpose) BETWEEN 1 AND 500);
GRANT UPDATE(purpose) ON assets TO rmm_app;
+6
View File
@@ -0,0 +1,6 @@
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '30s';
ALTER TABLE observations DROP CONSTRAINT observations_source_id_check;
ALTER TABLE observations ADD CONSTRAINT observations_source_id_check
CHECK (source_id IN ('linux.base','windows.base','agent.update','opnsense.base')) NOT VALID;
ALTER TABLE observations VALIDATE CONSTRAINT observations_source_id_check;
+62 -5
View File
@@ -20,6 +20,63 @@ test.beforeAll(async () => {
test.afterAll(async () => { await server?.close(); });
test('draws the free RAM share accurately on desktop and mobile', async ({ page }) => {
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'RAM-Test' };
const gib = 2 ** 30;
const readings = [
['mostly-free', 12 * gib, 16 * gib],
['all-used', 0, 16 * gib],
['all-free', 16 * gib, 16 * gib],
['missing-available', null, 16 * gib],
['invalid-range', 17 * gib, 16 * gib],
['invalid-total', 0, 0],
] as const;
const listing = (items: unknown[]) => ({
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-19T12:00:00Z'
});
await page.route(`${origin}/auth/config`, route => route.fulfill({
json: { local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }
}));
await page.route(`${origin}/auth/session`, route => route.fulfill({
json: { principal: 'ram-reader', testsimulation: false, tenant_id: customer.tenant_id,
csrf_token: 'ram-fixture', permissions: ['inventory:read'] }
}));
await page.route(`${origin}/api/v1/**`, route => {
const pathname = new URL(route.request().url()).pathname;
if (pathname === '/api/v1/tenants') return route.fulfill({ json: listing([customer]) });
if (pathname === '/api/v1/devices') return route.fulfill({
json: listing(readings.map(([hostname, free, total]) => ({
tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: hostname, agent_id: hostname,
lifecycle: 'current', status: 'online', hostname, ram_available_bytes: free, ram_total_bytes: total,
disk_free_bytes: 12 * gib, disk_total_bytes: 16 * gib
})))
});
return route.fulfill({ status: 404 });
});
await page.goto(`${origin}/#geraete`);
const row = (host: string) => page.getByRole('row').filter({ has: page.getByRole('button', { name: host, exact: true }) });
const ram = (host: string) => row(host).locator('[data-label="RAM frei / gesamt"]');
await expect(ram('mostly-free')).toContainText('12 / 16 GiB');
await expect(ram('mostly-free').locator('.capacity-caption')).toHaveText('75 % frei');
await expect(row('mostly-free').locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
for (const width of [1280, 900, 390]) {
await page.setViewportSize({ width, height: 844 });
for (const [host, free] of [['mostly-free', 75], ['all-used', 0], ['all-free', 100]] as const) {
const bar = ram(host).getByRole('img', { name: `${free} % frei, ${100 - free} % belegt` });
await expect(bar).toBeVisible();
const [track = 0, freeWidth = 0, usedWidth = 0] = await bar.evaluate(el => [el, ...Array.from(el.children)]
.map(part => part.getBoundingClientRect().width));
expect(track).toBeGreaterThan(0);
expect(freeWidth / track).toBeCloseTo(free / 100, 2);
expect(usedWidth / track).toBeCloseTo((100 - free) / 100, 2);
}
}
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) {
await expect(ram(host).locator('.capacity-track')).toHaveCount(0);
}
});
test('creates and renames a customer, opens its inventory, and hides editing for a reader', async ({ page }) => {
const home = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Testzentrale' };
const customerId = '22222222-2222-4222-8222-222222222222';
@@ -108,12 +165,12 @@ test('creates and renames a customer, opens its inventory, and hides editing for
const headers = page.locator('.fleet-table thead th[scope="col"]');
await expect(headers.nth(0)).toHaveText('Hostname');
await expect(headers.nth(1)).toHaveText('Type');
await expect(device.getByRole('cell').nth(2)).toHaveText('hypervisor');
await expect(device.getByRole('cell').nth(3)).toHaveText('Proxmox VE');
await expect(device.locator('[data-label="Type"]')).toHaveText('hypervisor');
await expect(device.locator('[data-label="OS"]')).toHaveText('Proxmox VE');
const memory = device.locator('[data-label="RAM frei / gesamt"]');
await expect(memory).toHaveText('6 / 16 GiB');
await expect(memory.locator('.capacity-track')).toHaveAttribute('title', '37,5 % frei');
await expect(memory.locator('.capacity-track i')).toHaveAttribute('style', 'width: 62.5%;');
await expect(memory).toContainText('6 / 16 GiB');
await expect(memory.getByRole('img', { name: '37,5 % frei, 62,5 % belegt' })).toBeVisible();
await expect(memory.locator('.capacity-free')).toHaveAttribute('style', 'width: 37.5%;');
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
+98
View File
@@ -0,0 +1,98 @@
import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
import { resolve } from 'node:path';
let server: ViteDevServer;
let origin: string;
test.beforeAll(async () => {
server = await createServer({
root: resolve(__dirname, '../../web'), configFile: false,
server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent'
});
await server.listen();
const address = server.httpServer!.address();
if (!address || typeof address === 'string') throw new Error('Missing local fixture address');
origin = `http://127.0.0.1:${address.port}`;
});
test.afterAll(async () => { await server?.close(); });
test('shows, edits and clears device purpose without giving readers an editor', async ({ page }) => {
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Fixture' };
const path = `/api/v1/tenants/${customer.tenant_id}/devices/device-1`;
const listing = (items: unknown[]) => ({
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-19T12:00:00Z'
});
let purpose: string | null = null;
let writer = true;
let reject = true;
const writes: string[] = [];
const device = () => ({
tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: 'device-1', agent_id: 'agent-1',
lifecycle: 'current', status: 'online', hostname: 'DATEN-SRV', os: 'Linux', purpose
});
await page.route(`${origin}/auth/config`, route => route.fulfill({
json: { local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }
}));
await page.route(`${origin}/auth/session`, route => route.fulfill({
json: {
principal: writer ? 'device-operator' : 'inventory-reader', testsimulation: false,
tenant_id: customer.tenant_id, csrf_token: 'purpose-csrf',
permissions: writer ? ['inventory:read', 'devices:revoke'] : ['inventory:read']
}
}));
await page.route(`${origin}/api/v1/**`, route => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
if (request.method() === 'GET') {
if (pathname === '/api/v1/tenants') return route.fulfill({ json: listing([customer]) });
if (pathname === '/api/v1/devices') return route.fulfill({ json: listing([device()]) });
if (pathname === path) return route.fulfill({ json: device() });
}
if (request.method() === 'PATCH' && pathname === `${path}/purpose`) {
expect(writer).toBe(true);
expect(request.headers()['x-csrf-token']).toBe('purpose-csrf');
expect(request.headers()['x-rmm-tenant']).toBe(customer.tenant_id);
const text = request.postDataJSON().purpose;
writes.push(text);
if (reject) return route.fulfill({ status: 403, json: { code: 'FORBIDDEN', message: 'Speichern abgelehnt' } });
purpose = text.trim() || null;
return route.fulfill({ json: { asset_id: 'device-1', purpose } });
}
return route.fulfill({ status: 404, json: { code: 'UNEXPECTED_FIXTURE_REQUEST', message: pathname } });
});
await page.goto(`${origin}/#geraete`);
await expect(page.getByRole('columnheader', { name: 'Zweck' })).toBeVisible();
await expect(page.getByRole('cell', { name: 'Nicht hinterlegt' })).toBeVisible();
await page.getByRole('button', { name: 'DATEN-SRV' }).click();
await page.getByRole('button', { name: 'Zweck bearbeiten' }).click();
const editor = page.getByRole('textbox', { name: 'Zweck des Geräts' });
const save = page.getByRole('button', { name: 'Zweck speichern' });
await editor.fill('ü'.repeat(501));
await expect(save).toBeDisabled();
expect(writes).toEqual([]);
const text = 'Dateien für Nürnberg\n<intern>';
await editor.fill(text);
await save.click();
await expect(page.getByRole('alert')).toContainText('Speichern abgelehnt');
await expect(editor).toHaveValue(text);
reject = false;
await save.click();
await expect(page.getByText('Zweck gespeichert.')).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await expect(page.locator('td[data-label="Zweck"]')).toHaveText(text.replace('\n', ' '));
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.locator('td[data-label="Zweck"]')).toBeVisible();
await page.getByRole('button', { name: 'DATEN-SRV' }).click();
await page.getByRole('button', { name: 'Zweck bearbeiten' }).click();
await expect(editor).toHaveValue(text);
await editor.fill('');
await save.click();
await expect(page.getByText('Nicht hinterlegt', { exact: true })).toBeVisible();
expect(writes).toEqual([text, text, '']);
writer = false;
purpose = text;
await page.reload();
await expect(page.locator('.device-purpose .purpose-text')).toHaveText(text.replace('\n', ' '));
await expect(page.getByRole('button', { name: 'Zweck bearbeiten' })).toHaveCount(0);
});
+9 -1
View File
@@ -14,7 +14,15 @@ function values(value: unknown) {
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
}
function observation(device: RecordValue, name: string) {
function observation(device: RecordValue, name: string): RecordValue | undefined {
if (device.source_id === 'opnsense.base') {
const inv = object(device.inventory);
if (name === 'hardware' || name === 'os') return { data: inv.hardware };
const report = object(inv[name]);
if (report.status === 'ok' || report.status === 'partial')
return { data: report.entries, truncated: report.status === 'partial' };
return undefined;
}
const observations = object(device.inventory).observations;
return Array.isArray(observations) ? observations.map(object).find(item =>
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
+107 -18
View File
@@ -17,6 +17,8 @@ import { allowed } from './safety';
import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { OPNsenseDetails } from './opnsense';
import { OPNsenseProbe } from './opnsense-probe';
import { DeviceCustomerTransfer } from './device-customer-transfer';
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
import { ErrorBox, errorText, useResource } from './resource';
@@ -29,6 +31,7 @@ import { SyncAlignmentReview } from './sync-alignment-review';
import { SystemNonstartReview } from './system-nonstart-review';
const unknown = 'Nicht gemeldet';
const noPurpose = 'Nicht hinterlegt';
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
function label(value: unknown) {
@@ -88,24 +91,35 @@ function Presence({ d }: { d: RecordValue }) {
</span>
);
}
function Capacity({ free, total }: { free: unknown; total: unknown }) {
function Capacity({ free, total, showBreakdown = false }: {
free: unknown;
total: unknown;
showBreakdown?: boolean;
}) {
const freePercent = typeof free === 'number' && typeof total === 'number' &&
Number.isFinite(total) && free >= 0 && free <= total && total > 0
? (free / total) * 100
: null;
const displayFree = freePercent === null ? null : Math.round(freePercent * 10) / 10;
const freeLabel = displayFree === null ? '' : `${number.format(displayFree)} % frei`;
const breakdown = displayFree === null ? '' : `${freeLabel}, ${number.format(100 - displayFree)} % belegt`;
return (
<>
<span>{capacity(free, total)}</span>
{typeof free === 'number' &&
typeof total === 'number' &&
Number.isFinite(total) &&
free >= 0 &&
free <= total &&
total > 0 && (
<span
className="capacity-track"
title={`${number.format((100 * free) / total)} % frei`}
aria-hidden="true"
>
<i style={{ width: `${(100 * (total - free)) / total}%` }} />
{freePercent !== null && (showBreakdown ? (
<>
<span className="capacity-track capacity-breakdown" role="img"
aria-label={breakdown} title={breakdown}>
<span className="capacity-free" style={{ width: `${freePercent}%` }} />
<span className="capacity-used" />
</span>
)}
<small className="capacity-caption" aria-hidden="true">{freeLabel}</small>
</>
) : (
<span className="capacity-track" title={freeLabel} aria-hidden="true">
<i style={{ width: `${100 - freePercent}%` }} />
</span>
))}
</>
);
}
@@ -127,6 +141,64 @@ function devicePath(customer: string, asset: string) {
return tenantPath(customer, '/devices/' + encodeURIComponent(asset));
}
function DevicePurpose({ value, path, customer, editor, success, onSaved }: {
value: string;
path: string;
customer: string;
editor: Session | null;
success: boolean;
onSaved: () => void;
}) {
const [draft, setDraft] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const tooLong = Array.from(draft?.trim() ?? '').length > 500;
const close = () => { setDraft(null); setError(null); };
return (
<section className="device-purpose">
<h2>Zweck</h2>
{editor && draft !== null ? (
<form onSubmit={async (e) => {
e.preventDefault();
if (busy || tooLong) return;
setBusy(true);
setError(null);
try {
await request(path + '/purpose', {
method: 'PATCH', tenantId: customer, csrf: editor.csrf_token, body: { purpose: draft }
});
close();
onSaved();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}}>
<label>
Zweck des Geräts
<textarea autoFocus rows={3} value={draft} disabled={busy}
aria-describedby="device-purpose-help" aria-invalid={tooLong}
onChange={(e) => setDraft(e.target.value)} />
</label>
<p id="device-purpose-help" className={tooLong ? 'error' : 'muted'}>
{tooLong ? 'Der Zweck ist zu lang. ' : ''}Maximal 500 Zeichen. Zum Entfernen das Feld leeren.
</p>
<ErrorBox error={error} />
<button type="submit" disabled={busy || tooLong}>{busy ? 'Speichert …' : 'Zweck speichern'}</button>{' '}
<button type="button" className="quiet" disabled={busy} onClick={close}>Abbrechen</button>
</form>
) : (
<>
<p className={'purpose-text' + (value ? '' : ' muted')}>{value || noPurpose}</p>
{editor && <button className="quiet" onClick={() => setDraft(value)}>Zweck bearbeiten</button>}
{success && <p role="status">Zweck gespeichert.</p>}
</>
)}
</section>
);
}
function reportedScriptProfiles(device: RecordValue) {
const os = devicePlatform(device);
if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet';
@@ -176,6 +248,7 @@ function DeviceDetail({
[error, setError] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
const [managing, setManaging] = useState(false);
const [purposeSaved, setPurposeSaved] = useState(false);
const d = detail.data;
const scoped = membership.data;
const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : [];
@@ -221,6 +294,16 @@ function DeviceDetail({
))}
</dl>
</section>
<DevicePurpose
value={typeof d.purpose === 'string' ? d.purpose : ''}
path={path}
customer={customer}
editor={scoped && allowed(scoped, 'devices:revoke') && allowed(scoped, 'inventory:read') ? scoped : null}
success={purposeSaved}
onSaved={() => { setPurposeSaved(true); detail.reload(); }}
/>
<OPNsenseDetails device={d} />
{scoped && <OPNsenseProbe key={`${customer}/${asset}/${agent}`} device={d} auth={scoped}/>}
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
@@ -557,9 +640,9 @@ export function Devices({
<span className="sr-only">Ziel auswählen</span>
</th>
)}
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
{['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
(h) => (
<th scope="col" key={h}>
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
{h}
</th>
)
@@ -571,7 +654,8 @@ export function Devices({
const asset = objectId(d, 'asset'),
agent = objectId(d, 'agent'),
customer = objectId(d, 'tenant'),
model = cpu(d);
model = cpu(d),
purpose = typeof d.purpose === 'string' ? d.purpose : '';
const show = () => {
setDeletionNotice('');
window.location.hash = ['geraete', customer, asset, agent]
@@ -608,6 +692,11 @@ export function Devices({
<HypervisorLabel device={d} />
</td>
<td data-label="Type">{label(d.device_type)}</td>
<td data-label="Zweck" className="purpose-col">
<span className={'purpose-text' + (purpose ? '' : ' muted')} title={purpose || undefined}>
{purpose || noPurpose}
</span>
</td>
<td data-label="OS">{label(d.os)}</td>
<td data-label="Status" className="device-presence">
<Presence d={d} />
@@ -619,7 +708,7 @@ export function Devices({
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} />
</td>
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} showBreakdown />
</td>
<td data-label="CPU">
{model.primary}
+48
View File
@@ -0,0 +1,48 @@
import { useState } from 'react';
import { objectId, record, request, tenantPath, type RecordValue, type Session } from './api';
import { allowed } from './safety';
import { verifiedScriptOrder } from './order-composer';
import { ErrorBox, errorText } from './resource';
export function OPNsenseProbe({ device, auth }: {device: RecordValue; auth: Session}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [ticket, setTicket] = useState<{id:string; hash:string} | null>(null);
const [operation, setOperation] = useState<string | null>(null);
if (device.source_id !== 'opnsense.base' || device.lifecycle !== 'current' ||
!Array.isArray(device.capabilities) || !device.capabilities.includes('opnsense.uname/1') ||
!allowed(auth,'operations:plan') || !allowed(auth,'scripts:execute')) return null;
const customer = objectId(device,'tenant'), asset = objectId(device,'asset'), agent = objectId(device,'agent');
const path = tenantPath(customer,'/operation-plans');
async function submit() {
setBusy(true); setError(null);
try {
let pending = ticket;
if (!pending) {
const now = Date.now(), start = new Date(now).toISOString(), end = new Date(now+86400000).toISOString();
const reason = 'OPNsense: Kernelname auf dem Dienstkonto prüfen';
const raw = await request(path, {csrf:auth.csrf_token,body:{tenant_id:customer,action:'run_script',
targets:{asset_ids:[asset]},parameters:{execution_identity:'agent_service',timeout_seconds:10,
max_output_bytes:1024,arguments:[],expected_stdout:'FreeBSD\n',
variants:[{os_family:'opnsense',interpreter:'posix_sh',encoding:'utf-8',script_utf8:'uname -s\n'}]},
schedule:{not_before:start,start_before:end,offline_policy:'wait_until_deadline'},
rollout:{max_parallel:1,halt_after_failures:1},reason}});
const checked = await verifiedScriptOrder(raw,customer,auth.principal.id), j = checked.jobs[0];
if (!j || checked.jobs.length!==1 || j.assetId!==asset || j.agentId!==agent || j.identity!=='agent_service' ||
j.script!=='uname -s\n' || j.expectedStdout!=='FreeBSD\n' || j.interpreter!=='posix_sh' ||
j.arguments.length || j.runtimeSeconds!==10 || j.outputBytes!==1024 || checked.reason!==reason ||
Date.parse(j.notBefore)!==now || Date.parse(j.startBefore)!==Date.parse(end) ||
checked.maxParallel!==1 || checked.halt!==1) throw Error('Plan weicht von der Kernelabfrage ab.');
pending = {id:objectId(checked.plan,'plan'),hash:String(checked.plan.plan_hash)};
setTicket(pending);
}
const r = record(await request(path+'/'+pending.id+'/submit',{csrf:auth.csrf_token,body:{idempotency_key:pending.id}}));
if (r.plan_id!==pending.id || r.plan_hash!==pending.hash) throw Error('Planbindung stimmt nicht.');
setOperation(objectId(r,'operation'));
} catch (e) { setError(errorText(e)); } finally { setBusy(false); }
}
return <section><h2>OPNsense-Kernelabfrage</h2><p><code>uname -s</code> als Dienstkonto · ein Versuch · 10 Sekunden · 1 KiB Ausgabe.</p>
{operation && ticket ? <p>Auftrag eingereicht. <a href={`#genehmigungen/pruefen/${customer}/${ticket.id}`}>Zur Genehmigung</a></p>
: <button disabled={busy} onClick={submit}>Kernelabfrage zur Genehmigung einreichen</button>}
<ErrorBox error={error}/></section>;
}
+24
View File
@@ -0,0 +1,24 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { OPNsenseDetails } from './opnsense';
import { DeviceInventoryPanels } from './device-inventory';
it('keeps missing, empty and partial appliance sources distinct and limits panels to OPNsense', () => {
const d = { source_id:'opnsense.base', inventory:{
ipsec:{status:'unavailable',entries:[]}, openvpn:{status:'ok',entries:[]},
firewall:{status:'partial', entries:['pass in on vtnet0']},
interfaces:{status:'ok', entries:[{name:'vtnet0',addresses:['192.0.2.1/24']}]},
software:{status:'ok',entries:[{name:'opnsense',version:'26.7'}]},
users:{status:'unavailable',entries:[]}
}};
const view = renderToStaticMarkup(<OPNsenseDetails device={d}/>);
expect(view).toMatch(/IPsec[^<]*<\/h3><p>Nicht ermittelbar/);
expect(view).toMatch(/OpenVPN[^<]*<\/h3><p>Keine Einträge/);
expect(view).toContain('unvollständige Liste');
expect(view).toContain('pass in on vtnet0');
expect(renderToStaticMarkup(<OPNsenseDetails device={{...d,source_id:'linux.base'}}/>)).toBe('');
const system = renderToStaticMarkup(<DeviceInventoryPanels device={d}/>);
expect(system).toContain('192.0.2.1/24');
expect(system).toContain('26.7');
expect(system).not.toContain('Keine Benutzer angemeldet');
});
+24
View File
@@ -0,0 +1,24 @@
import type { RecordValue } from './api';
export function OPNsenseDetails({ device }: { device: RecordValue }) {
if (device.source_id !== 'opnsense.base') return null;
const inventory = device.inventory as RecordValue | null;
function list(key: string, title: string) {
const report = inventory?.[key] as RecordValue | undefined;
const available = report?.status === 'ok' || report?.status === 'partial';
const rows = Array.isArray(report?.entries) ? report.entries.filter((x): x is string => typeof x === 'string') : [];
return <div key={key}><h3>{title}</h3>{!available ? <p>Nicht ermittelbar</p> : <>
{report?.status === 'partial' && <p>Auszug – unvollständige Liste</p>}
{rows.length ? <ol>{rows.map((line, i) => <li key={i}><code>{line}</code></li>)}</ol> : <p>Keine Einträge gemeldet.</p>}
</>}</div>;
}
return <>
<section><h2>VPN-Verbindungen</h2>
{list('vpn_configured', 'Konfigurierte VPNs')}
{list('wireguard', 'WireGuard · letzter Handshake je Peer')}
{list('openvpn', 'OpenVPN · Laufzeitstatus')}
{list('ipsec', 'IPsec · aktive Sicherheitsassoziationen')}
</section>
<section><h2>Firewallregeln</h2>{list('firewall', 'Aktive PF-Filterregeln · Hauptregelsatz in Auswertungsreihenfolge')}</section>
</>;
}
+1 -1
View File
@@ -81,7 +81,7 @@ function resumeTicket(key: string): Ticket | null {
}
return data;
}
async function verifiedScriptOrder(value: unknown, tenantId: string, principal: string) {
export async function verifiedScriptOrder(value: unknown, tenantId: string, principal: string) {
const plan = record(value, 'Auftragsplan');
await verifyPlanIntegrity(plan);
await verifyScriptPlan(plan);
+10 -1
View File
@@ -97,12 +97,20 @@ section.fleet { padding:0; overflow:hidden; }
.vm-hypervisor { display:flex; align-items:baseline; gap:6px; margin-top:5px; color:var(--subtle); font-size:.78rem; overflow-wrap:anywhere; }
.vm-hypervisor .nav-icon { width:13px; height:13px; flex:none; align-self:flex-start; margin-top:2px; }
.fleet-table .target-col { width:35px; }
.fleet-table th.purpose-col { width:17%; }
.purpose-text { white-space:pre-wrap; overflow-wrap:anywhere; }
.fleet-table .purpose-text { display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:3; overflow:hidden; }
.device-purpose textarea { font-family:inherit; }
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
.fleet-table input[type=checkbox] { margin:0; }
.host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; }
.fleet-table .capacity-cell { font-variant-numeric:tabular-nums; }
.capacity-track { display:block; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:4px; margin-top:6px; overflow:hidden; }
.capacity-track i { display:block; height:100%; background:#659d84; }
.capacity-breakdown { display:flex; height:6px; }
.capacity-free { flex:none; background:#2e7657; }
.capacity-used { flex:1; background:#b5c2be; }
.capacity-caption { display:block; color:var(--subtle); }
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }
.presence i { width:6px; height:6px; border-radius:50%; background:currentColor; }
.presence.online { color:#236343; background:#e6f4e9; }
@@ -156,7 +164,8 @@ section.fleet { padding:0; overflow:hidden; }
.fleet-table td,.fleet-table td:first-child,.fleet-table td:last-child {display:block;padding:0;border:0;font-size:.9rem;}
.fleet-table td[data-label]::before {content:attr(data-label);display:block;color:var(--subtle);font-size:.73rem;}
.fleet-table .hostname {grid-column:1/-1;padding-right:28px;} .host-link {font-size:1rem;}
.fleet-table .target-col {position:absolute;right:14px;top:14px;width:auto;} .capacity-track {width:76px;}
.fleet-table .purpose-col {grid-column:1/-1;}
.fleet-table .target-col {position:absolute;right:14px;top:14px;width:auto;} .capacity-track {width:min(76px,100%);}
.list-footer {border-top:1px solid var(--line);flex-wrap:wrap;} .facts {grid-template-columns:1fr 1fr;gap:12px;}
}
@media(max-width:450px) { .sidebar nav a {flex-direction:column;gap:2px;} .crumb span,.crumb i {display:none;} .login {margin:18px 12px;} .facts {grid-template-columns:1fr;} }