37 Commits
Author SHA1 Message Date
kevin_janssenandClaude Fable 5.2 e29257b808 Group the device overview by hypervisor, Hetzner, physical and unassigned devices
Rust development slice / linux (push) Failing after 7s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 22:57:02 +01:00
kevin_janssenandClaude Opus 5.5 dbfa76184d Record the Proxmox host acceptance: guests, backups, automatic VM mapping and failure cases
Rust development slice / linux (push) Failing after 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:05:05 +01:00
kevin_janssenandClaude Opus 5.5 a1b22070de Count a vzdump run that fails before its first guest as a failed backup
Rust development slice / linux (push) Failing after 7s
Found on the Proxmox test host: with the target storage disabled the scheduled
run ends with an error and its log names no guest, which was reported as
'missed'. Such a job-level or same-guest run now marks the covered guests failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:01:29 +01:00
kevin_janssenandClaude Opus 5.5 29acaa5b08 Pin backup evaluation to the report of the Proxmox VE 9.2 test host
Rust development slice / linux (push) Failing after 10s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:48:37 +01:00
kevin_janssenandClaude Opus 5.5 9fa6c05af7 Document the Proxmox host, its read-only access and the local Proxmox test VM
Rust development slice / linux (push) Failing after 15s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:17:23 +01:00
kevin_janssenandClaude Opus 5.5 63447f1b87 Provision a read-only Proxmox VE token during HTTPS installation
Rust development slice / linux (push) Failing after 15s
On hosts with pveversion and pveum the installer creates rmm-discovery@pve with
a privilege-separated PVEAuditor token, copies the cluster CA and passes both to
the agent through a systemd credential drop-in. Existing tokens are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:05 +01:00
kevin_janssenandClaude Opus 5.5 ce356f0de7 Show Proxmox guests and scheduled backup status in device details
Rust development slice / linux (push) Failing after 14s
The host detail lists VMs and containers with linked inventory devices and
last successful backup, each vzdump job with its due time and result, an
overall 'all scheduled backups ran' answer and guests without a job. VM hosts
detected from a Proxmox guest list are labelled and the assignment form can
hand the decision back to automatic detection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:12:54 +01:00
kevin_janssenandClaude Opus 5.5 70977df577 Validate Proxmox observations, evaluate scheduled backups and link VMs to their Proxmox host
Rust development slice / linux (push) Failing after 15s
linux.proxmox gets a strict validator and a 128 KiB scope budget. Device
details expose guests, backup jobs with ok/failed/missed/running status and
linked devices. Base snapshots reconcile unique guest MACs into
assets.hypervisor_asset_id with hypervisor_source='proxmox'; manual choices
are kept and can be handed back to automatic detection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:10:35 +01:00
kevin_janssenandClaude Opus 5.5 1d2d52847c Collect Proxmox VE guests, backup jobs and vzdump runs as a read-only linux.proxmox scope
Rust development slice / linux (push) Failing after 12s
The Linux agent queries the local PVE API with a PVEAuditor token from the
systemd credential rmm-proxmox-token and the pinned cluster CA. Guests carry
MAC addresses and SMBIOS UUIDs for hypervisor mapping; jobs carry covered
guests and the scheduler's last expected run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:04:13 +01:00
kevin_janssenandClaude Opus 5.5 4459fbf79f Merge live Windows agent 0.1.27 source into the deployed server state
Rust development slice / linux (push) Failing after 14s
main now matches what runs on discovery.ease-technologies.de on 2026-11-20:
- Server, gateway, public API and WebUI: image rmm-dev-server:79f236b
  (schema 47), plus the follow-up docs commit fb35dbd.
- Windows agent and helper 0.1.27: signed release build 28 from 52c352c;
  hashes verified on the Windows test guest.
- Linux agent 0.1.0-mvp.14 (62cb52b) and OPNsense agent 0.1.0-opnsense.6
  are already ancestors of 79f236b.

Conflict in crates/agent-windows/src/native.rs resolved to the released
Windows side (os_inventory with missing DisplayVersion handling).
cargo check passes for the Linux workspace and for rmm-agent-windows on
x86_64-pc-windows-gnu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:50:18 +01:00
kevin_janssen fb35dbd16f Document disk measurements and preserve published helper pins in inventory releases
Rust development slice / linux (push) Failing after 14s
2026-11-20 09:44:28 +01:00
kevin_janssen 79f236b3ea Show disk, pool and unassigned Linux capacity in device fleet views 2026-11-20 09:35:05 +01:00
kevin_janssen eaaa6ff228 Inventory Linux whole disks and account mounted filesystems by block topology 2026-11-20 09:34:17 +01:00
kevin_janssen 131cc53de2 Document Windows drive-letter inventory and native multi-drive checks
Rust development slice / linux (push) Failing after 14s
2026-11-20 08:58:56 +01:00
kevin_janssen 04037c7acf Display Windows fixed volumes individually in both fleet views 2026-11-20 08:53:20 +01:00
kevin_janssen 52c352c0d9 Collect capacity for every Windows fixed drive letter
Rust development slice / linux (push) Failing after 11s
2026-11-20 08:51:54 +01:00
kevin_janssen 9c61f8f2eb Collect capacity for every Windows fixed drive letter 2026-11-20 08:50:49 +01:00
kevin_janssen b5e96853c3 Show occupied disk and RAM capacity with matching used and free segments
Rust development slice / linux (push) Failing after 9s
2026-11-20 08:40:48 +01:00
kevin_janssen 957bf3cd58 Swap free and used colors on RAM and disk capacity bars
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:37:18 +01:00
kevin_janssen 021fdfc1bc Use muted terracotta for occupied RAM and disk capacity
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:35:50 +01:00
kevin_janssen 9057808d16 Show free disk capacity with the same bar and caption as RAM
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:31:15 +01:00
kevin_janssen 0b0790de71 Run approved FreeBSD root jobs through independently pinned and synchronized local helper
Rust development slice / linux (push) Failing after 11s
2026-11-20 08:27:13 +01:00
kevin_janssen 2e3916b84b Seed versioned OPNsense scripts and label the shared POSIX interpreter 2026-11-20 08:22:59 +01:00
kevin_janssen 1f3cd5ea0c Route OPNsense library and custom jobs through the standard order composer 2026-11-20 08:15:07 +01:00
kevin_janssen 8a1ea58d86 Plan OPNsense POSIX root scripts with explicit device policy, profile and approval 2026-11-20 08:12:52 +01:00
kevin_janssen 47249644b9 Record approved OPNsense kernel probe and matching native start evidence
Rust development slice / linux (push) Failing after 6s
2026-11-20 08:06:32 +01:00
kevin_janssen 6792b0dd11 Verify signed OPNsense kernel probes on the service account and retain exactly-once evidence
Rust development slice / linux (push) Failing after 13s
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 51ce8cde77 Record Windows inventory hotfix publication and native verification 2026-11-19 16:36:10 +01:00
kevin_janssen 037b5e39fa Handle missing DisplayVersion in Windows inventory 2026-11-19 16:30:39 +01:00
kevin_janssen 5cfa0cfdcf Record Windows local clock rollout and idle CPU verification
Rust development slice / linux (push) Failing after 10s
2026-11-19 11:58:48 +01:00
kevin_janssen b002202d62 Qualify enrolled Windows job clocks from the local time service
Rust development slice / linux (push) Failing after 15s
2026-11-19 11:47:49 +01:00
kevin_janssen 6aeb618170 Record local Windows time policy and native diagnostic limits
Rust development slice / linux (push) Failing after 14s
2026-11-19 11:32:25 +01:00
kevin_janssen 5a9eafbff1 Record Windows idle CPU and SYSTEM follow-up
Rust development slice / linux (push) Failing after 13s
2026-11-19 10:21:07 +01:00
kevin_janssen f01e81418e Verify damaged history still blocks durable no-start
Rust development slice / linux (push) Failing after 13s
2026-11-19 10:10:02 +01:00
kevin_janssen d4cbc40979 Avoid replaying the helper journal history during idle sync 2026-11-19 10:09:38 +01:00
kevin_janssen 478ee1fc1a Avoid repeated full journal scans and fast ticks in Windows idle 2026-11-19 10:04:26 +01:00
91 changed files with 6314 additions and 363 deletions
Generated
+22
View File
@@ -2210,6 +2210,7 @@ dependencies = [
"rmm-domain",
"serde",
"serde_json",
"tokio",
"uuid",
]
@@ -2286,6 +2287,27 @@ 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",
"serde_json",
"sha1",
"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"
+11 -3
View File
@@ -10,9 +10,15 @@ Jede Installation ist an Kunde, Gerät und Agentenidentität gebunden. Die Stand
Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` bezeichnet einen physischen Rechner, `virtual` ein virtualisiertes System und `hypervisor` eine erkannte Hostrolle. Proxmox VE erscheint als `hypervisor` mit `Proxmox VE` in der Spalte OS. Eine erkannte Hostrolle hat Vorrang, auch bei verschachtelter Virtualisierung. Bei fehlender Angabe zeigt die WebUI „Nicht gemeldet“. Die Geräteabfragen in WebUI und MCP verwenden denselben gespeicherten Typ. [Inventarprojektion](crates/server/src/devices.rs)
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.
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht des Bestands gliedert die Geräte einer Seite in Blöcke: je Hypervisor ein Block mit dem Host und seinen eingerückten VMs, danach „Hetzner Cloud“, „Physische Geräte“ und „Nicht zugeordnet“. Der Blockkopf des Hypervisors verlinkt auf dessen Gerätedetails, auch wenn der Host selbst nicht auf der Seite steht. An jeder VM steht, ob die Zuordnung automatisch erkannt oder manuell gesetzt wurde. Die Historie bleibt eine einfache Liste. 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. 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)
Ein aufgenommener Proxmox-VE-Host meldet über einen vom Installer eingerichteten, nur lesenden API-Token (`PVEAuditor`) die Gäste seines Nodes, die geplanten vzdump-Backupjobs und die Läufe der letzten acht Tage. Die Gerätedetails des Hosts listen VMs und Container mit Status, Ressourcen, zugeordnetem Gerät und letzter erfolgreicher Sicherung. Darunter folgen die Backupjobs mit Zeitplan, Storage, gesicherten Gästen, letztem fälligen Zeitpunkt, Ergebnis und nächstem Lauf sowie die Gäste ohne Backupjob. Der Server bewertet jeden aktiven Job als gelaufen, fehlgeschlagen, verpasst, laufend oder noch nicht fällig. Er beantwortet damit, ob alle geplanten Backups gelaufen sind. Ein virtuelles Gerät, dessen MAC-Adresse eindeutig in der Gastliste eines Proxmox-Hosts desselben Kunden steht, wird diesem Host automatisch als Hypervisor zugeordnet und so gekennzeichnet. Eine manuelle Zuordnung hat Vorrang und lässt sich wieder an die automatische Erkennung zurückgeben. [Proxmox-Host](deploy/proxmox/README.md)
Ab Windows-Client `0.1.27` zeigt die Spalte **Speicher belegt / gesamt** jedes lokale Festplattenvolume mit Laufwerksbuchstaben separat an, das Systemlaufwerk zuerst. Ein Laufwerk mit unbekannter Kapazität behält seinen Buchstaben ohne Belegungsbalken. Die Zuordnung erfolgt pro logischem Volume, nicht pro physischem Datenträger. Netzlaufwerke, optische Medien und Volumes ohne Laufwerksbuchstaben gehören nicht zu dieser Liste. Bei älteren Inventarmeldungen bleibt die vorhandene Systemlaufwerkskapazität sichtbar.
Unter Linux zeigt die Übersicht die vom Kernel erkannten ganzen Festplatten bzw. virtuellen Gastplatten mit Gerätename, Modell (falls verfügbar) und Rohkapazität. Für direkt zuordenbare lokale Dateisysteme zählt sie belegte und für Anwendungen verfügbare Bytes über alle Partitionen, dasselbe Dateisystem nur einmal. Rot bezeichnet nachgewiesene Belegung, Grün verfügbaren Dateisystemplatz und Grau den Rest, einschließlich Reserven, unpartitioniertem Platz und nicht messbarer Belegung. Ein vollständig unbekannter Wert ist kein Nullwert. Bei gestapelten Blockgeräten und plattenübergreifenden Dateisystemen erscheint die logische Belegung separat mit den ermittelbaren Mitgliedern; sie wird nicht auf physische Platten verteilt. ZFS meldet die gemeinsame Belegung des Pools bei lesbaren ZFS-Eigenschaften, nicht die Summe der freien Bytes seiner Datasets. Alte Clients weisen den Wert für `/` als Root-Dateisystem aus.
Geräteübersicht und Gerätedetails zeigen für Laufwerke und RAM „belegt / gesamt“ in GiB. Belegt ist die Gesamtkapazität abzüglich des freien Laufwerksplatzes bzw. des für Anwendungen verfügbaren Arbeitsspeichers. Die Balken in der Übersicht zeigen links den belegten Anteil in gedämpftem Rot und rechts den freien Anteil in Grün. Darunter steht der belegte Anteil in Prozent. Ohne gültiges Wertepaar erscheint kein Balken. 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.
@@ -24,7 +30,7 @@ Die Spalte **Zweck** und das Gerätedetail zeigen optionalen Freitext. Unter **Z
## Vom Skript zum Ergebnis
**OPNsense-Testprofil:** Das Gerätegateway akzeptiert `opnsense.base/1` als eigene passive Plattform. 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. Die Auslieferung und die Grenzen des Profils sind im [OPNsense-Betrieb](deploy/opnsense/README.md) beschrieben.
**OPNsense:** 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. Skriptaufträge gehören wie bei Linux und Windows unter **Aufträge**. Die WebUI bindet eine Bibliotheksrevision oder ein einmaliges POSIX-Skript an die ausgewählten OPNsense-Geräte. Für die Ausführung als `root` gelten zusätzlich zum normalen signierten Abgleich und persönlichen Freigabeverfahren `root:execute`, die zentrale Geräte- und Principalbindung sowie die unabhängige Prüfung durch den lokal provisionierten FreeBSD-Helper. [OPNsense-Betrieb](deploy/opnsense/README.md)
| Schritt | Verhalten |
| --- | --- |
@@ -36,6 +42,8 @@ Die Spalte **Zweck** und das Gerätedetail zeigen optionalen Freitext. Unter **Z
Linux führt Shellskripte unter dem Dienstkonto oder über den eingerichteten Helper als root aus. Windows führt PowerShell unter LocalService oder über den Helper als SYSTEM aus. Neustart und Installation von Windows-Updates sind Skriptaufträge. Bei einem Neustart kann das Skript bereits vor dem Herunterfahren erfolgreich enden. Der Betriebsnachweis verbindet den neuen Bootbezug mit dem nächsten authentisierten Kontakt und einem Folgeauftrag. [Skriptbibliothek](crates/server/src/script_library.rs) · [Auftragsverarbeitung](crates/server/src/jobs.rs)
Agent und privilegierter Helper prüfen jeweils den Synchronisationsstatus, eine begrenzte Zeitunsicherheit und die Kontinuität der lokalen Systemzeit. Die serverseitig signierte Starterlaubnis wird an der lokal geprüften Uhr gemessen. Linux liest dafür den Kernelstatus. Auf regulär aufgenommenen Windows-Geräten fragen der Agent und der dauerhaft eingerichtete SYSTEM-Helper den lokalen Windows-Zeitdienst jeweils selbst ab. Beide prüfen die Identität des Zeitdienstes an der Verbindung, die den Status liefert. Sie akzeptieren den zuletzt erfolgreichen Abgleich innerhalb eines Tages und eine geschätzte Unsicherheit bis zu zwei Sekunden. Bei einem erkannten Zeitsprung oder Standby warten sie auf einen neueren erfolgreichen Abgleich. Der bisherige signierte Zeitvergleich wird noch im separaten Windows-Update-Wartungsprofil und bei Installationen mit manueller Auftragsbindung verwendet. [Entscheidung zur Uhrprüfung](docs/project-decisions.md)
Ein Abbruchwunsch wird am Auftrag gespeichert. Bei unterbrochener Rückmeldung gleichen Server, Agent und gegebenenfalls Helper den gespeicherten Versuch ab. Bei `unknown` bleibt die Wirkung ungeklärt. Die WebUI kann einen solchen Fall dokumentiert abschließen. Agent und Helper übernehmen den Abschluss im signierten Abgleich auch dann, wenn der Agent den Abbruch seiner eigenen Ausführung protokolliert hat und im unabhängig gebundenen Verbrauchsjournal des Helpers ein Ergebnis fehlt. Beide bewahren die ursprünglichen Belege. Der Abschluss erteilt keine Freigabe für einen weiteren Versuch.
## Öffentliche Verwaltung und Berechtigungen
+1
View File
@@ -5,6 +5,7 @@ use anyhow::{Context, Result, ensure};
use chrono::{DateTime, TimeDelta, Utc};
use std::{mem::MaybeUninit, time::Instant};
#[derive(Clone)]
pub struct NativeClock {
origin: DateTime<Utc>,
monotonic: Instant,
+53 -27
View File
@@ -205,6 +205,7 @@ 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.
@@ -222,6 +223,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
born: clock.now()?,
capture: None,
lease: None,
integrity: None,
})
}
/// Select exactly one protected helper execution identity, closing leases.
@@ -230,6 +232,12 @@ 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;
@@ -288,7 +296,8 @@ impl<V: Ed25519Verifier> HelperSync<V> {
ledger_fingerprint: lease.fingerprint.clone(),
captured_at: capture.captured_at,
};
self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?;
let audit_history = self.integrity.is_none();
self.verify_no_start_anchor(db, guard, &anchor, clock, boot, audit_history)?;
Ok(anchor)
}
/// Consume exactly the approved update attempt and delegate its ORIGINAL
@@ -389,9 +398,9 @@ impl<V: Ed25519Verifier> HelperSync<V> {
tx.commit()?;
return Ok(outcome);
}
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
let observation = guard.verify_no_dispatch(request, anchor)?;
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
ensure!(
!observation.intent_id.is_nil()
&& digest(&observation.intent_sha256)
@@ -421,6 +430,7 @@ 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()?;
@@ -445,15 +455,18 @@ impl<V: Ed25519Verifier> HelperSync<V> {
&& ledger_fingerprint(db)? == anchor.ledger_fingerprint,
"DENIAL_HELPER_LINEAGE_CHANGED"
);
// 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,
)?;
// 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,
)?;
}
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()],
@@ -483,8 +496,12 @@ 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"
);
@@ -523,7 +540,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
);
let boot_id = boot.current_boot()?;
ensure!(!boot_id.is_nil(), "BOOT_ID_REQUIRED");
initialize(db, &self.binding)?;
if let Some(integrity) = &mut self.integrity {
integrity.check(db, false, "ROOT_LEDGER_INTEGRITY")?;
initialize_schema(db, &self.binding)?;
} else {
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");
@@ -1031,13 +1053,17 @@ struct Meta {
agent_checkpoint: u64,
}
fn initialize(db: &Connection, binding: &Binding) -> Result<()> {
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "ROOT_LEDGER_INTEGRITY");
crate::ledger::check_integrity(db, "ROOT_LEDGER_INTEGRITY")?;
initialize_schema(db, binding)
}
fn initialize_schema(db: &Connection, binding: &Binding) -> Result<()> {
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 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);")?;
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),
@@ -1175,23 +1201,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 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 entries = statement.query([])?;
let mut previous = None;
let mut previous_checkpoint = 0;
let mut previous_agent_checkpoint = 0;
for (signed, raw, checkpoint) in entries {
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)?;
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)?;
+72 -3
View File
@@ -7,7 +7,8 @@ use rmm_domain::{
jobs::hash,
reconciliation::{ReconciledOutcome, canonical_outcome_bytes},
};
use rusqlite::{OptionalExtension, TransactionBehavior, params};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use std::time::{Duration, Instant};
use uuid::Uuid;
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
@@ -29,11 +30,48 @@ 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);")?;
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
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}");
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(
@@ -379,3 +417,34 @@ 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();
}
}
+23 -3
View File
@@ -101,6 +101,7 @@ pub struct ClientSync<V = DefaultVerifier> {
verifier: V,
helper_identity: HelperIdentity,
pending: Option<PreparedSync>,
integrity: Option<crate::ledger::IntegrityMonitor>,
channel: Option<Channel>,
gate: Option<Gate>,
}
@@ -117,6 +118,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
verifier,
helper_identity: HelperIdentity::Root,
pending: None,
integrity: None,
channel: None,
gate: None,
}
@@ -127,6 +129,11 @@ 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;
@@ -606,7 +613,17 @@ impl<V: Ed25519Verifier> ClientSync<V> {
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
"UNAUTHENTICATED_CHANNEL"
);
initialize(db)?;
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)?;
}
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let meta = metadata(&tx)?;
ensure!(meta.fault.is_none(), "SYNC_MANUAL_RECOVERY_REQUIRED");
@@ -1147,8 +1164,11 @@ impl<V: Ed25519Verifier> ClientSync<V> {
}
pub fn initialize(db: &Connection) -> Result<()> {
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
crate::ledger::check_integrity(db, "JOURNAL_INTEGRITY")?;
initialize_schema(db)
}
fn initialize_schema(db: &Connection) -> Result<()> {
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,6 +466,31 @@ 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();
+2
View File
@@ -11,3 +11,5 @@ uuid.workspace = true
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
[dev-dependencies]
tokio = { workspace = true }
+17 -5
View File
@@ -4,6 +4,8 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
mod disks;
pub mod proxmox;
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
@@ -200,6 +202,8 @@ pub struct Dns {
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Volume {
#[serde(skip)]
pub(crate) devno: String,
pub mount_point: String,
pub filesystem: String,
pub device: String,
@@ -275,6 +279,7 @@ pub struct LinuxInventory {
pub routes: Observation<Vec<Route>>,
pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>,
pub disks: Observation<Vec<disks::Disk>>,
pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>,
@@ -282,6 +287,8 @@ pub struct LinuxInventory {
pub smart: Observation<()>,
}
pub fn collect_native() -> LinuxInventory {
let volumes = volumes();
let disks = disks::collect(&volumes);
LinuxInventory {
os: operating_system(),
cpu: cpu(),
@@ -289,7 +296,8 @@ pub fn collect_native() -> LinuxInventory {
interfaces: interfaces(),
routes: routes(),
dns: dns(),
volumes: volumes(),
volumes,
disks,
software: software(),
users: logged_in_users(),
updates: updates(),
@@ -937,7 +945,7 @@ pub fn volumes() -> Observation<Vec<Observation<Volume>>> {
));
continue;
};
observations.push(volume(&mount, right[0], right[1]));
observations.push(volume(&mount, left[2], right[0], right[1]));
}
Some(observations)
})
@@ -955,7 +963,7 @@ impl Observation<Vec<Observation<Volume>>> {
self
}
}
fn volume(mount: &str, filesystem: &str, device: &str) -> Observation<Volume> {
fn volume(mount: &str, devno: &str, filesystem: &str, device: &str) -> Observation<Volume> {
// Remote filesystems can hang statvfs indefinitely; explicitly do not probe.
const LOCAL: &[&str] = &[
"ext2", "ext3", "ext4", "xfs", "btrfs", "tmpfs", "overlay", "vfat", "exfat", "f2fs", "zfs",
@@ -999,6 +1007,7 @@ fn volume(mount: &str, filesystem: &str, device: &str) -> Observation<Volume> {
Observation::valid(
&source,
Volume {
devno: devno.to_owned(),
mount_point: mount.into(),
filesystem: filesystem.into(),
device: mount_unescape(device).unwrap_or_else(|| device.into()),
@@ -1273,6 +1282,10 @@ fn machine_type(proxmox_ve: bool) -> Option<DeviceType> {
virtualization_type(&output)
}
pub fn proxmox_ve() -> bool {
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file()
}
pub fn hardware() -> Observation<Hardware> {
const SOURCE: &str = "linux.dmi:/sys/class/dmi/id;systemd-detect-virt;pve-manager";
let mut readable_dmi = BTreeMap::new();
@@ -1290,8 +1303,7 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi.insert(field.into(), value);
}
}
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let proxmox_ve = proxmox_ve();
let device_type = machine_type(proxmox_ve);
let manufacturer = readable_dmi
.get("sys_vendor")
+427
View File
@@ -0,0 +1,427 @@
//! Disk capacity is a hardware measurement. Filesystem usage can only be
//! attributed where the block topology and mount identity agree.
use super::{Observation, Quality, Volume, command};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
os::unix::fs::{FileTypeExt, MetadataExt},
path::Path,
};
const SOURCE: &str = "linux.sysfs:block;mountinfo;statvfs";
#[derive(Debug, Clone, serde::Serialize)]
pub struct Disk {
name: String,
kind: &'static str,
model: Option<String>,
members: BTreeSet<String>,
total_bytes: u64,
used_bytes: Option<u64>,
available_bytes: Option<u64>,
}
impl Disk {
fn new(name: String, kind: &'static str, total_bytes: u64) -> Self {
Self {
name,
kind,
model: None,
members: BTreeSet::new(),
total_bytes,
used_bytes: None,
available_bytes: None,
}
}
}
struct Node {
parents: Vec<String>,
disk: bool,
stacked: bool,
label: String,
}
type Nodes = BTreeMap<String, Node>;
type Rows = BTreeMap<String, Disk>;
fn attr(path: impl AsRef<Path>) -> Option<String> {
fs::read_to_string(path)
.ok()
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty() && s.len() <= 256)
}
fn devno(dev: u64) -> String {
format!("{}:{}", libc::major(dev), libc::minor(dev))
}
fn block_id(path: &str) -> Option<String> {
if !path.starts_with("/dev/") {
return None;
}
let m = fs::metadata(path).ok()?;
m.file_type().is_block_device().then(|| devno(m.rdev()))
}
fn topology() -> std::io::Result<(Nodes, BTreeMap<String, String>, Rows)> {
let mut nodes = Nodes::new();
let mut ids = BTreeMap::new();
let mut rows = Rows::new();
for entry in fs::read_dir("/sys/class/block")? {
let entry = entry?;
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let Some(id) = attr(path.join("dev")) else {
continue;
};
let Ok(real) = path.canonicalize() else {
continue;
};
let part = path.join("partition").exists();
let parents = if part {
real.parent()
.and_then(Path::file_name)
.map(|n| n.to_string_lossy().into_owned())
.into_iter()
.collect()
} else {
fs::read_dir(path.join("slaves"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect::<Vec<_>>()
};
// virtio/SCSI/Xen disks in guests have real bus paths too. Exclude
// synthetic block devices, optical drives and eMMC boot areas.
let disk = !part
&& parents.is_empty()
&& !real.starts_with("/sys/devices/virtual/block")
&& attr(path.join("device/type")).is_none_or(|t| t == "0" || t == "14")
&& !name.starts_with("sr")
&& !(name.starts_with("mmcblk") && name.contains("boot"));
if disk {
if let Some(size) = attr(path.join("size"))
.and_then(|s| s.parse::<u64>().ok())
.and_then(|s| s.checked_mul(512))
.filter(|n| *n > 0)
{
let mut row = Disk::new(name.clone(), "disk", size);
row.model =
attr(path.join("device/model")).or_else(|| attr(path.join("device/name")));
rows.insert(name.clone(), row);
}
}
ids.insert(id, name.clone());
nodes.insert(
name.clone(),
Node {
stacked: !part && !parents.is_empty(),
disk,
parents,
label: attr(path.join("dm/name")).unwrap_or(name),
},
);
}
Ok((nodes, ids, rows))
}
fn owners(name: &str, nodes: &Nodes) -> (BTreeSet<String>, bool) {
let mut pending = vec![name];
let mut visited = BTreeSet::new();
let mut disks = BTreeSet::new();
let mut stacked = false;
while let Some(n) = pending.pop() {
if !visited.insert(n) {
continue;
}
if let Some(node) = nodes.get(n) {
if node.disk {
disks.insert(n.to_owned());
}
stacked |= node.stacked;
pending.extend(node.parents.iter().map(String::as_str));
}
}
(disks, stacked)
}
fn project(
nodes: &Nodes,
ids: &BTreeMap<String, String>,
rows: &mut Rows,
volumes: &[&Volume],
btrfs: &BTreeMap<String, (String, BTreeSet<String>, bool)>,
) {
let mut seen = BTreeSet::new();
let mut invalid = BTreeSet::new();
for v in volumes {
if v.total_bytes == 0 || v.available_bytes > v.free_bytes || v.free_bytes > v.total_bytes {
continue;
}
let (members, key, group) = if v.filesystem == "btrfs" {
// Subvolumes can have different anonymous st_dev numbers. Group by
// the filesystem UUID and never allocate replicated chunks per disk.
let Some((uuid, members, single)) = block_id(&v.device).and_then(|id| btrfs.get(&id))
else {
continue;
};
(
members.clone(),
format!("btrfs:{uuid}"),
(!single).then(|| format!("Btrfs {uuid}")),
)
} else {
let Some(name) = ids.get(&v.devno) else {
continue;
};
let (members, stacked) = owners(name, nodes);
if members.is_empty() {
continue;
}
(
members,
v.devno.clone(),
stacked.then(|| nodes[name].label.clone()),
)
};
if !seen.insert(key.clone()) {
continue;
}
let used = v.total_bytes - v.free_bytes;
if let Some(name) = group {
let mut row = Disk::new(name, "group", v.total_bytes);
row.members = members;
row.used_bytes = Some(used);
row.available_bytes = Some(v.available_bytes);
rows.insert(format!("group:{key}"), row);
} else if members.len() == 1 {
let disk = members.first().unwrap();
if invalid.contains(disk) {
continue;
}
let Some(row) = rows.get_mut(disk) else {
continue;
};
let u = row.used_bytes.unwrap_or(0).checked_add(used);
let a = row
.available_bytes
.unwrap_or(0)
.checked_add(v.available_bytes);
if u.zip(a)
.and_then(|(u, a)| u.checked_add(a))
.is_some_and(|n| n <= row.total_bytes)
{
row.used_bytes = u;
row.available_bytes = a;
} else {
invalid.insert(disk.clone());
row.used_bytes = None;
row.available_bytes = None;
}
}
}
}
fn btrfs_members(
nodes: &Nodes,
ids: &BTreeMap<String, String>,
) -> BTreeMap<String, (String, BTreeSet<String>, bool)> {
let mut result = BTreeMap::new();
for fs in fs::read_dir("/sys/fs/btrfs")
.into_iter()
.flatten()
.flatten()
{
let mut members = BTreeSet::new();
let mut devices = Vec::new();
let mut direct = true;
for dev in fs::read_dir(fs.path().join("devices"))
.into_iter()
.flatten()
.flatten()
{
if let Some(id) = attr(dev.path().join("dev")) {
if let Some(name) = ids.get(&id) {
let (disks, stacked) = owners(name, nodes);
direct &= !stacked && disks.len() == 1;
members.extend(disks);
} else {
direct = false
}
devices.push(id);
} else {
direct = false
}
}
let single = direct && devices.len() == 1;
for id in devices {
result.insert(
id,
(
fs.file_name().to_string_lossy().into_owned(),
members.clone(),
single,
),
);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
fn volume(id: &str, total: u64, free: u64, available: u64) -> Volume {
Volume {
devno: id.into(),
mount_point: "/".into(),
filesystem: "ext4".into(),
device: "".into(),
total_bytes: total,
free_bytes: free,
available_bytes: available,
available_percent: None,
total_inodes: 0,
free_inodes: 0,
available_inodes: 0,
available_inode_percent: None,
}
}
#[test]
fn partitions_count_once_pools_stay_separate_and_unmounted_is_unknown() {
let mut nodes = Nodes::new();
let mut rows = Rows::new();
for name in ["sda", "sdb", "vdc"] {
nodes.insert(
name.into(),
Node {
disk: true,
stacked: false,
parents: vec![],
label: name.into(),
},
);
rows.insert(name.into(), Disk::new(name.into(), "disk", 1000));
}
for (name, parents, stacked) in [
("sda1", vec!["sda"], false),
("sda2", vec!["sda"], false),
("md0", vec!["sda", "sdb"], true),
] {
nodes.insert(
name.into(),
Node {
disk: false,
stacked,
parents: parents.into_iter().map(String::from).collect(),
label: name.into(),
},
);
}
let ids = [("8:1", "sda1"), ("8:2", "sda2"), ("9:0", "md0")]
.map(|(a, b)| (a.into(), b.into()))
.into();
let a = volume("8:1", 100, 40, 30);
let b = volume("8:2", 200, 100, 80);
let raid = volume("9:0", 500, 250, 240);
project(
&nodes,
&ids,
&mut rows,
&[&a, &a, &b, &raid, &raid],
&BTreeMap::new(),
);
assert_eq!(
(rows["sda"].used_bytes, rows["sda"].available_bytes),
(Some(160), Some(110))
);
assert_eq!(rows["sdb"].used_bytes, None);
assert_eq!(rows["vdc"].available_bytes, None);
assert_eq!(
rows["group:9:0"].members,
["sda".into(), "sdb".into()].into()
);
assert_eq!(rows["group:9:0"].used_bytes, Some(250));
assert_eq!(rows.len(), 4);
}
}
fn zfs(rows: &mut Rows, nodes: &Nodes, ids: &BTreeMap<String, String>, volumes: &[&Volume]) {
let pools: BTreeSet<_> = volumes
.iter()
.filter(|v| v.filesystem == "zfs")
.filter_map(|v| v.device.split('/').next())
.collect();
if pools.is_empty() {
return;
}
// A pool's root dataset includes its children; don't sum dataset free space.
let usage = command(
"/usr/sbin/zfs",
&[
"list",
"-Hp",
"-t",
"filesystem",
"-o",
"name,used,available",
],
32768,
);
let topology = command("/usr/sbin/zpool", &["status", "-LP"], 32768);
let mut pool = "";
let mut members: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
for line in topology
.data
.as_deref()
.unwrap_or("")
.lines()
.map(str::trim)
{
if let Some(p) = line.strip_prefix("pool: ") {
pool = p;
continue;
}
if let Some(name) = line
.split_whitespace()
.next()
.and_then(block_id)
.and_then(|id| ids.get(&id))
{
members
.entry(pool)
.or_default()
.extend(owners(name, nodes).0);
}
}
for p in pools {
let measure = usage
.data
.as_deref()
.unwrap_or("")
.lines()
.find_map(|line| {
let mut cols = line.split('\t');
if cols.next() != Some(p) {
return None;
}
let used = cols.next()?.parse::<u64>().ok()?;
let free = cols.next()?.parse::<u64>().ok()?;
Some((used, free, used.checked_add(free)?))
});
let mut row = Disk::new(format!("ZFS {p}"), "group", measure.map_or(0, |m| m.2));
row.used_bytes = measure.map(|m| m.0);
row.available_bytes = measure.map(|m| m.1);
row.members = members.remove(p).unwrap_or_default();
rows.insert(format!("group:zfs:{p}"), row);
}
}
pub(super) fn collect(volumes: &Observation<Vec<Observation<Volume>>>) -> Observation<Vec<Disk>> {
let Ok((nodes, ids, mut rows)) = topology() else {
return Observation::unavailable(SOURCE, Quality::Unknown, "BLOCK_TOPOLOGY_UNAVAILABLE");
};
let mounted: Vec<_> = volumes
.data
.iter()
.flatten()
.filter_map(|o| o.data.as_ref())
// An over-mounted or replaced mountpoint may now refer to another device.
.filter(|v| fs::metadata(&v.mount_point).is_ok_and(|m| devno(m.dev()) == v.devno))
.collect();
let btrfs = btrfs_members(&nodes, &ids);
project(&nodes, &ids, &mut rows, &mounted, &btrfs);
zfs(&mut rows, &nodes, &ids, &mounted);
let mut result: Vec<_> = rows.into_values().collect();
result.sort_by(|a, b| (a.kind, &a.name).cmp(&(b.kind, &b.name)));
Observation::valid(SOURCE, result).partial("FILESYSTEM_COVERAGE_PARTIAL")
}
+574
View File
@@ -0,0 +1,574 @@
//! Read-only Proxmox VE observation: hosted guests, scheduled vzdump jobs and recent
//! backup runs. Uses a dedicated PVEAuditor API token supplied by the installer as a
//! systemd credential. No writes, no root, no shell; the transport is injected so the
//! orchestration and parsing stay testable without a Proxmox host.
use super::{Observation, Quality};
use serde::Serialize;
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
pub const SOURCE: &str = "proxmox.api:/api2/json";
pub const OBSERVATION_MAX_BYTES: usize = rmm_domain::inventory_document::PROXMOX_OBSERVATION_MAX_BYTES;
pub const MAX_GUESTS: usize = 512;
pub const MAX_JOBS: usize = 64;
pub const MAX_RUNS: usize = 64;
const MAX_LOG_LINES: usize = 4000;
/// Weekly schedules must still show their previous due time.
const SCHEDULE_LOOKBACK_SECONDS: i64 = 8 * 24 * 3600;
const SCHEDULE_ITERATIONS: usize = 100;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Proxmox {
pub node: String,
pub cluster: Option<String>,
pub version: Option<String>,
pub guests: Vec<Guest>,
pub backup_jobs: Vec<BackupJob>,
pub backup_runs: Vec<BackupRun>,
/// Local guests that no backup job selects (Proxmox's own analysis).
pub not_backed_up: Vec<u32>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Guest {
pub vmid: u32,
pub name: String,
pub kind: &'static str,
pub status: String,
pub template: bool,
pub cpus: Option<u32>,
pub memory_bytes: Option<u64>,
pub disk_bytes: Option<u64>,
pub uptime_seconds: Option<u64>,
pub pool: Option<String>,
pub macs: Vec<String>,
pub smbios_uuid: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BackupJob {
pub id: String,
pub enabled: bool,
pub schedule: Option<String>,
pub storage: Option<String>,
pub mode: Option<String>,
pub selection: &'static str,
/// Local guests this job backs up, resolved from all/vmid/pool minus exclude.
pub covered_vmids: Vec<u32>,
pub next_run: Option<i64>,
/// Most recent scheduled time at or before the observation time.
pub last_expected_run: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BackupRun {
pub upid: String,
pub started_at: i64,
pub ended_at: Option<i64>,
/// ok | warning | error | running
pub status: &'static str,
pub message: Option<String>,
pub guests: Vec<GuestResult>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GuestResult {
pub vmid: u32,
/// ok | error
pub result: &'static str,
}
/// Bounded GET of one `/api2/json` path, returning the `data` member.
pub trait Api {
fn get(&self, path: &str) -> impl std::future::Future<Output = anyhow::Result<Value>> + Send;
}
pub fn not_configured() -> Observation<Proxmox> {
Observation::unavailable(SOURCE, Quality::Unsupported, "PROXMOX_NOT_CONFIGURED")
}
pub fn failed(code: &str) -> Observation<Proxmox> {
Observation::unavailable(SOURCE, Quality::Error, code)
}
/// The token secret never appears in errors, logs or observations.
pub fn token_header(credential: &str) -> Option<String> {
let token = credential.trim();
let (id, secret) = token.split_once('=')?;
let (user, name) = id.split_once('!')?;
let ok = |s: &str| !s.is_empty() && s.len() <= 128
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.@".contains(&b));
(ok(user) && user.contains('@') && ok(name) && ok(secret))
.then(|| format!("PVEAPIToken={token}"))
}
pub async fn collect(api: &impl Api, now: i64) -> Observation<Proxmox> {
match collect_data(api, now).await {
Ok((data, truncated)) => {
let mut observation = Observation::valid(SOURCE, data);
if truncated {
observation = observation.partial("PROXMOX_LIMIT");
observation.truncated = true;
}
fit(observation)
}
Err(error) => {
let code = error.to_string();
failed(if code.starts_with("PROXMOX_") && code.len() <= 64 { &code } else { "PROXMOX_API_ERROR" })
}
}
}
async fn collect_data(api: &impl Api, now: i64) -> anyhow::Result<(Proxmox, bool)> {
let status = api.get("/cluster/status").await?;
let rows = status.as_array().ok_or_else(|| anyhow::anyhow!("PROXMOX_API_SHAPE"))?;
let node = rows.iter()
.find(|r| r["type"] == "node" && flag(&r["local"]) == Some(true))
.and_then(|r| r["name"].as_str())
.filter(|n| clean(n, 64))
.ok_or_else(|| anyhow::anyhow!("PROXMOX_LOCAL_NODE_UNKNOWN"))?
.to_owned();
let cluster = rows.iter().find(|r| r["type"] == "cluster")
.and_then(|r| r["name"].as_str()).filter(|n| clean(n, 64)).map(str::to_owned);
let version = api.get("/version").await.ok()
.and_then(|v| v["version"].as_str().filter(|s| clean(s, 32)).map(str::to_owned));
let mut truncated = false;
let resources = api.get("/cluster/resources?type=vm").await?;
let mut guests = Vec::new();
for row in resources.as_array().into_iter().flatten() {
if row["node"].as_str() != Some(node.as_str()) {
continue;
}
let Some(mut guest) = guest(row) else { continue };
if guests.len() == MAX_GUESTS {
truncated = true;
break;
}
let path = format!("/nodes/{node}/{}/{}/config", guest.kind, guest.vmid);
if let Ok(config) = api.get(&path).await {
guest.macs = macs(&config);
guest.smbios_uuid = config["smbios1"].as_str().and_then(smbios_uuid);
} else {
truncated = true;
}
guests.push(guest);
}
guests.sort_by_key(|g| g.vmid);
let jobs = api.get("/cluster/backup").await?;
let mut backup_jobs = Vec::new();
for row in jobs.as_array().into_iter().flatten() {
if row["type"].as_str().is_some_and(|t| t != "vzdump") {
continue;
}
if backup_jobs.len() == MAX_JOBS {
truncated = true;
break;
}
let Some(mut job) = backup_job(row, &node, &guests) else { continue };
if job.enabled && let Some(schedule) = &job.schedule {
job.last_expected_run = last_expected_run(api, schedule, now).await;
}
backup_jobs.push(job);
}
let local: BTreeSet<u32> = guests.iter().map(|g| g.vmid).collect();
let not_backed_up = api.get("/cluster/backup-info/not-backed-up").await.ok()
.and_then(|v| v.as_array().cloned()).unwrap_or_default().iter()
.filter_map(|r| vmid(&r["vmid"])).filter(|id| local.contains(id))
.collect::<BTreeSet<_>>().into_iter().collect();
let since = now - SCHEDULE_LOOKBACK_SECONDS;
let tasks = api.get(&format!(
"/nodes/{node}/tasks?typefilter=vzdump&source=all&since={since}&limit={MAX_RUNS}"
)).await?;
let mut backup_runs = Vec::new();
for row in tasks.as_array().into_iter().flatten() {
let Some(mut run) = backup_run(row) else { continue };
if backup_runs.len() == MAX_RUNS {
truncated = true;
break;
}
let encoded = percent_encode(&run.upid);
match api.get(&format!("/nodes/{node}/tasks/{encoded}/log?start=0&limit={MAX_LOG_LINES}")).await {
Ok(log) => {
let lines: Vec<&str> = log.as_array().into_iter().flatten()
.filter_map(|l| l["t"].as_str()).collect();
run.guests = guest_results(&lines);
if run.guests.is_empty() {
// A single-guest task names its guest in the UPID.
if let (Some(id), "ok" | "warning") = (upid_vmid(&run.upid), run.status) {
run.guests.push(GuestResult { vmid: id, result: "ok" });
}
}
if lines.len() >= MAX_LOG_LINES {
truncated = true;
}
}
Err(_) => truncated = true,
}
backup_runs.push(run);
}
backup_runs.sort_by(|a, b| b.started_at.cmp(&a.started_at).then_with(|| a.upid.cmp(&b.upid)));
Ok((Proxmox { node, cluster, version, guests, backup_jobs, backup_runs, not_backed_up }, truncated))
}
/// The scheduler's own calendar evaluation, so no local schedule parser can disagree.
/// The API returns at most 100 occurrences, so frequent schedules use shorter windows.
async fn last_expected_run(api: &impl Api, schedule: &str, now: i64) -> Option<i64> {
for lookback in [SCHEDULE_LOOKBACK_SECONDS, 86_400, 7_200, 600] {
let path = format!(
"/cluster/jobs/schedule-analyze?schedule={}&starttime={}&iterations={SCHEDULE_ITERATIONS}",
percent_encode(schedule), now - lookback
);
let runs: Vec<i64> = api.get(&path).await.ok()?.as_array()?.iter()
.filter_map(|r| r["timestamp"].as_i64()).collect();
if runs.len() < SCHEDULE_ITERATIONS || runs.iter().any(|t| *t > now) {
return runs.into_iter().filter(|t| *t <= now).max();
}
}
None
}
/// Keep the newest information when the scope exceeds its wire budget.
fn fit(mut observation: Observation<Proxmox>) -> Observation<Proxmox> {
let size = |o: &Observation<Proxmox>| serde_json::to_vec(o).map(|b| b.len()).unwrap_or(usize::MAX);
while size(&observation) > OBSERVATION_MAX_BYTES - 1024 {
let Some(data) = observation.data.as_mut() else { break };
if data.backup_runs.len() > 8 {
data.backup_runs.pop();
} else if !data.guests.is_empty() {
data.guests.pop();
} else {
return failed("WIRE_SCOPE_LIMIT");
}
observation.truncated = true;
observation = observation.partial("PROXMOX_LIMIT");
}
observation
}
fn guest(row: &Value) -> Option<Guest> {
let kind = match row["type"].as_str()? {
"qemu" => "qemu",
"lxc" => "lxc",
_ => return None,
};
let vmid = vmid(&row["vmid"])?;
let name = row["name"].as_str().filter(|n| clean(n, 128)).unwrap_or("").to_owned();
Some(Guest {
vmid,
name: if name.is_empty() { format!("{kind}-{vmid}") } else { name },
kind,
status: row["status"].as_str().filter(|s| clean(s, 32)).unwrap_or("unknown").to_owned(),
template: flag(&row["template"]) == Some(true),
cpus: row["maxcpu"].as_f64().filter(|c| *c >= 0.0 && *c < 65536.0).map(|c| c.ceil() as u32),
memory_bytes: row["maxmem"].as_u64(),
disk_bytes: row["maxdisk"].as_u64(),
uptime_seconds: row["uptime"].as_u64(),
pool: row["pool"].as_str().filter(|p| clean(p, 64)).map(str::to_owned),
macs: Vec::new(),
smbios_uuid: None,
})
}
fn backup_job(row: &Value, node: &str, guests: &[Guest]) -> Option<BackupJob> {
let id = row["id"].as_str().filter(|s| clean(s, 64))?.to_owned();
let text = |key: &str, limit| row[key].as_str().filter(|s| clean(s, limit)).map(str::to_owned);
let list = |key: &str| -> BTreeSet<u32> {
row[key].as_str().unwrap_or("").split([',', ' ', ';'])
.filter_map(|s| s.trim().parse().ok()).collect()
};
let exclude = list("exclude");
let pool = text("pool", 64);
let vmids = list("vmid");
let all = flag(&row["all"]) == Some(true);
let selection = if all { "all" } else if pool.is_some() { "pool" } else { "vmid" };
let node_matches = row["node"].as_str().is_none_or(|n| n == node);
let covered_vmids = guests.iter()
.filter(|g| node_matches && !g.template)
.filter(|g| match selection {
"all" => !exclude.contains(&g.vmid),
"pool" => g.pool == pool,
_ => vmids.contains(&g.vmid),
})
.map(|g| g.vmid).collect();
Some(BackupJob {
id,
enabled: flag(&row["enabled"]).unwrap_or(true),
schedule: text("schedule", 128).or_else(|| {
// Pre-7.1 format: days of week plus start time.
let time = text("starttime", 16)?;
Some(text("dow", 64).map_or(time.clone(), |dow| format!("{dow} {time}")))
}),
storage: text("storage", 64),
mode: text("mode", 16),
selection,
covered_vmids,
next_run: row["next-run"].as_i64(),
last_expected_run: None,
})
}
fn backup_run(row: &Value) -> Option<BackupRun> {
let upid = row["upid"].as_str().filter(|s| clean(s, 160))?.to_owned();
let started_at = row["starttime"].as_i64()?;
let ended_at = row["endtime"].as_i64();
let raw = row["status"].as_str();
let (status, message) = match (ended_at, raw) {
(None, _) | (_, None) => ("running", None),
(Some(_), Some("OK")) => ("ok", None),
(Some(_), Some(s)) if s.starts_with("WARNINGS") => ("warning", Some(s)),
(Some(_), Some(s)) => ("error", Some(s)),
};
Some(BackupRun {
upid,
started_at,
ended_at,
status,
message: message.map(|m| truncate(m, 256)),
guests: Vec::new(),
})
}
/// vzdump task log lines; the last statement per guest wins.
pub fn guest_results(lines: &[&str]) -> Vec<GuestResult> {
let mut results = BTreeMap::new();
for line in lines {
let line = line.trim();
if let Some(rest) = line.strip_prefix("INFO: Finished Backup of VM ")
&& let Some(id) = leading_number(rest)
{
results.insert(id, "ok");
} else if let Some(rest) = line.strip_prefix("ERROR: Backup of VM ")
&& let Some(id) = leading_number(rest)
{
results.insert(id, "error");
}
}
results.into_iter().map(|(vmid, result)| GuestResult { vmid, result }).collect()
}
/// `netN` values: qemu `virtio=AA:..,bridge=..`; lxc `name=eth0,hwaddr=AA:..`.
pub fn macs(config: &Value) -> Vec<String> {
let mut found = BTreeSet::new();
if let Some(map) = config.as_object() {
for (key, value) in map {
let is_net = key.strip_prefix("net").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
let Some(value) = value.as_str().filter(|_| is_net) else { continue };
for part in value.split(',') {
if let Some((_, candidate)) = part.split_once('=')
&& let Some(mac) = normalize_mac(candidate)
{
found.insert(mac);
}
}
}
}
found.into_iter().take(32).collect()
}
pub fn smbios_uuid(value: &str) -> Option<String> {
value.split(',').find_map(|part| part.strip_prefix("uuid="))
.and_then(|u| uuid::Uuid::parse_str(u.trim()).ok())
.filter(|u| !u.is_nil())
.map(|u| u.hyphenated().to_string())
}
pub fn normalize_mac(value: &str) -> Option<String> {
let parts: Vec<&str> = value.trim().split([':', '-']).collect();
(parts.len() == 6 && parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_hexdigit())))
.then(|| parts.join(":").to_ascii_lowercase())
.filter(|m| m != "00:00:00:00:00:00")
}
/// UPID:node:pid:pstart:starttime:type:id:user: — `id` is the vmid for single-guest runs.
fn upid_vmid(upid: &str) -> Option<u32> {
upid.split(':').nth(6).and_then(|id| id.parse().ok())
}
fn vmid(value: &Value) -> Option<u32> {
value.as_u64().or_else(|| value.as_str()?.parse().ok())
.filter(|id| (100..1_000_000_000).contains(id)).map(|id| id as u32)
}
fn flag(value: &Value) -> Option<bool> {
match value {
Value::Bool(b) => Some(*b),
Value::Number(n) => n.as_u64().map(|n| n != 0),
Value::String(s) => match s.as_str() { "1" | "true" => Some(true), "0" | "false" => Some(false), _ => None },
_ => None,
}
}
fn leading_number(text: &str) -> Option<u32> {
let digits: String = text.chars().take_while(char::is_ascii_digit).collect();
digits.parse().ok()
}
fn clean(s: &str, limit: usize) -> bool {
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
}
fn truncate(s: &str, limit: usize) -> String {
let s: String = s.chars().filter(|c| !c.is_control()).collect();
if s.len() <= limit {
return s;
}
let mut end = limit;
while !s.is_char_boundary(end) {
end -= 1;
}
s[..end].to_owned()
}
pub fn percent_encode(value: &str) -> String {
value.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
(b as char).to_string()
} else {
format!("%{b:02X}")
}).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::collections::HashMap;
struct Fixture(HashMap<String, Value>);
impl Api for Fixture {
async fn get(&self, path: &str) -> anyhow::Result<Value> {
let key = path.split('?').next().unwrap();
self.0.get(path).or_else(|| self.0.get(key)).cloned()
.ok_or_else(|| anyhow::anyhow!("PROXMOX_HTTP_404"))
}
}
fn block<F: std::future::Future>(future: F) -> F::Output {
tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future)
}
const NOW: i64 = 1_763_640_000;
const UPID_JOB: &str = "UPID:pve:00001234:00ABCDEF:691EE8A0:vzdump::root@pam:";
const UPID_ONE: &str = "UPID:pve:00001235:00ABCDF0:691EE000:vzdump:101:root@pam:";
fn fixture() -> Fixture {
let mut m = HashMap::new();
m.insert("/cluster/status".into(), json!([
{"type":"cluster","name":"lab"},
{"type":"node","name":"pve","local":1},
{"type":"node","name":"pve2","local":0}]));
m.insert("/version".into(), json!({"version":"9.2.4"}));
m.insert("/cluster/resources".into(), json!([
{"type":"qemu","vmid":100,"name":"debian","node":"pve","status":"running","maxcpu":2,"maxmem":1073741824u64,"maxdisk":10737418240u64,"uptime":42,"template":0},
{"type":"lxc","vmid":101,"name":"alpine","node":"pve","status":"stopped","maxcpu":1,"maxmem":134217728,"pool":"lab"},
{"type":"qemu","vmid":9000,"name":"tpl","node":"pve","status":"stopped","template":1},
{"type":"qemu","vmid":200,"name":"elsewhere","node":"pve2","status":"running"}]));
m.insert("/nodes/pve/qemu/100/config".into(), json!({
"net0":"virtio=BC:24:11:AA:BB:01,bridge=vmbr0,firewall=1",
"net1":"e1000=bc-24-11-aa-bb-02,bridge=vmbr1",
"smbios1":"uuid=6E1A2B3C-0000-4000-8000-0000000000AA",
"netmask":"virtio=BC:24:11:FF:FF:FF"}));
m.insert("/nodes/pve/lxc/101/config".into(), json!({
"net0":"name=eth0,bridge=vmbr0,hwaddr=BC:24:11:AA:BB:03,ip=dhcp,type=veth"}));
m.insert("/nodes/pve/qemu/9000/config".into(), json!({}));
m.insert("/cluster/backup".into(), json!([
{"id":"backup-a","type":"vzdump","schedule":"*/2:00","storage":"local","mode":"snapshot","vmid":"100,200","enabled":1,"next-run":NOW+3600},
{"id":"backup-all","type":"vzdump","schedule":"sat 03:00","all":1,"exclude":"100","enabled":0},
{"id":"backup-pool","type":"vzdump","dow":"mon,tue","starttime":"02:30","pool":"lab"},
{"id":"backup-other-node","type":"vzdump","schedule":"daily","all":1,"node":"pve2"}]));
m.insert("/cluster/jobs/schedule-analyze".into(), json!([
{"timestamp":NOW-7200},{"timestamp":NOW-1},{"timestamp":NOW+7199}]));
m.insert("/cluster/backup-info/not-backed-up".into(), json!([{"vmid":101},{"vmid":200}]));
m.insert("/nodes/pve/tasks".into(), json!([
{"upid":UPID_JOB,"starttime":NOW-600,"endtime":NOW-500,"status":"job errors"},
{"upid":UPID_ONE,"starttime":NOW-9000,"endtime":NOW-8900,"status":"OK"},
{"upid":"UPID:pve:1:2:3:vzdump::root@pam:","starttime":NOW-10}]));
m.insert(format!("/nodes/pve/tasks/{}/log", percent_encode(UPID_JOB)), json!([
{"n":1,"t":"INFO: starting new backup job: vzdump 100 101 --storage local"},
{"n":2,"t":"INFO: Starting Backup of VM 100 (qemu)"},
{"n":3,"t":"INFO: Finished Backup of VM 100 (00:00:12)"},
{"n":4,"t":"ERROR: Backup of VM 101 failed - storage full"}]));
m.insert(format!("/nodes/pve/tasks/{}/log", percent_encode(UPID_ONE)), json!([
{"n":1,"t":"INFO: Backup job finished successfully"}]));
m.insert("/nodes/pve/tasks/UPID%3Apve%3A1%3A2%3A3%3Avzdump%3A%3Aroot%40pam%3A/log".into(), json!([]));
Fixture(m)
}
#[test]
fn collects_local_guests_jobs_and_runs() {
let observation = block(collect(&fixture(), NOW));
assert_eq!(observation.quality, Quality::Valid);
let data = observation.data.unwrap();
assert_eq!(data.node, "pve");
assert_eq!(data.cluster.as_deref(), Some("lab"));
assert_eq!(data.guests.iter().map(|g| g.vmid).collect::<Vec<_>>(), [100, 101, 9000]);
let vm = &data.guests[0];
assert_eq!(vm.macs, ["bc:24:11:aa:bb:01", "bc:24:11:aa:bb:02"]);
assert_eq!(vm.smbios_uuid.as_deref(), Some("6e1a2b3c-0000-4000-8000-0000000000aa"));
assert_eq!(data.guests[1].macs, ["bc:24:11:aa:bb:03"]);
let jobs: BTreeMap<_, _> = data.backup_jobs.iter().map(|j| (j.id.as_str(), j)).collect();
assert_eq!(jobs["backup-a"].covered_vmids, [100]);
assert_eq!(jobs["backup-a"].last_expected_run, Some(NOW - 1));
assert!(!jobs["backup-all"].enabled);
assert_eq!(jobs["backup-all"].covered_vmids, [101]);
assert_eq!(jobs["backup-all"].last_expected_run, None);
assert_eq!(jobs["backup-pool"].schedule.as_deref(), Some("mon,tue 02:30"));
assert_eq!(jobs["backup-pool"].covered_vmids, [101]);
assert!(jobs["backup-other-node"].covered_vmids.is_empty());
assert_eq!(data.not_backed_up, [101]);
assert_eq!(data.backup_runs[0].status, "running");
assert_eq!(data.backup_runs[1].status, "error");
assert_eq!(data.backup_runs[1].guests,
[GuestResult { vmid: 100, result: "ok" }, GuestResult { vmid: 101, result: "error" }]);
assert_eq!(data.backup_runs[2].guests, [GuestResult { vmid: 101, result: "ok" }]);
}
#[test]
fn agent_document_passes_the_server_validator() {
let observation = block(collect(&fixture(), NOW));
let data = serde_json::to_value(observation.data.unwrap()).unwrap();
rmm_domain::inventory_document::proxmox::validate(&data).unwrap();
assert!(rmm_domain::inventory_document::proxmox::backup_status(&data).is_some());
}
#[test]
fn missing_local_node_or_api_is_an_error_observation() {
let observation = block(collect(&Fixture(HashMap::new()), NOW));
assert_eq!(observation.quality, Quality::Error);
assert_eq!(observation.error_code.as_deref(), Some("PROXMOX_HTTP_404"));
assert!(observation.data.is_none());
assert_eq!(not_configured().error_code.as_deref(), Some("PROXMOX_NOT_CONFIGURED"));
}
#[test]
fn oversized_observation_keeps_newest_runs_and_marks_truncation() {
let mut data = block(collect(&fixture(), NOW)).data.unwrap();
let guest = data.guests[0].clone();
data.guests = (0..512).map(|i| Guest { vmid: 100 + i, name: "x".repeat(120), ..guest.clone() }).collect();
let observation = fit(Observation::valid(SOURCE, data));
assert!(observation.truncated);
assert!(serde_json::to_vec(&observation).unwrap().len() <= OBSERVATION_MAX_BYTES);
assert_eq!(observation.data.unwrap().backup_runs.len(), 3);
}
#[test]
fn token_header_rejects_malformed_credentials() {
assert_eq!(token_header("rmm-agent@pve!inventory=0f3c-11\n").as_deref(),
Some("PVEAPIToken=rmm-agent@pve!inventory=0f3c-11"));
for bad in ["", "rmm-agent@pve=abc", "rmm-agent!x=abc", "a@pve!x=a b", "a@pve!x=a\r\nX: y"] {
assert!(token_header(bad).is_none(), "{bad}");
}
}
#[test]
fn mac_and_uuid_parsing_is_strict() {
assert_eq!(normalize_mac("BC:24:11:0a:0B:0c").as_deref(), Some("bc:24:11:0a:0b:0c"));
assert!(normalize_mac("bc:24:11:0a:0b").is_none());
assert!(normalize_mac("00:00:00:00:00:00").is_none());
assert!(smbios_uuid("manufacturer=QEMU").is_none());
assert!(smbios_uuid("uuid=00000000-0000-0000-0000-000000000000").is_none());
}
}
+2 -1
View File
@@ -27,7 +27,8 @@ pub fn apt_planning_metadata() -> Result<Vec<u8>> {
Ok(output.stdout)
}
/// Read-only local collection. No shell, package manager or hypervisor access.
/// Read-only local collection. No shell or package manager; Proxmox VE is read only
/// through its local API with a PVEAuditor token (`inventory::proxmox`).
pub fn collect() -> Result<Inventory> {
let os = fs::read_to_string("/etc/os-release").context("read OS release")?;
let hostname = fs::read_to_string("/proc/sys/kernel/hostname")?;
+1 -1
View File
@@ -78,7 +78,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 12);
assert_eq!(mapped.len(), 13);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null());
+24
View File
@@ -0,0 +1,24 @@
[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
serde.workspace = true
sha1 = "0.10"
uuid.workspace = true
[target.'cfg(target_os = "freebsd")'.dev-dependencies]
ed25519-dalek = "=2.2.0"
+20
View File
@@ -0,0 +1,20 @@
#[cfg(target_os = "freebsd")]
mod native;
#[cfg(target_os = "freebsd")]
mod root;
#[cfg(target_os = "freebsd")]
fn main() -> anyhow::Result<()> {
match std::env::args().nth(1).as_deref() {
Some("--root-helper") => root::serve(),
Some("--root-capabilities") => {
println!("{}", serde_json::to_string(&root::caps()?)?);
Ok(())
}
_ => native::main(),
}
}
#[cfg(not(target_os = "freebsd"))]
fn main() {
eprintln!("FreeBSD required");
std::process::exit(1);
}
+496
View File
@@ -0,0 +1,496 @@
//! One worker per authenticated Python HTTPS channel, never a network listener.
//! Executes approved service-account POSIX scripts or delegates approved root
//! scripts to the independently synchronized local helper.
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,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
};
use uuid::Uuid;
#[cfg(test)]
mod tests;
fn supported(job: &JobPayload) -> bool {
job.execution_identity == "agent_service"
&& job.action.opnsense_service_script()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
}
struct Running {
offer: JobOffer,
grant: rmm_domain::jobs::ExecutionPermitPayload,
cancel: Arc<AtomicBool>,
task: JoinHandle<Outcome>,
}
struct Worker {
binding: Binding,
channel: Channel,
sync: ClientSync,
clock: NativeClock,
db: Connection,
ledger: Connection,
sync_due: Instant,
permit_after: Instant,
root_enabled: bool,
pending_sync: Option<SyncRequest>,
running: Option<Running>,
}
impl Drop for Worker {
fn drop(&mut self) {
if let Some(r) = self.running.take() {
r.cancel.store(true, Ordering::Release);
let _ = r.task.join();
}
}
}
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 self.running.as_ref().is_some_and(|r| r.task.is_finished()) {
let r = self.running.take().unwrap();
let o = r
.task
.join()
.unwrap_or_else(|_| Outcome::unknown("WORKER_INTERRUPTED"));
ledger::persist_outcome(&self.ledger, &r.grant, &o)?;
self.result(&r.offer, &r.grant.grant_id.to_string(), o.clone())?;
ledger::finish(&self.ledger, &r.grant, &o)?;
}
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 self.running.is_some() {
return Ok(None);
}
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 snapshot = if self.root_enabled {
Some(crate::root::snapshot(self.channel.connection_generation)?)
} else {
None
};
let p = self.sync.prepare(
&mut self.db,
&self.ledger,
self.channel.clone(),
snapshot.as_ref(),
&self.clock,
)?;
self.pending_sync = Some(p.request);
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();
}
let root = self.root_enabled && crate::root::supported(&job);
ensure!(supported(&job) || root, "UNSUPPORTED_JOB");
if !self.sync.can_start(&self.channel, root, &self.clock) {
self.sync_due = Instant::now();
return Ok(None);
}
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 q = self.pending_sync.take().context("UNEXPECTED_SYNC")?;
let applied = self.sync.apply(&mut self.db, &s, &self.clock)?;
self.sync.apply_consumption(&mut self.ledger, &self.clock)?;
if applied.helper_instruction.is_some() {
ensure!(self.root_enabled, "UNEXPECTED_HELPER");
let snapshot = crate::root::apply(&q, &s)?;
if self.sync.can_start(&self.channel, false, &self.clock) {
self.sync.confirm_helper(&snapshot)?;
}
}
}
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, |j| {
supported(j) || (self.root_enabled && crate::root::supported(j))
})?;
jobs::event(&tx, &receipt)?;
tx.commit()?;
if fresh {
self.sync_due = Instant::now();
}
}
Payload::ExecutionPermit(p) => self.permit(p)?,
Payload::CancelRequest(c) => {
if let Some(r) = &self.running
&& r.offer.job_id == c.job_id
&& r.offer.attempt_id == c.attempt_id
{
r.cancel.store(true, Ordering::Release);
}
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 root = self.binding.job(&offer.payload_bytes)?.execution_identity == "root";
let verify = || -> Result<_> {
ensure!(
self.sync.can_start(&self.channel, root, &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) || (self.root_enabled && crate::root::supported(&job)),
"UNSUPPORTED_JOB"
);
let Action::RunScript {
script_utf8,
arguments,
expected_stdout,
..
} = &job.action
else {
bail!("SCRIPT_REQUIRED")
};
let script = ScriptRequest::new(
script_utf8.as_bytes().to_vec(),
Interpreter::PosixSh,
arguments.clone(),
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 cancel = Arc::new(AtomicBool::new(false));
let flag = cancel.clone();
let deadline = self.sync.validity_deadline().context("SYNC_LEASE")?;
let binding = self.binding.clone();
let generation = self.channel.connection_generation;
let expected = expected_stdout.clone();
let seconds = job.max_runtime_seconds;
let digest = hash(script_utf8.as_bytes());
let clock = self.clock.clone();
let task = std::thread::spawn(move || {
if root {
return crate::root::execute(generation, req, &flag, seconds)
.unwrap_or_else(|_| Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN"));
}
let mut first = true;
let result = run_script_controlled(&script, || {
ensure!(!flag.load(Ordering::Acquire), "CANCEL_OR_FENCE");
if first {
let (lo, hi) = clock.bounds()?;
ensure!(hi < deadline, "SYNC_EXPIRED");
binding.verify(&req, lo)?;
binding.verify(&req, hi)?;
first = false;
} else {
clock.now()?;
}
Ok(())
});
match result {
Ok(o) => {
let ok = o.code == Some(0)
&& !o.timed_out
&& !o.interrupted
&& expected
.as_ref()
.is_none_or(|v| !o.truncated && o.stdout == v.as_bytes());
Outcome {
state: if ok {
"succeeded"
} else if o.interrupted || o.timed_out || o.code.is_none() {
"unknown"
} 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()},"script_sha256":digest}),
error_code: if ok { "" } else { "PROBE_POSTCONDITION_FAILED" }.into(),
}
}
Err(_) => Outcome::unknown("PROBE_EFFECT_UNCERTAIN"),
}
});
self.running = Some(Running {
offer,
grant,
task,
cancel,
});
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(),
pending_sync: None,
running: None,
root_enabled: env::var_os("DISCOVERY_ROOT_SESSION").is_some(),
};
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,148 @@
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(),
pending_sync: None,
running: None,
root_enabled: false,
};
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())?;
let end = Instant::now() + Duration::from_secs(10);
while w.running.is_some() {
ensure!(Instant::now() < end, "execution timeout");
w.next()?;
std::thread::yield_now();
}
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(())
}
+543
View File
@@ -0,0 +1,543 @@
//! FreeBSD peer credentials, boot identity and executor lock around the same
//! independent HelperSync and consumption ledger used by the Linux root helper.
use anyhow::{Context, Result, bail, ensure};
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
freebsd_clock::NativeClock,
helper_reconcile::{self as h, BootSource, ExecutorLedgerGuard},
ledger,
reconcile::{HelperSnapshot, SyncClock},
};
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
use rmm_domain::jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload, hash};
use rmm_protocol::{SyncAttempt, SyncRequest, SyncResponse};
use rusqlite::{Connection, OptionalExtension};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha1::{Digest, Sha1};
use std::{
fs::{self, File, OpenOptions, Permissions},
io::{Read, Write},
os::{
fd::AsRawFd,
unix::{
fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
net::{UnixListener, UnixStream},
},
},
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
use uuid::Uuid;
const DIR: &str = "/var/db/discovery-root-jobs";
const SOCK: &str = "/var/run/discovery-root-jobs/control.sock";
pub const POLICY: &str = "/usr/local/etc/discovery-agent/root-policy.json";
const BINDING: &str = "/usr/local/etc/discovery-agent/job-binding.json";
const LIMIT: usize = 8 * 1024 * 1024;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u8,
profile: String,
agent_uid: u32,
agent_gid: u32,
binding_sha256: String,
helper_binary_sha256: String,
}
fn protected(path: &Path) -> Result<()> {
for p in path.ancestors() {
let m = fs::symlink_metadata(p)?;
ensure!(
m.uid() == 0
&& m.mode() & 0o022 == 0
&& !m.is_symlink()
&& (if p == path {
m.is_file() || m.is_dir()
} else {
m.is_dir()
}),
"UNPROTECTED_ROOT_PATH"
);
}
Ok(())
}
fn config() -> Result<(Policy, Binding, String)> {
protected(Path::new(POLICY))?;
protected(Path::new(BINDING))?;
let raw = fs::read(POLICY)?;
ensure!(raw.len() <= 8192, "POLICY_SIZE");
let p: Policy = serde_json::from_slice(&raw)?;
let bytes = fs::read(BINDING)?;
ensure!(
p.schema_version == 1
&& p.profile == "full_maintenance_v1"
&& p.agent_uid > 0
&& p.agent_gid > 0
&& p.binding_sha256 == hash(&bytes)
&& rmm_domain::agent_update::digest(&p.helper_binary_sha256),
"POLICY_INVALID"
);
Ok((p, serde_json::from_slice(&bytes)?, hash(&raw)))
}
struct Boot(Uuid);
impl BootSource for Boot {
fn current_boot(&self) -> Result<Uuid> {
// Same UUIDv5 derivation as the already enrolled Python agent. Obtain
// boottime independently, never trust a value supplied on the socket.
let r = Command::new("/sbin/sysctl")
.args(["-n", "kern.boottime"])
.env_clear()
.output()?;
ensure!(r.status.success(), "BOOT_UNAVAILABLE");
let s = std::str::from_utf8(&r.stdout)?
.split_once('}')
.context("BOOT_FORMAT")?
.0;
let mut sha = Sha1::new();
sha.update(self.0.as_bytes());
sha.update(s.as_bytes());
let mut b: [u8; 16] = sha.finalize()[..16].try_into()?;
b[6] = (b[6] & 15) | 0x50;
b[8] = (b[8] & 63) | 0x80;
Ok(Uuid::from_bytes(b))
}
}
struct Guard {
_lock: File,
db_file: File,
}
impl ExecutorLedgerGuard for Guard {
fn check(&self, db: &Connection) -> Result<()> {
let path: String = db.query_row(
"SELECT file FROM pragma_database_list WHERE name='main'",
[],
|r| r.get(0),
)?;
ensure!(
Path::new(&path) == Path::new(DIR).join("consumption.sqlite"),
"WRONG_HELPER_LEDGER"
);
let m = fs::symlink_metadata(path)?;
let f = self.db_file.metadata()?;
ensure!(
m.uid() == 0
&& m.mode() & 0o077 == 0
&& m.is_file()
&& (m.dev(), m.ino()) == (f.dev(), f.ino()),
"HELPER_LEDGER_REPLACED"
);
Ok(())
}
}
fn peer(s: &UnixStream) -> Result<u32> {
let (mut uid, mut gid) = (u32::MAX, u32::MAX);
ensure!(
unsafe { libc::getpeereid(s.as_raw_fd(), &mut uid, &mut gid) } == 0,
"PEER_IDENTITY"
);
Ok(uid)
}
fn frame<T: Serialize>(s: &mut UnixStream, value: &T) -> Result<()> {
let bytes = serde_json::to_vec(value)?;
ensure!(bytes.len() <= LIMIT, "IPC_SIZE");
s.write_all(&(bytes.len() as u32).to_be_bytes())?;
s.write_all(&bytes)?;
Ok(())
}
fn read<T: DeserializeOwned>(s: &mut UnixStream) -> Result<T> {
let mut len = [0; 4];
s.read_exact(&mut len)?;
let n = u32::from_be_bytes(len) as usize;
ensure!((1..=LIMIT).contains(&n), "IPC_SIZE");
let mut b = vec![0; n];
s.read_exact(&mut b)?;
Ok(serde_json::from_slice(&b)?)
}
#[derive(Serialize, Deserialize)]
enum Op {
Probe,
Snapshot(u64),
Apply(Vec<u8>, h::SignedResponse),
Execute(u64, Request),
}
#[derive(Serialize, Deserialize)]
struct Call {
nonce: Uuid,
policy: String,
image: String,
op: Op,
}
#[derive(Serialize, Deserialize)]
enum Data {
Pins,
Snapshot(h::Snapshot),
Outcome(Outcome),
}
#[derive(Serialize, Deserialize)]
struct Reply {
nonce: Uuid,
data: Data,
}
fn connect(op: Op) -> Result<(UnixStream, Uuid)> {
let (p, _, policy) = config()?;
let s = Path::new(SOCK);
protected(s.parent().unwrap())?;
let m = fs::symlink_metadata(s)?;
ensure!(
m.file_type().is_socket() && m.uid() == 0 && m.gid() == p.agent_gid && m.mode() & 7 == 0,
"HELPER_SOCKET_MODE"
);
let mut s = UnixStream::connect(s)?;
ensure!(peer(&s)? == 0, "HELPER_NOT_ROOT");
s.set_read_timeout(Some(Duration::from_secs(12)))?;
s.set_write_timeout(Some(Duration::from_secs(5)))?;
let nonce = Uuid::new_v4();
frame(
&mut s,
&Call {
nonce,
policy,
image: p.helper_binary_sha256,
op,
},
)?;
Ok((s, nonce))
}
fn call(op: Op) -> Result<Data> {
let (mut s, n) = connect(op)?;
let r: Reply = read(&mut s)?;
ensure!(r.nonce == n, "HELPER_CHALLENGE");
Ok(r.data)
}
pub fn caps() -> Result<Vec<String>> {
let (p, _, policy) = config()?;
ensure!(matches!(call(Op::Probe)?, Data::Pins), "HELPER_PROBE");
Ok(vec![
"opnsense.root.posix/1".into(),
"helper.root.v1".into(),
"root:run_script".into(),
FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.binary.sha256:{}", p.helper_binary_sha256),
format!("helper.policy.sha256:{policy}"),
])
}
fn mapped(data: Data) -> Result<HelperSnapshot> {
let Data::Snapshot(s) = data else {
bail!("HELPER_SNAPSHOT")
};
Ok(HelperSnapshot {
journal_id: s.journal_id,
checkpoint: s.checkpoint,
previous_decision_id: s.previous_decision_id,
attempts: s
.attempts
.into_iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash,
grant_id: a.grant_id.to_string(),
consumption: a.consumption,
state: a.state,
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256,
outcome_bytes: a.outcome_bytes,
..Default::default()
})
.collect(),
})
}
pub fn snapshot(g: u64) -> Result<HelperSnapshot> {
mapped(call(Op::Snapshot(g))?)
}
pub fn apply(q: &SyncRequest, s: &SyncResponse) -> Result<HelperSnapshot> {
mapped(call(Op::Apply(
q.encode_to_vec(),
h::SignedResponse {
decision_bytes: s.decision_bytes.clone(),
signature: s.signature.clone(),
},
))?)
}
pub fn execute(g: u64, req: Request, cancel: &AtomicBool, seconds: u32) -> Result<Outcome> {
let (mut s, n) = connect(Op::Execute(g, req))?;
let started = std::time::Instant::now();
// Poll only for response availability. On cancellation dropping the stream
// fences the root executor, which records the actual result in its own DB.
loop {
ensure!(
!cancel.load(Ordering::Acquire)
&& started.elapsed() < Duration::from_secs(u64::from(seconds) + 12),
"CALLER_FENCED"
);
let mut fd = libc::pollfd {
fd: s.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let r = unsafe { libc::poll(&mut fd, 1, 100) };
if r < 0 {
return Err(std::io::Error::last_os_error().into());
}
if r != 0 {
break;
}
}
let r: Reply = read(&mut s)?;
ensure!(r.nonce == n, "HELPER_CHALLENGE");
let Data::Outcome(o) = r.data else {
bail!("HELPER_RESULT")
};
Ok(o)
}
pub fn supported(j: &JobPayload) -> bool {
j.execution_identity == "root"
&& j.action.opnsense_root_script()
&& j.action
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
}
struct Helper {
db: Connection,
guard: Guard,
b: Binding,
clock: NativeClock,
boot: Boot,
sync: h::HelperSync,
p: Policy,
policy: String,
image: PathBuf,
}
impl Helper {
fn invoke(&mut self, s: &mut UnixStream) -> Result<()> {
ensure!(peer(s)? == self.p.agent_uid, "AGENT_PEER_DENIED");
s.set_read_timeout(Some(Duration::from_secs(5)))?;
s.set_write_timeout(Some(Duration::from_secs(5)))?;
let Call {
nonce,
policy,
image,
op,
} = read(s)?;
ensure!(
!nonce.is_nil() && policy == self.policy && image == self.p.helper_binary_sha256,
"PIN_MISMATCH"
);
let data = match op {
Op::Probe => Data::Pins,
Op::Snapshot(g) => Data::Snapshot(self.sync.snapshot(
&mut self.db,
&self.guard,
g,
&self.clock,
&self.boot,
)?),
Op::Apply(q, r) => Data::Snapshot(
self.sync
.apply(&mut self.db, &self.guard, &r, &q, &self.clock, &self.boot)?
.snapshot,
),
Op::Execute(g, req) => {
let (lo, hi) = self.clock.bounds()?;
let (job, grant) = self.b.verify(&req, lo)?;
self.b.verify(&req, hi)?;
ensure!(supported(&job), "ROOT_PROFILE_REQUIRED");
self.guard.check(&self.db)?;
let prior:Option<Option<Vec<u8>>>=self.db.query_row("SELECT COALESCE(result,(SELECT outcome FROM execution_evidence e WHERE e.grant_id=c.grant_id)) FROM consumed c WHERE grant_id=?1",
[grant.grant_id.to_string()],|r|r.get(0)).optional()?;
if let Some(old) = prior {
Data::Outcome(match old {
Some(bytes) => serde_json::from_slice(&bytes)?,
None => Outcome::unknown("PREVIOUS_EFFECT_UNRESOLVED"),
})
} else {
let Action::RunScript {
script_utf8,
arguments,
expected_stdout,
..
} = &job.action
else {
bail!("SCRIPT_REQUIRED")
};
let script = ScriptRequest::new(
script_utf8.as_bytes().to_vec(),
Interpreter::PosixSh,
arguments.clone(),
Duration::from_secs(job.max_runtime_seconds.into()),
job.max_output_bytes as usize,
)?;
ensure!(
self.sync
.can_start(&self.db, &self.guard, g, &self.clock, &self.boot),
"HELPER_SYNC_REQUIRED"
);
let until = self.sync.validity_deadline().context("HELPER_LEASE")?;
ensure!(
hash(&fs::read(&self.image)?) == image && config()?.2 == policy,
"HELPER_POLICY_CHANGED"
);
ledger::begin_execution(
&mut self.db,
&grant,
&req,
self.boot.current_boot()?,
self.clock.now()?,
)?;
let mut first = true;
let res = run_script_controlled(&script, || {
let (lo, hi) = self.clock.bounds()?;
if first {
ensure!(hi < until, "HELPER_LEASE_EXPIRED");
self.b.verify(&req, lo)?;
self.b.verify(&req, hi)?;
first = false;
}
let mut byte = 0u8;
let rc = unsafe {
libc::recv(
s.as_raw_fd(),
(&mut byte as *mut u8).cast(),
1,
libc::MSG_PEEK | libc::MSG_DONTWAIT,
)
};
ensure!(
rc < 0
&& std::io::Error::last_os_error().kind()
== std::io::ErrorKind::WouldBlock,
"CALLER_FENCED"
);
Ok(())
});
let out = match res {
Err(_) => Outcome::unknown("HELPER_SCRIPT_EFFECT_UNKNOWN"),
Ok(o) => {
let unknown = o.interrupted || o.timed_out || o.code.is_none();
let ok = !unknown
&& o.code == Some(0)
&& expected_stdout
.as_ref()
.is_none_or(|v| !o.truncated && o.stdout == v.as_bytes());
Outcome {
state: if unknown {
"unknown"
} else 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,"script_sha256":hash(script_utf8.as_bytes()),"execution_uid":unsafe{libc::geteuid()},
"privileged_script_profile":"full_maintenance_v1","output_encoding":"raw_native_bytes","termination_does_not_prove_absence_of_effects":unknown}),
error_code: if unknown {
"HELPER_SCRIPT_EFFECT_UNKNOWN"
} else if ok {
""
} else {
"SCRIPT_POSTCONDITION_FAILED"
}
.into(),
}
}
};
ledger::finish(&self.db, &grant, &out)?;
Data::Outcome(out)
}
}
};
frame(s, &Reply { nonce, data })
}
}
pub fn serve() -> Result<()> {
ensure!(
unsafe { libc::geteuid() } == 0 && unsafe { libc::getuid() } == 0,
"ROOT_REQUIRED"
);
unsafe { libc::umask(0o077) };
let (p, b, policy) = config()?;
let image = std::env::current_exe()?;
protected(&image)?;
ensure!(
hash(&fs::read(&image)?) == p.helper_binary_sha256,
"RUNNING_IMAGE_PIN"
);
let directory = Path::new(DIR);
protected(directory)?;
ensure!(
fs::metadata(directory)?.mode() & 0o077 == 0,
"ROOT_STATE_NOT_PRIVATE"
);
let open = |name: &str| {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(directory.join(name))
};
let lock = open("executor.lock")?;
ensure!(
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"HELPER_BUSY"
);
let guard = Guard {
_lock: lock,
db_file: open("consumption.sqlite")?,
};
let db = Connection::open(directory.join("consumption.sqlite"))?;
guard.check(&db)?;
ledger::initialize_ledger(&db)?;
let clock = NativeClock::default();
let sync = h::HelperSync::new(b.clone(), &clock)?;
let boot = Boot(b.agent_id);
let path = Path::new(SOCK);
protected(path.parent().unwrap())?;
if let Ok(m) = fs::symlink_metadata(path) {
ensure!(
m.uid() == 0 && m.file_type().is_socket(),
"UNEXPECTED_SOCKET"
);
fs::remove_file(path)?;
}
let listener = UnixListener::bind(path)?;
std::os::unix::fs::chown(path, Some(0), Some(p.agent_gid))?;
fs::set_permissions(path, Permissions::from_mode(0o660))?;
let mut helper = Helper {
db,
guard,
b,
p,
policy,
image,
clock,
boot,
sync,
};
for s in listener.incoming() {
if let Err(e) = helper.invoke(&mut s?) {
let code = e.to_string();
eprintln!(
"root helper: {}",
if code.len() < 80 && code.bytes().all(|v| v.is_ascii_uppercase() || v == b'_') {
&code
} else {
"REJECTED"
}
);
}
}
Ok(())
}
+6
View File
@@ -2,6 +2,8 @@ use std::{env, path::PathBuf, process::Command};
fn main() {
println!("cargo:rerun-if-changed=native/w32time.idl");
println!("cargo:rerun-if-changed=native/clock_rpc.c");
println!("cargo:rerun-if-changed=native/clock_local.c");
println!("cargo:rerun-if-changed=native/clock_status.h");
println!("cargo:rerun-if-changed=native/clock_endpoints.c");
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
@@ -52,10 +54,12 @@ fn main() {
.include(&out)
.file(out.join("w32time_c.c"))
.file("native/clock_rpc.c")
.file("native/clock_local.c")
.file("native/clock_endpoints.c")
.compile("rmm_clock_rpc");
println!("cargo:rustc-link-lib=rpcrt4");
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=secur32");
return;
}
assert_eq!(
@@ -89,8 +93,10 @@ fn main() {
.include(&out)
.file(out.join("w32time_c.c"))
.file("native/clock_rpc.c")
.file("native/clock_local.c")
.file("native/clock_endpoints.c")
.compile("rmm_clock_rpc");
println!("cargo:rustc-link-lib=rpcrt4");
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=secur32");
}
+288
View File
@@ -0,0 +1,288 @@
/* MS-W32T 2.2.17 / opnum 6 and MS-RPCE connection-oriented packet privacy.
* Keep the status RPC on the same local pipe handle whose server PID we verify
* against the Service Control Manager, before exchanging any auth tokens.
* SSPI performs the NTLM exchange and protects the RPC headers and payloads.
*/
#define _WIN32_WINNT 0x0a00
#define SECURITY_WIN32
#include <windows.h>
#include <rpc.h>
#include <security.h>
#include <string.h>
#include "clock_status.h"
enum {
RPC_HEADER = 16, CALL_HEADER = 24, SECURITY_TRAILER = 8, SIGNATURE = 16,
FIRST_LAST = 3, HEADER_SIGN = 4, FRAME_LIMIT = 4280, TOKEN_LIMIT = 16384,
STATUS_LAYOUT = 120, STATUS_FIXED_WIRE = 112, STATUS_SOURCE_PTR = 60,
};
enum { REQUEST = 0, RESPONSE = 2, BIND = 11, BIND_ACK = 12, AUTH3 = 16 };
enum { BIND_CALL_ID = 1, STATUS_CALL_ID = 2, AUTH_CONTEXT_ID = 1, STATUS_OPNUM = 6 };
static DWORD w32time_pid(void) {
SC_HANDLE manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
if (!manager) return 0;
SC_HANDLE service = OpenServiceW(manager, L"W32Time", SERVICE_QUERY_STATUS);
SERVICE_STATUS_PROCESS status = {0};
DWORD needed = 0;
BOOL ok = service && QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
(BYTE *)&status, sizeof status, &needed);
if (service) CloseServiceHandle(service);
CloseServiceHandle(manager);
return ok && status.dwCurrentState == SERVICE_RUNNING ? status.dwProcessId : 0;
}
static BOOL is_w32time(HANDLE pipe, DWORD expected_pid) {
ULONG peer_pid = 0;
return expected_pid != 0 && GetNamedPipeServerProcessId(pipe, &peer_pid)
&& peer_pid == expected_pid && w32time_pid() == expected_pid;
}
static DWORD pipe_io(HANDLE pipe, BYTE *buffer, DWORD capacity, BOOL writing,
DWORD *count, ULONGLONG deadline) {
ULONGLONG now = GetTickCount64();
if (now >= deadline) return ERROR_TIMEOUT;
OVERLAPPED io = {0};
io.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!io.hEvent) return GetLastError();
BOOL ok = writing ? WriteFile(pipe, buffer, capacity, NULL, &io)
: ReadFile(pipe, buffer, capacity, NULL, &io);
DWORD error = ok ? ERROR_SUCCESS : GetLastError();
if (error == ERROR_IO_PENDING) {
if (WaitForSingleObject(io.hEvent, (DWORD)(deadline - now)) != WAIT_OBJECT_0) {
CancelIoEx(pipe, &io);
/* Finish cancellation before releasing the stack buffer. */
GetOverlappedResult(pipe, &io, count, TRUE);
error = ERROR_TIMEOUT;
} else {
error = GetOverlappedResult(pipe, &io, count, FALSE)
? ERROR_SUCCESS : GetLastError();
}
} else if (ok) {
error = GetOverlappedResult(pipe, &io, count, FALSE)
? ERROR_SUCCESS : GetLastError();
}
CloseHandle(io.hEvent);
return error;
}
static void put16(BYTE *p, uint16_t v) { memcpy(p, &v, sizeof v); }
static void put32(BYTE *p, uint32_t v) { memcpy(p, &v, sizeof v); }
static uint16_t get16(const BYTE *p) { uint16_t v; memcpy(&v, p, sizeof v); return v; }
static uint32_t get32(const BYTE *p) { uint32_t v; memcpy(&v, p, sizeof v); return v; }
static uint64_t get64(const BYTE *p) { uint64_t v; memcpy(&v, p, sizeof v); return v; }
static int64_t get_i64(const BYTE *p) { int64_t v; memcpy(&v, p, sizeof v); return v; }
static DWORD align4(DWORD offset) { return (offset + 3) & ~3u; }
static void write_header(BYTE *p, BYTE type, BYTE flags, WORD length, WORD auth_length, DWORD call) {
memset(p, 0, RPC_HEADER);
p[0] = 5;
p[2] = type;
p[3] = flags;
p[4] = 0x10; /* little-endian NDR */
put16(p + 8, length);
put16(p + 10, auth_length);
put32(p + 12, call);
}
static void write_security_trailer(BYTE *p) {
memset(p, 0, SECURITY_TRAILER);
p[0] = RPC_C_AUTHN_WINNT;
p[1] = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
put32(p + 4, AUTH_CONTEXT_ID);
}
static BOOL valid_security_trailer(const BYTE *p) {
return p[0] == RPC_C_AUTHN_WINNT && p[1] == RPC_C_AUTHN_LEVEL_PKT_PRIVACY
&& p[3] == 0 && get32(p + 4) == AUTH_CONTEXT_ID;
}
static DWORD send_frame(HANDLE pipe, BYTE *frame, ULONGLONG deadline) {
DWORD length = get16(frame + 8);
DWORD count = 0;
DWORD error = pipe_io(pipe, frame, length, TRUE, &count, deadline);
return !error && count != length ? ERROR_INVALID_DATA : error;
}
static DWORD read_frame(HANDLE pipe, BYTE *frame, DWORD *length, BYTE type, DWORD call,
ULONGLONG deadline) {
DWORD error = pipe_io(pipe, frame, FRAME_LIMIT, FALSE, length, deadline);
if (error) return error;
if (*length < RPC_HEADER || frame[0] != 5 || frame[1] != 0 || frame[2] != type
|| (frame[3] & FIRST_LAST) != FIRST_LAST || get32(frame + 4) != 0x10
|| get16(frame + 8) != *length || get32(frame + 12) != call) {
return ERROR_INVALID_DATA;
}
return ERROR_SUCCESS;
}
static DWORD bind_status_rpc(HANDLE pipe, CredHandle *credentials, CtxtHandle *context,
ULONGLONG deadline) {
static const BYTE interface_v4_1[20] = {0x84,0xd8,0xb6,0x8f,0x88,0x23,0xd0,0x11,
0x8c,0x35,0,0xc0,0x4f,0xda,0x27,0x95,4,0,1,0};
static const BYTE ndr32_v2[20] = {0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,
0x9f,0xe8,0x08,0,0x2b,0x10,0x48,0x60,2};
const ULONG required = ISC_REQ_USE_DCE_STYLE | ISC_REQ_CONFIDENTIALITY
| ISC_REQ_INTEGRITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT;
ULONG attributes = 0;
BYTE out[TOKEN_LIMIT] = {0};
BYTE reply[FRAME_LIMIT] = {0};
SecBuffer token = {sizeof out - 80, SECBUFFER_TOKEN, out + 80};
SecBufferDesc output = {SECBUFFER_VERSION, 1, &token};
SECURITY_STATUS status = InitializeSecurityContextW(credentials, NULL, L"", required, 0,
SECURITY_NATIVE_DREP, NULL, 0, context, &output, &attributes, NULL);
if (status != SEC_I_CONTINUE_NEEDED) return status ? (DWORD)status : ERROR_INVALID_DATA;
if (!token.cbBuffer || token.cbBuffer > sizeof out - 80) return ERROR_INVALID_DATA;
write_header(out, BIND, FIRST_LAST | HEADER_SIGN, (WORD)(80 + token.cbBuffer),
(WORD)token.cbBuffer, BIND_CALL_ID);
put16(out + 16, FRAME_LIMIT);
put16(out + 18, FRAME_LIMIT);
out[24] = 1; /* one bind context */
out[30] = 1; /* one transfer syntax */
memcpy(out + 32, interface_v4_1, sizeof interface_v4_1);
memcpy(out + 52, ndr32_v2, sizeof ndr32_v2);
write_security_trailer(out + 72);
DWORD error = send_frame(pipe, out, deadline);
if (error) return error;
DWORD length = 0;
error = read_frame(pipe, reply, &length, BIND_ACK, BIND_CALL_ID, deadline);
if (error) return error;
DWORD challenge_length = get16(reply + 10);
if (reply[3] != (FIRST_LAST | HEADER_SIGN) || length < 56
|| !challenge_length || challenge_length > length - 56) return ERROR_INVALID_DATA;
DWORD verdict = align4(26 + get16(reply + 24));
DWORD trailer = length - SECURITY_TRAILER - challenge_length;
if (verdict > trailer || trailer - verdict < 28 || reply[verdict] != 1
|| get16(reply + verdict + 4) != 0 || get16(reply + verdict + 6) != 0
|| memcmp(reply + verdict + 8, ndr32_v2, sizeof ndr32_v2)
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
SecBuffer challenge = {challenge_length, SECBUFFER_TOKEN, reply + trailer + SECURITY_TRAILER};
SecBufferDesc input = {SECBUFFER_VERSION, 1, &challenge};
token.pvBuffer = out + 28;
token.cbBuffer = sizeof out - 28;
status = InitializeSecurityContextW(credentials, context, L"", required, 0,
SECURITY_NATIVE_DREP, &input, 0, context, &output, &attributes, NULL);
if (status == SEC_I_COMPLETE_NEEDED) status = CompleteAuthToken(context, &output);
if (status) return (DWORD)status;
if (!token.cbBuffer || token.cbBuffer > sizeof out - 28
|| !(attributes & ISC_RET_CONFIDENTIALITY) || !(attributes & ISC_RET_INTEGRITY)) {
return ERROR_INVALID_DATA;
}
write_header(out, AUTH3, FIRST_LAST, (WORD)(28 + token.cbBuffer),
(WORD)token.cbBuffer, BIND_CALL_ID);
memset(out + RPC_HEADER, 0, 4);
write_security_trailer(out + 20);
return send_frame(pipe, out, deadline);
}
static DWORD decode_status(const BYTE *body, DWORD length, RmmClockStatus *out) {
/* Unique NDR32 status pointer, x64 MS-W32T layout ID, no auxiliary entries. */
if (length < STATUS_FIXED_WIRE + 4 || !get32(body) || get32(body + 8) != STATUS_LAYOUT
|| get32(body + 104) || get32(body + 108)) return RPC_X_BAD_STUB_DATA;
DWORD result_offset = STATUS_FIXED_WIRE;
if (get32(body + STATUS_SOURCE_PTR)) {
/* Skip the optional conformant UTF-16 string without allocating or logging it. */
if (length - result_offset < 16) return RPC_X_BAD_STUB_DATA;
DWORD maximum = get32(body + result_offset);
DWORD offset = get32(body + result_offset + 4);
DWORD count = get32(body + result_offset + 8);
if (offset || !count || count > maximum || count > (length - result_offset - 16) / 2)
return RPC_X_BAD_STUB_DATA;
result_offset += 12 + 2 * count;
if (get16(body + result_offset - 2)) return RPC_X_BAD_STUB_DATA;
result_offset = align4(result_offset);
}
if (length - 4 != result_offset) return RPC_X_BAD_STUB_DATA;
DWORD result = get32(body + result_offset);
if (result) return result;
*out = (RmmClockStatus){
.leap = get32(body + 12), .stratum = get32(body + 16), .size = STATUS_LAYOUT,
.last_sync = get64(body + 32), .root_delay = get_i64(body + 40),
.root_dispersion = get64(body + 48), .phase = get_i64(body + 64),
.state = get32(body + 72), .flags = get32(body + 76),
.last_result = get32(body + 88), .sync_age = get64(body + 96),
};
return ERROR_SUCCESS;
}
static DWORD request_status(HANDLE pipe, CtxtHandle *context, ULONGLONG deadline,
DWORD expected_pid, RmmClockStatus *out) {
SecPkgContext_Sizes sizes = {0};
SECURITY_STATUS security = QueryContextAttributesW(context, SECPKG_ATTR_SIZES, &sizes);
if (security) return (DWORD)security;
if (sizes.cbSecurityTrailer != SIGNATURE) return ERROR_INVALID_DATA;
BYTE frame[CALL_HEADER + SECURITY_TRAILER + SIGNATURE] = {0};
write_header(frame, REQUEST, FIRST_LAST, sizeof frame, SIGNATURE, STATUS_CALL_ID);
put16(frame + 22, STATUS_OPNUM); /* only the read-only operation has an encoding */
write_security_trailer(frame + CALL_HEADER);
SecBuffer parts[] = {
{CALL_HEADER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame},
{0, SECBUFFER_DATA, frame + CALL_HEADER},
{SECURITY_TRAILER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame + CALL_HEADER},
{SIGNATURE, SECBUFFER_TOKEN, frame + CALL_HEADER + SECURITY_TRAILER},
};
SecBufferDesc message = {SECBUFFER_VERSION, 4, parts};
security = EncryptMessage(context, 0, &message, 0);
if (security) return (DWORD)security;
if (parts[3].cbBuffer != SIGNATURE) return ERROR_INVALID_DATA;
DWORD error = send_frame(pipe, frame, deadline);
if (error) return error;
BYTE reply[FRAME_LIMIT] = {0};
DWORD length = 0;
error = read_frame(pipe, reply, &length, RESPONSE, STATUS_CALL_ID, deadline);
if (error) return error;
if (reply[3] != FIRST_LAST || get16(reply + 10) != SIGNATURE || get16(reply + 20) != 0
|| length < sizeof frame) return ERROR_INVALID_DATA;
DWORD trailer = length - SECURITY_TRAILER - SIGNATURE;
BYTE padding = reply[trailer + 2];
if (padding > 15 || padding > trailer - CALL_HEADER
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
parts[0].pvBuffer = reply;
parts[1].pvBuffer = reply + CALL_HEADER;
parts[1].cbBuffer = trailer - CALL_HEADER;
parts[2].pvBuffer = reply + trailer;
parts[3].pvBuffer = reply + trailer + SECURITY_TRAILER;
ULONG qop = 0;
security = DecryptMessage(context, &message, 0, &qop);
if (security) return (DWORD)security;
if (qop != 0) return ERROR_INVALID_DATA;
if (!is_w32time(pipe, expected_pid)) return ERROR_ACCESS_DENIED;
return decode_status(reply + CALL_HEADER, trailer - CALL_HEADER - padding, out);
}
uint32_t rmm_local_clock_query(RmmClockStatus *out) {
memset(out, 0, sizeof *out);
DWORD expected_pid = w32time_pid();
if (!expected_pid) return ERROR_SERVICE_NOT_ACTIVE;
ULONGLONG deadline = GetTickCount64() + 750;
HANDLE pipe = CreateFileW(L"\\\\.\\pipe\\W32TIME_ALT", FILE_READ_DATA | FILE_WRITE_DATA
| FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, NULL);
if (pipe == INVALID_HANDLE_VALUE) return GetLastError();
DWORD mode = PIPE_READMODE_MESSAGE;
DWORD error;
if (!is_w32time(pipe, expected_pid)) {
error = ERROR_ACCESS_DENIED;
} else if (!SetNamedPipeHandleState(pipe, &mode, NULL, NULL)) {
error = GetLastError();
} else {
CredHandle credentials;
CtxtHandle context;
SecInvalidateHandle(&context);
error = (DWORD)AcquireCredentialsHandleW(NULL, L"NTLM", SECPKG_CRED_OUTBOUND,
NULL, NULL, NULL, NULL, &credentials, NULL);
if (!error) {
error = bind_status_rpc(pipe, &credentials, &context, deadline);
if (!error) error = request_status(pipe, &context, deadline, expected_pid, out);
if (SecIsValidHandle(&context)) DeleteSecurityContext(&context);
FreeCredentialsHandle(&credentials);
}
}
CloseHandle(pipe);
return error;
}
+1 -9
View File
@@ -9,6 +9,7 @@
#include <stdlib.h>
#include <string.h>
#include "w32time.h"
#include "clock_status.h"
/* Documented public SDK API; older MinGW headers omit its declaration. */
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
@@ -61,15 +62,6 @@ void __RPC_USER MIDL_user_free(void *memory) {
static void release_allocations(Arena *arena) {
while (arena->head) MIDL_user_free(arena->head + 1);
}
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
* leave C. A zero native return is meaningful only when return_present is1.
@@ -0,0 +1,17 @@
#ifndef RMM_CLOCK_STATUS_H
#define RMM_CLOCK_STATUS_H
#include <stdint.h>
/* Numeric Windows status only. No remote strings or pointers cross the ABI. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
#endif
+167 -25
View File
@@ -1,19 +1,20 @@
//! Read-only trusted clock gate for Windows 11. All MS-W32T time intervals are
//! 100 ns; last_sync alone is a FILETIME (1601 epoch), sync_age is a duration.
//! No W32Time reconfiguration, resync, unauthenticated pipe or server-time anchor.
//! Policy: <=1h successful sync age, SYNC state, stratum1..15, nonalarm leap,
//! <=2s root dispersion + roundtrip/2 + absolute phase + query latency.
//! Require a successful sync within one day, SYNC state, stratum 1..15 and no
//! leap alarm. Bound dispersion, half the round trip, phase, holdover and
//! query latency to two seconds.
//! A >1s wall step or suspend invalidates until a post-discontinuity sync.
use anyhow::{Result, anyhow, ensure};
use chrono::{DateTime, Utc};
use serde::Serialize;
use std::sync::Mutex;
/// Flip only after native account AND service-bound ALPC, positive readiness,
/// wrong-account/wrong-service denial and fail-closed qualification.
pub const ADAPTER_QUALIFIED: bool = false;
const ADAPTER_QUALIFIED: bool = cfg!(windows);
const SECOND: u64 = 10_000_000;
const MAX_AGE: u64 = 3600 * SECOND;
const MAX_AGE: u64 = 24 * 60 * 60 * SECOND;
const MAX_ERROR: u64 = 2 * SECOND;
const CACHE_AGE: u64 = 5 * SECOND;
const RETRY_AGE: u64 = SECOND;
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
#[derive(Clone, Copy, Debug, Default, Serialize)]
@@ -124,9 +125,11 @@ impl Continuity {
}
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
// Like the Linux kernel, retain a still-qualified last good sample when
// a poll has no new data. The service's state and age still govern trust.
ensure!(
status.state == 2
&& status.last_result == 0
&& matches!(status.last_result, 0..=2)
&& status.leap <= 2
&& (1..=15).contains(&status.stratum),
"CLOCK_UNSYNCHRONIZED"
@@ -152,6 +155,7 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
.root_dispersion
.checked_add((status.root_delay as u64).div_ceil(2))
.and_then(|v| v.checked_add(status.phase.unsigned_abs()))
.and_then(|v| v.checked_add(holdover_error(status.sync_age)))
.and_then(|v| v.checked_add(query_ticks))
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
ensure!(
@@ -160,8 +164,38 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
);
Ok(bound)
}
fn holdover_error(elapsed: u64) -> u64 {
// NTP's nominal dispersion growth (RFC 5905, PHI = 15 ppm).
elapsed.saturating_mul(15).div_ceil(1_000_000)
}
#[derive(Clone, Copy)]
struct CachedQualification {
sample: Sample,
bound: Option<u64>,
valid_for: u64,
}
impl CachedQualification {
fn bound_at(self, sample: Sample) -> Option<u64> {
let elapsed = sample.interrupt.checked_sub(self.sample.interrupt)?;
let awake = sample.unbiased.checked_sub(self.sample.unbiased)?;
let wall = sample.wall.checked_sub(self.sample.wall)?;
let wall_drift = elapsed.abs_diff(wall);
let bound = self
.bound?
.checked_add(holdover_error(elapsed))?
.checked_add(wall_drift)?;
(elapsed < self.valid_for
&& elapsed.abs_diff(awake) <= SECOND
&& wall_drift <= SECOND
&& bound <= MAX_ERROR)
.then_some(bound)
}
}
pub struct NativeClock {
state: Mutex<Continuity>,
cache: Mutex<Option<CachedQualification>>,
diagnostic: bool,
}
impl Default for NativeClock {
@@ -173,6 +207,7 @@ impl NativeClock {
pub fn new() -> Self {
Self {
state: Mutex::new(Continuity::default()),
cache: Mutex::new(None),
diagnostic: false,
}
}
@@ -192,7 +227,7 @@ impl NativeClock {
transport: if self.diagnostic {
"ncacn_np:W32TIME_ALT:diagnostic_only"
} else {
"ncalrpc:SID19:W32Time:V5_descriptor:mutual_auth"
"local_pipe:W32TIME_ALT:verified_service_pid"
},
status: None,
query_ticks: ticks,
@@ -222,7 +257,7 @@ impl NativeClock {
report.status = Some(raw);
match state.validate(&raw, after, ticks) {
Ok(bound) => {
report.trusted = !self.diagnostic;
report.trusted = ADAPTER_QUALIFIED && !self.diagnostic;
report.reason = if self.diagnostic {
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
} else {
@@ -235,26 +270,66 @@ impl NativeClock {
}
report
}
pub fn now(&self) -> Result<DateTime<Utc>> {
fn qualified_sample(&self) -> Result<(Sample, u64)> {
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
let mut cache = self
.cache
.lock()
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?;
let current = sample();
let observed = self
.state
.lock()
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?
.observe(current);
if observed.is_err() {
*cache = None;
observed?;
}
if let Some(cached) = *cache {
if let Some(bound) = cached.bound_at(current) {
return Ok((current, bound));
}
ensure!(
cached.bound.is_some()
|| current.interrupt.saturating_sub(cached.sample.interrupt) >= RETRY_AGE,
"CLOCK_RETRY_PENDING"
);
}
let report = self.report();
ensure!(report.trusted, "CLOCK_UNTRUSTED: {}", report.reason);
let ticks = report
.sample
.wall
.checked_sub(FILETIME_UNIX)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
DateTime::from_timestamp(
(ticks / SECOND).try_into()?,
((ticks % SECOND) * 100) as u32,
)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
let bound = report.error_bound_ticks.filter(|_| report.trusted);
*cache = Some(CachedQualification {
sample: report.sample,
bound,
valid_for: report.status.map_or(0, |status| {
CACHE_AGE.min(MAX_AGE.saturating_sub(status.sync_age))
}),
});
Ok((
report.sample,
bound.ok_or_else(|| anyhow!("CLOCK_UNTRUSTED: {}", report.reason))?,
))
}
pub fn now(&self) -> Result<DateTime<Utc>> {
utc(self.qualified_sample()?.0.wall)
}
}
fn utc(wall: u64) -> Result<DateTime<Utc>> {
let ticks = wall
.checked_sub(FILETIME_UNIX)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
DateTime::from_timestamp(
(ticks / SECOND).try_into()?,
((ticks % SECOND) * 100) as u32,
)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
}
/// Named-pipe diagnostics can never open the production clock gate.
pub fn named_pipe_diagnostic() -> ClockReport {
NativeClock {
state: Mutex::new(Continuity::default()),
cache: Mutex::new(None),
diagnostic: true,
}
.report()
@@ -376,6 +451,17 @@ impl rmm_agent_core::reconcile::SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
NativeClock::now(self)
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
let (sample, bound) = self.qualified_sample()?;
Ok(rmm_agent_core::reconcile::ClockReading {
own_wall: utc(sample.wall)?,
upper: utc(sample.wall + bound)?,
})
}
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let (sample, bound) = self.qualified_sample()?;
Ok((utc(sample.wall - bound)?, utc(sample.wall + bound)?))
}
}
#[cfg(windows)]
fn sample() -> Sample {
@@ -401,7 +487,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
#[link(name = "advapi32")]
unsafe extern "C" {
fn rmm_clock_query(status: *mut Status) -> u32;
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
fn rmm_local_clock_query(status: *mut Status) -> u32;
}
let mut status = Status::default();
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
@@ -409,7 +495,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
if diagnostic {
rmm_clock_query(&mut status)
} else {
rmm_clock_alpc_query(&mut status)
rmm_local_clock_query(&mut status)
}
};
(code, status)
@@ -522,8 +608,9 @@ mod tests {
},
)
}
#[cfg(not(windows))]
#[test]
fn production_clock_stays_closed_until_native_adapter_qualification() {
fn production_windows_clock_is_unavailable_on_other_platforms() {
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
assert_eq!(
NativeClock::new().now().unwrap_err().to_string(),
@@ -559,7 +646,7 @@ mod tests {
Status { state: 1, ..s },
Status { leap: 3, ..s },
Status {
last_result: 2,
last_result: 3,
..s
},
Status { stratum: 16, ..s },
@@ -585,6 +672,61 @@ mod tests {
}
}
#[test]
fn missed_poll_keeps_a_bounded_last_good_sample() {
let (s, v) = good();
let age = 2 * 3600 * SECOND;
for last_result in [1, 2] {
let held = Status {
last_result,
last_sync: v.wall - age,
sync_age: age,
..s
};
assert!(evaluate(&held, v.wall, 100).is_ok());
}
let old = Status {
last_result: 2,
last_sync: v.wall - MAX_AGE - 1,
sync_age: MAX_AGE + 1,
..s
};
assert!(evaluate(&old, v.wall, 100).is_err());
}
#[test]
fn cached_bound_expires_and_rejects_wall_step_and_suspend() {
let (_, mut sample) = good();
let cache = CachedQualification {
sample,
bound: Some(SECOND),
valid_for: CACHE_AGE,
};
sample.wall += SECOND;
sample.interrupt += SECOND;
sample.unbiased += SECOND;
assert_eq!(cache.bound_at(sample), Some(SECOND + 150));
assert_eq!(
cache.bound_at(Sample {
wall: sample.wall + 2 * SECOND,
..sample
}),
None
);
assert_eq!(
cache.bound_at(Sample {
unbiased: sample.unbiased - 2 * SECOND,
..sample
}),
None
);
let elapsed = CACHE_AGE;
let expired = Sample {
wall: cache.sample.wall + elapsed,
interrupt: cache.sample.interrupt + elapsed,
unbiased: cache.sample.unbiased + elapsed,
};
assert_eq!(cache.bound_at(expired), None);
}
#[test]
fn suspend_closes_until_actual_post_resume_sync() {
let (s, v) = good();
let mut c = Continuity::default();
+42 -22
View File
@@ -899,13 +899,15 @@ impl SystemHelper {
let pin = settings.pin()?;
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
let clock = if settings.windows_update_only() || settings.managed_scripts() {
let role = rmm_time_attestation::Role::SystemHelper;
let clock = if settings.managed_scripts() {
RuntimeClock::local(role)
} else if settings.windows_update_only() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
} else {
RuntimeClock::new(role)
}.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,
@@ -914,7 +916,8 @@ impl SystemHelper {
db,
clock,
boot,
sync,
// The initial connection creates the reconciler using its own qualified time.
sync: None,
last_diagnostic: None,
last_apply_diagnostic: None,
unsettled_msi: None,
@@ -1008,14 +1011,17 @@ impl SystemHelper {
}
fn sync(&mut self) -> Result<&mut HelperSync<DalekVerifier>> {
if self.sync.is_none() {
self.sync = Some(
HelperSync::with_verifier(
self.settings.binding.clone(),
DalekVerifier,
&self.clock,
)?
.with_helper_identity(HelperIdentity::System),
);
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.as_mut().context("SYSTEM_SYNC_CLOSED")
}
@@ -1290,6 +1296,16 @@ 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(
@@ -1795,14 +1811,18 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
let result = (|| -> Result<()> {
let mut helper = SystemHelper::open()?;
let server = ipc::Server::bind(helper.pin().clone())?;
let time_server = ipc::Server::bind_time(helper.pin().clone())?;
let update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
.map(crate::update_control_ipc::Server::bind).transpose()?;
let time_pin = helper.pin().clone();
let time_clock = helper.clock.source();
let time_worker = std::thread::Builder::new()
.name("rmm-helper-time-control".into())
.spawn(move || time_control(time_server, time_pin, time_clock))?;
let time_worker = if time_clock.uses_local_clock() {
None
} else {
let time_pin = helper.pin().clone();
let time_server = ipc::Server::bind_time(time_pin.clone())?;
Some(std::thread::Builder::new()
.name("rmm-helper-time-control".into())
.spawn(move || time_control(time_server, time_pin, time_clock))?)
};
scm_status(SERVICE_RUNNING, 0);
let mut next_update_unknown=Instant::now();
while !STOP.load(Ordering::SeqCst) {
@@ -1879,9 +1899,9 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
}
// The time lane has no ledger/job operation and its receive wait is
// bounded. Shutdown closes its private evidence before service exit.
time_worker
.join()
.map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
if let Some(worker) = time_worker {
worker.join().map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
}
Ok(())
})();
scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
@@ -53,6 +53,7 @@ pub fn clock_code(error: &anyhow::Error) -> &'static str {
"TIME_RUNTIME_NO_CONNECTION",
"TIME_LOCAL_WALL_OUTSIDE_BOUND",
"TIME_SOURCE_AGE_AT_CHECK",
"TIME_WINDOWS_LOCAL_CLOCK",
];
error
.chain()
+114 -33
View File
@@ -227,28 +227,51 @@ pub fn private_path(path: &Path, directory: bool) -> Result<()> {
}
fn registry_string(name: &str) -> Result<String> {
let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
let name = wide(name);
let value_name = wide(name);
let mut bytes = vec![0u16; 2048];
let mut size = (bytes.len() * 2) as u32;
let status = unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
value_name.as_ptr(),
RRF_RT_REG_SZ,
ptr::null_mut(),
bytes.as_mut_ptr().cast(),
&mut size,
)
};
ensure!(status == 0, "OS_REGISTRY {name} (Win32 {status})");
ensure!(
unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
name.as_ptr(),
RRF_RT_REG_SZ,
ptr::null_mut(),
bytes.as_mut_ptr().cast(),
&mut size,
)
} == 0,
"OS_REGISTRY"
size >= 2 && size % 2 == 0 && size as usize <= bytes.len() * 2,
"OS_REGISTRY_SIZE {name}"
);
ensure!(
size >= 2 && size as usize <= bytes.len() * 2,
"OS_REGISTRY_SIZE"
);
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
String::from_utf16(&bytes[..size as usize / 2 - 1])
.with_context(|| format!("OS_REGISTRY_ENCODING {name}"))
}
fn os_inventory(read: impl Fn(&str) -> Result<String>) -> Result<(String, Value)> {
let product = read("ProductName")?;
let build = read("CurrentBuildNumber")?;
// Older Windows releases can omit DisplayVersion. Both version labels are
// optional; the product and build still identify the OS without either.
let version = |name| read(name).ok().filter(|s| !s.trim().is_empty());
let display = version("DisplayVersion");
let release = if display.is_none() {
version("ReleaseId")
} else {
None
};
let os = match (&display, &release) {
(Some(display), _) => format!("{product}; DisplayVersion={display}; Build={build}"),
(None, Some(release)) => format!("{product}; ReleaseId={release}; Build={build}"),
(None, None) => format!("{product}; Build={build}"),
};
let mut data = json!({"product_name":product,"display_version":display,"build":build});
if let Some(release) = release {
data["release_id"] = json!(release);
}
Ok((os, data))
}
pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
let mut name = [0u16; 256];
@@ -277,28 +300,45 @@ pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None)
}
fn disk_space(root: &[u16]) -> Option<(u64, u64)> {
let (mut available, mut total) = (0, 0);
(unsafe { GetDiskFreeSpaceExW(root.as_ptr(), &mut available, &mut total, ptr::null_mut()) } != 0
&& total > 0 && available <= total).then_some((available, total))
}
fn fixed_volumes(system: &str, available: u64, total: u64) -> Vec<Value> {
use windows_sys::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
const DRIVE_FIXED: u32 = 3;
let mask = unsafe { GetLogicalDrives() };
let mut rows = vec![json!({"name":system,"free_bytes":available,"total_bytes":total})];
for letter in b'A'..=b'Z' {
if mask & (1 << (letter - b'A')) == 0 { continue; }
let name = format!("{}:", char::from(letter));
if name.eq_ignore_ascii_case(system) { continue; }
let root = wide(format!("{name}\\"));
if unsafe { GetDriveTypeW(root.as_ptr()) } != DRIVE_FIXED { continue; }
// Retain an identified but unreadable volume without claiming zero usage.
let sizes = disk_space(&root);
rows.push(json!({"name":name,"free_bytes":sizes.map(|s| s.0),"total_bytes":sizes.map(|s| s.1)}));
}
rows
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
let mut available = 0;
let mut total = 0;
let mut free = 0;
ensure!(
unsafe { GetDiskFreeSpaceExW(volume.as_ptr(), &mut available, &mut total, &mut free) } != 0,
"VOLUME_QUERY"
);
ensure!(total > 0 && available <= total, "VOLUME_VALUES");
let product = registry_string("ProductName")?;
let display = registry_string("DisplayVersion")?;
let build = registry_string("CurrentBuildNumber")?;
let os = format!("{product}; DisplayVersion={display}; Build={build}");
let system = std::env::var("SystemDrive").context("SYSTEM_DRIVE")?.to_ascii_uppercase();
let (available, total) = disk_space(&wide(format!("{system}\\"))).context("VOLUME_QUERY")?;
let volumes = fixed_volumes(&system, available, total);
let (os, mut os_data) = os_inventory(registry_string)?;
os_data["installed_at"] = json!(install_date());
os_data["booted_at"] = json!(booted_at);
let completed = Utc::now();
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":os_data},
{"scope":"windows.volumes","source_id":"windows.win32:GetLogicalDrives;GetDriveTypeW;GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available,"drives":volumes}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
snapshot["observations"]
@@ -356,6 +396,47 @@ pub async fn boot_id() -> Result<String> {
#[cfg(test)]
mod tests {
fn os_fixture(display: Option<&str>, release: Option<&str>) -> (String, serde_json::Value) {
super::os_inventory(|name| {
match name {
"ProductName" => Some("Windows 10 Enterprise LTSC"),
"CurrentBuildNumber" => Some("17763"),
"DisplayVersion" => display,
"ReleaseId" => release,
_ => panic!("unexpected registry value: {name}"),
}
.map(str::to_owned)
.ok_or_else(|| anyhow::anyhow!("missing {name}"))
})
.unwrap()
}
#[test]
fn os_inventory_prefers_display_version() {
let (os, data) = os_fixture(Some("22H2"), Some("2009"));
assert!(os.contains("DisplayVersion=22H2"));
assert_eq!(data["display_version"], "22H2");
assert!(data.get("release_id").is_none());
}
#[test]
fn os_inventory_uses_legacy_release_id_when_display_version_is_missing() {
let (os, data) = os_fixture(None, Some("1809"));
assert_eq!(os, "Windows 10 Enterprise LTSC; ReleaseId=1809; Build=17763");
assert!(data["display_version"].is_null());
assert_eq!(data["release_id"], "1809");
}
#[test]
fn os_inventory_keeps_product_and_build_without_version_labels() {
for display in [None, Some(" ")] {
let (os, data) = os_fixture(display, None);
assert_eq!(os, "Windows 10 Enterprise LTSC; Build=17763");
assert!(data["display_version"].is_null());
assert_eq!(data["build"], "17763");
}
}
#[test]
fn native_inventory_has_real_windows_sources_and_no_fake_inodes() {
let v = super::snapshot().unwrap();
+49 -12
View File
@@ -839,6 +839,10 @@ impl Agent {
) -> Result<()> {
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
let clock = self.clock.native.source();
if clock.uses_local_clock() {
return Ok(());
}
// Presence opts into sampling only. Each role opens and verifies the
// protected profile and signed response itself before accepting time.
let Some(mode) = SamplingMode::configured(self.config.enable_jobs, Path::new(CONFIG_PATH))?
@@ -860,7 +864,6 @@ impl Agent {
self.binding.as_ref(),
self.helper_lane.clone(),
)? };
let clock = self.clock.native.source();
let stop = Arc::new(AtomicBool::new(false));
let mut tasks = Vec::new();
let own_clock = clock.clone();
@@ -1291,8 +1294,8 @@ impl Agent {
&& !self.helper_apply_unconfirmed
&& !self.prepared
&& self.running.is_none()
&& !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)
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
{
let agent = self.identity.agent_id.clone();
let asset = self.identity.asset_id.clone();
@@ -2663,8 +2666,9 @@ 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 mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let active_tick = Duration::from_millis(20);
let idle_tick = Duration::from_millis(250);
let mut next_tick = tokio::time::Instant::now();
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);
@@ -2675,9 +2679,19 @@ 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;},
_=tick.tick()=>{
_=tokio::time::sleep_until(next_tick)=>{
next_tick = tokio::time::Instant::now() + cadence;
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();}
@@ -2709,7 +2723,9 @@ 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.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
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 {
// 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)?;
@@ -3059,10 +3075,17 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
let clock=JobClock::new(config.enable_jobs);
#[cfg(feature = "system-helper")]
let clock = if let Some(policy) = &config.localservice_time_policy {
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
).for_generation(0) }
use rmm_agent_windows::signed_clock::RuntimeClock;
let source = if config.windows_update_helper {
RuntimeClock::enrolled_local_service(
binding.clone().context("JOB_BINDING_REQUIRED")?,
policy.clone(),
installed_tenant.context("INSTALLED_TENANT_REQUIRED")?,
)
} else {
RuntimeClock::local(rmm_time_attestation::Role::Agent)
};
JobClock { enabled: true, native: source.for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
@@ -3078,7 +3101,19 @@ 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|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
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 (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
config,
@@ -3195,9 +3230,11 @@ pub fn main() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot_with_boot(Some(booted_at))?;
let drives = inventory["observations"].as_array().and_then(|observations|
observations.iter().find(|o| o["scope"] == "windows.volumes")).map(|o| &o["data"]["drives"]);
println!(
"{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"fixed_volumes":drives,"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
);
return Ok(());
}
+18
View File
@@ -1410,6 +1410,7 @@ mod installed {
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
native: Option<Arc<crate::clock::NativeClock>>,
enrolled_helper: Option<ipc::PeerPin>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
@@ -1423,11 +1424,20 @@ mod installed {
pub fn new(role: Role) -> Self {
Self {
role,
native: None,
enrolled_helper: None,
local_policy: None,
state: Arc::new(Mutex::new(None)),
}
}
pub fn local(role: Role) -> Self {
let mut clock = Self::new(role);
clock.native = Some(Arc::new(crate::clock::NativeClock::new()));
clock
}
pub fn uses_local_clock(&self) -> bool {
self.native.is_some()
}
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
@@ -1528,6 +1538,10 @@ mod installed {
}
fn bounds(&self) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::bounds(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state
@@ -1544,6 +1558,10 @@ mod installed {
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::reading(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state
+11 -3
View File
@@ -7,6 +7,7 @@ mod certificate_rotation;
mod helper_sync;
mod https_channel;
mod jobs;
mod proxmox_api;
mod reconcile;
#[cfg(test)]
mod runtime_tests;
@@ -524,14 +525,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
let extended = env::var("RMM_EXTENDED_INVENTORY").unwrap_or_else(|_| "1".into()) == "1";
let binding = self.binding.clone();
let catalog = self.catalog.cached(Utc::now());
let runtime = tokio::runtime::Handle::current();
tokio::task::spawn_blocking(move || {
let collected_at = Utc::now();
let result = rmm_agent_linux::wire::snapshot(extended).and_then(|mut inventory| {
if extended {
inventory["observations"]
let proxmox = runtime.block_on(proxmox_api::observation(
rmm_agent_linux::inventory::proxmox_ve(),
));
let scopes = inventory["observations"]
.as_array_mut()
.context("INVENTORY_OBSERVATIONS")?
.push(apt::planning_observation(binding.as_ref()));
.context("INVENTORY_OBSERVATIONS")?;
scopes.push(apt::planning_observation(binding.as_ref()));
if let Some(observation) = proxmox {
scopes.push(proxmox_api::wire(&observation)?);
}
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
}
if let Some(report) = catalog {
+88
View File
@@ -0,0 +1,88 @@
//! Local, read-only Proxmox VE API client for the `linux.proxmox` observation.
//!
//! Only `https://127.0.0.1:8006` with the cluster CA copied by the installer. The
//! PVEAuditor token arrives as the systemd credential `rmm-proxmox-token`; it is never
//! logged, persisted by the agent or placed in an observation.
use anyhow::{Context, Result, ensure};
use reqwest::{Client, StatusCode};
use rmm_agent_linux::inventory::{Observation, proxmox};
use serde_json::Value;
use std::{path::PathBuf, time::Duration};
const BASE: &str = "https://127.0.0.1:8006/api2/json";
const CREDENTIAL: &str = "rmm-proxmox-token";
const DEFAULT_CA: &str = "/etc/rmm/pve-ca.pem";
const MAX_RESPONSE: usize = 2 * 1024 * 1024;
const TOTAL_BUDGET: Duration = Duration::from_secs(45);
struct LocalApi {
client: Client,
authorization: String,
}
impl proxmox::Api for LocalApi {
async fn get(&self, path: &str) -> Result<Value> {
ensure!(path.starts_with('/') && !path.contains(".."), "PROXMOX_PATH");
let mut response = self.client.get(format!("{BASE}{path}"))
.header(reqwest::header::AUTHORIZATION, &self.authorization)
.send().await.map_err(|_| anyhow::anyhow!("PROXMOX_UNREACHABLE"))?;
match response.status() {
StatusCode::OK => (),
StatusCode::UNAUTHORIZED => anyhow::bail!("PROXMOX_TOKEN_REJECTED"),
StatusCode::FORBIDDEN => anyhow::bail!("PROXMOX_PERMISSION_DENIED"),
status => anyhow::bail!("PROXMOX_HTTP_{}", status.as_u16()),
}
ensure!(response.content_length().is_none_or(|n| n <= MAX_RESPONSE as u64), "PROXMOX_RESPONSE_LIMIT");
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(chunk.len() <= MAX_RESPONSE.saturating_sub(body.len()), "PROXMOX_RESPONSE_LIMIT");
body.extend_from_slice(&chunk);
}
let mut value: Value = serde_json::from_slice(&body).map_err(|_| anyhow::anyhow!("PROXMOX_API_SHAPE"))?;
Ok(value["data"].take())
}
}
fn credential_path() -> Option<PathBuf> {
std::env::var_os("CREDENTIALS_DIRECTORY").map(|d| PathBuf::from(d).join(CREDENTIAL))
}
fn client(ca: &[u8]) -> Result<Client> {
Ok(Client::builder()
.https_only(true)
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(ca)?)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15))
.build()?)
}
/// `None` on hosts without Proxmox VE: no scope is reported there at all.
pub async fn observation(proxmox_ve: bool) -> Option<Observation<proxmox::Proxmox>> {
if !proxmox_ve {
return None;
}
let Some(token) = credential_path().and_then(|p| std::fs::read_to_string(p).ok()) else {
return Some(proxmox::not_configured());
};
let Some(authorization) = proxmox::token_header(&token) else {
return Some(proxmox::failed("PROXMOX_TOKEN_INVALID"));
};
let ca_path = std::env::var("RMM_PROXMOX_CA_FILE").unwrap_or_else(|_| DEFAULT_CA.into());
let api = match std::fs::read(&ca_path).context("ca").and_then(|ca| client(&ca)) {
Ok(client) => LocalApi { client, authorization },
Err(_) => return Some(proxmox::failed("PROXMOX_CA_UNAVAILABLE")),
};
let now = chrono::Utc::now().timestamp();
Some(tokio::time::timeout(TOTAL_BUDGET, proxmox::collect(&api, now)).await
.unwrap_or_else(|_| proxmox::failed("PROXMOX_TIMEOUT")))
}
/// Wire form with the scope label the server's `linux.base` validation expects.
pub fn wire(observation: &Observation<proxmox::Proxmox>) -> Result<Value> {
let mut value = serde_json::to_value(observation)?;
value["scope"] = Value::String("linux.proxmox".into());
Ok(value)
}
+6
View File
@@ -1,11 +1,13 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
mod opnsense;
pub mod proxmox;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub const LINUX_SOFTWARE_OBSERVATION_MAX_BYTES: usize = 256 * 1024;
pub const PROXMOX_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub fn firmware_identifier(value: &str) -> Option<String> {
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
@@ -173,6 +175,7 @@ pub fn validate_for_scope(
for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) => LINUX_SOFTWARE_OBSERVATION_MAX_BYTES,
("linux.base", Some("linux.proxmox")) => PROXMOX_OBSERVATION_MAX_BYTES,
("windows.base", Some("windows.software")) => SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
@@ -214,6 +217,9 @@ pub fn validate_for_scope(
return Err("INVALID_AGENT_UPDATE_CATALOG_REPORT");
}
}
if o.scope == "linux.proxmox" && o.quality == "valid" {
proxmox::validate(&o.data)?;
}
if !o.scope.starts_with(prefix)
|| o.scope.len() > 64
|| !(o
@@ -0,0 +1,296 @@
//! Strict `linux.proxmox` wire document and the deterministic backup evaluation.
//! The agent reports raw scheduler data; whether every scheduled backup ran is
//! decided here so the server, API and UI share one rule.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
/// Runs that start shortly before the computed due time still count (clock skew).
const START_TOLERANCE_SECONDS: i64 = 120;
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Proxmox {
pub node: String,
pub cluster: Option<String>,
pub version: Option<String>,
pub guests: Vec<Guest>,
pub backup_jobs: Vec<BackupJob>,
pub backup_runs: Vec<BackupRun>,
pub not_backed_up: Vec<u32>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Guest {
pub vmid: u32,
pub name: String,
pub kind: String,
pub status: String,
pub template: bool,
pub cpus: Option<u32>,
pub memory_bytes: Option<u64>,
pub disk_bytes: Option<u64>,
pub uptime_seconds: Option<u64>,
pub pool: Option<String>,
pub macs: Vec<String>,
pub smbios_uuid: Option<String>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BackupJob {
pub id: String,
pub enabled: bool,
pub schedule: Option<String>,
pub storage: Option<String>,
pub mode: Option<String>,
pub selection: String,
pub covered_vmids: Vec<u32>,
pub next_run: Option<i64>,
pub last_expected_run: Option<i64>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BackupRun {
pub upid: String,
pub started_at: i64,
pub ended_at: Option<i64>,
pub status: String,
pub message: Option<String>,
pub guests: Vec<GuestResult>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GuestResult {
pub vmid: u32,
pub result: String,
}
fn clean(s: &str, limit: usize) -> bool {
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
}
fn opt(s: &Option<String>, limit: usize) -> bool {
s.as_deref().is_none_or(|s| clean(s, limit))
}
pub fn is_mac(s: &str) -> bool {
s.len() == 17 && s.split(':').count() == 6
&& s.split(':').all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
fn vmid(id: u32) -> bool {
(100..1_000_000_000).contains(&id)
}
/// Validates the `data` member of a valid `linux.proxmox` observation.
pub fn validate(data: &Value) -> Result<(), &'static str> {
let err = "INVALID_PROXMOX_OBSERVATION";
let p: Proxmox = serde_json::from_value(data.clone()).map_err(|_| err)?;
let guests_ok = p.guests.len() <= 512 && p.guests.iter().all(|g| {
vmid(g.vmid) && clean(&g.name, 128) && matches!(g.kind.as_str(), "qemu" | "lxc")
&& clean(&g.status, 32) && opt(&g.pool, 64) && g.macs.len() <= 32
&& g.macs.iter().all(|m| is_mac(m))
&& g.smbios_uuid.as_deref().is_none_or(|u| uuid::Uuid::parse_str(u).is_ok_and(|x| x.hyphenated().to_string() == u))
}) && p.guests.windows(2).all(|w| w[0].vmid < w[1].vmid);
let jobs_ok = p.backup_jobs.len() <= 64 && p.backup_jobs.iter().all(|j| {
clean(&j.id, 64) && opt(&j.schedule, 128) && opt(&j.storage, 64) && opt(&j.mode, 16)
&& matches!(j.selection.as_str(), "all" | "pool" | "vmid")
&& j.covered_vmids.len() <= 512 && j.covered_vmids.iter().all(|id| vmid(*id))
});
let runs_ok = p.backup_runs.len() <= 64 && p.backup_runs.iter().all(|r| {
clean(&r.upid, 160) && r.upid.starts_with("UPID:") && r.started_at > 0
&& r.ended_at.is_none_or(|e| e >= r.started_at)
&& matches!(r.status.as_str(), "ok" | "warning" | "error" | "running")
&& (r.status == "running") == r.ended_at.is_none()
&& opt(&r.message, 256) && r.guests.len() <= 512
&& r.guests.iter().all(|g| vmid(g.vmid) && matches!(g.result.as_str(), "ok" | "error"))
});
if !clean(&p.node, 64) || !opt(&p.cluster, 64) || !opt(&p.version, 32)
|| !guests_ok || !jobs_ok || !runs_ok
|| p.not_backed_up.len() > 512 || !p.not_backed_up.iter().all(|id| vmid(*id))
{
return Err(err);
}
Ok(())
}
/// Status per job and guest plus the overall answer "did every scheduled backup run?".
/// job: ok | failed | missed | running | pending (not yet due) | disabled | unknown
pub fn backup_status(data: &Value) -> Option<Value> {
let p: Proxmox = serde_json::from_value(data.clone()).ok()?;
let mut last_success: BTreeMap<u32, i64> = BTreeMap::new();
for run in &p.backup_runs {
for g in run.guests.iter().filter(|g| g.result == "ok") {
let at = run.ended_at.unwrap_or(run.started_at);
last_success.entry(g.vmid).and_modify(|t| *t = (*t).max(at)).or_insert(at);
}
}
let mut jobs = Vec::new();
let mut all_ran = true;
let mut problems = 0usize;
for job in &p.backup_jobs {
let mut guests = Vec::new();
let status = if !job.enabled {
"disabled"
} else if job.schedule.is_none() {
"unknown"
} else if let Some(due) = job.last_expected_run {
let since = due - START_TOLERANCE_SECONDS;
let window: Vec<&BackupRun> = p.backup_runs.iter().filter(|r| r.started_at >= since).collect();
let running = window.iter().any(|r| r.status == "running");
// vzdump can fail before its first guest (e.g. storage unavailable): the log
// then names no guest. Such a run counts as a failure, never as "missed".
let failed_before = |id: u32| window.iter().any(|r| r.status == "error" && r.guests.is_empty()
&& upid_vmid(&r.upid).is_none_or(|v| v == id));
let mut states = BTreeSet::new();
for id in &job.covered_vmids {
// Newest statement about this guest inside the due window wins.
let result = window.iter()
.filter_map(|r| r.guests.iter().find(|g| g.vmid == *id).map(|g| (r.started_at, g.result.as_str())))
.max_by_key(|(at, _)| *at).map(|(_, r)| r);
let state = match (result, running) {
(Some("ok"), _) => "ok",
(Some(_), _) => "failed",
(None, true) => "running",
(None, false) if failed_before(*id) => "failed",
(None, false) => "missed",
};
states.insert(state);
guests.push(json!({"vmid":id,"status":state,"last_success_at":last_success.get(id)}));
}
if states.contains("failed") { "failed" }
else if states.contains("missed") { "missed" }
else if states.contains("running") { "running" }
else { "ok" }
} else {
"pending"
};
if matches!(status, "failed" | "missed" | "unknown") {
all_ran = false;
problems += 1;
}
jobs.push(json!({"id":job.id,"status":status,"last_expected_run":job.last_expected_run,
"next_run":job.next_run,"guests":guests}));
}
let enabled = p.backup_jobs.iter().filter(|j| j.enabled).count();
Some(json!({
"all_scheduled_backups_ran": if enabled == 0 { Value::Null } else { Value::Bool(all_ran) },
"enabled_jobs": enabled,
"problem_jobs": problems,
"jobs": jobs,
"last_success_at": last_success,
}))
}
/// UPID:node:pid:pstart:starttime:type:id:user: with `id` set for single-guest tasks.
fn upid_vmid(upid: &str) -> Option<u32> {
upid.split(':').nth(6).filter(|id| !id.is_empty()).and_then(|id| id.parse().ok())
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Value {
json!({"node":"pve","cluster":null,"version":"9.2.2",
"guests":[
{"vmid":100,"name":"debian","kind":"qemu","status":"running","template":false,"cpus":1,
"memory_bytes":1,"disk_bytes":1,"uptime_seconds":5,"pool":null,
"macs":["bc:24:11:88:35:97"],"smbios_uuid":"787f4ae9-446f-4fac-b3d8-4074170bf823"},
{"vmid":101,"name":"alpine","kind":"lxc","status":"running","template":false,"cpus":1,
"memory_bytes":1,"disk_bytes":1,"uptime_seconds":5,"pool":null,"macs":[],"smbios_uuid":null}],
"backup_jobs":[
{"id":"a","enabled":true,"schedule":"*/2:00","storage":"local","mode":"snapshot",
"selection":"vmid","covered_vmids":[100],"next_run":2000,"last_expected_run":1000},
{"id":"b","enabled":true,"schedule":"daily","storage":"local","mode":"snapshot",
"selection":"all","covered_vmids":[100,101],"next_run":5000,"last_expected_run":900},
{"id":"c","enabled":false,"schedule":"daily","storage":null,"mode":null,
"selection":"all","covered_vmids":[101],"next_run":null,"last_expected_run":null},
{"id":"d","enabled":true,"schedule":"sat 03:00","storage":null,"mode":null,
"selection":"vmid","covered_vmids":[101],"next_run":9000,"last_expected_run":null}],
"backup_runs":[
{"upid":"UPID:pve:1:2:3:vzdump::root@pam:","started_at":1001,"ended_at":1050,"status":"error",
"message":"job errors","guests":[{"vmid":100,"result":"ok"},{"vmid":101,"result":"error"}]},
{"upid":"UPID:pve:1:2:4:vzdump:100:root@pam:","started_at":100,"ended_at":120,"status":"ok",
"message":null,"guests":[{"vmid":100,"result":"ok"}]}],
"not_backed_up":[]})
}
#[test]
fn accepts_agent_shape_and_rejects_unsafe_values() {
assert!(validate(&sample()).is_ok());
for (pointer, bad) in [
("/guests/0/macs/0", json!("BC:24:11:88:35:97")),
("/guests/0/kind", json!("docker")),
("/guests/0/vmid", json!(5)),
("/guests/0/smbios_uuid", json!("not-a-uuid")),
("/backup_runs/0/status", json!("running")),
("/backup_jobs/0/selection", json!("tag")),
("/node", json!("pve\nX")),
] {
let mut doc = sample();
*doc.pointer_mut(pointer).unwrap() = bad;
assert!(validate(&doc).is_err(), "{pointer}");
}
let mut doc = sample();
doc["extra"] = json!(1);
assert!(validate(&doc).is_err());
}
#[test]
fn evaluates_due_runs_per_job_and_guest() {
let status = backup_status(&sample()).unwrap();
let jobs: BTreeMap<String, Value> = status["jobs"].as_array().unwrap().iter()
.map(|j| (j["id"].as_str().unwrap().to_owned(), j.clone())).collect();
assert_eq!(jobs["a"]["status"], "ok");
assert_eq!(jobs["b"]["status"], "failed");
assert_eq!(jobs["b"]["guests"][1]["status"], "failed");
assert_eq!(jobs["c"]["status"], "disabled");
assert_eq!(jobs["d"]["status"], "pending");
assert_eq!(status["all_scheduled_backups_ran"], false);
assert_eq!(status["last_success_at"]["100"], 1050);
}
/// Observation reported by the Proxmox VE 9.2 test host on 2026-11-20.
#[test]
fn real_proxmox_92_report_validates_and_counts_the_due_run() {
let data: Value = serde_json::from_str(include_str!("proxmox_pve92_fixture.json")).unwrap();
validate(&data).unwrap();
let status = backup_status(&data).unwrap();
assert_eq!(status["jobs"][0]["id"], "backup-debian");
assert_eq!(status["jobs"][0]["status"], "ok");
assert_eq!(status["all_scheduled_backups_ran"], true);
assert_eq!(data["not_backed_up"], json!([101]));
}
/// Same host at 14:00: the scheduled run failed because its storage was disabled.
#[test]
fn a_run_failing_before_any_guest_is_failed_not_missed() {
let data: Value = serde_json::from_str(include_str!("proxmox_pve92_failed_fixture.json")).unwrap();
validate(&data).unwrap();
let status = backup_status(&data).unwrap();
assert_eq!(status["jobs"][0]["status"], "failed");
assert_eq!(status["jobs"][0]["guests"][0]["status"], "failed");
assert_eq!(status["all_scheduled_backups_ran"], false);
// The earlier successful backup stays visible as the last success.
assert!(status["last_success_at"]["100"].is_number());
// A failed single-guest task of another guest does not fail this job.
let mut other = data.clone();
other["backup_runs"][0]["upid"] = json!("UPID:pve:00006CA0:000B1402:6B004453:vzdump:101:root@pam:");
assert_eq!(backup_status(&other).unwrap()["jobs"][0]["status"], "missed");
}
#[test]
fn missing_and_running_runs_are_distinguished() {
let mut doc = sample();
doc["backup_runs"] = json!([]);
let status = backup_status(&doc).unwrap();
assert_eq!(status["jobs"][0]["status"], "missed");
doc["backup_runs"] = json!([{"upid":"UPID:pve:9:9:9:vzdump::root@pam:","started_at":1000,
"ended_at":null,"status":"running","message":null,"guests":[]}]);
assert_eq!(backup_status(&doc).unwrap()["jobs"][0]["status"], "running");
doc["backup_jobs"] = json!([]);
assert!(backup_status(&doc).unwrap()["all_scheduled_backups_ran"].is_null());
}
}
@@ -0,0 +1,80 @@
{
"backup_jobs": [
{
"covered_vmids": [
100
],
"enabled": true,
"id": "backup-debian",
"last_expected_run": 1795179600,
"mode": "snapshot",
"next_run": 1795186800,
"schedule": "*/2:00",
"selection": "vmid",
"storage": "local"
}
],
"backup_runs": [
{
"ended_at": 1795179610,
"guests": [],
"message": "could not activate storage 'local': storage 'local' is disabled",
"started_at": 1795179603,
"status": "error",
"upid": "UPID:pve:00006CA0:000B1402:6B004453:vzdump:100:root@pam:"
},
{
"ended_at": 1795172488,
"guests": [
{
"result": "ok",
"vmid": 100
}
],
"message": null,
"started_at": 1795172468,
"status": "ok",
"upid": "UPID:pve:00000C75:000030ED:6B002874:vzdump:100:root@pam:"
}
],
"cluster": null,
"guests": [
{
"cpus": 1,
"disk_bytes": 8589934592,
"kind": "qemu",
"macs": [
"bc:24:11:88:35:97"
],
"memory_bytes": 1073741824,
"name": "debian-guest",
"pool": null,
"smbios_uuid": "787f4ae9-446f-4fac-b3d8-4074170bf823",
"status": "running",
"template": false,
"uptime_seconds": 7166,
"vmid": 100
},
{
"cpus": 1,
"disk_bytes": 1020702720,
"kind": "lxc",
"macs": [
"bc:24:11:b7:4c:99"
],
"memory_bytes": 134217728,
"name": "alpine-ct",
"pool": null,
"smbios_uuid": null,
"status": "running",
"template": false,
"uptime_seconds": 7164,
"vmid": 101
}
],
"node": "pve",
"not_backed_up": [
101
],
"version": "9.2.2"
}
@@ -0,0 +1,72 @@
{
"backup_jobs": [
{
"covered_vmids": [
100
],
"enabled": true,
"id": "backup-debian",
"last_expected_run": 1795172400,
"mode": "snapshot",
"next_run": 1795179600,
"schedule": "*/2:00",
"selection": "vmid",
"storage": "local"
}
],
"backup_runs": [
{
"ended_at": 1795172488,
"guests": [
{
"result": "ok",
"vmid": 100
}
],
"message": null,
"started_at": 1795172468,
"status": "ok",
"upid": "UPID:pve:00000C75:000030ED:6B002874:vzdump:100:root@pam:"
}
],
"cluster": null,
"guests": [
{
"cpus": 1,
"disk_bytes": 8589934592,
"kind": "qemu",
"macs": [
"bc:24:11:88:35:97"
],
"memory_bytes": 1073741824,
"name": "debian-guest",
"pool": null,
"smbios_uuid": "787f4ae9-446f-4fac-b3d8-4074170bf823",
"status": "running",
"template": false,
"uptime_seconds": 2716,
"vmid": 100
},
{
"cpus": 1,
"disk_bytes": 1020702720,
"kind": "lxc",
"macs": [
"bc:24:11:b7:4c:99"
],
"memory_bytes": 134217728,
"name": "alpine-ct",
"pool": null,
"smbios_uuid": null,
"status": "running",
"template": false,
"uptime_seconds": 2714,
"vmid": 101
}
],
"node": "pve",
"not_backed_up": [
101
],
"version": "9.2.2"
}
+55 -1
View File
@@ -480,7 +480,25 @@ 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")
}
pub fn opnsense_root_script(&self) -> bool {
matches!(self, Self::RunScript {interpreter, windows_execution_profile:None,
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1), ..}
if interpreter=="posix_sh") && self.validate()
}
pub fn opnsense_service_script(&self) -> bool {
matches!(self, Self::RunScript {interpreter,windows_execution_profile:None,privileged_script_profile:None,..}
if interpreter=="posix_sh") && self.validate()
}
/// 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 +508,13 @@ impl Action {
return false;
}
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
if has("opnsense.base/1") {
return has("run_script") && has("rmm.sync.v1") && !has("windows.base/1") && !has("linux.base/1")
&& ((identity=="agent_service" && ((has("opnsense.uname/1") && self.opnsense_kernel_probe())
|| (has("opnsense.posix/1") && self.opnsense_service_script())))
|| (identity=="root" && has("opnsense.root.posix/1") && has(FULL_MAINTENANCE_CAPABILITY)
&& has("helper.root.v1") && has("root:run_script") && self.opnsense_root_script()));
}
if !has(self.name())
|| (self.full_maintenance()
&& !((has(FULL_MAINTENANCE_CAPABILITY)
@@ -828,6 +853,35 @@ 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 opnsense_root_requires_full_profile_and_separate_capabilities() {
let caps:Vec<_>=["opnsense.base/1","run_script","rmm.sync.v1","opnsense.root.posix/1",
FULL_MAINTENANCE_CAPABILITY,"helper.root.v1","root:run_script"].map(str::to_owned).into();
let mut a=Action::RunScript{interpreter:"posix_sh".into(),script_utf8:"id -u\n".into(),
arguments:vec![],expected_stdout:None,windows_execution_profile:None,
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1)};
assert!(a.available_for("root",&caps));
for omitted in &caps { assert!(!a.available_for("root",&caps.iter().filter(|x|*x!=omitted).cloned().collect::<Vec<_>>())); }
assert!(!a.available_for("agent_service",&caps));
if let Action::RunScript{interpreter,..}=&mut a { *interpreter="bash".into(); }
assert!(!a.available_for("root",&caps));
}
#[test]
fn windows_update_final_report_and_policy_are_exact() {
assert_eq!(
windows_update_reboot_report(
+3
View File
@@ -190,6 +190,9 @@ pub async fn ingest(
.fetch_one(&mut *tx)
.await?;
ensure!(stored == hash, "message identity conflict");
if matches!(s.scope.as_str(), "linux.base" | "windows.base") {
crate::proxmox_links::reconcile(&mut tx, tenant).await;
}
}
Some(Payload::JobAccepted(_) | Payload::JobStateChanged(_) | Payload::JobResult(_)) => {
crate::job_gateway::event(&mut tx, tenant, agent, e).await?
+47
View File
@@ -494,6 +494,52 @@ def provision_serial_credential():
save(dropin, content)
def provision_proxmox_credential():
# Proxmox VE hosts: a dedicated read-only API token (PVEAuditor) lets the
# unprivileged agent list guests and backup jobs. The secret is only shown by
# Proxmox at creation, so an existing token without a local copy is rotated.
pveum = Path('/usr/sbin/pveum')
if not (Path('/usr/bin/pveversion').is_file() and pveum.is_file()):
return
user, name = 'rmm-discovery@pve', 'inventory'
target, ca = ROOT / 'proxmox-token', ROOT / 'pve-ca.pem'
dropin = UNIT_DIR / (SERVICE + '.d') / '41-proxmox-api.conf'
content = f'[Service]\nLoadCredential=rmm-proxmox-token:{target}\nEnvironment=RMM_PROXMOX_CA_FILE={ca}\n'.encode()
require(not dropin.parent.is_symlink(), 'proxmox credential directory conflict')
def pve(*args):
return subprocess.run([str(pveum), *args], check=True, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, timeout=60).stdout
try:
save(ca, Path('/etc/pve/pve-root-ca.pem').read_bytes(), 0o644)
current = target.read_text().strip() if target.is_file() else ''
if not current.startswith(f'{user}!{name}='):
users = json.loads(pve('user', 'list', '--output-format', 'json'))
if not any(u.get('userid') == user for u in users):
pve('user', 'add', user, '--comment', 'Rust Discovery inventory (read-only)')
tokens = json.loads(pve('user', 'token', 'list', user, '--output-format', 'json'))
if any(t.get('tokenid') == name for t in tokens):
pve('user', 'token', 'remove', user, name)
created = json.loads(pve('user', 'token', 'add', user, name, '--privsep', '1',
'--comment', 'Rust Discovery agent', '--output-format', 'json'))
secret = created['value']
require(re.fullmatch('[0-9a-f-]{36}', secret), 'unexpected proxmox token format')
save(target, f'{user}!{name}={secret}\n'.encode(), 0o600)
# A privilege-separated token holds the intersection of user and token rights.
pve('acl', 'modify', '/', '--users', user, '--roles', 'PVEAuditor')
pve('acl', 'modify', '/', '--tokens', f'{user}!{name}', '--roles', 'PVEAuditor')
except (OSError, ValueError, KeyError, subprocess.SubprocessError):
print('Proxmox VE read access could not be prepared; guest and backup inventory stays unavailable',
file=sys.stderr)
return
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'proxmox credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(dropin, content)
def enable():
for name, data in units().items():
path = UNIT_DIR / name
@@ -502,6 +548,7 @@ def enable():
else:
save(path, data.encode())
provision_serial_credential()
provision_proxmox_credential()
service('daemon-reload')
service('enable', '--now', SERVICE)
+23 -9
View File
@@ -208,6 +208,9 @@ struct HypervisorAssignment {
// null clears the relation. A missing field is a malformed update.
#[serde(deserialize_with = "required_hypervisor_value")]
hypervisor_asset_id: Option<Uuid>,
/// true hands the decision back to automatic Proxmox detection (requires null id).
#[serde(default)]
automatic: bool,
}
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
@@ -227,24 +230,35 @@ async fn assign_hypervisor(
// Match the asset lock order for simultaneous edits of the same two devices.
let ids = [asset, input.hypervisor_asset_id.unwrap_or(asset)];
let rows: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id FROM assets
if input.automatic && input.hypervisor_asset_id.is_some() {
return Err(Error(StatusCode::UNPROCESSABLE_ENTITY, "AUTOMATIC_REQUIRES_NULL_HYPERVISOR"));
}
let rows: Vec<(Uuid, Option<Uuid>, Option<String>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id,hypervisor_source FROM assets
WHERE tenant_id=$1 AND asset_id=ANY($2) ORDER BY asset_id FOR UPDATE",
)
.bind(tenant).bind(ids.as_slice()).fetch_all(&mut *tx).await?;
let previous = rows.into_iter().find(|(id, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?.1;
let (_, previous, previous_source) = rows.into_iter().find(|(id, _, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
crate::devices::validate_vm_host_assignment(
&mut tx, tenant, asset, pair.agent_id, input.hypervisor_asset_id,
).await?;
if previous != input.hypervisor_asset_id {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).execute(&mut *tx).await?;
let source = (!input.automatic).then_some("manual");
if previous != input.hypervisor_asset_id || previous_source.as_deref() != source {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3,hypervisor_source=$4 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).bind(source).execute(&mut *tx).await?;
audit(&mut tx, &p, EVENT, json!({"asset_id":asset,"agent_id":pair.agent_id,
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id})).await?;
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id,
"previous_source":previous_source,"source":source.unwrap_or("automatic")})).await?;
}
if input.automatic {
crate::proxmox_links::reconcile(&mut tx, tenant).await;
}
let (current, current_source): (Option<Uuid>, Option<String>) = sqlx::query_as(
"SELECT hypervisor_asset_id,hypervisor_source FROM assets WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).fetch_one(&mut *tx).await?;
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":current,"hypervisor_source":current_source})))
}
async fn remove_device(
+1 -1
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,asset.purpose,t.name AS customer_name,
asset.archived_at,asset.hypervisor_asset_id,asset.hypervisor_source,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'
+164 -1
View File
@@ -261,7 +261,12 @@ pub async fn detail(
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?;
let mut item = project(&row, now, true, &hosts);
item["volumes"] = volumes(&item["inventory"]);
if item["proxmox"]["data"].is_object() {
let rows: Vec<(Uuid, Uuid, Option<String>, Option<String>, Value)> =
sqlx::query_as(include_str!("proxmox_guest_devices.sql"))
.bind(tenant).bind(asset).fetch_all(&mut *tx).await?;
item["proxmox"]["guest_devices"] = proxmox_guest_devices(&item["proxmox"]["data"], &rows);
}
item["recent_jobs"] = if p.permits_scope("operations:read")
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
{
@@ -283,6 +288,25 @@ pub async fn detail(
Ok(Json(item))
}
/// Linked devices per reported guest, matched by the MACs both sides report.
fn proxmox_guest_devices(
data: &Value,
rows: &[(Uuid, Uuid, Option<String>, Option<String>, Value)],
) -> Value {
let mut result = Vec::new();
for guest in data["guests"].as_array().into_iter().flatten() {
let macs: Vec<&str> = guest["macs"].as_array().into_iter().flatten()
.filter_map(Value::as_str).collect();
let linked = rows.iter().find(|(_, _, _, _, device)| device.as_array().into_iter().flatten()
.filter_map(Value::as_str).any(|m| macs.contains(&m)));
if let (Some(vmid), Some((asset_id, agent_id, source, hostname, _))) = (guest["vmid"].as_u64(), linked) {
result.push(json!({"vmid":vmid,"asset_id":asset_id,"agent_id":agent_id,
"hostname":hostname,"source":source}));
}
}
Value::Array(result)
}
fn observed<'a>(data: &'a Value, scope: &str) -> &'a Value {
data["observations"]
.as_array()
@@ -296,6 +320,14 @@ fn observed<'a>(data: &'a Value, scope: &str) -> &'a Value {
}
fn volumes(data: &Value) -> Value {
let mut items = Vec::new();
if let Some(drives) = observed(data, "windows.volumes")["drives"].as_array() {
let mut seen = std::collections::HashSet::new();
for drive in drives.iter().take(26) {
let Some(name) = drive["name"].as_str() else { continue };
if !matches!(name.as_bytes(), [b'A'..=b'Z', b':']) || !seen.insert(name) { continue; }
items.push(json!({"name":name,"free_bytes":drive["free_bytes"].as_u64(),"total_bytes":drive["total_bytes"].as_u64()}));
}
}
if let Some(rows) = observed(data, "linux.volumes").as_array() {
for entry in rows.iter().filter(|entry| entry["quality"] == "valid") {
let v = &entry["data"];
@@ -552,12 +584,43 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
"completeness":"partial","health":"unknown"
});
if full || observed(&data, "windows.volumes").is_object() {
item["volumes"] = volumes(&data);
}
if let Some(scope) = data["observations"].as_array().and_then(|scopes|
scopes.iter().find(|s| s["scope"] == "linux.disks")) {
item["disks"] = if scope["quality"] == "valid" && scope["data"].is_array() {
scope["data"].clone()
} else { Value::Null };
item["disks_truncated"] = json!(scope["truncated"] == true);
}
if let Some(scope) = data["observations"].as_array().and_then(|scopes|
scopes.iter().find(|s| s["scope"] == "linux.proxmox")) {
let status = (scope["quality"] == "valid")
.then(|| rmm_domain::inventory_document::proxmox::backup_status(&scope["data"]))
.flatten();
item["proxmox_backup"] = status.as_ref().map_or(Value::Null, |s| json!({
"all_scheduled_backups_ran":s["all_scheduled_backups_ran"],
"problem_jobs":s["problem_jobs"],"enabled_jobs":s["enabled_jobs"]}));
if full {
item["proxmox"] = json!({
"quality":scope["quality"],"error_code":scope["error_code"],
"observed_at":scope["observed_at"],"truncated":scope["truncated"],
"data":if scope["quality"] == "valid" { scope["data"].clone() } else { Value::Null },
"backup_status":status,"guest_devices":[]});
}
}
if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" {
let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id");
let assigned = assigned_id.and_then(|id| hosts.get(&id));
item["hypervisor"] = hypervisor_display(&data, assigned);
let source = row.get::<Option<String>, _>("hypervisor_source");
if item["hypervisor"]["kind"] == "device" {
item["hypervisor"]["source"] = json!(source);
}
if full {
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
item["hypervisor_source"] = json!(source);
}
}
if full {
@@ -578,6 +641,18 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
mod tests {
use super::*;
#[test]
fn windows_drives_include_other_letters_and_preserve_legacy_system_volume() {
let mut snapshot = json!({"root_available_bytes":4,"root_total_bytes":8,"observations":[
{"scope":"windows.volumes","quality":"valid","data":{}}]});
assert_eq!(volumes(&snapshot)[0]["name"], "Systemvolume");
let drives = json!([{"name":"C:","free_bytes":4,"total_bytes":8},
{"name":"D:","free_bytes":0,"total_bytes":64},
{"name":"E:","free_bytes":null,"total_bytes":null}]);
snapshot["observations"][0]["data"]["drives"] = drives.clone();
assert_eq!(volumes(&snapshot), drives);
}
fn windows_os(name: &str, build: &str) -> String {
let old = json!({"os":name,"observations":[{"scope":"windows.os","quality":"valid",
"data":{"product_name":name,"build":build,"display_version":"26H2"}}]});
@@ -639,6 +714,94 @@ mod tests {
assert!(hypervisor_display(&data, None).is_null());
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn proxmox_guest_macs_link_vms_automatically_but_never_override_people() {
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await.unwrap();
let app = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await.unwrap();
let (tenant, other) = (Uuid::new_v4(), Uuid::new_v4());
let (host, vm, manual_vm, foreign_vm, twin_a, twin_b) =
(Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4());
for customer in [tenant, other] {
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Proxmox link test')")
.bind(customer).execute(&admin).await.unwrap();
}
let guests = |macs: &[&str]| json!({"node":"pve","guests":macs.iter().enumerate().map(|(i, m)|
json!({"vmid":100 + i,"macs":[m]})).collect::<Vec<_>>()});
let device = |kind: &str, mac: &str, proxmox: Option<Value>| {
let mut scopes = vec![
json!({"scope":"linux.hardware","quality":"valid","data":{"device_type":kind}}),
json!({"scope":"linux.interfaces","quality":"valid","data":[{"name":"eth0","mac":mac}]}),
];
if let Some(data) = proxmox {
scopes.push(json!({"scope":"linux.proxmox","quality":"valid","data":data}));
}
json!({"hostname":"h","os":"Debian","root_available_bytes":1,"root_total_bytes":2,"observations":scopes})
};
let insert = |customer: Uuid, id: Uuid, data: Value, sequence: i64| {
let admin = admin.clone();
async move {
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,$5,now(),'linux.base','valid','partial',$6,$7,$8)")
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4()).bind(sequence)
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
}
};
let all = ["bc:24:11:00:00:01", "bc:24:11:00:00:02", "bc:24:11:00:00:03", "bc:24:11:00:00:04"];
for (customer, id, data) in [
(tenant, host, device("hypervisor", "52:54:00:00:00:99", Some(guests(&all)))),
(tenant, vm, device("virtual", "BC:24:11:00:00:01", None)),
(tenant, manual_vm, device("virtual", "bc:24:11:00:00:02", None)),
(other, foreign_vm, device("virtual", "bc:24:11:00:00:03", None)),
(tenant, twin_a, device("virtual", "bc:24:11:00:00:04", None)),
(tenant, twin_b, device("virtual", "bc:24:11:00:00:04", None)),
] {
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(customer).bind(id).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,last_authenticated_at,last_authenticated_certificate_sha256) VALUES($1,$2,$2,$3,now(),now(),$3)")
.bind(customer).bind(id).bind(rmm_domain::jobs::hash(format!("{customer}:{id}").as_bytes()))
.execute(&admin).await.unwrap();
insert(customer, id, data, 1).await;
}
sqlx::query("UPDATE assets SET hypervisor_source='manual' WHERE asset_id=$1")
.bind(manual_vm).execute(&admin).await.unwrap();
let link = |id: Uuid| {
let admin = admin.clone();
async move {
sqlx::query_as::<_, (Option<Uuid>, Option<String>)>(
"SELECT hypervisor_asset_id,hypervisor_source FROM assets WHERE asset_id=$1")
.bind(id).fetch_one(&admin).await.unwrap()
}
};
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
assert_eq!(link(vm).await, (Some(host), Some("proxmox".into())));
assert_eq!(link(manual_vm).await, (None, Some("manual".into())));
assert_eq!(link(foreign_vm).await, (None, None));
assert_eq!(link(twin_a).await, (None, None), "duplicate MACs are ambiguous");
let audits: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_hypervisor_detected'")
.bind(tenant).fetch_one(&admin).await.unwrap();
assert_eq!(audits, 1);
// Idempotent: a second pass changes nothing.
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
let audits: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1")
.bind(tenant).fetch_one(&admin).await.unwrap();
assert_eq!(audits, 1);
// The guest left the host: the automatic link is released.
insert(tenant, host, device("hypervisor", "52:54:00:00:00:99", Some(guests(&all[1..]))), 2).await;
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
crate::proxmox_links::reconcile(&mut tx, tenant).await;
tx.commit().await.unwrap();
assert_eq!(link(vm).await, (None, None));
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn host_links_resolve_outside_the_page_and_stay_inside_the_customer() {
+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 input.execution_identity=="agent_service" && caps.iter().any(|s| s=="opnsense.base/1") && !caps.iter().any(|s| s=="opnsense.posix/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"));
}
+1
View File
@@ -27,6 +27,7 @@ mod monitoring;
mod oidc;
mod pagination;
mod permissions;
mod proxmox_links;
mod root_policy;
mod managed_scripts;
mod scheduler;
+5 -1
View File
@@ -16,6 +16,8 @@ use uuid::Uuid;
struct Policy {
schema_version: u8,
linux: Vec<RootScope>,
#[serde(default)]
opnsense: Vec<RootScope>,
windows: Vec<SystemScope>,
#[serde(default)]
release_anchors: Vec<ReleaseAnchor>,
@@ -123,6 +125,8 @@ impl Policy {
return false;
}
let permits_subject = |subject: &str| match job.execution_identity.as_str() {
"root" if caps.iter().any(|c| c=="opnsense.base/1") => self.opnsense.iter()
.any(|scope| scope.permits(subject,job,caps,None)),
"root" => self
.linux
.iter()
@@ -206,7 +210,7 @@ pub(crate) async fn permits(
.map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
if policy.schema_version != 1
|| policy.linux.len() + policy.windows.len() > 64
|| policy.linux.len() + policy.windows.len() + policy.opnsense.len() > 64
|| policy.release_anchors.len() > 64
|| policy
.release_anchors
@@ -0,0 +1,28 @@
-- Current devices of customer $1 linked to host $2, with the MACs they report themselves.
SELECT asset.asset_id, inst.agent_id, asset.hypervisor_source,
inventory.data->>'hostname' AS hostname,
COALESCE((
SELECT jsonb_agg(DISTINCT lower(i->>'mac'))
FROM jsonb_array_elements(CASE WHEN jsonb_typeof(inventory.data->'observations')='array'
THEN inventory.data->'observations' ELSE '[]'::jsonb END) o,
jsonb_array_elements(CASE
WHEN jsonb_typeof(o->'data')='array' THEN o->'data'
WHEN jsonb_typeof(o#>'{data,entries}')='array' THEN o#>'{data,entries}'
ELSE '[]'::jsonb END) i
WHERE o->>'scope' IN ('linux.interfaces','windows.interfaces') AND o->>'quality'='valid'
AND i->>'mac' IS NOT NULL
), '[]'::jsonb) AS macs
FROM assets asset
JOIN LATERAL (
SELECT a.agent_id, a.revoked_at FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id AND NOT a.customer_transfer_pending
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id LIMIT 1
) inst ON inst.revoked_at IS NULL
LEFT JOIN LATERAL (
SELECT data FROM observations
WHERE tenant_id=asset.tenant_id AND agent_id=inst.agent_id AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC LIMIT 1
) inventory ON true
WHERE asset.tenant_id=$1 AND asset.hypervisor_asset_id=$2 AND asset.archived_at IS NULL
ORDER BY asset.asset_id
LIMIT 1024
+24
View File
@@ -0,0 +1,24 @@
//! Automatic VM -> Proxmox host mapping from the hosts' `linux.proxmox` guest lists.
//! Runs inside the ingesting customer transaction behind a savepoint: a failed
//! reconciliation never blocks acknowledging the inventory snapshot itself.
use sqlx::{Acquire, Postgres, Transaction};
use uuid::Uuid;
pub async fn reconcile(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) {
let result = async {
let mut savepoint = tx.begin().await?;
let events: Vec<Uuid> = sqlx::query_scalar(include_str!("proxmox_links.sql"))
.bind(tenant)
.fetch_all(&mut *savepoint)
.await?;
savepoint.commit().await?;
Ok::<_, sqlx::Error>(events.len())
}
.await;
match result {
Ok(0) => (),
Ok(changed) => eprintln!("proxmox guest links updated: {changed}"),
// Database detail stays out of the log line; the snapshot is still acknowledged.
Err(_) => eprintln!("proxmox guest link reconciliation skipped"),
}
}
+103
View File
@@ -0,0 +1,103 @@
-- Automatic VM -> Proxmox host links for one customer ($1). A link is set only for a
-- unique MAC match between a host's current guest list and a current virtual device of
-- the same customer. Manual decisions (hypervisor_source='manual') are never touched.
WITH current_installation AS (
SELECT asset.asset_id, asset.hypervisor_asset_id, asset.hypervisor_source, inst.agent_id
FROM assets asset
JOIN LATERAL (
SELECT a.agent_id, a.revoked_at
FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id
AND NOT a.customer_transfer_pending
AND a.last_authenticated_at IS NOT NULL
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
LIMIT 1
) inst ON inst.revoked_at IS NULL
WHERE asset.tenant_id=$1 AND asset.archived_at IS NULL
),
latest AS (
SELECT c.*, inventory.data
FROM current_installation c
JOIN LATERAL (
SELECT data FROM observations
WHERE tenant_id=$1 AND agent_id=c.agent_id AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC
LIMIT 1
) inventory ON true
),
scopes AS (
SELECT l.asset_id, o
FROM latest l,
jsonb_array_elements(CASE WHEN jsonb_typeof(l.data->'observations')='array'
THEN l.data->'observations' ELSE '[]'::jsonb END) o
WHERE o->>'quality'='valid'
),
proxmox_hosts AS (
SELECT asset_id, o->'data' AS data FROM scopes WHERE o->>'scope'='linux.proxmox'
),
guest_macs AS (
SELECT DISTINCT h.asset_id AS host_asset_id, lower(mac) AS mac
FROM proxmox_hosts h,
jsonb_array_elements(h.data->'guests') g,
jsonb_array_elements_text(g->'macs') mac
),
virtual_devices AS (
SELECT asset_id FROM scopes
WHERE o->>'scope' IN ('linux.hardware','windows.hardware') AND o#>>'{data,device_type}'='virtual'
),
device_macs AS (
SELECT DISTINCT s.asset_id, lower(i->>'mac') AS mac
FROM scopes s
JOIN virtual_devices v ON v.asset_id=s.asset_id,
jsonb_array_elements(CASE
WHEN jsonb_typeof(s.o->'data')='array' THEN s.o->'data'
WHEN jsonb_typeof(s.o#>'{data,entries}')='array' THEN s.o#>'{data,entries}'
ELSE '[]'::jsonb END) i
WHERE s.o->>'scope' IN ('linux.interfaces','windows.interfaces')
AND i->>'mac' ~* '^[0-9a-f]{2}(:[0-9a-f]{2}){5}$'
AND lower(i->>'mac') <> '00:00:00:00:00:00'
),
-- A MAC that more than one device or more than one host claims proves nothing.
unique_macs AS (
SELECT d.asset_id, g.host_asset_id
FROM device_macs d JOIN guest_macs g ON g.mac=d.mac
WHERE d.asset_id <> g.host_asset_id
AND (SELECT count(*) FROM device_macs d2 WHERE d2.mac=d.mac)=1
AND (SELECT count(*) FROM guest_macs g2 WHERE g2.mac=d.mac)=1
),
matches AS (
SELECT asset_id, min(host_asset_id::text)::uuid AS host_asset_id
FROM unique_macs GROUP BY asset_id HAVING count(DISTINCT host_asset_id)=1
),
desired AS (
-- New or changed automatic links.
SELECT l.asset_id, l.hypervisor_asset_id AS previous, m.host_asset_id AS next
FROM latest l JOIN matches m ON m.asset_id=l.asset_id
WHERE l.hypervisor_source IS DISTINCT FROM 'manual'
AND (l.hypervisor_asset_id IS DISTINCT FROM m.host_asset_id OR l.hypervisor_source IS NULL)
UNION ALL
-- The assigned host reports a valid guest list that no longer contains this device.
SELECT l.asset_id, l.hypervisor_asset_id, NULL
FROM latest l
WHERE l.hypervisor_source='proxmox'
AND NOT EXISTS (SELECT FROM matches m WHERE m.asset_id=l.asset_id)
AND EXISTS (SELECT FROM proxmox_hosts h WHERE h.asset_id=l.hypervisor_asset_id)
AND EXISTS (SELECT FROM device_macs d WHERE d.asset_id=l.asset_id)
),
changed AS (
UPDATE assets a
SET hypervisor_asset_id=d.next,
hypervisor_source=CASE WHEN d.next IS NULL THEN NULL ELSE 'proxmox' END
FROM desired d
WHERE a.tenant_id=$1 AND a.asset_id=d.asset_id
RETURNING a.asset_id, d.previous, d.next
)
INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data,created_at)
SELECT $1, gen_random_uuid(), 'system:proxmox-guest-detection',
CASE WHEN next IS NULL THEN 'device_hypervisor_released' ELSE 'device_hypervisor_detected' END,
jsonb_build_object('asset_id',asset_id,'previous_hypervisor_asset_id',previous,
'hypervisor_asset_id',next,'match','mac'),
now()
FROM changed
WHERE previous IS DISTINCT FROM next
RETURNING event_id
+3
View File
@@ -380,6 +380,9 @@ pub async fn authorize(
if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
return Ok(());
}
if caps.iter().any(|c| c=="opnsense.base/1") {
return Err(Error(StatusCode::FORBIDDEN,"SCRIPT_HELPER_SCOPE_DENIED"));
}
let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
+4 -2
View File
@@ -17,6 +17,8 @@ Der OPNsense-eigene Python-Interpreter führt zwei Zipapps aus. Der lokale Colle
**Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze.
**Grenzen:** Das passive Profil meldet keine Skript-, Root- oder Release-Capability. Der bestehende Linux-Jobpfad verwendet Linux-spezifische Uhren, Helper und Interpreterprüfung. Für Parität benötigt OPNsense eigene native Adapter für den signierten Abgleich, den Startgrant und das Ausführungsjournal sowie einen eigenen signierten Installer-/Updatekanal. Der OPNsense-Gast darf nicht als Linuxziel für APT- oder Bash-Vorlagen angeboten werden.
**Skripte:** Unter **Aufträge → Neuer Auftrag** die OPNsense-Zielgeräte wählen. Unter **Aus der Bibliothek** eine feste POSIX-Shell-Revision wählen, alternativ ein **Einmaliges Skript** eingeben. **Ausführen als** unterstützt Dienstkonto und bei entsprechender Berechtigung `root`. **Zusammenfassung ansehen** bindet das Skript samt Zielen und Grenzen; **Zur Genehmigung einreichen** legt den Antrag an. Die persönliche Freigabe erfolgt unter **Genehmigungen**, die Ausgabe erscheint im Auftrag. OPNsense kann POSIX-Shellskripte ausführen; Linux-spezifische Programme und Optionen werden nicht übersetzt. Zwei [Startrevisionen aus dem Repository](../../migrations/0047_opnsense_library.sql) zeigen Version/Ausführungskonto bzw. aktive Firewallregeln. Im Gerätedetail stehen Inventar und Verweise auf vorhandene Aufträge.
**Stand des Rust-Ports:** Im Gast steht die gepinnte native Toolchain unter `/opt/discovery-rust`. Der gemeinsame Abgleich, die Signatur-/Journalverträge, die native Abfrage von `ntp_gettime` mit Zeitfehlergrenze und die Prozessgruppenbeobachtung ohne Linux-`/proc` sind nativ getestet. `cargo check -p rmm-agent --bin rmm-agent` erreicht nach der `waitid`-Portierung den Linux-Helper, scheitert dort aber an `SO_PEERCRED`, `adjtimex` und den nur für Linux exportierten Updater-Modulen. Der laufende Telemetriedienst verwendet diese unvollständige Jobstrecke nicht. Ein Shellprozess-Test auf FreeBSD ist kein genehmigter Discovery-Auftrag. Zum nächsten Nachweis gehören ein über die WebUI genehmigter fester POSIX-Auftrag, sein genau einmal verbrauchter Startgrant und ein natives Ergebnis unter derselben Geräteidentität.
**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.
**Root-Helper (ab `0.1.0-opnsense.6`):** Native Binärdatei zusätzlich in den privaten Stagingordner kopieren. Auf dem Gast `python3 -I enable-root.py /absoluter/Stagingpfad/rmm-opnsense-jobs` und `sh install-dev.sh /absoluter/Stagingpfad` ausführen. Die lokale Policy bindet Worker-Hash, Gerätebindung, Dienst-UID und Gruppe. Der zusätzliche `rc.d`-Prozess läuft als root, hört ausschließlich auf einem geschützten Unix-Socket und prüft den Peer über `getpeereid`. Den vom Helper bestätigten Binär- und Policyhash mit `tools/dev_opnsense_root_scope.py --help` für die genaue Kopplung und den berechtigten lokalen Principal registrieren. Es gibt keine automatische Freigabe oder automatische Pinrotation. Root akzeptiert `posix_sh` mit `full_maintenance_v1` (bis 300 Sekunden und 65536 Ausgabebyte), verifiziert selbst Sync, Grant, Skriptbytes, Boot und Uhr, und führt ein eigenes Verbrauchsjournal in `/var/db/discovery-root-jobs`. Ohne Startbeleg gibt es kein positives Ergebnis. Bei `unknown` zuerst die bestehenden Journale abgleichen. Der [isolierte native Helper-Test](test_root_helper.py) benutzt nur eine Wegwerfidentität und separate Journale.
+111 -9
View File
@@ -1,5 +1,7 @@
"""Unprivileged OPNsense telemetry channel. Input never selects a local command."""
"""Unprivileged OPNsense telemetry and signed job transport."""
import hashlib
import contextlib
import fcntl
import http.client
import json
import os
@@ -18,7 +20,9 @@ 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.4'
VERSION = '0.1.0-opnsense.6'
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):
@@ -111,10 +115,73 @@ def usage(previous):
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
@@ -136,12 +203,11 @@ def session(db, identity, boot, instance):
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))
if reply.protocol_major != 1 or len(reply.messages) != 1:
raise ValueError('unexpected reply')
r = reply.messages[0]
if (r.protocol_major,r.agent_id,r.enrollment_generation,r.boot_id,r.sequence) != (
1,e.agent_id,1,e.boot_id,e.sequence):
raise ValueError('reply identity')
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
@@ -158,7 +224,33 @@ def session(db, identity, boot, instance):
if renew(ctx, identity):
ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=['heartbeat/1','opnsense.base/1']))
caps = ['heartbeat/1','opnsense.base/1']
root_caps=[]
if enabled:
caps.extend(['rmm.sync.v1','run_script','opnsense.uname/1','opnsense.posix/1'])
if Path('/usr/local/etc/discovery-agent/root-policy.json').is_file():
probe=subprocess.run([WORKER,'--root-capabilities'],capture_output=True,timeout=15)
if probe.returncode==0:
root_caps=json.loads(probe.stdout)
caps.extend(root_caps)
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=caps))
if enabled:
env=os.environ.copy();env.pop('DISCOVERY_ROOT_SESSION',None)
if root_caps:env['DISCOVERY_ROOT_SESSION']='1'
p = subprocess.Popen([WORKER,identity['agent_id'],identity['asset_id'],boot,str(generation)],env=env,
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
@@ -187,6 +279,13 @@ def session(db, identity, boot, instance):
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 and (root_caps or not Path('/usr/local/etc/discovery-agent/root-policy.json').is_file()):
jobs.pump(ctx,identity['agent_id'],boot,generation)
elif jobs:
# Preserve the established helper journal chain across a helper
# restart. Keep telemetry flowing, then renegotiate capabilities.
if subprocess.run([WORKER,'--root-capabilities'],capture_output=True,timeout=15).returncode==0:
return
time.sleep(20)
@@ -194,6 +293,9 @@ 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:
+10 -1
View File
@@ -11,6 +11,15 @@ start_cmd=discovery_start
stop_cmd=discovery_stop
discovery_start() {
if [ -f /usr/local/etc/discovery-agent/root-policy.json ]; then
install -d -o root -g wheel -m 0700 /var/db/discovery-root-jobs || return 1
install -d -o root -g discovery -m 0750 /var/run/discovery-root-jobs || return 1
pid=/var/run/discovery-root-jobs.pid
if [ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ]; then
/usr/sbin/daemon -f -r -R 5 -P "$pid" -S -T discovery-root-jobs \
/usr/local/libexec/discovery-agent/rmm-opnsense-jobs --root-helper || return 1
fi
fi
for part in collect agent; do
pid=/var/run/discovery-$part.pid
[ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue
@@ -21,7 +30,7 @@ discovery_start() {
done
}
discovery_stop() {
for part in agent collect; do
for part in agent collect root-jobs; do
pid=$(check_pidfile "/var/run/discovery-$part.pid" /usr/sbin/daemon)
[ -z "$pid" ] || kill -TERM "$pid"
done
+38
View File
@@ -0,0 +1,38 @@
"""In the guest, bind a staged native helper to the existing signed job identity.
Print only the hashes used by the central operator. Never replace another policy.
"""
import hashlib
import json
import os
from pathlib import Path
import pwd
import stat
import sys
def main():
if os.getuid()!=0 or os.geteuid()!=0 or len(sys.argv)!=2:
raise SystemExit('Run as root: enable-root.py /absolute/staging/rmm-opnsense-jobs')
app=Path(sys.argv[1]).resolve(strict=True)
conf=Path('/usr/local/etc/discovery-agent')
binding=conf/'job-binding.json'
for path in (app,*app.parents,binding,*binding.parents):
info=path.lstat()
if info.st_uid!=0 or info.st_mode & 0o022 or stat.S_ISLNK(info.st_mode):
raise ValueError('untrusted provisioning path')
user=pwd.getpwnam('discovery')
if not user.pw_uid or not user.pw_gid: raise ValueError('invalid agent identity')
image=hashlib.file_digest(app.open('rb'),'sha256').hexdigest()
policy=dict(schema_version=1,profile='full_maintenance_v1',agent_uid=user.pw_uid,agent_gid=user.pw_gid,
binding_sha256=hashlib.sha256(binding.read_bytes()).hexdigest(),helper_binary_sha256=image)
raw=(json.dumps(policy,separators=(',',':'))+'\n').encode()
path=conf/'root-policy.json'
if path.exists():
if path.is_symlink() or path.read_bytes()!=raw: raise ValueError('existing policy differs')
else:
with path.open('xb') as f:
os.fchmod(f.fileno(),0o444); f.write(raw);f.flush();os.fsync(f.fileno())
print(json.dumps(dict(helper_binary_sha256=image,helper_policy_sha256=hashlib.sha256(raw).hexdigest())))
if __name__=='__main__':main()
+11 -2
View File
@@ -24,13 +24,22 @@ 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
[ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || [ -f /var/run/discovery-root-jobs.pid ] || break
sleep 1
done
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ]; then
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || [ -f /var/run/discovery-root-jobs.pid ]; then
echo 'Existing service still running' >&2; exit 1
fi
fi
if [ -f "$src/rmm-opnsense-jobs" ]; then
install -o root -g wheel -m 0555 "$src/rmm-opnsense-jobs" "$app/jobs.next"
if [ -f "$conf/root-policy.json" ] && ! /usr/local/bin/python3 -I -c \
'import hashlib,json,sys;sys.exit(hashlib.file_digest(open(sys.argv[1],"rb"),"sha256").hexdigest()!=json.load(open(sys.argv[2]))["helper_binary_sha256"])' \
"$app/jobs.next" "$conf/root-policy.json"; then
echo 'Native helper differs from the local policy pin' >&2; "$rc" start; exit 1
fi
mv -f "$app/jobs.next" "$app/rmm-opnsense-jobs"
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"
+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()
+13
View File
@@ -16,6 +16,19 @@ 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:')
+132
View File
@@ -0,0 +1,132 @@
"""Native development integration: private chroot, disposable signer and identities.
Runs the installed FreeBSD helper binary and a child with the discovery uid in an
empty root; the installed device's socket, config, keys and journals are not used.
"""
import datetime
import hashlib
import json
import os
from pathlib import Path
import pwd
import re
import shutil
import socket
import sqlite3
import struct
import subprocess
import sys
import tempfile
import time
import uuid
APP='/usr/local/libexec/discovery-agent/rmm-opnsense-jobs'
CONF='/usr/local/etc/discovery-agent'
SOCK='/var/run/discovery-root-jobs/control.sock'
STATE='/var/db/discovery-root-jobs'
pack=lambda v:json.dumps(v,separators=(',',':')).encode()
sha=lambda b:hashlib.sha256(b).hexdigest()
new=lambda:str(uuid.uuid4())
now=lambda:datetime.datetime.now(datetime.timezone.utc)
def check(jail, folder, result):
import agent_pb2 as pb
u=pwd.getpwnam('discovery')
def inside(path):return jail/path.lstrip('/')
def copy(path):
dst=inside(path);dst.parent.mkdir(exist_ok=True,parents=True);shutil.copyfile(path,dst);dst.chmod(0o555)
copy('/libexec/ld-elf.so.1')
for path in [APP,'/bin/sh','/usr/bin/id','/sbin/sysctl']:
copy(path)
for lib in re.findall(r'=> (/\S+)',subprocess.check_output(['ldd',path],text=True)):copy(lib)
for path in [CONF,STATE,str(Path(SOCK).parent),'/tmp','/dev']:inside(path).mkdir(exist_ok=True,parents=True)
inside(STATE).chmod(0o700);inside('/tmp').chmod(0o1777);inside('/dev/null').touch()
key=folder/'fixture.key'
subprocess.run(['openssl','genpkey','-algorithm','Ed25519','-out',key],check=True)
public=subprocess.check_output(['openssl','pkey','-in',key,'-pubout','-outform','DER'])[-32:]
def signed(data):
f=folder/'message';f.write_bytes(data)
return list(subprocess.check_output(['openssl','pkeyutl','-sign','-rawin','-inkey',key,'-in',f]))
b=dict(tenant_id=new(),asset_id=new(),agent_id=new(),assignment_version=1,enrollment_generation=1)
binding=pack(dict(**b,public_key_hex=public.hex()));inside(CONF+'/job-binding.json').write_bytes(binding)
image=sha(inside(APP).read_bytes())
policy=pack(dict(schema_version=1,profile='full_maintenance_v1',agent_uid=u.pw_uid,agent_gid=u.pw_gid,
helper_binary_sha256=image,binding_sha256=sha(binding)))
inside(CONF+'/root-policy.json').write_bytes(policy)
helper=subprocess.Popen([APP,'--root-helper'],preexec_fn=lambda:(os.chroot(jail),os.chdir('/')),
stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL)
def invoke(op,deny=False,uid=u.pw_uid):
# Socket comes from the isolated chroot. The peer uid seen by getpeereid
# must be a real kernel credential, not a field in the test frame.
a,z=socket.socketpair();pid=os.fork()
if pid==0:
a.close()
try:
os.chroot(jail);os.chdir('/');os.setgroups([]);os.setgid(u.pw_gid);os.setuid(uid)
with socket.socket(socket.AF_UNIX) as s:
s.settimeout(12);s.connect(SOCK)
nonce=new();raw=pack(dict(nonce=nonce,policy=sha(policy),image=image,op=op))
s.sendall(struct.pack('>I',len(raw))+raw)
with s.makefile('rb') as f:
hdr=f.read(4)
if not hdr:os._exit(0 if deny else 1)
n=struct.unpack('>I',hdr)[0];assert n<=8*1024*1024
r=json.loads(f.read(n));assert not deny and r['nonce']==nonce
z.sendall(pack(r['data']))
os._exit(0)
except (ConnectionResetError,BrokenPipeError):
os._exit(0 if deny else 1)
except BaseException:os._exit(1)
z.close()
with a,a.makefile('rb') as f:data=f.read()
assert os.waitpid(pid,0)[1]==0, 'unexpected response from helper'
return json.loads(data) if data else None
try:
end=time.monotonic()+8
while not inside(SOCK).is_socket():
assert helper.poll() is None and time.monotonic()<end
time.sleep(.05)
invoke('Probe',True,uid=65534)
assert invoke('Probe')=='Pins'
snap=invoke({'Snapshot':1})['Snapshot']; q=pb.SyncRequest(request_id=new(),journal_id=new(),checkpoint=1,
helper_journal_id=snap['journal_id'],helper_checkpoint=snap['checkpoint'],assignment_version=1,journal_complete=True)
raw=q.SerializeToString();t=now()
dec=pack(dict(**b,domain='rmm.reconciliation-decision',schema_version=1,decision_id=new(),request_id=q.request_id,
request_hash=sha(raw),connection_generation=1,boot_id=snap['boot_id'],journal_id=q.journal_id,checkpoint=1,
helper_journal_id=q.helper_journal_id,helper_checkpoint=q.helper_checkpoint,issued_at=t.isoformat(),
valid_until=(t+datetime.timedelta(seconds=59)).isoformat(),ready=True,helper_ready=True,reason='CONSISTENT',
attempts=[],acknowledged_message_ids=[],key_id=sha(public)))
invoke({'Apply':[list(raw),dict(decision_bytes=list(dec),signature=signed(dec))]})
t=now();job=dict(**b,schema_version=1,job_id=new(),attempt_id=new(),execution_identity='root',
not_before=(t-datetime.timedelta(minutes=2)).isoformat(),start_before=(t+datetime.timedelta(minutes=2)).isoformat(),
max_runtime_seconds=10,max_output_bytes=1024,action=dict(action='run_script',interpreter='posix_sh',
script_utf8='id -u\n',arguments=[],expected_stdout='0\n',privileged_script_profile='full_maintenance_v1'))
body=pack(job);aid=new();ph=sha(b'isolated plan')
permit=pack(dict(**b,domain='rmm.execution-permit',schema_version=1,grant_id=new(),authorization_id=aid,
job_id=job['job_id'],attempt_id=job['attempt_id'],plan_hash=ph,job_payload_hash=sha(body),action='run_script',
execution_identity='root',not_before=(t-datetime.timedelta(seconds=6)).isoformat(),
start_before=(t+datetime.timedelta(seconds=50)).isoformat(),max_runtime_seconds=10,key_id=sha(public)))
req=dict(job_bytes=list(body),permit_bytes=list(permit),signature=signed(permit),plan_hash=ph,authorization_id=aid)
invoke({'Execute':[1,dict(req,signature=[0]*64)]},True)
invoke({'Execute':[2,req]},True)
invoke({'Execute':[1,dict(req,job_bytes=list(body.replace(b'id -u',b'id -g')))]},True)
db=sqlite3.connect('file:'+str(inside(STATE+'/consumption.sqlite'))+'?mode=ro',uri=True)
assert db.execute('SELECT count(*) FROM consumed').fetchone()==(0,)
out=invoke({'Execute':[1,req]})['Outcome']
assert out['state']=='succeeded' and out['exit_code']==0 and bytes(out['stdout'])==b'0\n'
assert out['evidence']['execution_uid']==0 and out['evidence']['script_sha256']==sha(b'id -u\n')
assert invoke({'Execute':[1,req]})['Outcome']==out
assert db.execute('SELECT count(*) FROM consumed JOIN execution_evidence USING(grant_id) WHERE result IS NOT NULL AND start IS NOT NULL').fetchone()==(1,)
db.close()
result.update(native_chroot_root_uid=0,replay_consumptions=1,foreign_peer_denied=True,
bad_signature_denied=True,altered_script_denied=True,stale_channel_denied=True)
finally:
helper.terminate();helper.wait(timeout=8)
if __name__=='__main__':
if not sys.platform.startswith('freebsd') or os.getuid()!=0:sys.exit('requires FreeBSD test guest as root')
sys.path.insert(0,'/usr/local/libexec/discovery-agent/agent.pyz')
with tempfile.TemporaryDirectory(prefix='discovery-helper-fixture-') as name:
folder=Path(name);jail=folder/'root';jail.mkdir();result={};check(jail,folder,result);print(json.dumps(result))
+45
View File
@@ -0,0 +1,45 @@
# Proxmox-VE-Host
Ein Proxmox-VE-Host ist ein Debian-System. Er verwendet deshalb den regulären Linux-Agenten, seinen Helper und seinen Updater. Zusätzlich liest der Agent über die lokale Proxmox-API die gehosteten Gäste, die geplanten Backupjobs und die Ergebnisse der letzten vzdump-Läufe. Er meldet sie als Inventarbereich `linux.proxmox`. Die WebUI zeigt diese Daten in den Gerätedetails des Hosts. Der Agent ordnet die gemeldeten VMs automatisch dem Host zu. [Sammelmodul](../../crates/agent-linux/src/inventory/proxmox.rs) · [API-Zugriff](../../crates/agent/src/proxmox_api.rs)
## Aufnahme
Für die Aufnahme den gemeinsamen [HTTPS-Installer](../../docs/development.md#linux-gerät-per-https-aufnehmen) als `root` auf dem Proxmox-Host ausführen. Der Installer erkennt Proxmox VE an `pveversion` und `pveum` und richtet einen nur lesenden Zugang ein:
- Proxmox-Benutzer `rmm-discovery@pve` und das privilegiengetrennte API-Token `rmm-discovery@pve!inventory`. Beide erhalten auf `/` ausschließlich die Rolle `PVEAuditor`. Bei einem privilegiengetrennten Token gilt die Schnittmenge aus Benutzer- und Tokenrechten. Deshalb braucht auch der Benutzer die Rolle.
- Den Tokenwert schreibt er nach `/opt/rust-discovery-client/proxmox-token` (Eigentümer root, Modus 0600). Die Cluster-CA landet als `/opt/rust-discovery-client/pve-ca.pem`.
- Das systemd-Drop-in `rmm-discovery-agent.service.d/41-proxmox-api.conf` übergibt den Token mit `LoadCredential=rmm-proxmox-token` an den Dienst und setzt `RMM_PROXMOX_CA_FILE`.
Der Agent läuft weiter unprivilegiert als `rmm-discovery`. Er verbindet sich nur mit `https://127.0.0.1:8006` und prüft das Zertifikat ausschließlich gegen die kopierte Cluster-CA. Token und Tokenwert erscheinen weder im Inventar noch im Log. Bei einer erneuten Installation bleiben ein vorhandener Token und die Geräteidentität erhalten. Fehlt die lokale Kopie, erzeugt der Installer das Token neu, weil Proxmox den Wert nur bei der Erstellung ausgibt.
## Gemeldete Daten
- **Gäste des lokalen Nodes:** VMID, Name, VM oder Container, Status, Vorlage, vCPU, RAM, Disk, Pool, MAC-Adressen der `netN`-Schnittstellen und für QEMU die SMBIOS-UUID. Höchstens 512 Gäste. Gäste auf anderen Cluster-Nodes meldet der Agent des jeweiligen Nodes.
- **Backupjobs** aus `/cluster/backup`: Zeitplan, Storage, Modus, Auswahl (alle, Pool oder VMIDs, abzüglich Ausnahmen) und die danach gesicherten lokalen Gäste. Den letzten fälligen Zeitpunkt berechnet der Proxmox-Scheduler selbst über `/cluster/jobs/schedule-analyze`.
- **vzdump-Läufe** der letzten acht Tage (höchstens 64) mit Start, Ende und Gesamtstatus. Das Ergebnis je Gast stammt aus den Zeilen `Finished Backup of VM` bzw. `Backup of VM … failed` des Tasklogs.
- **Gäste ohne Backupjob** aus `/cluster/backup-info/not-backed-up`.
Der Server bewertet jeden aktiven Job: **Gelaufen**, wenn jeder gesicherte Gast seit dem letzten fälligen Zeitpunkt (zwei Minuten Toleranz) erfolgreich gesichert wurde. **Fehlgeschlagen** bei einem gemeldeten Fehler, **Verpasst** ohne Lauf, **Läuft** bei aktivem vzdump. Ein Job, der in den letzten acht Tagen noch nicht fällig war, gilt als **Noch nicht fällig**. „Alle geplanten Backups sind gelaufen“ steht nur, wenn kein aktiver Job fehlgeschlagen oder verpasst ist. [Bewertung](../../crates/domain/src/inventory_document/proxmox.rs)
## Zuordnung der VMs
Nach jeder Linux- oder Windows-Inventarmeldung vergleicht der Server die MAC-Adressen der aktuellen Proxmox-Gastlisten mit den Netzwerkkarten der aktuellen virtuellen Geräte desselben Kunden. Bei einem eindeutigen Treffer trägt er den Proxmox-Host als Hypervisor ein (`hypervisor_source = proxmox`) und auditiert `device_hypervisor_detected`. Eine MAC, die mehrere Geräte oder mehrere Hosts melden, führt zu keiner Zuordnung. Verschwindet der Gast aus der gültigen Gastliste seines Hosts, wird die automatische Zuordnung gelöst. Eine manuelle Auswahl unter **Gerät verwalten → Hypervisor zuordnen** hat Vorrang. Die Option **Automatisch (Proxmox-Gastliste)** gibt die Entscheidung an die Erkennung zurück. [Abgleich](../../crates/server/src/proxmox_links.sql)
## Diagnose
| Anzeige im Gerätedetail | Ursache |
| --- | --- |
| „kein Lesezugang eingerichtet“ (`PROXMOX_NOT_CONFIGURED`) | Credential fehlt. HTTPS-Installer erneut als root ausführen und den Agentdienst neu starten. |
| `PROXMOX_TOKEN_REJECTED` | Token gelöscht oder abgelaufen. `/opt/rust-discovery-client/proxmox-token` entfernen und den Installer erneut ausführen. |
| `PROXMOX_PERMISSION_DENIED` | Der Benutzer oder das Token hat keine Rolle `PVEAuditor` auf `/`. |
| `PROXMOX_CA_UNAVAILABLE`, `PROXMOX_UNREACHABLE` | CA-Kopie fehlt bzw. `pveproxy` ist auf Port 8006 nicht erreichbar. |
Zum Widerrufen `pveum user token remove rmm-discovery@pve inventory` ausführen. Die übrige Inventur läuft dann weiter, der Proxmox-Bereich meldet einen Fehler.
## Testhost auf dem Entwicklungsnotebook
VM `proxmox` auf `qemu:///system`: 4 vCPU (`host-passthrough`, verschachtelte Virtualisierung), 4 GiB RAM, 64 GiB qcow2 im Pool `default`, Netz `default` mit fester DHCP-Reservierung `192.168.122.50` (MAC `52:54:00:50:7e:01`). Basis ist das offizielle `proxmox-ve_9.2-1.iso` (SHA-256 `4e88fe416df9b527624a175f24c9aa07c714d3332afb1ee3dbf3879573ef2c6c`). Die Installation erfolgte unbeaufsichtigt mit dem `proxmox-auto-install-assistant` aus dem Proxmox-Repository. Die Paketquelle ist `pve-no-subscription`. FQDN `pve.discovery.lan`, WebUI `https://192.168.122.50:8006`.
Testobjekte: VM 100 `debian-guest` (Debian-13-Cloud-Image, 1 GiB, cloud-init) und Container 101 `alpine-ct` (Alpine 3.24, ohne Backupjob). Der Backupjob `backup-debian` sichert VM 100 alle zwei Stunden (`*/2:00`) nach `local`.
SSH-Zugang, Root-Passwort und Hostpin liegen im privaten Zugangsverzeichnis (`proxmox-vm.conf`, `proxmox-dev-key`, `proxmox-dev-root`, `proxmox-dev.known_hosts`). `tools/dev_stage.py proxmox …` verwendet diese Dateien. Start bei Bedarf: `virsh -c qemu:///system start proxmox`.
+2
View File
@@ -54,6 +54,8 @@ python3 tools/dev_agent_release.py --official-windows \
Für Linux gilt derselbe Ablauf mit dem Linux-Buildordner und ohne `--official-windows`. Die Mindestversion entsprechend der vom Paket benötigten Updaterfähigkeit setzen. Der offizielle Windows-Kanal nutzt einen eigenen Signierschlüssel. Linux x86-64 und ARM64 haben ebenfalls getrennte Signierschlüssel, Starter und Updater-Pins. Private Signierschlüssel verbleiben auf dem Signierhost.
Für ein reines Linux-Inventarupdate kann `tools/linux_inventory_release.py` den neuen Agenten mit dem bisherigen Helper und Updater zusammenstellen. `--new` und `--previous` bezeichnen die hashadressierten Buildordner derselben Zielarchitektur; `--published-helper-sha256` stammt aus dem bisherigen signierten Release. Die neue Paketquittung hält pro Datei den tatsächlichen Quellbuild fest. Der resultierende Ordner durchläuft anschließend dieselbe Signaturprüfung und Veröffentlichung.
Für die Erstaufnahme in neuen Kundenkatalogen kann der Betreiber einen veröffentlichten Release als Starter auswählen. Die Quelle wird anhand ihrer Kunden-, Plattform- und Release-ID geprüft. Bereits befüllte Kataloge werden je Kunde gepflegt. [Starter veröffentlichen](../tools/dev_customer_starters.py)
```sh
@@ -0,0 +1,55 @@
{
"server_ui": "79f236b",
"client_source": "62cb52b",
"public_arm64_bar_verified": true,
"signed_releases": {
"x64": "29bf9d1f-364a-40a1-a0c3-0acba88688a3",
"arm64": "4621b068-fb11-44a8-a8f7-30e31a2d39e1"
},
"observations": [
{
"disks": [
{
"kind": "disk",
"name": "sda",
"model": "QEMU HARDDISK",
"members": [],
"used_bytes": 24612440576,
"total_bytes": 81923145728,
"available_bytes": 52636656128
}
],
"hostname": "EASE-OTRS-Production",
"observed_at": "2026-11-20T08:43:27.566+00:00",
"architecture": "aarch64",
"agent_version_now": "0.1.0-arm64.8"
},
{
"disks": [
{
"kind": "disk",
"name": "sda",
"model": "QEMU HARDDISK",
"members": [],
"used_bytes": 21805532672,
"total_bytes": 40961572864,
"available_bytes": 16748480000
},
{
"kind": "disk",
"name": "sdb",
"model": "Volume",
"members": [],
"used_bytes": 95375511552,
"total_bytes": 118111600640,
"available_bytes": 14446292992
}
],
"hostname": "dev-znuny-db",
"observed_at": "2026-11-20T08:39:30.902+00:00",
"architecture": "x86_64",
"agent_version_now": "0.1.0-mvp.13"
}
],
"x64_dev_guest": "Two disks reported, then the lifecycle verifier restored sequence 13. The configured required script helper belongs to the earlier tenant/agent; sequence 14 rejected."
}
@@ -0,0 +1,28 @@
{
"verified_at": "2026-11-20T07:05:34Z",
"plan_id": "c3aa157c-4908-45c1-b7f4-0f588879d1af",
"operation_id": "67205987-0fda-4635-ae7a-4b7979c274dc",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"job_id": "446ac3ca-ee0a-4d33-bd0e-1c80f9edd5c9",
"attempt_id": "ea526a57-d3f0-4ae6-8d52-d6ffdf89dfa9",
"server": {
"approval_state": "approved",
"state": "succeeded",
"revision": 2,
"exit_code": 0,
"stdout": "FreeBSD\n",
"effective_uid": 1001,
"postconditions_passed": true,
"start_grants": 1
},
"guest": {
"account": "discovery",
"journal_state": "succeeded",
"revision": 2,
"consumed_grant_id": "8faf4595-61ef-442f-9d02-18f4429002d7",
"consumed_grants_for_attempt": 1,
"start_witness_present": true,
"outcome_persisted": true,
"consumption_finished": true
}
}
@@ -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,53 @@
{
"server_revision": "2e3916b84bcfa0b99bcac7562a3bbccb2996df4c",
"helper_binary_sha256": "57f48d09541049b0e6ec8a4cc90d269866cfc9f22af441fb0f881d15e302a32b",
"public_device_detail_kernel_submit_absent": true,
"native_isolated_helper": {
"uid": 0,
"stdout": "0\n",
"exit_code": 0,
"consumptions_after_replay": 1,
"rejections": [
"foreign_peer",
"invalid_signature",
"changed_script",
"wrong_channel"
]
},
"public_order_readback": [
{
"now": "2026-11-20T07:26:45.296935+00:00",
"jobs": 0,
"grants": 0,
"source": "custom",
"plan_id": "69d9f89d-159e-4a9a-aacd-6666ec55aace",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"identity": "root",
"revision": null,
"attempt_id": "8efca471-0665-4ab9-906f-50653da14d16",
"expires_at": "2026-11-20T08:20:00+00:00",
"sync_ready": true,
"helper_ready": true,
"operation_id": "042e156b-7d5c-4458-936d-d22fb162a3e7",
"agent_version": "0.1.0-opnsense.6",
"approval_state": "pending_approval"
},
{
"now": "2026-11-20T07:26:45.296935+00:00",
"jobs": 0,
"grants": 0,
"source": "OPNsense · Version und Ausführungskonto",
"plan_id": "5683ab96-e321-4f9c-a27c-c17403e6bacd",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"identity": "agent_service",
"revision": 1,
"attempt_id": "f86e06cf-b4c1-48f9-b6c2-5d0013852aa6",
"expires_at": "2026-11-20T08:26:00+00:00",
"sync_ready": true,
"helper_ready": true,
"operation_id": "6f109d89-29f4-466b-9b99-f713d31e03d0",
"agent_version": "0.1.0-opnsense.6",
"approval_state": "pending_approval"
}
]
}
+111
View File
@@ -0,0 +1,111 @@
{
"date": "2026-11-20",
"branch": "proxmox-agent",
"server_revision": "63447f1b87800e72e0515b383c7fcaf88c6fb4d3",
"client_source": "63447f1b87800e72e0515b383c7fcaf88c6fb4d3",
"signed_release": {
"version": "0.1.0-mvp.15",
"release_id": "fbc9680c-ae30-48a0-9b51-a3e36a5ee422",
"manifest_sha256": "06ca25e046972cf584a9f2a9f596b41d45bebf542d29a44ae68d5665eba0ae29",
"agent_sha256": "51f048fdd5a78bd69598fbd37175aa9ff5dd404053ce73be5754e12efe640688",
"helper_sha256_unchanged": "e1c7e0fbe252d5df9a0998cd8350f51ad5eff3561a74bf7335fa39114fca555a",
"catalogs": {
"11111111-1111-4111-8111-111111111111": "published with tools/dev_agent_release.py",
"9d730e0a-ba31-402c-8b82-8995c2585f59": "copied unchanged from the development catalog by a one-time direct database write permitted by the operator; audit event agent_update_release_imported, principal dev-db:claude-code"
}
},
"host": {
"vm": "proxmox (qemu:///system, 4 vCPU host-passthrough, 4 GiB, 64 GiB)",
"iso": "proxmox-ve_9.2-1.iso sha256 4e88fe416df9b527624a175f24c9aa07c714d3332afb1ee3dbf3879573ef2c6c",
"pve_version": "9.2.2",
"hostname": "pve",
"asset_id": "90d14524-dc01-43af-b84e-defbb751dfd9",
"tenant_id": "9d730e0a-ba31-402c-8b82-8995c2585f59",
"enrollment": "HTTPS installer; created rmm-discovery@pve and token inventory (privsep), PVEAuditor on / for user and token, token file 0600 root, drop-in 41-proxmox-api.conf; agent runs as rmm-discovery",
"self_update": "0.1.0-mvp.14 -> 0.1.0-mvp.15 by the regular update timer"
},
"linux_proxmox_observation": {
"observed_at": "2026-11-20T11:46:14Z",
"quality": "valid",
"guests": [
{
"vmid": 100,
"name": "debian-guest",
"kind": "qemu",
"macs": [
"bc:24:11:88:35:97"
]
},
{
"vmid": 101,
"name": "alpine-ct",
"kind": "lxc",
"macs": [
"bc:24:11:b7:4c:99"
]
}
],
"backup_job": {
"id": "backup-debian",
"schedule": "*/2:00",
"covered_vmids": [
100
],
"last_expected_run": "2026-11-20T12:00:00+01:00"
},
"backup_run": {
"started_at": "2026-11-20T12:01:08+01:00",
"status": "ok",
"guests": [
{
"vmid": 100,
"result": "ok"
}
]
},
"not_backed_up": [
101
],
"server_evaluation": {
"backup-debian": "ok",
"all_scheduled_backups_ran": true
}
},
"automatic_mapping": {
"vm_asset_id": "9cbbf1c9-b6d2-4d9e-92b9-934c4e2087e7",
"vm_hostname": "debian-guest",
"hypervisor_asset_id": "90d14524-dc01-43af-b84e-defbb751dfd9",
"hypervisor_source": "proxmox",
"audit": "device_hypervisor_detected, match=mac"
},
"token_revocation": {
"revoked_at": "2026-11-20T11:47:02Z",
"observation": "error PROXMOX_TOKEN_REJECTED at 11:47:22Z; other inventory continued; VM link kept",
"restored": "token file removed, HTTPS installer rerun, agent restarted; valid again at 11:47:54Z with unchanged identity"
},
"server_revision_after_fix": "a1b22070de4311d68349419d5268570879e798ee",
"scheduled_backup_failure": {
"method": "target storage local disabled from 13:59 to 14:00:40 CET, re-enabled immediately afterwards; an earlier attempt at 13:00 CET hit no scheduled run because */2:00 means even local hours",
"task": {
"upid": "UPID:pve:00006CA0:000B1402:6B004453:vzdump:100:root@pam:",
"started": "2026-11-20T14:00:03+01:00",
"status": "could not activate storage 'local': storage 'local' is disabled"
},
"observation": {
"observed_at": "2026-11-20T13:00:29Z",
"last_expected_run": "2026-11-20T14:00:00+01:00",
"run_status": "error",
"run_guests": []
},
"finding": "the log of a run failing before its first guest names no guest; the first evaluation reported missed",
"fix": "commit a1b2207: such a job-level or same-guest run marks covered guests failed; pinned by proxmox_pve92_failed_fixture.json",
"server_evaluation": {
"backup-debian": "failed",
"all_scheduled_backups_ran": false
}
},
"not_verified": [
"WebUI rendering of the live host detail page was not viewed with a personal session; the component is covered by vitest and the Playwright fixture",
"missed status on a live host (scheduler stopped over a due time) is covered by unit tests only"
]
}
@@ -0,0 +1,201 @@
{
"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
}
@@ -0,0 +1,99 @@
{
"device": "discwindowstest",
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
"service_account_sid": "S-1-5-19",
"approval_origin": "dev_test_browser_simulation",
"testsimulation": true,
"probes": [
{
"probe": "event_log_access",
"operation_id": "a1c51c29-691e-4b70-aa94-d2967ffece45",
"job_id": "a94170e7-97e4-4092-9cfb-76394f43b891",
"attempt_id": "d01accc7-cb36-4a92-b31a-0a34e5642bd9",
"plan_hash": "09b0d80a2ce0c68300f4a2a2639af2dc7a40a7a75b3011e26ae0e0de7e30bded",
"observed_at": "2026-11-19T10:25:20.806Z"
},
{
"probe": "w32tm_exit_and_event_260_fields",
"operation_id": "9354d97c-dc14-436b-9da5-5c665dbf5ee4",
"job_id": "4a2fd66e-2ba8-4414-a19e-38911e08a1ad",
"attempt_id": "5e1cb739-aac4-48e1-9a7a-72c52aa3a366",
"plan_hash": "e18a81044b5f249709cf18c90df01e6d8a904f9e714ba736341e89a7d3546f14",
"observed_at": "2026-11-19T10:26:17.521Z"
},
{
"probe": "w32tm_status_and_instance_creation_acl",
"operation_id": "174c88c2-bbf9-4f94-9ac3-c2421205b36c",
"job_id": "93546a51-9a55-444d-8a51-0a28b72868a2",
"attempt_id": "4767c1d0-574d-4867-abaf-c4fe5540f5f3",
"plan_hash": "63a34cfa84f8b6cb2c97685ea4cdf3c5a4833d4f47536d5a9b784cb814657ef2",
"observed_at": "2026-11-19T10:27:49.448Z"
},
{
"probe": "w32tm_status_and_pipe_owner_pid",
"operation_id": "f5398a75-358b-41df-8891-41a294f03865",
"job_id": "e38e9eaf-f987-4fcf-8fe6-38b3e1f213f5",
"attempt_id": "89d476f3-de30-48da-8fe9-1259634daa04",
"plan_hash": "d37cbf6ff3b705e1d2b9637cc4f357989e774a8b1201892084abfecd42b82399",
"observed_at": "2026-11-19T10:29:10.112Z"
}
],
"first_w32tm_invocation_exit_observed": false,
"w32time_running": true,
"last_w32tm_query_exit_code": 0,
"last_w32tm_query": {
"leap": 0,
"stratum": 5,
"state": 2,
"root_delay_seconds": 0.0171354,
"root_dispersion_seconds": 1.1443877,
"phase_offset_seconds": 0.0090787,
"last_successful_sync_age_seconds": 6310.7259763
},
"newest_operational_status_event_260": {
"id": 260,
"count": 10,
"last_age_seconds": 28666,
"fields": [
"Configuration",
"TimeProviders",
"LeapIndicator",
"Stratum",
"Precision",
"RootDelay",
"RootDispersion",
"ReferenceId",
"LastSuccessfulSyncTime",
"Source",
"PollInterval",
"PhaseOffset",
"ClockRate",
"StateMachine",
"TimeSourceFlags",
"ServerRole",
"LastSyncError",
"TimeSinceLastGoodSync",
"TickCount"
]
},
"direct_local_w32time_alt_pipe": {
"owner_sid": "S-1-5-19",
"owner_rights": "READ_CONTROL",
"create_instance_sid_matches_w32time": true,
"peer_pid_matches_service_manager": true
},
"existing_native_adapter_max_sync_age_seconds": 3600,
"native_job_clock_accepted": false,
"agent_or_helper_released": false,
"workspace_base_revision": "5a9eafbff17b782081bf0ebe67a75b93122e5eac",
"w32tm_rpc_peer_identity_verified_in_probe": false,
"post_diagnostics": {
"checked_at": "2026-11-19T10:32:09.314887+00:00",
"release_version": "0.1.24",
"release_id": "2032b236-4ab7-4dad-8e74-1144c5a5d165",
"active_jobs": 0,
"agent_ready": true,
"helper_ready": true,
"system_script_capability": true
}
}
@@ -0,0 +1,217 @@
{
"device": "discwindowstest",
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
"source_revision": "b002202d625720694a3792c3e15d3a94719b7099",
"release": {
"version": "0.1.25",
"id": "2a41f8c8-dd1a-46d9-bef1-9ad5cddf5966",
"sequence": 26,
"signing_key_id": "0cd5b3f3e2ddf7669df05e759f48e6398548112fc5c6fd9b9128ef3243561b10",
"authenticated_contact_at": "2026-11-19T10:54:12.386781+00:00",
"local_service_readiness": {
"observed_at": "2026-11-19T10:54:13.672532300Z",
"ready": true,
"helper_ready": true,
"clock_qualified": true,
"counts": {
"accepted": 0,
"requesting": 0,
"running": 0,
"verifying": 0,
"unknown": 0,
"awaiting_reboot": 0,
"events": 0,
"legacy_events": 0
}
},
"running_images": {
"RmmDiscoverySystemHelper": "b7a6a451647bd840524067270ed96fdfea84cd5b2a60d84445eacc90d544c9f1",
"RmmDiscoveryWindows": "a687961919ab30d539105ad7e693666bcd38d26515a11d8d486364ffb156fcf5"
}
},
"direct_pipe_probe_as_localservice": {
"job_id": "e6cad92f-6474-4693-bf1a-73cf72ad81bb",
"state": 2,
"stratum": 5,
"sync_age_seconds": 7203.0809513,
"root_dispersion_seconds": 1.1443877
},
"native_clock_tests_passed": 17,
"job_approval_origin": "dev_test_browser_simulation",
"system_job": {
"operation_id": "fee07cb4-a708-41e9-9690-e84a9b960f64",
"job_id": "49536eaa-dd7a-4f7e-910d-34a120e5c404",
"attempt_id": "cd00f3db-6f57-411f-ad1b-c89e4f83c37d",
"plan_hash": "3115b232e66a0766b075f223165e5e32824329ff2fcefd77e09adb7c91eb6920",
"stdout": "Windows-Konto S-1-5-18",
"exit_code": 0,
"observed_at": "2026-11-19T10:54:54.535Z"
},
"localservice_job": {
"operation_id": "3a82b9f8-6b90-403b-bc07-af3fd5577765",
"job_id": "ea8fc366-cea5-44e5-aea2-92a614b3d584",
"attempt_id": "41915f64-0c33-43b9-a6c2-abe4b5daf2fd",
"plan_hash": "61310d106e488185f8dad1490dde0a21878d744b2e3ceefafef8cad98794399b",
"stdout": "Windows-Konto S-1-5-19",
"exit_code": 0,
"observed_at": "2026-11-19T10:55:15.164Z"
},
"idle_cpu": {
"method": "Deltas of accumulated user and kernel CPU time, normalized to all guest logical CPUs. No active jobs at either endpoint of each measurement.",
"before": [
{
"start": "2026-11-19T10:34:46.3830134Z",
"end": "2026-11-19T10:36:17.5961401Z",
"version": "0.1.24",
"cpu_count": 2,
"duration_seconds": 90.878517,
"journal_bytes": 490684416,
"ledger_bytes": 364482560,
"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.71875,
"cpu_percent": 0.9456,
"read_mib_s": 19.5365,
"write_mib_s": 0.0099
},
"rmm-agent-windows.exe": {
"pid": 404,
"cpu_seconds": 1.46875,
"cpu_percent": 0.8081,
"read_mib_s": 12.3542,
"write_mib_s": 0.0265
}
},
"signed_sync_decisions": 3,
"readiness_samples": 19,
"clock_and_both_processes_ready_samples": 18
},
{
"start": "2026-11-19T10:48:29.8083475Z",
"end": "2026-11-19T10:50:00.9952167Z",
"version": "0.1.24",
"cpu_count": 2,
"duration_seconds": 90.893371,
"journal_bytes": 501288960,
"ledger_bytes": 371404800,
"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": 4168,
"cpu_seconds": 1.609375,
"cpu_percent": 0.8853,
"read_mib_s": 16.8442,
"write_mib_s": 0.015
},
"rmm-agent-windows.exe": {
"pid": 404,
"cpu_seconds": 2.015625,
"cpu_percent": 1.1088,
"read_mib_s": 18.2974,
"write_mib_s": 0.0426
}
},
"signed_sync_decisions": 5,
"readiness_samples": 19,
"clock_and_both_processes_ready_samples": 17
}
],
"after": [
{
"start": "2026-11-19T10:55:17.1079639Z",
"end": "2026-11-19T10:56:48.1011210Z",
"version": "0.1.25",
"cpu_count": 2,
"duration_seconds": 90.804969,
"journal_bytes": 505876480,
"ledger_bytes": 375373824,
"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": 7736,
"cpu_seconds": 0.453125,
"cpu_percent": 0.2495,
"read_mib_s": 3.5594,
"write_mib_s": 0.0106
},
"rmm-agent-windows.exe": {
"pid": 6660,
"cpu_seconds": 0.515625,
"cpu_percent": 0.2839,
"read_mib_s": 2.0611,
"write_mib_s": 0.0297
}
},
"signed_sync_decisions": 3,
"readiness_samples": 19,
"clock_and_both_processes_ready_samples": 19
},
{
"start": "2026-11-19T10:56:51.2093465Z",
"end": "2026-11-19T10:58:22.2709313Z",
"version": "0.1.25",
"cpu_count": 2,
"duration_seconds": 90.875229,
"journal_bytes": 507482112,
"ledger_bytes": 376291328,
"processes": {
"rmm-updater-windows.exe": {
"pid": 2384,
"cpu_seconds": 0.015625,
"cpu_percent": 0.0086,
"read_mib_s": 0.0003,
"write_mib_s": 0.0
},
"rmm-helper-windows.exe": {
"pid": 7736,
"cpu_seconds": 0.984375,
"cpu_percent": 0.5416,
"read_mib_s": 10.2012,
"write_mib_s": 0.0206
},
"rmm-agent-windows.exe": {
"pid": 6660,
"cpu_seconds": 0.671875,
"cpu_percent": 0.3697,
"read_mib_s": 3.283,
"write_mib_s": 0.0803
}
},
"signed_sync_decisions": 5,
"readiness_samples": 19,
"clock_and_both_processes_ready_samples": 18
}
],
"weighted_mean_percent": {
"agent": {
"before": 0.9584,
"after": 0.3268
},
"system_helper": {
"before": 0.9155,
"after": 0.3956
}
}
}
}
@@ -0,0 +1,36 @@
{
"source_revision": "037b5e39fa5c23689984061efded0628e6914dab",
"platform": "x86_64-pc-windows-gnu",
"release": {
"version": "0.1.26",
"sequence": 27,
"release_id": "979ff20e-e412-402f-85ea-fa6c50ae4b7b",
"manifest_sha256": "31d22becc730eb4a2817dcd9b6aee2924b3416d3956c9a8b1bc6d2f79749499e",
"minimum_updater_version": 2,
"published_to_affected_customer": true,
"official_windows_starter": true
},
"native_windows_tests": {
"display_version_has_priority": "passed",
"missing_display_version_uses_release_id": "passed",
"missing_version_labels_keep_product_and_build": "passed",
"existing_windows_inventory_collection": "passed"
},
"native_test_vm_self_update": {
"previous_sequence": 26,
"installed_sequence": 27,
"same_agent_identity": true,
"new_heartbeat_at_utc": "2026-11-19T15:35:18.825174Z",
"updater_status": "ok",
"updater_status_at_utc": "2026-11-19T15:35:21.661912200Z",
"running_agent_sha256": "a23edbe35c089e1788939c42274dba58ad5b33bf344997fb85b023355b97de64",
"running_helper_sha256": "68a952a4d42375bc4119486c72f4714ca47e72348e15ef013eda9892614f088d"
},
"affected_device": {
"enrollment_accepted": true,
"last_observed_version": "0.1.22",
"local_error": "OS_REGISTRY",
"display_version_missing_confirmed_by_operator": true,
"updated_and_reported_first_heartbeat": "not yet observed"
}
}
+1
View File
@@ -12,6 +12,7 @@
| MCP und Administrator-Skripte | [Werkzeuge](../crates/server/src/mcp.rs), [Tokenrechte](../crates/server/src/mcp_tokens.rs), [Helper und zentrale Geräteregel](../crates/server/src/managed_scripts.rs) |
| Geräteaufnahme und Releasewechsel | [HTTPS-Installer und Lebenszyklus](../crates/server/src/bootstrap), [Releasekatalog](../crates/server/src/agent_updates.rs), [Signaturprüfung](../crates/updater/src/manifest.rs) |
| Native Laufzeiten | [Linux-Agent](../crates/agent/src/main.rs), [Linux-Inventar und Skripte](../crates/agent-linux/src), [Windows-Agent](../crates/agent-windows/src/runtime.rs), [Agentprotokoll](../proto/BACKEND_CONTRACT.md) |
| Proxmox-Host und VM-Zuordnung | [Sammelmodul](../crates/agent-linux/src/inventory/proxmox.rs), [Validierung und Backupbewertung](../crates/domain/src/inventory_document/proxmox.rs), [automatische Zuordnung](../crates/server/src/proxmox_links.sql), [Detailansicht](../web/src/proxmox.tsx), [Betrieb](../deploy/proxmox/README.md) |
## Einen vorhandenen Auftrag nachvollziehen
+17 -1
View File
@@ -13,11 +13,25 @@
## Ergänzungen zur Geräteansicht
- **Linux-Festplatten, 20.11.2026:** Der x64-Testgast meldete `sda` (38,1 GiB, mehrere Partitionen) und `sdb` (110 GiB) jeweils einmal, ohne das DVD-Laufwerk. Auf ARM64 wurde `sda` mit Modell, Kapazität und rot/grün/grauer Aufteilung in der öffentlichen Geräteübersicht geprüft. Die [Zuordnungstests](../crates/agent-linux/src/inventory/disks.rs) decken doppelte Mounts, mehrere Partitionen, einen RAID-Verbund und unbekannte Belegung ab. Auf `dev-znuny-db` konnte der Updater nach der gültigen Inventarmeldung die erforderliche Helper-Bindung nicht bestätigen: Der konfigurierte Helper gehört zur Identität vor dem Kundenwechsel. Der Updater stellte Sequenz 13 wieder her; die Rückkehrbestätigung ist offen. Der Update-Timer wurde auf diesem Gast gestoppt (weiterhin `enabled`), um wiederholte Agentneustarts zu vermeiden. Vor Wiederaufnahme die kundenspezifische Helper-Einrichtung klären, den regulären Wiederanlauf prüfen und eine höhere signierte Sequenz verwenden. [Gerätenachweis](evidence/linux-whole-disks-20261120.json)
- **Windows-Laufwerke, 20.11.2026:** Der signierte Client `0.1.27` aus `52c352c` (Sequenz 28) wurde auf Basis des ausgelieferten `0.1.26` gebaut. Die native Probe auf `discwindowstest` erkannte neben `C:` zwei temporäre lokale Testbuchstaben `X:` und `Y:`; das DVD-Laufwerk `D:` fehlte wie vorgesehen. Die Buchstaben waren Testzuordnungen auf demselben Volume. Nach dem regulären Update meldete der echte Dienst unter seiner bisherigen Geräteidentität `C:` mit Kapazität und freien Bytes. Server und WebUI `04037c7` zeigen ein eigenes Wertepaar pro Laufwerk. [Browserprüfung mit drei Laufwerken](../tests/browser/customer-management.spec.ts) · [Abwärtskompatible Projektion](../crates/server/src/devices.rs)
- **Belegt / gesamt, 20.11.2026:** Bei 12 GiB frei von 16 GiB zeigte die Geräteübersicht für Speicher und RAM jeweils „4 / 16 GiB“ und „25 % belegt“. Die [Browserprüfung](../tests/browser/customer-management.spec.ts) bestätigte Farben und Segmentbreiten (rot belegt, grün frei) bei 0 %, 25 % und 100 % Belegung auf 1280, 900 und 390 px. Fehlende oder widersprüchliche Messwerte ergaben keine Belegungsangabe.
- **Speicherbalken, 20.11.2026:** Die Geräteübersicht verwendet für Laufwerk und RAM dieselbe Darstellung. Die [Browserprüfung](../tests/browser/customer-management.spec.ts) bestätigte für beide Spalten bei 1280, 900 und 390 px die Segmentbreiten und Beschriftungen für 0 %, 75 % und 100 % frei. Bei fehlenden oder ungültigen Werten erschien kein Balken.
- **OPNsense-Standardaufträge, 20.11.2026:** Server/WebUI `2e3916b`, Schema 47, Client `0.1.0-opnsense.6`. Im öffentlichen Browser fehlt der frühere Sonderknopf im Gerätedetail. Über **Aufträge** wurden ein einmaliges POSIX-Skript `id -u` als `root` und die mitgelieferte Bibliotheksrevision „OPNsense · Version und Ausführungskonto“ v1 als Dienstkonto eingereicht. Beide standen beim Nachlesen auf `pending_approval`, ohne Jobs oder Grants. Derselbe Gast meldete Agent- und Helper-Abgleich bereit. Ein separater nativer Test des installierten FreeBSD-Helpers mit Wegwerfschlüssel und unabhängigen Journalen lieferte UID 0 und bestätigte nach Wiederzustellung nur einen Start. Fremder Peer, manipuliertes Skript, ungültige Signatur und falsche Verbindung wurden abgelehnt. Für die Live-Abnahme fehlen die persönlichen Freigaben und Ergebnisse dieser beiden Versuche. [Nachweis](evidence/opnsense-root-orders-20261120.json)
- **OPNsense-Kernelabfrage, 20.11.2026 — abgenommen:** Vor der persönlichen Freigabe hatte der [Geräteantrag](evidence/opnsense-probe-submission-20261119.json) null Jobs, Outbox-Einträge und Startgrants. Danach lieferte genau der geplante Versuch `ea526a57…` auf der bestehenden VM `FreeBSD\n`, Exitcode 0, als `discovery` (UID 1001). Server und Gastjournal meldeten `succeeded`, Revision 2. Ein ausgestellter Startgrant, ein lokaler Verbrauch mit Start- und Ergebnisbeleg. Der getrennte native Integrationstest prüfte die doppelte Zustellung. [End-to-End-Ergebnis](evidence/opnsense-probe-result-20261120.json)
- **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)
- **Proxmox-VE-Host, 20.11.2026:** Lokale VM mit Proxmox VE 9.2 per HTTPS-Installer aufgenommen. Der Installer legte `rmm-discovery@pve` mit privilegiengetrenntem `PVEAuditor`-Token an, der Agent läuft unprivilegiert und aktualisierte sich regulär von `0.1.0-mvp.14` auf `0.1.0-mvp.15`. `linux.proxmox` meldete VM 100 und Container 101 mit MACs, den Job `backup-debian` (`*/2:00`) und den erfolgreichen Lauf von 12:01 Uhr; Bewertung „Gelaufen“, Container 101 „Ohne Backupjob“. Der Linux-Agent in VM 100 wurde über die MAC automatisch dem Host zugeordnet (`hypervisor_source = proxmox`, Audit `device_hypervisor_detected`). Nach Tokenwiderruf meldete der Bereich `PROXMOX_TOKEN_REJECTED`, die übrige Inventur und die Zuordnung blieben; Wiederherstellung über den Installer. Der geplante Lauf um 14:00 Uhr schlug bei deaktiviertem Storage fehl. Er nannte keinen Gast und wurde zunächst als „verpasst“ bewertet; seit `a1b2207` gilt er als „fehlgeschlagen“. Die Live-Detailseite wurde nicht mit persönlicher Sitzung angesehen. Das Release kam in den Katalog von Kunde `9d730e0a-…` einmalig per direktem Datenbankeintrag mit Freigabe des Betreibers und Auditvermerk. [Gerätenachweis](evidence/proxmox-host-20261120.json) · [Betrieb](../deploy/proxmox/README.md)
## 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.
@@ -39,10 +53,12 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
| RAM und CPU-Auslastung in der Übersicht | RAM als verfügbar / gesamt in GiB mit demselben Belegungsbalken wie beim Speicherplatz. Die CPU-Spalte zeigt die letzte gemessene Auslastung in Prozent. Am 18. November wurde `6ed57c4` mit Schema 41 produktiv aktiviert. Beide TLS-Healthchecks und der öffentliche WebUI-Index stimmten mit dem Build überein. Die öffentliche Übersicht zeigte die RAM-Balken auf Desktop und bei 390 px Breite für alle drei Geräte. Die Detailansicht und die automatische Aktualisierung wurden in Chromium auf Linux x64 und ARM64 nachgelesen. OTRS meldete um 18:05 UTC nach dem signierten Wechsel auf `0.1.0-arm64.3` `6,2 / 7,6 GiB` und `1,1 %`. Um 18:06 UTC meldeten Linux x64 `0.1.0-mvp.9`, Windows `0.1.18` und ARM64 frische CPU-Werte und waren authentisiert erreichbar. [Geräteansicht](../web/src/devices.tsx) · [Geräteprojektion](../crates/server/src/devices.rs) |
| Gerätetyp in der Übersicht | Spalte „Type“ nach „Hostname“ mit `physical`, `virtual` und `hypervisor`. Erkannte Proxmox-VE-Hosts zeigen `Proxmox VE` als OS. Am 18. November wurde `c599baa` auf dem öffentlichen Server aktiviert. Der Serverrunner bestätigte API, Gateway und öffentlichen API-Dienst mit Binärhash `4f9c8c60…`. Der öffentliche WebUI-Index stimmte mit dem gebauten Bundle überein. Die unveränderten Geräteidentitäten meldeten nach regulärem signierten Update `virtual` auf Linux mit `0.1.0-mvp.7` um 16:45 UTC und Windows mit `0.1.17` um 16:47 UTC. Geräteliste, Details, Mobilansicht mit 390 px und Historie sind in der öffentlichen WebUI geprüft. Beide Pakete sind in Development A und B und als Starter für leere Kataloge veröffentlicht. Die Typen `physical` und `hypervisor` sind mit Testdaten geprüft. Die Feldabnahme auf einem physischen Gerät und einem Proxmox-VE-Host steht aus. [Inventarprojektion](../crates/server/src/devices.rs) · [Geräteansicht](../web/src/devices.tsx) |
| Hostzuordnung bei VMs | Die WebUI zeigt einen zugeordneten Hypervisor direkt an der VM. Der Browsertest prüfte Zuordnung, Verlinkung, Entfernen und den Hetzner-Platzhalter bei 390 px Breite. In PostgreSQL wurden die Page-Grenze, archivierte Hypervisoren und die Trennung der Kunden geprüft. 80 WebUI-Tests, vier Browsertests und fünf Rust-Gerätetests bestanden. Revision `bcd3bd8` wurde am 18. November um 21:43 UTC mit Schema 43 aktiviert. Der Serverrunner bestätigte die TLS-Healthchecks und der öffentliche Index entsprach dem Build. In der öffentlichen WebUI zeigten zwei vorhandene Hetzner-VMs den Platzhalter auf Desktop und Mobil. Die Auswahl war im Gerätedetail verfügbar. Der Bestand enthielt zum Prüfzeitpunkt keinen registrierten Hypervisor. [Geräteansicht](../web/src/device-hypervisor.tsx) · [Hostsuche](../crates/server/src/hypervisors.sql) |
| Gruppierte Geräteübersicht | Der Bestand zeigt je Hypervisor einen Block mit Host und eingerückten VMs, danach „Hetzner Cloud“, „Physische Geräte“ und „Nicht zugeordnet“. Am 20. November bestanden 87 WebUI-Tests, darunter vier zur Gruppierung (Reihenfolge, Host außerhalb der Seite, Kundentrennung, manuell zugeordneter Host), und die lokale Browsersuite mit dem angepassten Zuordnungstest bei 390 px Breite. Desktop- und Mobildarstellung wurden mit Beispieldaten im Browser angesehen. Eine Sichtprüfung mit persönlicher Sitzung auf dem Entwicklungsserver steht aus. [Gruppierung](../web/src/device-groups.ts) · [Geräteliste](../web/src/devices.tsx) |
| 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) |
| Erste Windows-Meldung ohne `DisplayVersion` | Bei einem betroffenen Gerät nahm das Gateway das Enrollment und die authentisierten Verbindungsaufbauten an, erhielt aber weder Inventar noch Heartbeat. Windows GNU `0.1.26` aus `037b5e3` nutzt bei fehlendem `DisplayVersion` den Registrywert `ReleaseId` oder meldet Produkt und Build ohne Versionsbezeichnung. Drei Regressionen und die Inventarprobe liefen nativ auf der Windows-Test-VM. Das offiziell signierte Paket (Sequenz 27) ist im Katalog des betroffenen Kunden und als Starter für neue Windows-Kataloge verfügbar. Die Test-VM übernahm das reguläre Update, meldete einen neuen Heartbeat mit derselben Identität und startete beide signierten Binärdateien mit den erwarteten Hashes. Die erneute Meldung des betroffenen Geräts mit derselben Identität steht aus. Bei durch den Erstkontakt blockiertem Installer den vorhandenen `RmmDiscoveryReleasePull` lokal starten; nach erfolgreichem Update den Installer mit derselben Identität abschließen. [Nachweis](evidence/windows-missing-display-version-20261119.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) |
| 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) Der lokale Windows-Zeitstatus konnte am 19. November lesend unter LocalService abgefragt werden. Der Testgast meldete Synchronisierung mit Stratum 5 bei rund 105 Minuten seit der letzten erfolgreichen Synchronisierung. Das Betriebsprotokoll lieferte knapp acht Stunden alte Statusdaten. Der direkt geprüfte Pipe-Handle gehörte zu W32Time. Für die tatsächliche Statusverbindung und den SYSTEM-Helper steht die native Qualifikation aus. Die Umstellung war bei dieser Diagnose offen. Agent und SYSTEM-Helper meldeten mit Version `0.1.24` weiterhin Bereitschaft. [Zeitstatus und Prüfergebnis](evidence/windows-local-clock-20261119.json) Windows GNU `0.1.25` aus `b002202` prüft die Systemzeit bei regulär aufgenommenen Geräten lokal über W32Time. Agent und SYSTEM-Helper prüfen unabhängig die Identität der Statusverbindung, den Synchronisationsstatus, den Zeitfehler und die Kontinuität. 17 native Uhrtests bestanden. Der Testgast übernahm das signierte Paket mit unveränderter Geräteidentität und bestätigte beide laufenden Binärhashes. Die in der Entwicklungs-WebUI genehmigten Aufträge lieferten je einen Startgrant, Exitcode 0 und `S-1-5-18` für SYSTEM beziehungsweise `S-1-5-19` für LocalService. Im Mittel aus jeweils zwei rund 91 Sekunden langen Leerlaufmessungen sank die Gast-CPU-Last von 0,96 % auf 0,33 % beim Agenten und von 0,92 % auf 0,40 % beim Helper. [Native Abnahme der lokalen Uhrprüfung](evidence/windows-local-clock-release-20261119.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) |
+2 -1
View File
@@ -11,6 +11,7 @@ Die Werkzeuge werden im Repository als Eigentümer der lokalen Entwicklungsprofi
| `server` | Dedizierter ARM64-Host `discovery.ease-technologies.de` | `server.conf`, vorhandener SSH-Schlüssel und geprüfter Hostkey |
| `linux` | Cloud-Linux-Gast `dev-znuny-db` | `linux-vm.conf`, vorhandener SSH-Schlüssel und geprüfter Hostkey |
| `windows` | Windows-11-Gast `discwindowstest` | `windows-dev-access.json`, `windows-dev.known_hosts`, Alias `rmm-windows-dev` und SSH-Rückkanal über den Server |
| `proxmox` | Lokale Proxmox-VE-9.2-VM `pve.discovery.lan` (`192.168.122.50`) auf dem Notebook | `proxmox-vm.conf`, eigener Schlüssel `proxmox-dev-key`, Hostpin `proxmox-dev.known_hosts` (beim ersten Start im NAT-Netz `default` der frisch installierten VM erfasst) |
Der folgende Befehl liest vom Wurzelverzeichnis des Worktrees aus den Hostnamen der Linux-Test-VM.
@@ -23,7 +24,7 @@ subprocess.run([*ssh_prefix("linux"), "hostname"], check=True, timeout=20)
PY
```
`ssh_prefix` verwendet Batchbetrieb, bestehende Schlüssel und strikte Hostprüfung. Die Hostpins für Server und Linux stehen im vorhandenen SSH-Truststore des Benutzers (`~/.ssh/known_hosts`). Windows verwendet die oben genannte separate Hostpindatei. Für Windows wird der geprüfte Proxyweg mit dem gespeicherten Profil abgeglichen. Vor Änderungen an einem Pin den neuen Fingerabdruck unabhängig mit dem Zieladministrator bestätigen. [SSH-Auflösung und Staging](../tools/dev_stage.py)
`ssh_prefix` verwendet Batchbetrieb, bestehende Schlüssel und strikte Hostprüfung. Die Hostpins für Server und Linux stehen im vorhandenen SSH-Truststore des Benutzers (`~/.ssh/known_hosts`). Windows und Proxmox verwenden die oben genannten separaten Hostpindateien. [Proxmox-Testhost](../deploy/proxmox/README.md#testhost-auf-dem-entwicklungsnotebook) Für Windows wird der geprüfte Proxyweg mit dem gespeicherten Profil abgeglichen. Vor Änderungen an einem Pin den neuen Fingerabdruck unabhängig mit dem Zieladministrator bestätigen. [SSH-Auflösung und Staging](../tools/dev_stage.py)
## Interne Test-WebUI
+9
View File
@@ -0,0 +1,9 @@
# Produktentscheidungen
## Lokaler Zeitstatus für Windows-Aufträge · 19. November 2026
Die Uhrprüfung des Windows-Agenten und des SYSTEM-Helpers soll denselben Zweck und dieselbe Vertrauensbasis wie unter Linux haben. Beide Prozesse prüfen vor zeitgebundenen Auftragsentscheidungen die lokale Betriebssystemuhr auf Synchronisierung, Unsicherheit und Zeitsprünge. Die Prüfung muss mit den bestehenden Dienstkonten auskommen. Mit der Umstellung entfallen die separaten signierten RMM-Zeitabfragen für diese Prozesse. Signaturen, Genehmigung sowie Zeit- und Versuchsbindung der Aufträge gelten weiterhin.
Der signierte Zeitvergleich wurde am 14. November als Windows-Ausweichlösung vereinbart, nachdem der Statusabruf und die Herkunft des abgerufenen Status offen geblieben waren. Die erste Diagnose am 19. November bestätigte die lesende Abfrage als LocalService und die Identität des Zeitdienstes am separat geöffneten Pipe-Handle. Der damalige Kandidat verlangte einen höchstens 60 Minuten alten Abgleich. Der Testgast meldete rund 105 Minuten. [Erste Diagnose](evidence/windows-local-clock-20261119.json)
Der lokale Adapter verwendet die Pipe, deren Serverprozess er über die Windows-Dienstverwaltung W32Time zuordnet, für die gesamte verschlüsselte und signierte Statusabfrage. Er verwendet die gemeldete Synchronisierung und den Zeitpunkt des letzten erfolgreichen Abgleichs. Ein ausgefallener Abruf oder ein älteres Paket des Zeitservers kann die Synchronisierung weiter gültig lassen, solange der letzte erfolgreiche Abgleich und die Fehlergrenze sie tragen. Die Prüfung berücksichtigt die mit dem Alter wachsende Unsicherheit. Jeder Prozess hält einen gültigen Status höchstens fünf Sekunden im Speicher und prüft bei seiner Verwendung erneut die Kontinuität der lokalen Uhr. Die Auftragsausführung setzt die lokale W32Time-Pipe und die dafür verwendete NTLM-Authentisierung voraus. [Windows-Zeitstatus](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/f60ebce0-df96-4c96-b40b-fdbd34a2c936) · [NTP-Fehlermodell](https://www.rfc-editor.org/rfc/rfc5905#section-9)
+3 -1
View File
@@ -4,10 +4,12 @@ Die öffentliche WebUI verwendet ein lokales Benutzerkonto mit Passwort und eine
## Geräte und Kunden
**Geräte** zeigt bestätigte Online- und Offline-Geräte der berechtigten Kunden mit Hostname, Betriebssystem, Status, freiem und gesamtem Speicherplatz, RAM, CPU und Kunde. Die Historie enthält unter anderem archivierte und widerrufene Installationen. Ein Klick auf den Hostnamen öffnet das Inventar und die letzten Aufträge. Der Kundenname in der Kopfzeile zeigt, in welchem Kunden die nächste Änderung erfolgt.
**Geräte** zeigt bestätigte Online- und Offline-Geräte der berechtigten Kunden mit Hostname, Betriebssystem, Status, Speicher, RAM, CPU und Kunde. Speicher und RAM stehen als **belegt / gesamt** in GiB. Ab Windows-Client `0.1.27` erscheinen nach der nächsten Inventur alle lokalen Festplattenlaufwerke mit Buchstaben untereinander, jeweils mit eigenem Balken (rot belegt, grün frei). Ein DVD- oder Netzlaufwerk zählt nicht dazu. Ältere Clients melden nur die Systemplatte. Die Historie enthält unter anderem archivierte und widerrufene Installationen. Ein Klick auf den Hostnamen öffnet das Inventar und die letzten Aufträge. Der Kundenname in der Kopfzeile zeigt, in welchem Kunden die nächste Änderung erfolgt.
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)
**Linux-Speicher ab x64 `0.1.0-mvp.14` bzw. ARM64 `0.1.0-arm64.8`:** Unter **Speicher belegt / gesamt** steht beispielsweise `sda` einmal, auch wenn `/` und `/boot` auf unterschiedlichen Partitionen derselben Platte liegen. Grau bedeutet „nicht zugeordnet“: Dazu gehören nicht nutzbare Reserven und Platz, dessen Belegung nicht messbar ist. Ein vollständig grauer Balken bedeutet nicht, dass die Platte leer ist. RAID, LVM und ZFS können eigene Verbundzeilen haben. Diese Werte nicht zu den Plattengrößen addieren. In einer VM sieht der Agent nur die vom Host bereitgestellten Platten.
### 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.
+47
View File
@@ -0,0 +1,47 @@
-- As with the Linux/Windows starting revisions, preserve any existing customer revision.
CREATE FUNCTION seed_opnsense_scripts(target_tenant uuid) RETURNS void
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
BEGIN
PERFORM set_config('app.tenant_id', target_tenant::text, true);
INSERT INTO public.script_revisions(tenant_id,name,version,interpreter,execution_identity,created_by,script_utf8)
SELECT target_tenant,name,1,'posix_sh',identity,'system:bootstrap',body
FROM (VALUES
('OPNsense · Version und Ausführungskonto','agent_service',$sh$#!/bin/sh
set -eu
/usr/local/sbin/opnsense-version
/usr/bin/uname -sr
/usr/bin/id
$sh$),
('OPNsense · Aktive Firewallregeln anzeigen','root',$sh$#!/bin/sh
set -eu
[ -x /usr/local/sbin/opnsense-version ]
exec /sbin/pfctl -sr
$sh$)) AS scripts(name,identity,body)
ON CONFLICT (tenant_id,name,version) DO NOTHING;
PERFORM set_config('app.tenant_id', previous_tenant, true);
END
$$;
REVOKE ALL ON FUNCTION seed_opnsense_scripts(uuid) FROM PUBLIC;
CREATE OR REPLACE FUNCTION seed_tenant_script_library() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
BEGIN
PERFORM set_config('app.tenant_id', NEW.tenant_id::text, true);
PERFORM public.seed_windows_update_script(NEW.tenant_id);
PERFORM public.seed_standard_diagnostic_scripts(NEW.tenant_id);
PERFORM public.seed_restart_scripts(NEW.tenant_id);
PERFORM public.seed_windows_restart_receipt(NEW.tenant_id);
PERFORM public.seed_opnsense_scripts(NEW.tenant_id);
PERFORM set_config('app.tenant_id', previous_tenant, true);
RETURN NEW;
END
$$;
DO $$
BEGIN
LOCK TABLE tenants IN SHARE ROW EXCLUSIVE MODE;
PERFORM public.seed_opnsense_scripts(tenant_id) FROM tenants;
END
$$;
+10
View File
@@ -0,0 +1,10 @@
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '30s';
-- NULL: no automatic decision yet, 'proxmox': set from a Proxmox host's guest list,
-- 'manual': chosen by a person and never overwritten by automatic detection.
ALTER TABLE assets
ADD COLUMN hypervisor_source text,
ADD CONSTRAINT assets_hypervisor_source_check
CHECK (hypervisor_source IN ('manual','proxmox'));
UPDATE assets SET hypervisor_source='manual' WHERE hypervisor_asset_id IS NOT NULL;
GRANT UPDATE (hypervisor_source) ON assets TO rmm_app;
+88 -33
View File
@@ -20,7 +20,7 @@ test.beforeAll(async () => {
test.afterAll(async () => { await server?.close(); });
test('draws the free RAM share accurately on desktop and mobile', async ({ page }) => {
test('shows used disk and RAM in GiB and draws the occupied share in red on desktop and mobile', async ({ page }) => {
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'RAM-Test' };
const gib = 2 ** 30;
const readings = [
@@ -30,6 +30,7 @@ test('draws the free RAM share accurately on desktop and mobile', async ({ page
['missing-available', null, 16 * gib],
['invalid-range', 17 * gib, 16 * gib],
['invalid-total', 0, 0],
['linux-drives', null, null],
] as const;
const listing = (items: unknown[]) => ({
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-19T12:00:00Z'
@@ -48,32 +49,63 @@ test('draws the free RAM share accurately on desktop and mobile', async ({ page
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
disk_free_bytes: free, disk_total_bytes: total,
...(hostname === 'linux-drives' ? {disks:[
{kind:'disk',name:'sda',model:'Testplatte',total_bytes:64*gib,used_bytes:16*gib,available_bytes:40*gib},
{kind:'disk',name:'sdb',total_bytes:64*gib,used_bytes:null,available_bytes:null},
{kind:'group',name:'md0',members:['sda','sdb'],total_bytes:8*gib,used_bytes:2*gib,available_bytes:6*gib}
]} : {}),
...(hostname === 'mostly-free' ? { volumes: [
{ name: 'C:', free_bytes: free, total_bytes: total },
{ name: 'D:', free_bytes: 0, total_bytes: 64 * gib },
{ name: 'E:', free_bytes: null, total_bytes: null }
] } : {})
})))
});
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 label of ['RAM', 'Speicher']) {
const cell = (host: string) => {
const column = row(host).locator(`[data-label="${label} belegt / gesamt"]`);
return host === 'mostly-free' && label === 'Speicher'
? column.locator('.drive-capacity').filter({ hasText: 'C:' }) : column;
};
for (const [host, used, usedGiB] of [['mostly-free', 25, 4], ['all-used', 100, 16], ['all-free', 0, 0]] as const) {
await expect(cell(host)).toContainText(`${usedGiB} / 16 GiB`);
await expect(cell(host).locator('.capacity-caption')).toHaveText(`${used} % belegt`);
const bar = cell(host).getByRole('img', { name: `${used} % belegt, ${100 - used} % frei` });
await expect(bar).toBeVisible();
await expect(bar.locator('.capacity-used')).toHaveCSS('background-color', 'rgb(199, 137, 128)');
await expect(bar.locator('.capacity-free')).toHaveCSS('background-color', 'rgb(46, 118, 87)');
const [track = 0, usedWidth = 0, freeWidth = 0] = await bar.evaluate(el => [el, ...Array.from(el.children)]
.map(part => part.getBoundingClientRect().width));
expect(track).toBeGreaterThan(0);
expect(usedWidth / track).toBeCloseTo(used / 100, 2);
expect(freeWidth / track).toBeCloseTo((100 - used) / 100, 2);
}
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) {
await expect(cell(host).locator('.capacity-track')).toHaveCount(0);
await expect(cell(host)).toHaveText(host === 'invalid-total' ? 'Nicht gemeldet' : '– / 16 GiB');
}
}
}
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) {
await expect(ram(host).locator('.capacity-track')).toHaveCount(0);
const drives = row('mostly-free').locator('.drive-capacity');
await expect(drives).toHaveCount(3);
await expect(drives.nth(1)).toContainText('D: 64 / 64 GiB');
await expect(drives.nth(1).getByRole('img', { name: '100 % belegt, 0 % frei' })).toBeVisible();
await expect(drives.nth(2)).toHaveText('E: Nicht gemeldet');
await expect(drives.nth(2).getByRole('img')).toHaveCount(0);
const linux = row('linux-drives').locator('.drive-capacity');
await expect(linux).toHaveCount(3);
await expect(linux.nth(0)).toContainText('16 / 64 GiB');
await expect(linux.nth(0).getByRole('img',{name:'25 % belegt, 62,5 % frei, 12,5 % nicht zugeordnet'})).toBeVisible();
await expect(linux.nth(1)).toContainText('Belegung nicht ermittelbar');
await expect(linux.nth(1)).toContainText('Im Verbund: md0');
await expect(linux.nth(2)).toContainText('Verbund: md0');
await expect(linux.nth(2)).toContainText('2 / 8 GiB');
}
});
@@ -167,12 +199,10 @@ test('creates and renames a customer, opens its inventory, and hides editing for
await expect(headers.nth(1)).toHaveText('Type');
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).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%;');
const memory = device.locator('[data-label="RAM belegt / gesamt"]');
await expect(memory).toContainText('10 / 16 GiB');
await expect(memory.getByRole('img', { name: '62,5 % belegt, 37,5 % frei' })).toBeVisible();
await expect(device.locator('[data-label="Speicher belegt / gesamt"]').getByRole('img', { name: '25 % belegt, 75 % frei' })).toBeVisible();
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' });
await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click();
@@ -356,10 +386,25 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
lifecycle: 'current', status: 'online', recent_jobs: [], volumes: [] };
const vm = { ...base, hostname: 'Test-VM', asset_id: 'vm-asset', agent_id: 'vm-agent', device_type: 'virtual' };
const pve = { ...base, hostname: 'pve-01', asset_id: 'pve-asset', agent_id: 'pve-agent',
device_type: 'hypervisor', os: 'Proxmox VE' };
device_type: 'hypervisor', os: 'Proxmox VE', tenant_id: tenant,
proxmox: { quality: 'valid', error_code: null, observed_at: new Date().toISOString(), truncated: false,
data: { node: 'pve-01', cluster: null, version: '9.2.2', not_backed_up: [101],
guests: [
{ vmid: 100, name: 'Test-VM', kind: 'qemu', status: 'running', template: false, cpus: 2,
memory_bytes: 2 ** 31, disk_bytes: 2 ** 33, macs: ['bc:24:11:00:00:01'] },
{ vmid: 101, name: 'alpine-ct', kind: 'lxc', status: 'stopped', template: false, cpus: 1,
memory_bytes: 2 ** 27, disk_bytes: 2 ** 30, macs: [] }],
backup_jobs: [{ id: 'backup-nightly', enabled: true, schedule: '21:00', storage: 'local',
selection: 'vmid', covered_vmids: [100], last_expected_run: 1795118400, next_run: 1795204800 }],
backup_runs: [] },
backup_status: { all_scheduled_backups_ran: false, enabled_jobs: 1, problem_jobs: 1,
last_success_at: {}, jobs: [{ id: 'backup-nightly', status: 'missed',
guests: [{ vmid: 100, status: 'missed', last_success_at: null }] }] },
guest_devices: [{ vmid: 100, asset_id: 'vm-asset', agent_id: 'vm-agent', hostname: 'Test-VM', source: 'proxmox' }] } };
const placeholder = { kind: 'placeholder', provider: 'hetzner', hostname: 'Hetzner Cloud' };
let assigned = false;
const guest = () => ({ ...vm, assigned_hypervisor_asset_id: assigned ? pve.asset_id : null,
hypervisor_source: assigned ? 'manual' : null,
hypervisor: assigned ? { kind: 'device', hostname: pve.hostname, asset_id: pve.asset_id, agent_id: pve.agent_id } : placeholder });
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
@@ -396,9 +441,10 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
});
await page.goto(origin + '/#geraete');
const vmRow = page.getByRole('row').filter({ has: page.getByRole('button', { name: vm.hostname }) });
await expect(vmRow).toContainText('Hetzner Cloud');
await expect(vmRow).toContainText('Platzhalter');
const block = (name: string) => page.getByRole('group', { name });
await expect(block('Hetzner Cloud')).toContainText('Platzhalter');
await expect(block('Hetzner Cloud').getByRole('button', { name: vm.hostname })).toBeVisible();
await expect(block('Hypervisor pve-01')).toContainText('Keine zugeordneten virtuellen Maschinen');
await expect(page.getByRole('button', { name: 'Hetzner Cloud' })).toHaveCount(0);
await expect(page.locator('.fleet-table tbody tr')).toHaveCount(2);
await page.getByRole('button', { name: vm.hostname }).click();
@@ -410,11 +456,20 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
await expect(page.getByText('Hypervisor zugeordnet.', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await page.setViewportSize({ width: 390, height: 844 });
const hostLink = vmRow.getByRole('link', { name: pve.hostname });
await expect(hostLink).toBeVisible();
await expect(vmRow).not.toContainText('Hetzner Cloud');
await hostLink.click();
const hostBlock = block('Hypervisor pve-01');
await expect(hostBlock.locator('tbody tr')).toHaveCount(2);
await expect(hostBlock.locator('tbody tr').first()).toContainText(pve.hostname);
await expect(hostBlock.locator('tr.guest')).toContainText(vm.hostname);
await expect(hostBlock.locator('tr.guest')).toContainText('manuell zugeordnet');
await expect(hostBlock).toContainText('1 virtuelle Maschine');
await expect(block('Hetzner Cloud')).toHaveCount(0);
await hostBlock.getByRole('link', { name: pve.hostname }).click();
await expect(page.getByRole('heading', { name: pve.hostname })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Virtuelle Maschinen und Container' })).toBeVisible();
await expect(page.getByRole('row').filter({ hasText: 'alpine-ct' })).toContainText('Container');
await expect(page.getByRole('row').filter({ hasText: 'backup-nightly' })).toContainText('Verpasst');
await expect(page.getByText('Nicht alle geplanten Backups sind gelaufen.')).toBeVisible();
await expect(page.getByRole('link', { name: 'Test-VM' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await page.getByRole('button', { name: vm.hostname }).click();
await page.getByText('Gerät verwalten', { exact: true }).click();
@@ -423,5 +478,5 @@ test('shows real VM hosts and the Hetzner placeholder without adding a device',
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
await expect(page.getByText('Hostzuordnung entfernt.', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await expect(vmRow).toContainText('Hetzner Cloud');
await expect(block('Hetzner Cloud').getByRole('button', { name: vm.hostname })).toBeVisible();
});
+1 -1
View File
@@ -568,7 +568,7 @@ test('publishes versions in the library and keeps the earlier script readable',
await page.getByRole('button', { name: 'Version veröffentlichen' }).click();
await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.');
await page.getByText('Frühere Versionen (1)').click();
await page.getByText('Version 1 · Linux · Shell · Agent-Dienstkonto').click();
await page.getByText('Version 1 · POSIX-Shell · Agent-Dienstkonto').click();
await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click();
await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1);
+54
View File
@@ -0,0 +1,54 @@
"""Register an explicitly pinned FreeBSD helper in the existing managed-script policy."""
import argparse
import fcntl
import inspect
import json
import re
import stat
import subprocess
import uuid
from dev_linux_helper_rollover import POLICY, encoded, protected, replace, require
from dev_stage import ssh_prefix
def register(path, scope):
uid=(path.parent.parent/'jobs/ed25519.pem').lstat().st_uid
lock=path.with_name('operator.lock')
info=lock.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid in (0,uid) and not info.st_mode&0o022,'bad operator lock')
with lock.open('rb') as guard:
fcntl.flock(guard,fcntl.LOCK_EX)
info=protected(path,uid)
require(stat.S_IMODE(info.st_mode)==0o600 and info.st_size<=65536,'unsafe policy')
p=json.loads(path.read_bytes())
require(p['schema_version']==1,'unsupported policy')
rows=p.setdefault('opnsense',[])
existing=[r for r in rows if r['agent_id']==scope['agent_id']]
if existing:
require(existing==[scope],'existing rule differs')
else:
rows.append(scope)
data=encoded(p)
require(len(data)<=65536 and sum(len(p[k]) for k in ('windows','linux','opnsense'))<=64,'policy capacity')
replace(path,data)
def main():
parser=argparse.ArgumentParser(description=__doc__)
for k in ('tenant','asset','agent','principal'): parser.add_argument('--'+k,required=True,type=uuid.UUID)
for k in ('policy','binary'): parser.add_argument('--'+k,required=True)
for k in ('enrollment-generation','assignment-version'):parser.add_argument('--'+k,required=True,type=int)
a=parser.parse_args()
require(all(re.fullmatch('[a-f0-9]{64}',s) for s in [a.policy,a.binary]) and
min(a.enrollment_generation,a.assignment_version)>0,'invalid pins or generations')
scope=dict(tenant_id=str(a.tenant),asset_id=str(a.asset),agent_id=str(a.agent),
enrollment_generation=a.enrollment_generation,assignment_version=a.assignment_version,
principals=['local:'+str(a.principal)],helper_policy_sha256=a.policy,helper_binary_sha256=a.binary,
allowed_script_profiles=['full_maintenance_v1'],allow_root_scripts=True,allow_reboot=False,
allowed_services=[],acceptance_evidence_id='opnsense-root-'+str(a.agent))
program='import fcntl,json,os,stat,tempfile\nfrom pathlib import Path\n'
for f in (require,protected,encoded,replace,register):program+=inspect.getsource(f)+'\n'
subprocess.run([*ssh_prefix('server'),'python3 -I -'],input=program+f'register(Path({str(POLICY)!r}),{scope!r})\n',text=True,check=True)
if __name__=='__main__': main()
+7 -2
View File
@@ -30,12 +30,17 @@ def credentials_directory():
def ssh_prefix(target):
credentials = credentials_directory()
config = load_config(credentials / ("linux-vm.conf" if target == "linux" else "server.conf"))
profile = {"linux": "linux-vm.conf", "proxmox": "proxmox-vm.conf"}.get(target, "server.conf")
config = load_config(credentials / profile)
host = config["username"] + "@" + config["address"]
key = str(Path(config["ssh_key_path"]).expanduser())
base = ["ssh", "-F", "/dev/null", "-T"]
direct = [*base, "-p", config.get("port", "22"), "-i", key, "-o", "StrictHostKeyChecking=yes",
"-o", "BatchMode=yes", "-o", "ForwardAgent=no", "-o", "IdentitiesOnly=yes"]
if target == "proxmox":
# Local test host: its own pin file, not the user's global known_hosts.
return [*direct, "-o", "UserKnownHostsFile=" + str(credentials / "proxmox-dev.known_hosts"),
"-o", "GlobalKnownHostsFile=/dev/null", "-o", "ConnectTimeout=10", host]
if target != "windows":
return [*direct, "-o", "ConnectTimeout=10", host]
# Match the pinned access registered by deploy/windows/prepare_dev_access.py.
@@ -154,7 +159,7 @@ def main():
"Ziel: rmm-dev-stage/<SHA-256>/<Dateiname> im SSH-Benutzerprofil. "
"Identische Dateien werden wiederverwendet. Dienste und Releases werden separat aktiviert."))
parser.add_argument("--plan", action="store_true", help="Nur lokale Hashes und Zielpfade anzeigen")
parser.add_argument("target", choices=("server", "linux", "windows"), help="Entwicklungsziel")
parser.add_argument("target", choices=("server", "linux", "windows", "proxmox"), help="Entwicklungsziel")
parser.add_argument("files", nargs="+", type=Path, metavar="DATEI", help="Vorhandene lokale Artefakte")
args = parser.parse_args()
for path in args.files:
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Compose a Linux inventory-only release without rotating the installed helper or updater.
Use two build directories from tools/build.py, and the helper SHA-256 from
the currently published release for the target platform. The composition
receipt identifies the actual source build for every file.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import tempfile
from agent_release import binaries, FILES, LINUX, LINUX_ARM64
def compose(new, previous, helper_sha, destination):
def receipt(folder):
r = folder / 'manifest.json'
target, _ = binaries(folder, r)
digest = hashlib.sha256(r.read_bytes()).hexdigest()
if folder.name != digest or target not in (LINUX, LINUX_ARM64):
raise ValueError('Expected a receipt-addressed Linux build')
meta = json.loads(r.read_bytes())
return target, dict(revision=meta['revision'], receipt_sha256=digest,
builder=meta['builder']), meta['sha256']
target, fresh, new_hashes = receipt(new)
old_target, old, old_hashes = receipt(previous)
if target != old_target or old_hashes['rmm-privileged-helper'] != helper_sha:
raise ValueError('Prior build does not match selected platform and published helper')
with tempfile.TemporaryDirectory(dir=destination.parent) as tmp:
bundle = Path(tmp) / 'bundle'
bundle.mkdir()
hashes, origins = {}, {}
for name in FILES[target]:
folder, source, digests = (new, fresh, new_hashes) if name == 'rmm-agent' else (previous, old, old_hashes)
shutil.copy2(folder / name, bundle / name)
origins[name], hashes[name] = source, digests[name]
r = bundle / 'manifest.json'
r.write_text(json.dumps(dict(target=target, sha256=hashes, sources=origins), indent=2) + '\n')
binaries(bundle, r)
os.rename(bundle, destination)
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
for opt in ['new', 'previous', 'destination']:
p.add_argument('--' + opt, type=Path, required=True)
p.add_argument('--published-helper-sha256', required=True)
a = p.parse_args()
compose(a.new, a.previous, a.published_helper_sha256, a.destination)
+1
View File
@@ -193,6 +193,7 @@ export function validateInput(input: PlanInput): void {
validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter);
const bytes = new TextEncoder().encode(script).length;
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|| variant.os_family === 'opnsense' && variant.interpreter === 'posix_sh'
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
+54
View File
@@ -0,0 +1,54 @@
import { expect, it } from 'vitest';
import type { RecordValue } from './api';
import { groupDevices } from './device-groups';
const tenant = '11111111-1111-4111-8111-111111111111';
const device = (hostname: string, device_type: string | null, extra: RecordValue = {}): RecordValue => ({
tenant_id: tenant, customer_name: 'Testkunde', asset_id: hostname + '-asset', agent_id: hostname + '-agent',
hostname, device_type, ...extra });
const on = (host: string, tenantHost = host) => ({ hypervisor: {
kind: 'device', asset_id: tenantHost + '-asset', agent_id: tenantHost + '-agent', hostname: host } });
const hetzner = { hypervisor: { kind: 'placeholder', provider: 'hetzner', hostname: 'Hetzner Cloud' } };
const shape = (items: RecordValue[]) => groupDevices(items).map(g =>
[g.kind, g.title, g.rows.map(r => r.role + ':' + String(r.device.hostname)).join(',')]);
it('lists each hypervisor with its virtual machines, then Hetzner, physical and unassigned devices', () => {
expect(shape([
device('vm-b', 'virtual', on('pve-01')),
device('laptop', 'physical'),
device('cloud', 'virtual', hetzner),
device('pve-01', 'hypervisor'),
device('stray', 'virtual'),
device('vm-a', 'virtual', on('pve-01')),
device('pve-02', 'hypervisor'),
device('untyped', null),
])).toEqual([
['hypervisor', 'pve-01', 'host:pve-01,guest:vm-b,guest:vm-a'],
['hypervisor', 'pve-02', 'host:pve-02'],
['hetzner', '', 'guest:cloud'],
['physical', '', 'plain:laptop'],
['unassigned', '', 'plain:stray,plain:untyped'],
]);
});
it('keeps the block and the link of a hypervisor that is not on this page', () => {
const [group] = groupDevices([device('vm-a', 'virtual', on('pve-01'))]);
expect(group).toMatchObject({ kind: 'hypervisor', title: 'pve-01', hostListed: false,
hostPath: 'geraete/' + tenant + '/pve-01-asset/pve-01-agent' });
expect(group?.rows.map(r => r.role)).toEqual(['guest']);
});
it('never merges hosts of two customers that share an asset id', () => {
const other = { tenant_id: '22222222-2222-4222-8222-222222222222', customer_name: 'Anderer Kunde' };
const groups = groupDevices([
device('pve-01', 'hypervisor'),
device('vm-a', 'virtual', { ...on('pve-01'), ...other }),
]);
expect(groups.map(g => [g.customer, g.hostListed, g.rows.length])).toEqual([
['Testkunde', true, 1], ['Anderer Kunde', false, 1]]);
});
it('uses a manually assigned host as the head of its block whatever type it reports', () => {
expect(shape([device('vm-a', 'virtual', on('esx')), device('esx', 'physical')])).toEqual([
['hypervisor', 'esx', 'host:esx,guest:vm-a']]);
});
+91
View File
@@ -0,0 +1,91 @@
import { record, type RecordValue } from './api';
export type GroupKind = 'hypervisor' | 'hetzner' | 'physical' | 'unassigned';
export type RowRole = 'host' | 'guest' | 'plain';
export type FleetGroup = {
key: string;
kind: GroupKind;
/** Hostname of the hypervisor; empty for the fixed blocks. */
title: string;
customer: string;
/** Detail route of the hypervisor, also when its row is not part of this page. */
hostPath: string | null;
hostListed: boolean;
rows: { device: RecordValue; role: RowRole }[];
};
const text = (value: unknown) => (typeof value === 'string' ? value : '');
const route = (tenant: string, asset: string, agent: string) =>
tenant && asset && agent ? ['geraete', tenant, asset, agent].map(encodeURIComponent).join('/') : null;
/** The registered hypervisor a virtual device is assigned to, if any. */
function assignedHost(device: RecordValue) {
if (device.device_type !== 'virtual' || !device.hypervisor || typeof device.hypervisor !== 'object') return null;
const info = record(device.hypervisor);
const asset = text(info.asset_id);
return info.kind === 'device' && asset ? { asset, agent: text(info.agent_id), hostname: text(info.hostname) } : null;
}
function isHetzner(device: RecordValue) {
if (device.device_type !== 'virtual' || !device.hypervisor || typeof device.hypervisor !== 'object') return false;
const info = record(device.hypervisor);
return info.kind === 'placeholder' && info.provider === 'hetzner';
}
/**
* Sorts one page of the device list into blocks: one per hypervisor with its virtual
* machines, then Hetzner guests, physical devices and everything without a known place.
* A hypervisor is a block of its own within its customer; guests whose host is not on
* this page still get that host's block, without the host row.
*/
export function groupDevices(items: RecordValue[]): FleetGroup[] {
const hosts = new Map<string, FleetGroup>();
const fixed = new Map<GroupKind, FleetGroup>();
const hostGroup = (tenant: string, asset: string) => {
const key = tenant + '/' + asset;
let group = hosts.get(key);
if (!group) {
group = { key, kind: 'hypervisor', title: '', customer: '', hostPath: null, hostListed: false, rows: [] };
hosts.set(key, group);
}
return group;
};
const fixedGroup = (kind: GroupKind) => {
let group = fixed.get(kind);
if (!group) {
group = { key: kind, kind, title: '', customer: '', hostPath: null, hostListed: false, rows: [] };
fixed.set(kind, group);
}
return group;
};
const referenced = new Set<string>();
for (const device of items) {
const host = assignedHost(device);
if (host) referenced.add(text(device.tenant_id) + '/' + host.asset);
}
for (const device of items) {
const tenant = text(device.tenant_id), asset = text(device.asset_id);
const host = assignedHost(device);
if (device.device_type === 'hypervisor' || (!host && referenced.has(tenant + '/' + asset))) {
const group = hostGroup(tenant, asset);
group.title = text(device.hostname);
group.customer = text(device.customer_name);
group.hostPath = route(tenant, asset, text(device.agent_id));
group.hostListed = true;
group.rows.unshift({ device, role: 'host' });
} else if (host) {
const group = hostGroup(tenant, host.asset);
if (!group.hostListed) {
group.title = host.hostname;
group.customer = text(device.customer_name);
group.hostPath = route(tenant, host.asset, host.agent);
}
group.rows.push({ device, role: 'guest' });
} else {
const kind = isHetzner(device) ? 'hetzner' : device.device_type === 'physical' ? 'physical' : 'unassigned';
fixedGroup(kind).rows.push({ device, role: kind === 'hetzner' ? 'guest' : 'plain' });
}
}
return [...hosts.values(),
...(['hetzner', 'physical', 'unassigned'] as const).flatMap(kind => fixed.get(kind) ?? [])];
}
+11 -5
View File
@@ -4,6 +4,8 @@ import { NavIcon } from './navigation';
import { ErrorBox, errorText, useResource } from './resource';
type Host = { asset_id: string; agent_id: string; hostname: string };
/** Select value that hands the decision back to automatic Proxmox detection. */
const AUTO = 'automatic';
function host(value: unknown): Host | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
@@ -24,7 +26,7 @@ export function HypervisorLabel({ device }: { device: RecordValue }) {
return <span className="vm-hypervisor">
<NavIcon name="geraete" /><span>Hypervisor <a href={'#' + path} onClick={event => event.stopPropagation()}>
{target.hostname}
</a></span>
</a>{info.source === 'proxmox' && <span className="muted"> · automatisch über Proxmox erkannt</span>}</span>
</span>;
}
return info.kind === 'placeholder' && info.provider === 'hetzner' ? (
@@ -53,7 +55,8 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState('');
const [error, setError] = useState<string | null>(null);
const assigned = typeof device.assigned_hypervisor_asset_id === 'string' ? device.assigned_hypervisor_asset_id : '';
const automatic = device.hypervisor_source !== 'manual';
const assigned = automatic ? AUTO : typeof device.assigned_hypervisor_asset_id === 'string' ? device.assigned_hypervisor_asset_id : '';
const value = draft ?? assigned;
useEffect(() => {
@@ -70,7 +73,7 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
}, [customer, open, query]);
const assignedHost = host(device.hypervisor);
const hosts = options.data?.hosts ?? [];
const selectedMissing = !!value && !hosts.some(item => item.asset_id === value);
const selectedMissing = !!value && value !== AUTO && !hosts.some(item => item.asset_id === value);
const canSave = value !== assigned && (!value || !selectedMissing);
return <details onToggle={e => {
@@ -91,9 +94,11 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
setNotice('');
try {
await request(tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/hypervisor?agent_id=' + encodeURIComponent(agent)), {
tenantId: customer, csrf: auth.csrf_token, body: { hypervisor_asset_id: value || null }
tenantId: customer, csrf: auth.csrf_token,
body: value === AUTO ? { hypervisor_asset_id: null, automatic: true } : { hypervisor_asset_id: value || null }
});
setNotice(value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
setNotice(value === AUTO ? 'Automatische Zuordnung über Proxmox aktiviert.'
: value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
} catch (e) {
setError(assignmentError(e));
} finally {
@@ -106,6 +111,7 @@ export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
{options.data?.truncated && <p className="muted">Weitere Hypervisoren lassen sich über die Suche finden.</p>}
<label>Hypervisor auswählen<select aria-label="Hypervisor auswählen" value={value}
onChange={e => { setDraft(e.target.value); setNotice(''); setError(null); }} disabled={busy}>
<option value={AUTO}>Automatisch (Proxmox-Gastliste)</option>
<option value="">Kein konkreter Hypervisor</option>
{selectedMissing && <option value={value} disabled>
{assignedHost?.asset_id === value ? assignedHost.hostname : 'Zugeordneter Host außerhalb der Treffer'}
+226 -121
View File
@@ -18,8 +18,10 @@ import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { OPNsenseDetails } from './opnsense';
import { ProxmoxDetails } from './proxmox';
import { DeviceCustomerTransfer } from './device-customer-transfer';
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
import { groupDevices, type FleetGroup, type RowRole } from './device-groups';
import { ErrorBox, errorText, useResource } from './resource';
import { NavIcon, orderDetailRoute } from './navigation';
import { orderTitle, Status } from './order-presentation';
@@ -31,6 +33,49 @@ import { SystemNonstartReview } from './system-nonstart-review';
const unknown = 'Nicht gemeldet';
const noPurpose = 'Nicht hinterlegt';
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
function groupName(group: FleetGroup) {
return group.kind === 'hypervisor' ? 'Hypervisor ' + (group.title || 'unbekannt')
: group.kind === 'hetzner' ? 'Hetzner Cloud'
: group.kind === 'physical' ? 'Physische Geräte' : 'Nicht zugeordnet';
}
/** How a listed virtual machine got its place under a registered hypervisor. */
function linkSource(d: RecordValue) {
if (!d.hypervisor || typeof d.hypervisor !== 'object') return '';
const info = record(d.hypervisor);
return info.kind !== 'device' ? '' : info.source === 'proxmox' ? 'automatisch erkannt' : 'manuell zugeordnet';
}
function GroupHeader({ group, showCustomer }: { group: FleetGroup; showCustomer: boolean }) {
const guests = group.rows.filter((r) => r.role !== 'host').length;
const machines = plural(guests, 'virtuelle Maschine', 'virtuelle Maschinen');
const [icon, eyebrow, title, facts] =
group.kind === 'hypervisor'
? (['server', 'Hypervisor',
group.hostPath ? <a href={'#' + group.hostPath}>{group.title || 'Unbekannter Host'}</a> : group.title || 'Unbekannter Host',
[guests ? machines : 'Keine zugeordneten virtuellen Maschinen',
!group.hostListed && 'Host in dieser Ansicht nicht enthalten',
showCustomer && group.customer]] as const)
: group.kind === 'hetzner'
? (['cloud', 'Externer Anbieter', 'Hetzner Cloud', [machines, 'Platzhalter, kein Gerät im Bestand']] as const)
: group.kind === 'physical'
? (['geraete', 'Eigene Hardware', 'Physische Geräte', [plural(guests, 'Gerät', 'Geräte')]] as const)
: (['offen', 'Ohne Zuordnung', 'Nicht zugeordnet',
[plural(guests, 'Gerät', 'Geräte'), 'kein Hypervisor oder Gerätetyp erkannt']] as const);
return (
<div className="fleet-group-head">
<span className="group-icon"><NavIcon name={icon} /></span>
<div>
<span className="group-eyebrow">{eyebrow}</span>
<strong>{title}</strong>
</div>
<p>{facts.filter(Boolean).map((fact, i) => <span key={i}>{fact}</span>)}</p>
</div>
);
}
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
function label(value: unknown) {
@@ -44,9 +89,13 @@ function gib(v: unknown) {
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null;
}
function capacity(free: unknown, total: unknown) {
const f = gib(free),
t = gib(total);
return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`;
if (typeof total !== 'number' || !Number.isFinite(total) || total <= 0)
return { text: unknown, usedPercent: null };
const used = typeof free === 'number' && free >= 0 && free <= total ? total - free : null;
return {
text: `${gib(used) ?? '–'} / ${gib(total)} GiB`,
usedPercent: used === null ? null : (used / total) * 100
};
}
function cpuUsage(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100
@@ -90,39 +139,73 @@ function Presence({ d }: { d: RecordValue }) {
</span>
);
}
function Capacity({ free, total, showBreakdown = false }: {
function Capacity({ free, total }: {
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`;
const { text, usedPercent } = capacity(free, total);
const displayUsed = usedPercent === null ? null : Math.round(usedPercent * 10) / 10;
const usedLabel = displayUsed === null ? '' : `${number.format(displayUsed)} % belegt`;
const breakdown = displayUsed === null ? '' : `${usedLabel}, ${number.format(100 - displayUsed)} % frei`;
return (
<>
<span>{capacity(free, total)}</span>
{freePercent !== null && (showBreakdown ? (
<span>{text}</span>
{usedPercent !== null && (
<>
<span className="capacity-track capacity-breakdown" role="img"
<span className="capacity-track" role="img"
aria-label={breakdown} title={breakdown}>
<span className="capacity-free" style={{ width: `${freePercent}%` }} />
<span className="capacity-used" />
<span className="capacity-used" style={{ width: `${usedPercent}%` }} />
<span className="capacity-free" />
</span>
<small className="capacity-caption" aria-hidden="true">{freeLabel}</small>
<small className="capacity-caption" aria-hidden="true">{usedLabel}</small>
</>
) : (
<span className="capacity-track" title={freeLabel} aria-hidden="true">
<i style={{ width: `${100 - freePercent}%` }} />
</span>
))}
)}
</>
);
}
function LinuxDisk({ disk, groups }: { disk: RecordValue; groups: string[] }) {
const { used_bytes: used, available_bytes: free, total_bytes: total } = disk;
const size = typeof total === 'number' && Number.isFinite(total) && total > 0 ? total : null;
const valid = size !== null && typeof used === 'number' && used >= 0 && typeof free === 'number' && free >= 0 && used + free <= size;
const usedPct = valid ? used / size * 100 : 0, freePct = valid ? free / size * 100 : 0;
const summary = valid ? `${number.format(usedPct)} % belegt, ${number.format(freePct)} % frei, ${number.format(Math.max(0,100-usedPct-freePct))} % nicht zugeordnet` : 'Belegung nicht ermittelbar';
const group = disk.kind === 'group';
return <div className="drive-capacity">
<strong>{group ? 'Verbund: ' : ''}{label(disk.name)}</strong>
{typeof disk.model === 'string' && <small>{disk.model}</small>}
{group && Array.isArray(disk.members) && disk.members.length > 0 && <small>{disk.members.filter(v => typeof v === 'string').join(', ')}</small>}
{!group && groups.length > 0 && <small>Im Verbund: {groups.join(', ')}</small>}
<div>{size === null ? 'Größe nicht gemeldet' : `${valid ? gib(used) : '–'} / ${gib(size)} GiB`}</div>
{size !== null && <span className="capacity-track disk-track" role="img" aria-label={summary} title={summary}>
<span className="capacity-used" style={{width:`${usedPct}%`}} />
<span className="capacity-free" style={{width:`${freePct}%`}} />
</span>}
<small>{valid ? `${number.format(usedPct)} % belegt` : summary}</small>
</div>;
}
function DiskCapacity({ device }: { device: RecordValue }) {
if ('disks' in device) {
const disks = Array.isArray(device.disks) ? device.disks.filter(d => d && typeof d === 'object' && ['disk','group'].includes(d.kind) && typeof d.name === 'string') : [];
return <>{disks.length ? disks.map((disk,i) => <LinuxDisk key={`${disk.kind}/${disk.name}/${i}`} disk={disk}
groups={disk.kind === 'disk' ? disks.filter(g => g.kind === 'group' && Array.isArray(g.members) && g.members.includes(disk.name)).map(g => g.name) : []}/>) :
<small>Keine Festplatten gemeldet</small>}
{device.disks_truncated === true && <small>Liste gekürzt</small>}</>;
}
// Only Windows fleet rows use drive letters. Linux mount inventories remain
// available in the detail view, without expanding every fleet row.
const drives = Array.isArray(device.volumes)
? device.volumes.map(v => record(v)).filter(v => typeof v.name === 'string' && /^[A-Z]:$/.test(v.name)) : [];
if (!drives.length) return <>{device.source_id === 'linux.base' && <small>Root-Dateisystem /</small>}
<Capacity free={device.disk_free_bytes} total={device.disk_total_bytes} /></>;
return <>{drives.map(drive => (
<div className="drive-capacity" key={String(drive.name)}>
<strong>{String(drive.name)}</strong>{' '}<Capacity free={drive.free_bytes} total={drive.total_bytes} />
</div>
))}</>;
}
type Target = { customer: string; ids: string[] };
type Props = {
detailPath: string;
@@ -205,7 +288,7 @@ function reportedScriptProfiles(device: RecordValue) {
if (!caps.has('run_script')) return 'Nicht gemeldet';
const windows = os === 'windows';
const identity = windows ? 'system' : 'root';
const service = windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
const service = os==='opnsense' && !caps.has('opnsense.posix/1') ? 'Kernelabfrage als Dienstkonto' : windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet';
if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap)))
return 'Nicht gemeldet';
@@ -257,10 +340,10 @@ function DeviceDetail({
['Type', label(d.device_type)],
['Betriebssystem', label(d.os)],
...systemDetails(d, time),
['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)],
['RAM belegt / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes).text],
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)],
['Speicher belegt / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes).text],
['Letzter Kontakt', time(d.last_contact_at)],
['Inventar erhoben', time(d.observed_at)],
['Agentversion', label(d.agent_version)],
@@ -302,6 +385,7 @@ function DeviceDetail({
onSaved={() => { setPurposeSaved(true); detail.reload(); }}
/>
<OPNsenseDetails device={d} />
<ProxmoxDetails device={d} />
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
@@ -311,14 +395,14 @@ function DeviceDetail({
<thead>
<tr>
<th>Laufwerk</th>
<th>Speicher frei / gesamt</th>
<th>Speicher belegt / gesamt</th>
</tr>
</thead>
<tbody>
{volumes.map((v, i) => (
<tr key={i}>
<td>{label(v.name)}</td>
<td>{capacity(v.free_bytes, v.total_bytes)}</td>
<td>{capacity(v.free_bytes, v.total_bytes).text}</td>
</tr>
))}
</tbody>
@@ -540,6 +624,105 @@ export function Devices({
}}
/>
);
const columns = ['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher belegt / gesamt', 'RAM belegt / gesamt', 'CPU', 'Kunde'];
const row = (d: RecordValue, role: RowRole | 'flat') => {
const asset = objectId(d, 'asset'),
agent = objectId(d, 'agent'),
customer = objectId(d, 'tenant'),
model = cpu(d),
purpose = typeof d.purpose === 'string' ? d.purpose : '';
const show = () => {
setDeletionNotice('');
window.location.hash = ['geraete', customer, asset, agent]
.map(encodeURIComponent)
.join('/');
};
const another = selection.ids.length > 0 && selection.customer !== customer;
return (
<tr key={agent} onClick={show} className={role === 'flat' ? undefined : role}>
{!history && (
<td className="target-col" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
aria-label={'Ziel ' + asset}
title={
another ? 'Aufträge werden je Kunde geplant' : 'Für Auftrag auswählen'
}
disabled={another}
checked={selection.customer === customer && selection.ids.includes(asset)}
onChange={(e) => select(d, e.target.checked)}
/>
</td>
)}
<td className="hostname">
<button
className="host-link"
onClick={(e) => {
e.stopPropagation();
show();
}}
>
{label(d.hostname)}
</button>
{role === 'flat' && <HypervisorLabel device={d} />}
{role === 'guest' && linkSource(d) && <small className="link-source">{linkSource(d)}</small>}
</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} />
{d.status === 'offline' && d.lifecycle === 'current' && (
<small>Zuletzt {time(d.last_contact_at)}</small>
)}
</td>
<td data-label="Speicher belegt / gesamt" className="capacity-cell">
<DiskCapacity device={d} />
</td>
<td data-label="RAM belegt / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
</td>
<td data-label="CPU">
{model.primary}
{model.secondary && <small>{model.secondary}</small>}
<small title={measuredAt(d.cpu_usage_observed_at)}>
Auslastung {cpuUsage(d.cpu_usage_percent)}
</small>
</td>
<td data-label="Kunde">{label(d.customer_name)}</td>
</tr>
);
};
/** Every block shares these column widths, so the blocks line up under one heading. */
const table = (rows: { device: RecordValue; role: RowRole | 'flat' }[], heading: 'visible' | 'hidden' | 'only') => (
<div className={'table fleet-table' + (heading === 'only' ? ' fleet-head' : '')} aria-hidden={heading === 'only' || undefined}>
<table>
<colgroup>
{!history && <col className="target-col" />}
{columns.map((h) => <col key={h} className={h === 'Zweck' ? 'purpose-col' : h === 'Hostname' ? 'host-col' : undefined} />)}
</colgroup>
<thead className={heading === 'hidden' ? 'sr-only' : undefined}>
<tr>
{!history && (
<th className="target-col">
<span className="sr-only">Ziel auswählen</span>
</th>
)}
{columns.map((h) => (
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
{h}
</th>
))}
</tr>
</thead>
{heading !== 'only' && <tbody>{rows.map((r) => row(r.device, r.role))}</tbody>}
</table>
</div>
);
return (
<>
<div className="page-title">
@@ -629,99 +812,21 @@ export function Devices({
{!list.data && !list.error && <p className="list-message">Geräte werden geladen …</p>}
{list.data && (
<>
<div className="table fleet-table">
<table>
<thead>
<tr>
{!history && (
<th className="target-col">
<span className="sr-only">Ziel auswählen</span>
</th>
)}
{['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
(h) => (
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
{h}
</th>
)
)}
</tr>
</thead>
<tbody>
{list.data.items.map((d) => {
const asset = objectId(d, 'asset'),
agent = objectId(d, 'agent'),
customer = objectId(d, 'tenant'),
model = cpu(d),
purpose = typeof d.purpose === 'string' ? d.purpose : '';
const show = () => {
setDeletionNotice('');
window.location.hash = ['geraete', customer, asset, agent]
.map(encodeURIComponent)
.join('/');
};
const another = selection.ids.length > 0 && selection.customer !== customer;
return (
<tr key={agent} onClick={show}>
{!history && (
<td className="target-col" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
aria-label={'Ziel ' + asset}
title={
another ? 'Aufträge werden je Kunde geplant' : 'Für Auftrag auswählen'
}
disabled={another}
checked={selection.customer === customer && selection.ids.includes(asset)}
onChange={(e) => select(d, e.target.checked)}
/>
</td>
)}
<td className="hostname">
<button
className="host-link"
onClick={(e) => {
e.stopPropagation();
show();
}}
>
{label(d.hostname)}
</button>
<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} />
{d.status === 'offline' && d.lifecycle === 'current' && (
<small>Zuletzt {time(d.last_contact_at)}</small>
)}
</td>
<td data-label="Speicher frei / gesamt" className="capacity-cell">
<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} showBreakdown />
</td>
<td data-label="CPU">
{model.primary}
{model.secondary && <small>{model.secondary}</small>}
<small title={measuredAt(d.cpu_usage_observed_at)}>
Auslastung {cpuUsage(d.cpu_usage_percent)}
</small>
</td>
<td data-label="Kunde">{label(d.customer_name)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
{history ? (
table(list.data.items.map((device) => ({ device, role: 'flat' as const })), 'visible')
) : (
!!list.data.items.length && (
<div className="fleet-groups">
{table([], 'only')}
{groupDevices(list.data.items).map((group) => (
<div className={'fleet-group ' + group.kind} role="group" aria-label={groupName(group)} key={group.key}>
<GroupHeader group={group} showCustomer={!filter} />
{table(group.rows, 'hidden')}
</div>
))}
</div>
)
)}
{!list.data.items.length && (
<div className="empty-list">
<NavIcon name="geraete" />
+4 -1
View File
@@ -12,7 +12,10 @@ const glyphs = {
suchen: 'M16 16l5 5 M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0',
plus: 'M12 5v14 M5 12h14',
abmelden: 'M10 4H4v16h6 M8 12h13 M16 7l5 5-5 5',
zurueck: 'M20 12H4 M10 6l-6 6 6 6'
zurueck: 'M20 12H4 M10 6l-6 6 6 6',
server: 'M3 4h18v7H3z M3 13h18v7H3z M7 7.5h.01 M7 16.5h.01 M11 7.5h6 M11 16.5h6',
cloud: 'M7 19a4.5 4.5 0 0 1-.6-9A6 6 0 0 1 18 11.2a3.9 3.9 0 0 1 0 7.8z',
offen: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z M9.6 9.4a2.5 2.5 0 1 1 3.6 2.3c-.8.5-1.2 1-1.2 1.9 M12 17h.01'
};
export function NavIcon({ name }: { name: keyof typeof glyphs }) {
return (
+19 -10
View File
@@ -43,7 +43,7 @@ type Target = {
id: string;
name: string;
os: string;
platform: 'linux' | 'windows' | null;
platform: 'linux' | 'windows' | 'opnsense' | null;
state: string;
current: boolean;
};
@@ -143,6 +143,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [opnsense,setOpnsense] = useState<Script>(() => emptyScript('posix_sh'));
const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now()));
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
@@ -217,6 +218,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const targets = selected.map((id) => directory.get(id));
const hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows');
const hasOPNsense = targets.some((d) => d?.platform === 'opnsense');
const scripts = useResource(
(signal) => (canPlan && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket, mode]
@@ -225,21 +227,23 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity;
const restartPlatform = hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
: (hasOPNsense ? opnsense : hasWindows ? windows : linux).execution_identity;
const restartPlatform = hasOPNsense || hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
const restartScript = restartPlatform && heads.find(revision =>
revision.name === (hasWindows ? 'Windows neu starten' : 'Linux neu starten') &&
scriptPlatform(revision.interpreter) === restartPlatform &&
revision.execution_identity === (hasWindows ? 'system' : 'root')
);
const issues: string[] = [];
if (hasOPNsense && (hasLinux || hasWindows)) issues.push('OPNsense-Geräte bitte in einem eigenen Auftrag planen.');
if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter((d) => d && !d.platform);
if (unidentified.length)
issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', '));
if (mode === 'library' && revision) {
const incompatible = targets.filter((d) => d?.platform && d.platform !== scriptPlatform(revision.interpreter));
const incompatible = targets.filter((d) => d?.platform && (d.platform==='opnsense'
? revision.interpreter!=='posix_sh' : d.platform !== scriptPlatform(revision.interpreter)));
if (incompatible.length)
issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
@@ -304,10 +308,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
}
});
} else {
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
const variants = [hasLinux ? linux : null, hasWindows ? windows : null, hasOPNsense ? opnsense : null]
.filter((s): s is Script => !!s)
.map((s) => ({
os_family: scriptPlatform(s.interpreter),
os_family: s===opnsense ? 'opnsense' : scriptPlatform(s.interpreter),
interpreter: s.interpreter,
encoding: 'utf-8',
script_utf8: s.script_utf8,
@@ -341,7 +345,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id);
const mismatchedJob = checked.jobs.some((j) => {
const script =
mode === 'library' ? revision : directory.get(j.assetId)?.platform === 'windows' ? windows : linux;
mode === 'library' ? revision : hasOPNsense ? opnsense : directory.get(j.assetId)?.platform === 'windows' ? windows : linux;
return (
!selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
@@ -643,8 +647,8 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
Neustartskript auswählen
</button>
)}
<label>
Bibliotheksskript
<label>
Bibliotheksskript
<select
required
value={revision?.name ?? ''}
@@ -659,7 +663,8 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
</option>
))}
</select>
</label>
</label>
{hasOPNsense && <p className="muted">OPNsense verwendet die POSIX-Shell von FreeBSD. Wählen Sie eine passende Revision; Linux-spezifische Programme wie systemctl stehen hier nicht zur Verfügung.</p>}
{scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
{revision && (
<>
@@ -703,6 +708,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{hasOPNsense && <fieldset><legend>OPNsense-Skript</legend>
<ScriptFields script={opnsense} change={setOpnsense}
ids={allowed(auth,'root:execute') ? ['agent_service','root'] : ['agent_service']} interpreters={['posix_sh']} />
</fieldset>}
</>
)}
{identity && identity !== 'agent_service' && (
+40
View File
@@ -0,0 +1,40 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { ProxmoxDetails } from './proxmox';
const data = { node: 'pve', cluster: null, version: '9.2.2', not_backed_up: [101],
guests: [
{ vmid: 100, name: 'debian-guest', kind: 'qemu', status: 'running', template: false, cpus: 1,
memory_bytes: 2 ** 30, disk_bytes: 2 ** 33, macs: ['bc:24:11:88:35:97'] },
{ vmid: 101, name: 'alpine-ct', kind: 'lxc', status: 'running', template: false, cpus: 1,
memory_bytes: 2 ** 27, disk_bytes: 2 ** 30, macs: [] }],
backup_jobs: [{ id: 'backup-debian', enabled: true, schedule: '*/2:00', storage: 'local',
selection: 'vmid', covered_vmids: [100], last_expected_run: 1795172400, next_run: 1795179600 }],
backup_runs: [] };
it('lists guests, linked devices and an overall backup answer', () => {
const view = renderToStaticMarkup(<ProxmoxDetails device={{ tenant_id: 't', proxmox: {
quality: 'valid', observed_at: '2026-11-20T12:00:00Z', data,
backup_status: { all_scheduled_backups_ran: true, last_success_at: { '100': 1795172488 },
jobs: [{ id: 'backup-debian', status: 'ok', guests: [{ vmid: 100, status: 'ok' }] }] },
guest_devices: [{ vmid: 100, asset_id: 'a', agent_id: 'b', hostname: 'debian-guest' }] } }} />);
expect(view).toContain('Alle geplanten Backups sind gelaufen.');
expect(view).toContain('href="#geraete/t/a/b"');
expect(view).toContain('Container');
expect(view).toMatch(/Ohne Backupjob<\/h3><p>101 alpine-ct/);
expect(view).toContain('Gelaufen');
});
it('names failed guests and explains a missing read token', () => {
const failed = renderToStaticMarkup(<ProxmoxDetails device={{ proxmox: { quality: 'valid', data,
backup_status: { all_scheduled_backups_ran: false, last_success_at: {},
jobs: [{ id: 'backup-debian', status: 'failed', guests: [{ vmid: 100, status: 'failed' }] }] },
guest_devices: [] } }} />);
expect(failed).toContain('Nicht alle geplanten Backups sind gelaufen.');
expect(failed).toContain('100 debian-guest: Fehlgeschlagen');
expect(failed).toContain('nicht zugeordnet');
const missing = renderToStaticMarkup(<ProxmoxDetails device={{ proxmox: {
quality: 'unsupported', error_code: 'PROXMOX_NOT_CONFIGURED', data: null } }} />);
expect(missing).toContain('kein Lesezugang');
expect(renderToStaticMarkup(<ProxmoxDetails device={{}} />)).toBe('');
});
+114
View File
@@ -0,0 +1,114 @@
import { record, type RecordValue } from './api';
const dateFormat = new Intl.DateTimeFormat('de-DE', { dateStyle: 'short', timeStyle: 'short' });
const gib = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
const JOB_STATUS: Record<string, [string, string]> = {
ok: ['Gelaufen', 'online'],
failed: ['Fehlgeschlagen', 'failed'],
missed: ['Verpasst', 'failed'],
running: ['Läuft', 'historic'],
pending: ['Noch nicht fällig', ''],
disabled: ['Deaktiviert', ''],
unknown: ['Unbekannt', 'historic'],
};
const GUEST_STATUS: Record<string, string> = { running: 'Läuft', stopped: 'Gestoppt', paused: 'Pausiert' };
function list(value: unknown): RecordValue[] {
return Array.isArray(value) ? value.filter(v => v && typeof v === 'object' && !Array.isArray(v)).map(v => record(v)) : [];
}
function epoch(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? dateFormat.format(value * 1000) : '–';
}
function size(value: unknown) {
return typeof value === 'number' && value > 0 ? gib.format(value / 2 ** 30) + ' GiB' : '–';
}
function text(value: unknown) {
return typeof value === 'string' && value.trim() ? value : '–';
}
function Badge({ status }: { status: unknown }) {
const [title, tone] = JOB_STATUS[typeof status === 'string' ? status : 'unknown'] ?? ['Unbekannt', 'historic'];
return <span className={'presence ' + tone}><i />{title}</span>;
}
function deviceLink(tenant: unknown, link: RecordValue | undefined) {
if (!link || typeof tenant !== 'string' || typeof link.asset_id !== 'string' || typeof link.agent_id !== 'string') return null;
const path = ['geraete', tenant, link.asset_id, link.agent_id].map(encodeURIComponent).join('/');
return <a href={'#' + path}>{text(link.hostname)}</a>;
}
/** Hosted guests and scheduled vzdump backups reported by a Proxmox VE host. */
export function ProxmoxDetails({ device }: { device: RecordValue }) {
if (!device.proxmox || typeof device.proxmox !== 'object') return null;
const report = record(device.proxmox);
if (report.quality !== 'valid' || !report.data) {
const reason = report.error_code === 'PROXMOX_NOT_CONFIGURED'
? 'Für diesen Proxmox-Host ist kein Lesezugang eingerichtet. Der HTTPS-Installer richtet ihn bei der Aufnahme ein.'
: 'Nicht ermittelbar' + (typeof report.error_code === 'string' ? ` (${report.error_code})` : '') + '.';
return <section><h2>Proxmox VE</h2><p>{reason}</p></section>;
}
const data = record(report.data);
const status = report.backup_status ? record(report.backup_status) : {};
const jobStatus = new Map(list(status.jobs).map(j => [j.id, j]));
const lastSuccess = status.last_success_at ? record(status.last_success_at) : {};
const links = new Map(list(report.guest_devices).map(l => [l.vmid, l]));
const guests = list(data.guests);
const names = new Map(guests.map(g => [g.vmid, text(g.name)]));
const jobs = list(data.backup_jobs);
const notBackedUp = Array.isArray(data.not_backed_up) ? data.not_backed_up : [];
const allRan = status.all_scheduled_backups_ran;
const guestName = (id: unknown) => `${String(id)} ${names.get(id) ?? ''}`.trim();
return <>
<section>
<h2>Virtuelle Maschinen und Container</h2>
<p className="muted">Node {text(data.node)}{typeof data.cluster === 'string' ? ` · Cluster ${data.cluster}` : ''}
{typeof data.version === 'string' ? ` · Proxmox VE ${data.version}` : ''} · erhoben {typeof report.observed_at === 'string' ? dateFormat.format(Date.parse(report.observed_at)) : '–'}
{report.truncated === true ? ' · Auszug – unvollständige Liste' : ''}</p>
{guests.length === 0 ? <p>Keine Gäste auf diesem Node.</p> : <div className="table"><table>
<thead><tr><th>VMID</th><th>Name</th><th>Typ</th><th>Status</th><th>vCPU</th><th>RAM</th><th>Disk</th><th>Gerät im Bestand</th><th>Letzte Sicherung</th></tr></thead>
<tbody>{guests.map(g => <tr key={String(g.vmid)}>
<td>{String(g.vmid)}</td>
<td>{text(g.name)}{g.template === true && <span className="muted"> · Vorlage</span>}</td>
<td>{g.kind === 'lxc' ? 'Container' : 'VM'}</td>
<td>{GUEST_STATUS[String(g.status)] ?? text(g.status)}</td>
<td>{typeof g.cpus === 'number' ? g.cpus : '–'}</td>
<td>{size(g.memory_bytes)}</td>
<td>{size(g.disk_bytes)}</td>
<td>{deviceLink(device.tenant_id, links.get(g.vmid)) ?? <span className="muted">nicht zugeordnet</span>}</td>
<td>{epoch(lastSuccess[String(g.vmid)])}</td>
</tr>)}</tbody>
</table></div>}
</section>
<section>
<h2>Geplante Backups</h2>
<p role="status">{allRan === true ? <><Badge status="ok" /> Alle geplanten Backups sind gelaufen.</>
: allRan === false ? <><Badge status="failed" /> Nicht alle geplanten Backups sind gelaufen.</>
: 'Keine aktiven Backupjobs für diesen Node.'}</p>
{jobs.length > 0 && <div className="table"><table>
<thead><tr><th>Job</th><th>Zeitplan</th><th>Storage</th><th>Gäste</th><th>Zuletzt fällig</th><th>Ergebnis</th><th>Nächster Lauf</th></tr></thead>
<tbody>{jobs.map(job => {
const evaluated = jobStatus.get(job.id);
const problems = list(evaluated?.guests).filter(g => g.status !== 'ok');
const covered = Array.isArray(job.covered_vmids) ? job.covered_vmids : [];
return <tr key={String(job.id)}>
<td>{text(job.id)}</td>
<td><code>{text(job.schedule)}</code></td>
<td>{text(job.storage)}</td>
<td>{covered.length ? covered.map(guestName).join(', ') : <span className="muted">keine lokalen Gäste</span>}
{job.selection === 'all' && <span className="muted"> (alle)</span>}</td>
<td>{epoch(job.last_expected_run)}</td>
<td><Badge status={evaluated?.status} />
{problems.length > 0 && <ul className="compact">{problems.map(g =>
<li key={String(g.vmid)}>{guestName(g.vmid)}: {JOB_STATUS[String(g.status)]?.[0] ?? text(g.status)}</li>)}</ul>}</td>
<td>{epoch(job.next_run)}</td>
</tr>;
})}</tbody>
</table></div>}
{notBackedUp.length > 0 && <>
<h3>Ohne Backupjob</h3>
<p>{notBackedUp.map(guestName).join(', ')}</p>
</>}
</section>
</>;
}
+2 -1
View File
@@ -14,7 +14,7 @@ export interface Revision extends Script {
script_sha256: string;
}
export const interpreterNames: Record<Interpreter, string> = {
posix_sh: 'Linux · Shell',
posix_sh: 'POSIX-Shell',
bash: 'Linux · Bash',
powershell: 'Windows · PowerShell'
};
@@ -71,6 +71,7 @@ export function latestRevisions(revisions: Revision[]) {
}
export function devicePlatform(row: RecordValue) {
if (row.source_id === 'opnsense.base') return 'opnsense';
if (row.source_id === 'windows.base') return 'windows';
if (row.source_id === 'linux.base') return 'linux';
return null;
+3 -2
View File
@@ -117,7 +117,7 @@ export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Sess
const latest = versions[0];
const query = search.trim().normalize('NFC').toLocaleLowerCase('de');
const shown = latestRevisions(library.data ?? []).filter((item) =>
(!platform || scriptPlatform(item.interpreter) === platform) &&
(!platform || (platform==='opnsense' ? item.interpreter==='posix_sh' : scriptPlatform(item.interpreter) === platform)) &&
item.name.normalize('NFC').toLocaleLowerCase('de').includes(query));
function edit(existing?: Revision) {
setBase(existing?.version ?? 0);
@@ -258,7 +258,8 @@ export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Sess
<label><span>Plattform</span>
<select aria-label="Plattform" value={platform} onChange={e => setPlatform(e.target.value)}>
<option value="">Alle Plattformen</option>
<option value="linux">Linux</option>
<option value="linux">Linux</option>
<option value="opnsense">OPNsense (POSIX-Shell)</option>
<option value="windows">Windows</option>
</select>
</label>
+38 -6
View File
@@ -97,7 +97,32 @@ 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%; }
.fleet-table th.purpose-col,.fleet-table col.purpose-col { width:17%; }
.fleet-groups { --group:var(--accent); --group-soft:#eaf3ef; padding:0 14px 16px; background:#f7f9f8; border-top:1px solid var(--line); }
.fleet-head thead th { background:none; border-bottom:0; padding-block:11px 9px; }
.fleet-group { background:var(--surface); border:1px solid var(--line); border-left:4px solid var(--group); border-radius:10px; overflow:hidden; box-shadow:0 1px 2px rgba(21,45,42,.05); }
.fleet-group + .fleet-group { margin-top:14px; }
.fleet-group.hetzner { --group:#b4432f; --group-soft:#fbeeea; }
.fleet-group.physical { --group:var(--blue); --group-soft:#e8f1f4; }
.fleet-group.unassigned { --group:#a8791f; --group-soft:#faf1df; border-style:dashed; border-left-style:solid; }
.fleet-group-head { display:flex; align-items:center; gap:12px; padding:11px 16px 11px 14px; background:linear-gradient(90deg,var(--group-soft),transparent 75%); border-bottom:1px solid var(--line); }
.group-icon { display:grid; place-items:center; flex:none; width:34px; height:34px; border-radius:9px; background:var(--group); color:#fff; }
.group-icon .nav-icon { width:18px; height:18px; }
.fleet-group-head > div { display:flex; flex-direction:column; min-width:0; }
.group-eyebrow { color:var(--group); font-size:.68rem; font-weight:700; letter-spacing:.08em; text-transform:uppercase; }
.fleet-group-head strong { font-size:1.04rem; letter-spacing:-.015em; overflow-wrap:anywhere; }
.fleet-group-head strong a { color:inherit; text-decoration:none; } .fleet-group-head strong a:hover { text-decoration:underline; }
.fleet-group-head p { display:flex; flex-wrap:wrap; justify-content:flex-end; gap:6px; margin:0 0 0 auto; }
.fleet-group-head p span { border-radius:20px; padding:2px 10px; background:var(--surface); border:1px solid var(--line); color:var(--subtle); font-size:.78rem; white-space:nowrap; }
.fleet-group-head p span:first-child { border-color:transparent; background:var(--group-soft); color:var(--group); font-weight:650; }
.fleet-group .fleet-table tbody tr:last-child td { border-bottom:0; }
.fleet-group tr.host { background:#fbfdfc; } .fleet-group tr.host .host-link { color:var(--ink); }
.link-source { display:block; color:var(--subtle); overflow-wrap:normal; }
.fleet-table col.host-col { width:15%; }
/* Guests hang on a branch below their host. */
.fleet-group tr.guest td.hostname { position:relative; padding-left:38px; }
.fleet-group tr.guest td.hostname::before { content:''; position:absolute; left:12px; top:0; bottom:50%; width:16px; border-left:2px solid var(--group); border-bottom:2px solid var(--group); border-bottom-left-radius:8px; opacity:.45; }
.fleet-group tr.guest:not(:last-child) td.hostname::after { content:''; position:absolute; left:12px; top:50%; bottom:0; border-left:2px solid var(--group); opacity:.45; }
.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; }
@@ -105,16 +130,19 @@ section.fleet { padding:0; overflow:hidden; }
.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; }
.drive-capacity + .drive-capacity { margin-top:8px; }
.capacity-track { display:flex; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:6px; margin-top:6px; overflow:hidden; }
.capacity-used { flex:none; background:#c78980; }
.capacity-free { flex:1; background:#2e7657; }
.disk-track { background:#aebbb6; }
.disk-track .capacity-free { flex:none; }
.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; }
.presence.historic { color:#80581c; background:#faf1df; }
.presence.failed { color:#7b3029; background:#fdf1ee; }
ul.compact { margin:4px 0 0; padding-left:18px; font-size:.85rem; }
.fleet small { font-size:.75rem; margin-top:3px; }
.list-message,.history-hint,.empty-list,.fleet > .error { margin:14px 20px; }
.history-hint,.list-footer { color:var(--subtle); font-size:.83rem; }
@@ -164,6 +192,10 @@ 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-head {display:none;} .fleet-groups {padding:12px 10px;border-top:0;} .fleet-group .fleet-table tr:first-child {border-top:0;}
.fleet-group-head {flex-wrap:wrap;} .fleet-group-head p span {white-space:normal;} .fleet-group-head p {margin-left:46px;justify-content:flex-start;flex-basis:100%;}
.fleet-group tr.guest {margin-left:16px;border-left:2px solid color-mix(in srgb,var(--group) 45%,transparent);}
.fleet-group tr.guest td.hostname {padding-left:0;} .fleet-group tr.guest td.hostname::before,.fleet-group tr.guest td.hostname::after {display:none;}
.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;}