Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71adc2adf6 | ||
|
|
8acbee6a60 | ||
|
|
6bf6e2539c | ||
|
|
50b1fa4033 | ||
|
|
b7d9046996 | ||
|
|
d05caf6fd3 | ||
|
|
89a58c609c | ||
|
|
ac6f940e2e | ||
|
|
577a6eea75 | ||
|
|
58236bc8f0 | ||
|
|
2070ae95e7 | ||
|
|
01960477f8 | ||
|
|
480e3749a6 | ||
|
|
65d84a19c0 | ||
|
|
cad188aeb7 | ||
|
|
bcd3bd86ad | ||
|
|
08177d8843 | ||
|
|
dd59052e7c | ||
|
|
a4bcebf440 |
Generated
+1
@@ -2187,6 +2187,7 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"hex",
|
"hex",
|
||||||
|
"libc",
|
||||||
"openssl",
|
"openssl",
|
||||||
"prost",
|
"prost",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
|
|||||||
@@ -10,16 +10,22 @@ 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)
|
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)
|
||||||
|
|
||||||
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Wie beim Speicherplatz zeigt ein Balken den belegten Anteil. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
|
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.
|
||||||
|
|
||||||
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. Nach der ersten Inventarmeldung beim Zielkunden bestätigt die Person den Abschluss in der WebUI. Der Server sperrt die bisherige Geräteidentität. 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.
|
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Im RAM-Balken ist der verfügbare Anteil (links) grün und der belegte Anteil grau. Die sichtbare Prozentangabe benennt den verfügbaren Anteil. Ohne gültiges Wertepaar erscheint kein Balken. Der Laufwerksbalken hebt weiterhin den belegten Anteil hervor. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
|
||||||
|
|
||||||
|
Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Mit der ersten gültigen Inventarmeldung der authentisierten neuen Kopplung schließt der Server den Wechsel automatisch ab. Er sperrt die bisherige Geräteidentität und schaltet den Bestand in derselben Transaktion auf den Zielkunden um. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung.
|
||||||
|
|
||||||
Eine ausgeschiedene Installation kann nach Widerruf und persönlicher Bestätigung endgültig gelöscht werden. Ein noch gültiger offener Genehmigungsantrag oder ein nicht abgeschlossener Job einschließlich `unknown` sperrt die Löschung. Daten weiterhin beteiligter Zielgeräte bleiben erhalten. [Regeln zur Löschung](migrations/0036_delete_device_pairing.sql)
|
Eine ausgeschiedene Installation kann nach Widerruf und persönlicher Bestätigung endgültig gelöscht werden. Ein noch gültiger offener Genehmigungsantrag oder ein nicht abgeschlossener Job einschließlich `unknown` sperrt die Löschung. Daten weiterhin beteiligter Zielgeräte bleiben erhalten. [Regeln zur Löschung](migrations/0036_delete_device_pairing.sql)
|
||||||
|
|
||||||
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
|
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
|
||||||
|
|
||||||
|
Die Spalte **Zweck** und das Gerätedetail zeigen optionalen Freitext. Unter **Zweck bearbeiten** können Betreiber mit Inventarlese- und Geräteverwaltungsrecht für den betreffenden Kunden bis zu 500 Zeichen speichern oder den Text entfernen. Der Zweck gehört zum Gerät beim bisherigen Kunden und wird beim Kundenwechsel nicht übernommen. Die Änderung wird ohne den Text auditiert und erzeugt keinen Geräteauftrag.
|
||||||
|
|
||||||
## Vom Skript zum Ergebnis
|
## 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.
|
||||||
|
|
||||||
| Schritt | Verhalten |
|
| Schritt | Verhalten |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Skript veröffentlichen | In der Bibliothek eines Kunden erhält ein Skript einen Namen, einen Interpreter, einen Standard-Ausführungskontext und eine unveränderliche Version. Eine Bearbeitung veröffentlicht eine weitere Version. |
|
| Skript veröffentlichen | In der Bibliothek eines Kunden erhält ein Skript einen Namen, einen Interpreter, einen Standard-Ausführungskontext und eine unveränderliche Version. Eine Bearbeitung veröffentlicht eine weitere Version. |
|
||||||
|
|||||||
@@ -31,3 +31,6 @@ openssl = { workspace = true, optional = true }
|
|||||||
|
|
||||||
[target.'cfg(unix)'.dev-dependencies]
|
[target.'cfg(unix)'.dev-dependencies]
|
||||||
openssl.workspace = true
|
openssl.workspace = true
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "freebsd")'.dependencies]
|
||||||
|
libc = "0.2"
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
//! Read-only FreeBSD kernel discipline for the signed reconciliation clock.
|
||||||
|
//! Never adjust the guest clock. No cached qualification across a failed read.
|
||||||
|
use crate::reconcile::{ClockReading, SyncClock};
|
||||||
|
use anyhow::{Context, Result, ensure};
|
||||||
|
use chrono::{DateTime, TimeDelta, Utc};
|
||||||
|
use std::{mem::MaybeUninit, time::Instant};
|
||||||
|
|
||||||
|
pub struct NativeClock {
|
||||||
|
origin: DateTime<Utc>,
|
||||||
|
monotonic: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for NativeClock {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
origin: Utc::now(),
|
||||||
|
monotonic: Instant::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NativeClock {
|
||||||
|
fn observation(&self) -> Result<(DateTime<Utc>, TimeDelta)> {
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut raw = MaybeUninit::<libc::ntptimeval>::zeroed();
|
||||||
|
// SAFETY: the read-only syscall writes the platform's ntptimeval.
|
||||||
|
let result = unsafe { libc::ntp_gettime(raw.as_mut_ptr()) };
|
||||||
|
ensure!(result == libc::TIME_OK, "FREEBSD_CLOCK_UNQUALIFIED");
|
||||||
|
let sample = unsafe { raw.assume_init() };
|
||||||
|
let wall =
|
||||||
|
DateTime::from_timestamp(sample.time.tv_sec, u32::try_from(sample.time.tv_nsec)?)
|
||||||
|
.context("FREEBSD_CLOCK_INVALID")?;
|
||||||
|
let duration = TimeDelta::from_std(start.elapsed())?;
|
||||||
|
ensure!(
|
||||||
|
sample.time_state == libc::TIME_OK
|
||||||
|
&& (0..=5_000_000).contains(&sample.maxerror)
|
||||||
|
&& (0..=sample.maxerror).contains(&sample.esterror)
|
||||||
|
&& sample.time.tv_nsec < 1_000_000_000
|
||||||
|
&& duration <= TimeDelta::milliseconds(100)
|
||||||
|
&& ((wall - self.origin) - TimeDelta::from_std(self.monotonic.elapsed())?)
|
||||||
|
.num_milliseconds()
|
||||||
|
.unsigned_abs()
|
||||||
|
<= 5000,
|
||||||
|
"FREEBSD_CLOCK_UNQUALIFIED"
|
||||||
|
);
|
||||||
|
Ok((wall, TimeDelta::microseconds(sample.maxerror) + duration))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SyncClock for NativeClock {
|
||||||
|
fn now(&self) -> Result<DateTime<Utc>> {
|
||||||
|
Ok(self.observation()?.0)
|
||||||
|
}
|
||||||
|
fn reading(&self) -> Result<ClockReading> {
|
||||||
|
let (wall, error) = self.observation()?;
|
||||||
|
Ok(ClockReading {
|
||||||
|
own_wall: wall,
|
||||||
|
upper: wall + error,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
|
||||||
|
let (wall, error) = self.observation()?;
|
||||||
|
Ok((wall - error, wall + error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "requires a FreeBSD guest synchronized by ntpd"]
|
||||||
|
fn native_bounds_and_monotonic_fence() -> Result<()> {
|
||||||
|
let mut clock = NativeClock::default();
|
||||||
|
let (low, high) = clock.bounds()?;
|
||||||
|
ensure!(low <= high && high - low <= TimeDelta::milliseconds(10200));
|
||||||
|
clock.origin += TimeDelta::minutes(1);
|
||||||
|
ensure!(clock.bounds().is_err());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod customer_transfer;
|
pub mod customer_transfer;
|
||||||
pub mod crypto;
|
pub mod crypto;
|
||||||
|
#[cfg(target_os = "freebsd")]
|
||||||
|
pub mod freebsd_clock;
|
||||||
pub mod helper_reconcile;
|
pub mod helper_reconcile;
|
||||||
pub mod jobs;
|
pub mod jobs;
|
||||||
pub mod ledger;
|
pub mod ledger;
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ pub(crate) fn run_controlled(
|
|||||||
let state = unsafe {
|
let state = unsafe {
|
||||||
libc::waitid(
|
libc::waitid(
|
||||||
libc::P_PID,
|
libc::P_PID,
|
||||||
child.id(),
|
child.id() as libc::id_t,
|
||||||
info.as_mut_ptr(),
|
info.as_mut_ptr(),
|
||||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||||
)
|
)
|
||||||
@@ -232,6 +232,7 @@ fn drain(
|
|||||||
}
|
}
|
||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
|
#[cfg(not(target_os = "freebsd"))]
|
||||||
fn group_has_no_live_members(pgid: u32) -> bool {
|
fn group_has_no_live_members(pgid: u32) -> bool {
|
||||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||||
return false;
|
return false;
|
||||||
@@ -265,6 +266,48 @@ fn group_has_no_live_members(pgid: u32) -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "freebsd")]
|
||||||
|
fn group_has_no_live_members(pgid: u32) -> bool {
|
||||||
|
// FreeBSD has no Linux /proc/<pid>/stat. Ask the kernel for this
|
||||||
|
// process group while its original leader's PID is still reserved.
|
||||||
|
use std::{mem, ptr};
|
||||||
|
let mib = [
|
||||||
|
libc::CTL_KERN,
|
||||||
|
libc::KERN_PROC,
|
||||||
|
libc::KERN_PROC_PGRP,
|
||||||
|
pgid as i32,
|
||||||
|
];
|
||||||
|
let mut size = 0;
|
||||||
|
let query = |out, n: &mut usize| unsafe {
|
||||||
|
libc::sysctl(mib.as_ptr(), mib.len() as _, out, n, ptr::null(), 0)
|
||||||
|
};
|
||||||
|
let unit = mem::size_of::<libc::kinfo_proc>();
|
||||||
|
if query(ptr::null_mut(), &mut size) != 0 || size == 0 || size > 16 * 1024 * 1024 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut rows = vec![mem::MaybeUninit::<libc::kinfo_proc>::zeroed(); size.div_ceil(unit) + 1];
|
||||||
|
size = rows.len() * unit;
|
||||||
|
if query(rows.as_mut_ptr().cast(), &mut size) != 0
|
||||||
|
|| !size.is_multiple_of(unit)
|
||||||
|
|| size / unit > rows.len()
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut leader = false;
|
||||||
|
for row in &rows[..size / unit] {
|
||||||
|
// A successful MIB read returned this complete aligned record.
|
||||||
|
let row = unsafe { row.assume_init_ref() };
|
||||||
|
if row.ki_structsize as usize != unit
|
||||||
|
|| row.ki_pgid != pgid as i32
|
||||||
|
|| row.ki_stat != libc::SZOMB
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
leader |= row.ki_pid == pgid as i32;
|
||||||
|
}
|
||||||
|
leader
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//! Additive bounded passive metadata; the strict original Inventory stays intact.
|
//! Additive bounded passive metadata; the strict original Inventory stays intact.
|
||||||
|
mod opnsense;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
@@ -64,6 +65,9 @@ pub fn validate_for_scope(
|
|||||||
now: DateTime<Utc>,
|
now: DateTime<Utc>,
|
||||||
scope: &str,
|
scope: &str,
|
||||||
) -> Result<Value, &'static str> {
|
) -> Result<Value, &'static str> {
|
||||||
|
if scope == "opnsense.base" {
|
||||||
|
return opnsense::validate(bytes);
|
||||||
|
}
|
||||||
if scope == "agent.update" {
|
if scope == "agent.update" {
|
||||||
if bytes.len() > 65536 {
|
if bytes.len() > 65536 {
|
||||||
return Err("AGENT_UPDATE_INVENTORY_SIZE");
|
return Err("AGENT_UPDATE_INVENTORY_SIZE");
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
//! Allowlisted wire document. No appliance configuration or VPN secrets on the wire.
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Snapshot {
|
||||||
|
os: String,
|
||||||
|
hostname: String,
|
||||||
|
architecture: String,
|
||||||
|
root_total_bytes: u64,
|
||||||
|
root_available_bytes: u64,
|
||||||
|
cpu_model: String,
|
||||||
|
logical_processors: u32,
|
||||||
|
memory_total_bytes: u64,
|
||||||
|
firewall: Rows,
|
||||||
|
vpn_configured: Rows,
|
||||||
|
wireguard: Rows,
|
||||||
|
openvpn: Rows,
|
||||||
|
ipsec: Rows,
|
||||||
|
hardware: Option<Hardware>,
|
||||||
|
software: Option<Records<Software>>,
|
||||||
|
interfaces: Option<Records<Interface>>,
|
||||||
|
users: Option<Rows>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Hardware {
|
||||||
|
device_type: String,
|
||||||
|
booted_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
manufacturer: Option<String>,
|
||||||
|
bios_serial_number: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Records<T> { status: String, entries: Vec<T> }
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Software { name: String, version: String }
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Interface { name: String, mac: Option<String>, addresses: Vec<String> }
|
||||||
|
impl<T> Records<T> {
|
||||||
|
fn valid(&self, limit: usize, check: impl Fn(&T) -> bool) -> bool {
|
||||||
|
matches!(self.status.as_str(),"ok"|"partial"|"unavailable")
|
||||||
|
&& (self.status != "unavailable" || self.entries.is_empty())
|
||||||
|
&& self.entries.len() <= limit && self.entries.iter().all(check)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Rows {
|
||||||
|
status: String,
|
||||||
|
entries: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rows {
|
||||||
|
fn valid(&self) -> bool {
|
||||||
|
matches!(self.status.as_str(), "ok" | "partial" | "unavailable")
|
||||||
|
&& (self.status != "unavailable" || self.entries.is_empty())
|
||||||
|
&& self.entries.len() <= 128
|
||||||
|
&& self.entries.iter().all(|s| clean(s, 512))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn clean(s: &str, limit: usize) -> bool {
|
||||||
|
!s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
pub(super) fn validate(bytes: &[u8]) -> Result<Value, &'static str> {
|
||||||
|
let err = "INVALID_OPNSENSE_INVENTORY";
|
||||||
|
if bytes.len() > 384 * 1024 { return Err(err); }
|
||||||
|
let s: Snapshot = serde_json::from_slice(bytes).map_err(|_| err)?;
|
||||||
|
if !s.os.starts_with("OPNsense ") || !clean(&s.os, 128)
|
||||||
|
|| !clean(&s.hostname, 255) || s.architecture != "amd64"
|
||||||
|
|| s.root_total_bytes == 0 || s.root_available_bytes > s.root_total_bytes
|
||||||
|
|| !clean(&s.cpu_model, 256) || s.logical_processors == 0 || s.memory_total_bytes == 0
|
||||||
|
|| ![&s.firewall,&s.vpn_configured,&s.wireguard,&s.openvpn,&s.ipsec].iter().all(|r| r.valid())
|
||||||
|
|| s.users.is_some_and(|r| !r.valid())
|
||||||
|
|| s.hardware.is_some_and(|h| !matches!(h.device_type.as_str(),"physical"|"virtual")
|
||||||
|
|| h.booted_at.timestamp() < 0
|
||||||
|
|| [h.manufacturer,h.bios_serial_number].into_iter().flatten().any(|v| !clean(&v,256)))
|
||||||
|
|| s.software.is_some_and(|r| !r.valid(1024, |p| clean(&p.name,256) && clean(&p.version,256)))
|
||||||
|
|| s.interfaces.is_some_and(|r| !r.valid(128, |i| clean(&i.name,128)
|
||||||
|
&& i.mac.as_ref().is_none_or(|m| clean(m,64)) && i.addresses.len()<=256
|
||||||
|
&& i.addresses.iter().all(|s| clean(s,128))))
|
||||||
|
{ return Err(err); }
|
||||||
|
serde_json::from_slice(bytes).map_err(|_| err)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
#[test]
|
||||||
|
fn no_config_blob_and_no_false_empty_on_error() {
|
||||||
|
let rows = json!({"status":"ok","entries":[]});
|
||||||
|
let mut doc = json!({"os":"OPNsense 26.7","hostname":"test","architecture":"amd64",
|
||||||
|
"root_total_bytes":20,"root_available_bytes":10,"cpu_model":"Test","logical_processors":2,
|
||||||
|
"memory_total_bytes":10,"firewall":rows,"vpn_configured":rows,"wireguard":rows,"ipsec":rows,"openvpn":rows});
|
||||||
|
assert!(validate(doc.to_string().as_bytes()).is_ok());
|
||||||
|
doc["wireguard"]["private_key"] = json!("not-permitted");
|
||||||
|
assert!(validate(doc.to_string().as_bytes()).is_err());
|
||||||
|
doc["wireguard"] = json!({"status":"unavailable","entries":["peer"]});
|
||||||
|
assert!(validate(doc.to_string().as_bytes()).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -105,7 +105,7 @@ pub async fn ingest(
|
|||||||
);
|
);
|
||||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||||
control_lock(&mut tx, tenant, agent).await?;
|
control_lock(&mut tx, tenant, agent).await?;
|
||||||
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
|
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities,customer_transfer_pending FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
|
||||||
let active = row.get::<Option<DateTime<Utc>>, _>("revoked_at").is_none()
|
let active = row.get::<Option<DateTime<Utc>>, _>("revoked_at").is_none()
|
||||||
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
|
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
|
||||||
&& row.get::<String, _>("transport") == transport;
|
&& row.get::<String, _>("transport") == transport;
|
||||||
@@ -160,7 +160,7 @@ pub async fn ingest(
|
|||||||
ensure!(
|
ensure!(
|
||||||
matches!(
|
matches!(
|
||||||
s.scope.as_str(),
|
s.scope.as_str(),
|
||||||
"linux.base" | "windows.base" | "agent.update"
|
"linux.base" | "windows.base" | "opnsense.base" | "agent.update"
|
||||||
) && s.schema_version == 1
|
) && s.schema_version == 1
|
||||||
&& s.chunk_count == 1
|
&& s.chunk_count == 1
|
||||||
&& s.chunk_index == 0
|
&& s.chunk_index == 0
|
||||||
@@ -196,6 +196,16 @@ pub async fn ingest(
|
|||||||
}
|
}
|
||||||
_ => anyhow::bail!("unsupported capability"),
|
_ => anyhow::bail!("unsupported capability"),
|
||||||
}
|
}
|
||||||
|
if row.get::<bool, _>("customer_transfer_pending")
|
||||||
|
&& (matches!(&e.payload, Some(Payload::Heartbeat(_)))
|
||||||
|
|| matches!(&e.payload, Some(Payload::InventorySnapshot(s)) if s.scope != "agent.update"))
|
||||||
|
{
|
||||||
|
sqlx::query("SELECT finish_device_customer_transfer($1,$2)")
|
||||||
|
.bind(tenant)
|
||||||
|
.bind(agent)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok(reply(
|
Ok(reply(
|
||||||
e,
|
e,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use axum::{
|
|||||||
Json, Router,
|
Json, Router,
|
||||||
extract::{Path, Query, State},
|
extract::{Path, Query, State},
|
||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
routing::{delete, post},
|
routing::{delete, patch, post},
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -26,10 +26,18 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
|||||||
post(revoke_device),
|
post(revoke_device),
|
||||||
)
|
)
|
||||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
|
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
|
||||||
|
.route(
|
||||||
|
"/api/v1/tenants/{tenant}/devices/{asset}/hypervisor",
|
||||||
|
post(assign_hypervisor),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
||||||
post(archive_device),
|
post(archive_device),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/tenants/{tenant}/devices/{asset}/purpose",
|
||||||
|
patch(update_device_purpose),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
|
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
|
||||||
post(revoke_plan),
|
post(revoke_plan),
|
||||||
@@ -128,12 +136,117 @@ async fn archive_device(
|
|||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
|
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Purpose {
|
||||||
|
purpose: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_purpose(raw: &str) -> Result<Option<String>, Error> {
|
||||||
|
let normalized = raw.replace("\r\n", "\n");
|
||||||
|
let text = normalized.trim();
|
||||||
|
if text.chars().count() > 500
|
||||||
|
|| normalized
|
||||||
|
.chars()
|
||||||
|
.any(|c| c.is_control() && !matches!(c, '\n' | '\t'))
|
||||||
|
{
|
||||||
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||||
|
}
|
||||||
|
Ok((!text.is_empty()).then(|| text.to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_device_purpose(
|
||||||
|
State(s): State<crate::State>,
|
||||||
|
h: HeaderMap,
|
||||||
|
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||||
|
Json(input): Json<Purpose>,
|
||||||
|
) -> Result<Json<Value>, Error> {
|
||||||
|
const EVENT: &str = "device_purpose_updated";
|
||||||
|
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
|
||||||
|
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||||
|
let purpose = normalize_purpose(&input.purpose)?;
|
||||||
|
let current: Option<String> = sqlx::query_scalar(
|
||||||
|
"SELECT purpose FROM assets WHERE tenant_id=$1 AND asset_id=$2
|
||||||
|
AND EXISTS (SELECT 1 FROM agent_installations a WHERE a.tenant_id=$1 AND a.asset_id=$2
|
||||||
|
AND NOT a.customer_transfer_pending)
|
||||||
|
FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(tenant)
|
||||||
|
.bind(asset)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?
|
||||||
|
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||||
|
if current != purpose {
|
||||||
|
sqlx::query("UPDATE assets SET purpose=$3 WHERE tenant_id=$1 AND asset_id=$2")
|
||||||
|
.bind(tenant)
|
||||||
|
.bind(asset)
|
||||||
|
.bind(&purpose)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
audit(
|
||||||
|
&mut tx,
|
||||||
|
&p,
|
||||||
|
EVENT,
|
||||||
|
json!({"asset_id":asset,"cleared":purpose.is_none()}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(json!({"asset_id":asset,"purpose":purpose})))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
struct Pairing {
|
struct Pairing {
|
||||||
agent_id: Uuid,
|
agent_id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct HypervisorAssignment {
|
||||||
|
// null clears the relation. A missing field is a malformed update.
|
||||||
|
#[serde(deserialize_with = "required_hypervisor_value")]
|
||||||
|
hypervisor_asset_id: Option<Uuid>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
|
||||||
|
Option::deserialize(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn assign_hypervisor(
|
||||||
|
State(s): State<crate::State>,
|
||||||
|
h: HeaderMap,
|
||||||
|
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||||
|
Query(pair): Query<Pairing>,
|
||||||
|
Json(input): Json<HypervisorAssignment>,
|
||||||
|
) -> Result<Json<Value>, Error> {
|
||||||
|
const EVENT: &str = "device_hypervisor_assigned";
|
||||||
|
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
|
||||||
|
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||||
|
|
||||||
|
// 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
|
||||||
|
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;
|
||||||
|
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?;
|
||||||
|
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?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
|
||||||
|
}
|
||||||
|
|
||||||
async fn remove_device(
|
async fn remove_device(
|
||||||
State(s): State<crate::State>,
|
State(s): State<crate::State>,
|
||||||
h: HeaderMap,
|
h: HeaderMap,
|
||||||
|
|||||||
@@ -158,11 +158,13 @@ async fn status(
|
|||||||
return Ok(private_json(json!({"transfer":null})));
|
return Ok(private_json(json!({"transfer":null})));
|
||||||
};
|
};
|
||||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||||
let hostname = target_hostname(&mut tx, &t).await?;
|
let hostname = if t.completed_at.is_some() {
|
||||||
|
target_hostname(&mut tx, &t).await?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let state = if t.completed_at.is_some() {
|
let state = if t.completed_at.is_some() {
|
||||||
"completed"
|
"completed"
|
||||||
} else if hostname.is_some() {
|
|
||||||
"ready"
|
|
||||||
} else if t.target_agent_id.is_some() {
|
} else if t.target_agent_id.is_some() {
|
||||||
"enrolled"
|
"enrolled"
|
||||||
} else {
|
} else {
|
||||||
@@ -186,7 +188,7 @@ async fn lock_source(
|
|||||||
sqlx::query_scalar(
|
sqlx::query_scalar(
|
||||||
"SELECT i.revoked_at IS NULL AND i.last_authenticated_at IS NOT NULL AND a.archived_at IS NULL
|
"SELECT i.revoked_at IS NULL AND i.last_authenticated_at IS NOT NULL AND a.archived_at IS NULL
|
||||||
FROM agent_installations i JOIN assets a USING (tenant_id,asset_id)
|
FROM agent_installations i JOIN assets a USING (tenant_id,asset_id)
|
||||||
WHERE i.asset_id=$1 AND i.agent_id=$2 FOR UPDATE OF i",
|
WHERE i.asset_id=$1 AND i.agent_id=$2 AND NOT i.customer_transfer_pending FOR UPDATE OF i",
|
||||||
)
|
)
|
||||||
.bind(asset)
|
.bind(asset)
|
||||||
.bind(agent)
|
.bind(agent)
|
||||||
@@ -320,34 +322,16 @@ async fn complete(
|
|||||||
Query(pair): Query<Pairing>,
|
Query(pair): Query<Pairing>,
|
||||||
) -> Result<Response, Error> {
|
) -> Result<Response, Error> {
|
||||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||||
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
|
verify_pairing(&mut tx, asset, pair.agent_id).await?;
|
||||||
let t = transfer(&mut tx, pair.agent_id)
|
let t = transfer(&mut tx, pair.agent_id)
|
||||||
.await?
|
.await?
|
||||||
.filter(|t| t.transfer_id == id)
|
.filter(|t| t.transfer_id == id)
|
||||||
.ok_or(NOT_FOUND)?;
|
.ok_or(NOT_FOUND)?;
|
||||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||||
if t.completed_at.is_some() {
|
// Older WebUI bundles may still request completion after the atomic cutover.
|
||||||
return Ok(private_json(json!({"state":"completed"})));
|
if t.completed_at.is_none() {
|
||||||
}
|
|
||||||
if target_hostname(&mut tx, &t).await?.is_none() {
|
|
||||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_TARGET_NOT_READY"));
|
return Err(Error(StatusCode::CONFLICT, "TRANSFER_TARGET_NOT_READY"));
|
||||||
}
|
}
|
||||||
select_tenant(&mut tx, tenant).await?;
|
|
||||||
ensure_idle(&mut tx, pair.agent_id).await?;
|
|
||||||
sqlx::query(
|
|
||||||
"UPDATE agent_installations SET revoked_at=now(), connection_generation=connection_generation+1,
|
|
||||||
previous_certificate_sha256=NULL,previous_certificate_until=NULL
|
|
||||||
WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
|
|
||||||
)
|
|
||||||
.bind(asset).bind(pair.agent_id).execute(&mut *tx).await?;
|
|
||||||
sqlx::query("UPDATE device_customer_transfers SET completed_at=now() WHERE transfer_id=$1")
|
|
||||||
.bind(id)
|
|
||||||
.execute(&mut *tx)
|
|
||||||
.await?;
|
|
||||||
audit(&mut tx, &p, "device_customer_transfer_completed", json!({
|
|
||||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":t.target_tenant_id,
|
|
||||||
"target_asset_id":t.target_asset_id,"target_agent_id":t.target_agent_id
|
|
||||||
})).await?;
|
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok(private_json(json!({"state":"completed"})))
|
Ok(private_json(json!({"state":"completed"})))
|
||||||
}
|
}
|
||||||
@@ -443,8 +427,8 @@ async fn device_certificate(
|
|||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation)
|
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation,customer_transfer_pending)
|
||||||
VALUES($1,$2,$3,$4,$5,$6)",
|
VALUES($1,$2,$3,$4,$5,$6,true)",
|
||||||
).bind(t.target_tenant_id).bind(new_asset).bind(new_agent)
|
).bind(t.target_tenant_id).bind(new_asset).bind(new_agent)
|
||||||
.bind(hash(&certificate.to_der().map_err(anyhow::Error::from)?)).bind(&pem).bind(generation)
|
.bind(hash(&certificate.to_der().map_err(anyhow::Error::from)?)).bind(&pem).bind(generation)
|
||||||
.execute(&mut *tx).await?;
|
.execute(&mut *tx).await?;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ WITH classified AS (
|
|||||||
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
|
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.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
|
||||||
a.system_usage,a.system_usage_observed_at,
|
a.system_usage,a.system_usage_observed_at,
|
||||||
asset.archived_at,t.name AS customer_name,
|
asset.archived_at,asset.hypervisor_asset_id,asset.purpose,t.name AS customer_name,
|
||||||
CASE
|
CASE
|
||||||
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
||||||
WHEN asset.archived_at IS NOT NULL THEN 'archived'
|
WHEN asset.archived_at IS NOT NULL THEN 'archived'
|
||||||
@@ -25,6 +25,8 @@ WITH classified AS (
|
|||||||
JOIN assets asset USING (tenant_id,asset_id)
|
JOIN assets asset USING (tenant_id,asset_id)
|
||||||
JOIN tenants t USING(tenant_id)
|
JOIN tenants t USING(tenant_id)
|
||||||
WHERE a.tenant_id=$1 AND a.created_at<=$2 AND a.agent_id>$3
|
WHERE a.tenant_id=$1 AND a.created_at<=$2 AND a.agent_id>$3
|
||||||
|
AND NOT a.customer_transfer_pending
|
||||||
|
AND (a.customer_transfer_activated_at IS NULL OR a.customer_transfer_activated_at<=$2)
|
||||||
AND ($4::uuid IS NULL OR a.asset_id=$4)
|
AND ($4::uuid IS NULL OR a.asset_id=$4)
|
||||||
AND ($5::uuid IS NULL OR a.agent_id=$5)
|
AND ($5::uuid IS NULL OR a.agent_id=$5)
|
||||||
)
|
)
|
||||||
@@ -32,7 +34,7 @@ SELECT c.*,o.observed_at,o.received_at,o.data,o.source_id FROM classified c
|
|||||||
LEFT JOIN LATERAL (
|
LEFT JOIN LATERAL (
|
||||||
SELECT observed_at,received_at,data,source_id FROM observations
|
SELECT observed_at,received_at,data,source_id FROM observations
|
||||||
WHERE tenant_id=c.tenant_id AND agent_id=c.agent_id AND received_at<=$2
|
WHERE tenant_id=c.tenant_id AND agent_id=c.agent_id AND received_at<=$2
|
||||||
AND source_id IN ('linux.base','windows.base')
|
AND source_id IN ('linux.base','windows.base','opnsense.base')
|
||||||
ORDER BY observed_at DESC,received_at DESC,sequence DESC LIMIT 1
|
ORDER BY observed_at DESC,received_at DESC,sequence DESC LIMIT 1
|
||||||
) o ON true
|
) o ON true
|
||||||
WHERE ($6::text IS NULL OR (c.lifecycle='current')=($6='current'))
|
WHERE ($6::text IS NULL OR (c.lifecycle='current')=($6='current'))
|
||||||
|
|||||||
+260
-16
@@ -14,6 +14,7 @@ use rmm_domain::inventory_document::DeviceType;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||||||
|
use std::collections::HashMap;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
||||||
@@ -121,15 +122,13 @@ pub async fn list(
|
|||||||
};
|
};
|
||||||
tenants.sort_unstable();
|
tenants.sort_unstable();
|
||||||
tenants.dedup();
|
tenants.dedup();
|
||||||
let hostname = q.q.as_deref().unwrap_or("").trim();
|
let hostname = hostname_filter(q.q.as_deref())?;
|
||||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
|
||||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
||||||
}
|
|
||||||
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
|
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
|
||||||
let scope = format!(
|
let scope = format!(
|
||||||
"device-fleet:{}",
|
"device-fleet:{}",
|
||||||
rmm_domain::jobs::hash(binding.to_string().as_bytes())
|
rmm_domain::jobs::hash(binding.to_string().as_bytes())
|
||||||
);
|
);
|
||||||
|
let first_page = q.cursor.is_none();
|
||||||
let mut page = Cursor::parse(
|
let mut page = Cursor::parse(
|
||||||
s,
|
s,
|
||||||
&p,
|
&p,
|
||||||
@@ -145,10 +144,15 @@ pub async fn list(
|
|||||||
let mut last = None;
|
let mut last = None;
|
||||||
let mut truncated = false;
|
let mut truncated = false;
|
||||||
let mut authorized = false;
|
let mut authorized = false;
|
||||||
|
let mut principals = Vec::new();
|
||||||
for customer in tenants {
|
for customer in tenants {
|
||||||
if page.last_tenant.is_some_and(|after| customer < after) {
|
if page.last_tenant.is_some_and(|after| customer < after) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if customer == p.tenant {
|
||||||
|
principals.push(p.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let mut headers = h.clone();
|
let mut headers = h.clone();
|
||||||
headers.insert(
|
headers.insert(
|
||||||
"x-rmm-tenant",
|
"x-rmm-tenant",
|
||||||
@@ -157,7 +161,25 @@ pub async fn list(
|
|||||||
);
|
);
|
||||||
let current = crate::jobs::principal(s, &headers, false).await?;
|
let current = crate::jobs::principal(s, &headers, false).await?;
|
||||||
crate::jobs::scope(¤t, customer, false)?;
|
crate::jobs::scope(¤t, customer, false)?;
|
||||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, customer).await?;
|
principals.push(current);
|
||||||
|
}
|
||||||
|
// Read all customers from the same snapshot so a transfer cannot appear
|
||||||
|
// under both customers if its cutover commits while listing the fleet.
|
||||||
|
let mut tx = s.pool.begin().await?;
|
||||||
|
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if first_page {
|
||||||
|
page.as_of = sqlx::query_scalar("SELECT clock_timestamp()")
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
for current in principals {
|
||||||
|
let customer = current.tenant;
|
||||||
|
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||||
|
.bind(customer.to_string())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
match crate::permissions::require_principal(&mut tx, ¤t, "inventory:read").await {
|
match crate::permissions::require_principal(&mut tx, ¤t, "inventory:read").await {
|
||||||
Err(Error(StatusCode::FORBIDDEN, _)) if tenant.is_none() => continue,
|
Err(Error(StatusCode::FORBIDDEN, _)) if tenant.is_none() => continue,
|
||||||
other => other?,
|
other => other?,
|
||||||
@@ -180,19 +202,20 @@ pub async fn list(
|
|||||||
}
|
}
|
||||||
.rows(&mut tx)
|
.rows(&mut tx)
|
||||||
.await?;
|
.await?;
|
||||||
tx.commit().await?;
|
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
|
||||||
for row in rows {
|
for row in rows {
|
||||||
if items.len() == capacity {
|
if items.len() == capacity {
|
||||||
truncated = true;
|
truncated = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
last = Some((customer, row.get::<Uuid, _>("agent_id")));
|
last = Some((customer, row.get::<Uuid, _>("agent_id")));
|
||||||
items.push(project(&row, page.as_of, tenant.is_some()));
|
items.push(project(&row, page.as_of, tenant.is_some(), &hosts));
|
||||||
}
|
}
|
||||||
if truncated {
|
if truncated {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tx.commit().await?;
|
||||||
if !authorized {
|
if !authorized {
|
||||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||||
}
|
}
|
||||||
@@ -236,7 +259,8 @@ pub async fn detail(
|
|||||||
.await?
|
.await?
|
||||||
.pop()
|
.pop()
|
||||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||||
let mut item = project(&row, now, true);
|
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"]);
|
item["volumes"] = volumes(&item["inventory"]);
|
||||||
item["recent_jobs"] = if p.permits_scope("operations:read")
|
item["recent_jobs"] = if p.permits_scope("operations:read")
|
||||||
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||||
@@ -294,6 +318,136 @@ fn device_type(hardware: &Value) -> Option<DeviceType> {
|
|||||||
DeviceType::deserialize(&hardware["device_type"]).ok()
|
DeviceType::deserialize(&hardware["device_type"]).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn inventory_device_type(data: &Value) -> Option<DeviceType> {
|
||||||
|
device_type(observed(data, "linux.hardware"))
|
||||||
|
.or_else(|| device_type(observed(data, "windows.hardware")))
|
||||||
|
.or_else(|| device_type(&data["hardware"]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hostname_filter(query: Option<&str>) -> Result<&str, Error> {
|
||||||
|
let hostname = query.unwrap_or("").trim();
|
||||||
|
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||||
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||||
|
}
|
||||||
|
Ok(hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct Host {
|
||||||
|
asset_id: Uuid,
|
||||||
|
agent_id: Uuid,
|
||||||
|
hostname: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn hypervisors(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
tenant: Uuid,
|
||||||
|
as_of: DateTime<Utc>,
|
||||||
|
ids: Option<&[Uuid]>,
|
||||||
|
hostname: &str,
|
||||||
|
limit: i64,
|
||||||
|
) -> Result<Vec<Host>, Error> {
|
||||||
|
let rows: Vec<(Uuid, Uuid, String)> = sqlx::query_as(include_str!("hypervisors.sql"))
|
||||||
|
.bind(tenant)
|
||||||
|
.bind(as_of)
|
||||||
|
.bind(ids)
|
||||||
|
.bind(hostname)
|
||||||
|
.bind(limit)
|
||||||
|
.fetch_all(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
Ok(rows.into_iter().map(|(asset_id, agent_id, hostname)| Host {
|
||||||
|
asset_id, agent_id, hostname,
|
||||||
|
}).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn assigned_hosts(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
tenant: Uuid,
|
||||||
|
as_of: DateTime<Utc>,
|
||||||
|
rows: &[PgRow],
|
||||||
|
) -> Result<HashMap<Uuid, Host>, Error> {
|
||||||
|
let mut ids: Vec<Uuid> = rows.iter().filter_map(|row| row.get("hypervisor_asset_id")).collect();
|
||||||
|
ids.sort_unstable();
|
||||||
|
ids.dedup();
|
||||||
|
if ids.is_empty() {
|
||||||
|
return Ok(HashMap::new());
|
||||||
|
}
|
||||||
|
Ok(hypervisors(tx, tenant, as_of, Some(&ids), "", ids.len() as i64)
|
||||||
|
.await?.into_iter().map(|host| (host.asset_id, host)).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hypervisor_display(data: &Value, assigned: Option<&Host>) -> Value {
|
||||||
|
if inventory_device_type(data) != Some(DeviceType::Virtual) {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
if let Some(host) = assigned {
|
||||||
|
return json!({"kind":"device","asset_id":host.asset_id,
|
||||||
|
"agent_id":host.agent_id,"hostname":host.hostname});
|
||||||
|
}
|
||||||
|
let linux = observed(data, "linux.hardware");
|
||||||
|
let windows = observed(data, "windows.hardware");
|
||||||
|
let manufacturer = linux["manufacturer"].as_str()
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
.or_else(|| linux["readable_dmi"]["sys_vendor"].as_str())
|
||||||
|
.or_else(|| windows["manufacturer"].as_str());
|
||||||
|
if manufacturer.is_some_and(|name| matches!(name.trim().to_ascii_lowercase().as_str(),
|
||||||
|
"hetzner" | "hetzner cloud" | "hetzner online" | "hetzner online gmbh")) {
|
||||||
|
return json!({"kind":"placeholder","provider":"hetzner","hostname":"Hetzner Cloud"});
|
||||||
|
}
|
||||||
|
Value::Null
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct HypervisorFilter {
|
||||||
|
q: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn hypervisor_options(
|
||||||
|
State(s): State<crate::State>,
|
||||||
|
h: HeaderMap,
|
||||||
|
Path(tenant): Path<Uuid>,
|
||||||
|
Query(query): Query<HypervisorFilter>,
|
||||||
|
) -> Result<Json<Value>, Error> {
|
||||||
|
let p = crate::jobs::principal(&s, &h, false).await?;
|
||||||
|
crate::jobs::scope(&p, tenant, false)?;
|
||||||
|
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||||
|
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||||
|
let mut hosts = hypervisors(&mut tx, tenant, Utc::now(), None,
|
||||||
|
hostname_filter(query.q.as_deref())?, 51).await?;
|
||||||
|
let truncated = hosts.len() > 50;
|
||||||
|
hosts.truncate(50);
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Json(json!({"items":hosts,"truncated":truncated})))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn validate_vm_host_assignment(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
tenant: Uuid,
|
||||||
|
asset: Uuid,
|
||||||
|
agent: Uuid,
|
||||||
|
host: Option<Uuid>,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let now = Utc::now();
|
||||||
|
let row = Selection {
|
||||||
|
tenant, asset: Some(asset), agent: Some(agent), view: Some(View::Current),
|
||||||
|
status: None, hostname: "", last: Uuid::nil(), as_of: now, limit: 1,
|
||||||
|
}.rows(tx).await?.pop().ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||||
|
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||||
|
if inventory_device_type(&data) != Some(DeviceType::Virtual) {
|
||||||
|
return Err(Error(StatusCode::CONFLICT, "HYPERVISOR_REQUIRES_VM"));
|
||||||
|
}
|
||||||
|
if let Some(host) = host {
|
||||||
|
if asset == host {
|
||||||
|
return Err(Error(StatusCode::CONFLICT, "INVALID_HYPERVISOR"));
|
||||||
|
}
|
||||||
|
if hypervisors(tx, tenant, now, Some(&[host]), "", 1).await?.is_empty() {
|
||||||
|
return Err(Error(StatusCode::NOT_FOUND, "HYPERVISOR_UNAVAILABLE"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn os_label(data: &Value) -> Option<String> {
|
fn os_label(data: &Value) -> Option<String> {
|
||||||
let linux_hardware = observed(data, "linux.hardware");
|
let linux_hardware = observed(data, "linux.hardware");
|
||||||
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
|
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
|
||||||
@@ -348,7 +502,7 @@ fn os_label(data: &Value) -> Option<String> {
|
|||||||
Some("Linux".to_owned())
|
Some("Linux".to_owned())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Host>) -> Value {
|
||||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||||
let cpu = observed(&data, "linux.cpu");
|
let cpu = observed(&data, "linux.cpu");
|
||||||
let windows = observed(&data, "windows.hardware");
|
let windows = observed(&data, "windows.hardware");
|
||||||
@@ -364,9 +518,9 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
|||||||
let ram_total = usage["ram_total_bytes"]
|
let ram_total = usage["ram_total_bytes"]
|
||||||
.as_u64()
|
.as_u64()
|
||||||
.or_else(|| linux_memory["total_bytes"].as_u64())
|
.or_else(|| linux_memory["total_bytes"].as_u64())
|
||||||
.or_else(|| windows["memory_total_bytes"].as_u64());
|
.or_else(|| windows["memory_total_bytes"].as_u64())
|
||||||
let device_type =
|
.or_else(|| data["memory_total_bytes"].as_u64());
|
||||||
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
|
let device_type = inventory_device_type(&data);
|
||||||
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
|
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
|
||||||
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
||||||
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
||||||
@@ -381,10 +535,11 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
|||||||
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
|
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
|
||||||
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
|
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
|
||||||
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
|
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
|
||||||
"hostname":data["hostname"].as_str(),"device_type":device_type,"os":os_label(&data),
|
"hostname":data["hostname"].as_str(),"purpose":row.get::<Option<String>,_>("purpose"),
|
||||||
|
"device_type":device_type,"os":os_label(&data),
|
||||||
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
|
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
|
||||||
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
|
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()).or_else(||data["cpu_model"].as_str()),
|
||||||
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
|
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()).or_else(||data["logical_processors"].as_u64()),
|
||||||
"cpu_usage_percent":cpu_usage,
|
"cpu_usage_percent":cpu_usage,
|
||||||
"cpu_usage_observed_at":cpu_observed_at,
|
"cpu_usage_observed_at":cpu_observed_at,
|
||||||
"ram_total_bytes":ram_total,
|
"ram_total_bytes":ram_total,
|
||||||
@@ -397,6 +552,14 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
|||||||
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
|
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
|
||||||
"completeness":"partial","health":"unknown"
|
"completeness":"partial","health":"unknown"
|
||||||
});
|
});
|
||||||
|
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);
|
||||||
|
if full {
|
||||||
|
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
if full {
|
if full {
|
||||||
item["inventory"] = data;
|
item["inventory"] = data;
|
||||||
item["capabilities"] = row.get("capabilities");
|
item["capabilities"] = row.get("capabilities");
|
||||||
@@ -457,6 +620,87 @@ mod tests {
|
|||||||
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
|
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hetzner_placeholder_requires_a_valid_guest_and_yields_to_a_registered_host() {
|
||||||
|
let mut data = json!({"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||||
|
"data":{"device_type":"virtual","readable_dmi":{"sys_vendor":" Hetzner "}}}]});
|
||||||
|
assert_eq!(hypervisor_display(&data, None)["kind"], "placeholder");
|
||||||
|
let host = Host { asset_id: Uuid::new_v4(), agent_id: Uuid::new_v4(), hostname: "pve01".into() };
|
||||||
|
assert_eq!(hypervisor_display(&data, Some(&host))["asset_id"], json!(host.asset_id));
|
||||||
|
data["observations"][0]["data"]["device_type"] = json!("physical");
|
||||||
|
assert!(hypervisor_display(&data, None).is_null());
|
||||||
|
data["observations"][0]["data"]["device_type"] = json!("virtual");
|
||||||
|
data["observations"][0]["quality"] = json!("error");
|
||||||
|
assert!(hypervisor_display(&data, None).is_null());
|
||||||
|
data["observations"][0] = json!({"scope":"windows.hardware","quality":"valid",
|
||||||
|
"data":{"device_type":"virtual","manufacturer":"HETZNER ONLINE GMBH"}});
|
||||||
|
assert_eq!(hypervisor_display(&data, None)["hostname"], "Hetzner Cloud");
|
||||||
|
data["observations"][0]["data"]["manufacturer"] = json!("Other company");
|
||||||
|
assert!(hypervisor_display(&data, None).is_null());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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() {
|
||||||
|
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 = Uuid::new_v4();
|
||||||
|
let other = Uuid::new_v4();
|
||||||
|
let mut ids = [Uuid::new_v4(), Uuid::new_v4()];
|
||||||
|
ids.sort_unstable();
|
||||||
|
let [vm, host] = ids;
|
||||||
|
let foreign_host = Uuid::new_v4();
|
||||||
|
for customer in [tenant, other] {
|
||||||
|
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Hypervisor test')")
|
||||||
|
.bind(customer).execute(&admin).await.unwrap();
|
||||||
|
}
|
||||||
|
for (customer, id, name, kind) in [
|
||||||
|
(tenant, vm, "guest", "virtual"),
|
||||||
|
(tenant, host, "hypervisor-1", "hypervisor"),
|
||||||
|
(other, foreign_host, "hypervisor-2", "hypervisor"),
|
||||||
|
] {
|
||||||
|
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();
|
||||||
|
let data = json!({"hostname":name,"os":"Ubuntu","root_available_bytes":10,"root_total_bytes":20,
|
||||||
|
"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||||
|
"data":{"device_type":kind,"manufacturer":"Hetzner"}}]});
|
||||||
|
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,1,now(),'linux.base','valid','partial',$5,$6,$7)")
|
||||||
|
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4())
|
||||||
|
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
|
||||||
|
}
|
||||||
|
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||||
|
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(foreign_host)).await.is_err());
|
||||||
|
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(vm)).await.is_err());
|
||||||
|
validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(host)).await.unwrap();
|
||||||
|
|
||||||
|
sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||||
|
.bind(vm).bind(host).execute(&mut *tx).await.unwrap();
|
||||||
|
let q = Selection { tenant, asset: None, agent: None, view: Some(View::Current), status: None,
|
||||||
|
hostname: "", last: Uuid::nil(), as_of: Utc::now(), limit: 1 };
|
||||||
|
let page = q.rows(&mut tx).await.unwrap();
|
||||||
|
assert_eq!(page[0].get::<Uuid,_>("asset_id"), vm);
|
||||||
|
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||||
|
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["hostname"], "hypervisor-1");
|
||||||
|
let options = hypervisors(&mut tx, tenant, q.as_of, None, "HYPERVISOR", 51).await.unwrap();
|
||||||
|
assert_eq!(options.len(), 1);
|
||||||
|
assert_eq!(options[0].asset_id, host);
|
||||||
|
|
||||||
|
sqlx::query("UPDATE assets SET archived_at=now() WHERE asset_id=$1")
|
||||||
|
.bind(host).execute(&mut *tx).await.unwrap();
|
||||||
|
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||||
|
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["kind"], "placeholder");
|
||||||
|
|
||||||
|
let result = sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||||
|
.bind(vm).bind(foreign_host).execute(&mut *tx).await.unwrap_err();
|
||||||
|
assert_eq!(result.as_database_error().unwrap().code().as_deref(), Some("23503"));
|
||||||
|
tx.rollback().await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||||
@@ -499,7 +743,7 @@ mod tests {
|
|||||||
limit: 1,
|
limit: 1,
|
||||||
};
|
};
|
||||||
let row = q.rows(&mut tx).await.unwrap().pop().unwrap();
|
let row = q.rows(&mut tx).await.unwrap().pop().unwrap();
|
||||||
let summary = project(&row, q.as_of, false);
|
let summary = project(&row, q.as_of, false, &HashMap::new());
|
||||||
assert_eq!(summary["status"], "offline");
|
assert_eq!(summary["status"], "offline");
|
||||||
assert_eq!(summary["ram_total_bytes"], 1024);
|
assert_eq!(summary["ram_total_bytes"], 1024);
|
||||||
assert_eq!(summary["cpu_model"], "Test CPU");
|
assert_eq!(summary["cpu_model"], "Test CPU");
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
SELECT asset.asset_id, host.agent_id, inventory.data->>'hostname' AS hostname
|
||||||
|
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 a.created_at<=$2
|
||||||
|
AND NOT a.customer_transfer_pending
|
||||||
|
AND (a.customer_transfer_activated_at IS NULL OR a.customer_transfer_activated_at<=$2)
|
||||||
|
AND a.last_authenticated_at IS NOT NULL AND a.last_contact_at IS NOT NULL
|
||||||
|
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
|
||||||
|
LIMIT 1
|
||||||
|
) host ON host.revoked_at IS NULL
|
||||||
|
JOIN LATERAL (
|
||||||
|
SELECT data FROM observations
|
||||||
|
WHERE tenant_id=asset.tenant_id AND agent_id=host.agent_id AND received_at<=$2
|
||||||
|
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.archived_at IS NULL
|
||||||
|
AND ($3::uuid[] IS NULL OR asset.asset_id=ANY($3))
|
||||||
|
AND nullif(btrim(inventory.data->>'hostname'),'') IS NOT NULL
|
||||||
|
AND ($4='' OR strpos(lower(inventory.data->>'hostname'), lower($4))>0)
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT FROM jsonb_array_elements(CASE WHEN jsonb_typeof(inventory.data->'observations')='array'
|
||||||
|
THEN inventory.data->'observations' ELSE '[]'::jsonb END) o
|
||||||
|
WHERE o->>'scope' IN ('linux.hardware','windows.hardware')
|
||||||
|
AND o->>'quality'='valid' AND o#>>'{data,device_type}'='hypervisor'
|
||||||
|
)
|
||||||
|
ORDER BY lower(inventory.data->>'hostname'), asset.asset_id
|
||||||
|
LIMIT $5
|
||||||
@@ -427,7 +427,7 @@ pub(crate) async fn plan_resolved(
|
|||||||
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
||||||
let mut jobs = Vec::new();
|
let mut jobs = Vec::new();
|
||||||
for asset in ids {
|
for asset in ids {
|
||||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL AND NOT customer_transfer_pending AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||||
if rows.len() != 1 {
|
if rows.len() != 1 {
|
||||||
return Err(fail(if rows.is_empty() {
|
return Err(fail(if rows.is_empty() {
|
||||||
"NOT_FOUND"
|
"NOT_FOUND"
|
||||||
@@ -683,7 +683,7 @@ async fn recheck_for(
|
|||||||
if job.payload.start_before <= Utc::now() {
|
if job.payload.start_before <= Utc::now() {
|
||||||
return Err(fail("PLAN_EXPIRED"));
|
return Err(fail("PLAN_EXPIRED"));
|
||||||
}
|
}
|
||||||
let r=sqlx::query("SELECT enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) FOR SHARE").bind(job.payload.agent_id).bind(job.payload.asset_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AUTHORIZATION_REVOKED"))?;
|
let r=sqlx::query("SELECT enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND NOT customer_transfer_pending AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) FOR SHARE").bind(job.payload.agent_id).bind(job.payload.asset_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AUTHORIZATION_REVOKED"))?;
|
||||||
if r.get::<i64, _>("assignment_version") as u64 != job.payload.assignment_version
|
if r.get::<i64, _>("assignment_version") as u64 != job.payload.assignment_version
|
||||||
|| r.get::<i64, _>("enrollment_generation") as u64 != job.payload.enrollment_generation
|
|| r.get::<i64, _>("enrollment_generation") as u64 != job.payload.enrollment_generation
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -492,6 +492,8 @@ mod tests {
|
|||||||
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
|
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
|
||||||
for request in [
|
for request in [
|
||||||
client.get(format!("{base}/{b}/devices/{asset}")),
|
client.get(format!("{base}/{b}/devices/{asset}")),
|
||||||
|
client.patch(format!("{base}/{b}/devices/{asset}/purpose"))
|
||||||
|
.json(&json!({"purpose":"foreign write"})),
|
||||||
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
|
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
|
||||||
client
|
client
|
||||||
.post(format!("{base}/{b}/operation-plans"))
|
.post(format!("{base}/{b}/operation-plans"))
|
||||||
@@ -530,6 +532,14 @@ mod tests {
|
|||||||
.send().await.unwrap().json::<Value>().await.unwrap();
|
.send().await.unwrap().json::<Value>().await.unwrap();
|
||||||
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
|
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
|
||||||
let csrf = session["csrf_token"].as_str().unwrap();
|
let csrf = session["csrf_token"].as_str().unwrap();
|
||||||
|
let detail = format!("{base}/{a}/devices/{asset}");
|
||||||
|
let purpose = format!("{detail}/purpose");
|
||||||
|
let update = |text: &str| client.patch(&purpose).header("origin", origin)
|
||||||
|
.header("cookie", cookie).json(&json!({"purpose":text}));
|
||||||
|
assert_eq!(client.patch(&purpose).bearer_auth(&token).json(&json!({"purpose":"token write"}))
|
||||||
|
.send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(update("reader denied").header("x-csrf-token", csrf)
|
||||||
|
.send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||||
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
|
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
|
||||||
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
|
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
|
||||||
@@ -537,6 +547,25 @@ mod tests {
|
|||||||
.bind(a).bind(asset).execute(&admin).await.unwrap();
|
.bind(a).bind(asset).execute(&admin).await.unwrap();
|
||||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
|
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
|
||||||
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
|
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
|
||||||
|
assert_eq!(update("missing CSRF").send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(update(&"ü".repeat(501)).header("x-csrf-token", csrf)
|
||||||
|
.send().await.unwrap().status(), StatusCode::BAD_REQUEST);
|
||||||
|
let text = "Dateiserver für Nürnberg\nNur Entwicklung";
|
||||||
|
let saved: Value = update(" Dateiserver für Nürnberg\r\nNur Entwicklung ")
|
||||||
|
.header("x-csrf-token", csrf).send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
|
||||||
|
assert_eq!(saved["purpose"], text);
|
||||||
|
let device: Value = client.get(&detail).bearer_auth(&token)
|
||||||
|
.send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
|
||||||
|
assert_eq!(device["purpose"], text);
|
||||||
|
let other: Option<String> = sqlx::query_scalar("SELECT purpose FROM assets WHERE tenant_id=$1 AND asset_id=$2")
|
||||||
|
.bind(b).bind(asset).fetch_one(&admin).await.unwrap();
|
||||||
|
assert!(other.is_none());
|
||||||
|
let cleared: Value = update(" \n ").header("x-csrf-token", csrf)
|
||||||
|
.send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
|
||||||
|
assert_eq!(cleared["purpose"], Value::Null);
|
||||||
|
let events: Vec<Value> = sqlx::query_scalar("SELECT data->'decision' FROM audit_events WHERE tenant_id=$1 AND event_type='device_purpose_updated' ORDER BY created_at")
|
||||||
|
.bind(a).fetch_all(&admin).await.unwrap();
|
||||||
|
assert_eq!(events, [json!({"asset_id":asset,"cleared":false}), json!({"asset_id":asset,"cleared":true})]);
|
||||||
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
|
||||||
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
|
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
|
||||||
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
|
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
|
||||||
|
|||||||
@@ -217,6 +217,7 @@ async fn main() -> Result<()> {
|
|||||||
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
|
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
|
||||||
.route("/api/v1/devices", get(devices::all))
|
.route("/api/v1/devices", get(devices::all))
|
||||||
.route("/api/v1/tenants/{tenant}/devices", get(devices::page))
|
.route("/api/v1/tenants/{tenant}/devices", get(devices::page))
|
||||||
|
.route("/api/v1/tenants/{tenant}/hypervisors", get(devices::hypervisor_options))
|
||||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(devices::detail));
|
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(devices::detail));
|
||||||
routes = mcp_tokens::routes(routes);
|
routes = mcp_tokens::routes(routes);
|
||||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# OPNsense-Testclient
|
||||||
|
|
||||||
|
Test-VM `discovery-opnsense` auf `qemu:///system`, 2 vCPU, 1536 MiB RAM, 12 GiB virtuelle Platte. Basis: offizielles Nano-Image OPNsense 26.7 amd64; SHA-256 des komprimierten Images `28d5e2f37e40d87468a924e3006ef10e2ddc6de485b85333d9e3958c84d0cb9d`, gegen die Herstellerankündigung verglichen und die Signatur des entpackten Images geprüft. Start bei Bedarf: `virsh -c qemu:///system start discovery-opnsense`. Konsole: `virsh -c qemu:///system console discovery-opnsense`. Das LAN `192.168.247.0/24` ist eine isolierte libvirt-Bridge, das WAN `192.168.246.0/24` verwendet NAT. Management vom Notebook: `https://192.168.247.1`. Der Hostpin stammt aus der seriellen Konsole; Zugangswerte liegen ausschließlich im privaten Zugangsspeicher des ursprünglichen Checkouts.
|
||||||
|
|
||||||
|
## Quelle und Entwicklungsinstallation
|
||||||
|
|
||||||
|
Der OPNsense-eigene Python-Interpreter führt zwei Zipapps aus. Der lokale Collector läuft mit den für PF, VPN-Sockets und Konfiguration nötigen Rechten. Er veröffentlicht ausschließlich den ausgewählten Bestand atomar in `/var/db/discovery-observations/inventory.json`. Das Dienstkonto `discovery` kann die Datei lesen, aber weder Collector noch Cache verändern. Nur dieses Konto hält die Geräteidentität und nutzt den ausgehenden HTTPS-Kanal. Für die Erfassung wird keine eingehende Netzwerkverbindung benötigt.
|
||||||
|
|
||||||
|
1. In einer Build-venv `grpcio-tools==1.76.0` und `protobuf==6.33.5` installieren. `python deploy/opnsense/build.py ARTIFAKTORDNER` generiert die Protobuf-Bindung aus `proto/agent.proto` und packt die portable Python-Laufzeit mit ein. `python deploy/opnsense/test_agent.py ARTIFAKTORDNER/agent.pyz` prüft die Wiederholung einer nicht bestätigten Inventarmeldung mit unveränderter Nachrichtenidentität.
|
||||||
|
2. Über den gepinnten Entwicklungszugang `agent.pyz`, `collect.pyz`, `discovery_agent` und den **bestätigten öffentlichen CA-Anker des Gerätegateways** als `ca.pem` in einen privaten Stagingordner im Gast übertragen. `sh install-dev.sh STAGINGORDNER` auf dem Gast ausführen. Diese Strecke ist eine direkte Entwicklungsbereitstellung, kein signierter Releasekanal.
|
||||||
|
3. Bei einer frischen Installation in der Discovery-WebUI den Testkunden wählen und einen Einmalcode erzeugen. Den Code über geschützte Standardeingabe an `su -m discovery -c '/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/agent.pyz enroll'` übergeben. Danach `service discovery_agent start`. Bei vorhandener Identität nicht neu enrollen. Der Dienst verwaltet beide Prozesse; `rc.conf.local` aktiviert sie beim Start.
|
||||||
|
4. In **Geräte** den Hostnamen öffnen. Das Inventar wird ungefähr einmal pro Minute erhoben, der Heartbeat etwa alle 20 Sekunden gesendet. Das Betriebssystem liefert CPU-Zeitdifferenzen und eine RAM-Schätzung aus freien und inaktiven Seiten. Fehlgeschlagene Quellen erscheinen als „Nicht ermittelbar“, ein erfolgreicher leerer Befund gesondert. Pro Liste werden höchstens 128 Zeilen gemeldet; Auszüge sind gekennzeichnet.
|
||||||
|
|
||||||
|
**Systeminventar:** Kern-Bootzeit, VM-Erkennung, verfügbare SMBIOS-Daten, Netzwerkkarten mit MAC und IPs, angemeldete Benutzer und lokale FreeBSD-Pakete mit Version. Bei Software liegt die Obergrenze bei 1024 Paketen.
|
||||||
|
|
||||||
|
**VPN:** Beschreibungen und Aktivierung der OPNsense-Modelle für WireGuard-Instanzen/-Peers, OpenVPN-Instanzen und IPsec-Verbindungen. Separat: WireGuard-Handshakes (kein dauerhafter Online-Status), OpenVPN-Managementstatus und IKE-Sicherheitsassoziationen. Ohne erreichbaren IPsec-Dienst ist der Laufzeitstatus unbekannt. Keine privaten Schlüssel, PSKs, Zertifikate oder vollständige Gerätekonfiguration im Inventar.
|
||||||
|
|
||||||
|
**Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze.
|
||||||
|
|
||||||
|
**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.
|
||||||
|
|
||||||
|
**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.
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
"""Unprivileged OPNsense telemetry channel. Input never selects a local command."""
|
||||||
|
import hashlib
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import agent_pb2 as pb
|
||||||
|
|
||||||
|
STATE = Path('/var/db/discovery-agent')
|
||||||
|
CA = '/usr/local/etc/discovery-agent/ca.pem'
|
||||||
|
HOST = 'discovery.ease-technologies.de'
|
||||||
|
MEDIA = 'application/x-protobuf'
|
||||||
|
VERSION = '0.1.0-opnsense.4'
|
||||||
|
|
||||||
|
|
||||||
|
def post(ctx, path, data, media):
|
||||||
|
conn = http.client.HTTPSConnection(HOST, context=ctx, timeout=15)
|
||||||
|
try:
|
||||||
|
conn.request('POST', '/agent/v1/'+path, data, {'Content-Type':media, 'Accept':media})
|
||||||
|
res = conn.getresponse()
|
||||||
|
if res.status != 200 or res.getheader('Content-Type', '').split(';')[0] != media:
|
||||||
|
raise ValueError(f'{path}: HTTP {res.status}')
|
||||||
|
body = res.read(1024*1024 + 1)
|
||||||
|
if len(body) > 1024*1024:
|
||||||
|
raise ValueError('response size')
|
||||||
|
return body
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def context():
|
||||||
|
return ssl.create_default_context(cafile=CA)
|
||||||
|
|
||||||
|
|
||||||
|
def enroll():
|
||||||
|
# Existing keys are never overwritten, including after an ambiguous POST.
|
||||||
|
key = STATE/'device.key'
|
||||||
|
if key.exists() or (STATE/'identity.json').exists():
|
||||||
|
raise RuntimeError('installation already initialized')
|
||||||
|
token = sys.stdin.readline(128).strip()
|
||||||
|
if not re.fullmatch('[0-9a-f]{64}', token):
|
||||||
|
raise ValueError('invalid enrollment code')
|
||||||
|
csr = subprocess.check_output(['/usr/bin/openssl','req','-new','-newkey','ec','-pkeyopt',
|
||||||
|
'ec_paramgen_curve:P-256','-nodes','-subj','/CN=discovery-agent','-keyout',str(key)],
|
||||||
|
stderr=subprocess.DEVNULL)
|
||||||
|
result = json.loads(post(context(), 'enroll', json.dumps(dict(token=token, csr_pem=csr.decode())),
|
||||||
|
'application/json'))
|
||||||
|
for name in ('agent_id','asset_id'):
|
||||||
|
uuid.UUID(result[name])
|
||||||
|
(STATE/'device.pem').write_text(result.pop('certificate_pem'))
|
||||||
|
context().load_cert_chain(STATE/'device.pem', key)
|
||||||
|
(STATE/'identity.json').write_text(json.dumps(result))
|
||||||
|
|
||||||
|
|
||||||
|
def durable_write(path, data):
|
||||||
|
tmp = path.with_suffix('.new')
|
||||||
|
with tmp.open('wb') as f:
|
||||||
|
f.write(data)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp, path)
|
||||||
|
fd = os.open(STATE, os.O_DIRECTORY)
|
||||||
|
try:
|
||||||
|
os.fsync(fd)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
|
def renew(ctx, identity):
|
||||||
|
# Reuse a durable request after a lost reply; gateway renewal is idempotent
|
||||||
|
# for the same CSR. Keep the currently working certificate until key match.
|
||||||
|
cert, key, csr = (STATE/n for n in ('device.pem','device.key','renewal.csr'))
|
||||||
|
if not csr.exists():
|
||||||
|
check = subprocess.run(['/usr/bin/openssl','x509','-in',str(cert),'-noout','-checkend','604800'],
|
||||||
|
stdout=subprocess.DEVNULL, check=False)
|
||||||
|
if check.returncode == 0:
|
||||||
|
return False
|
||||||
|
durable_write(csr,subprocess.check_output(['/usr/bin/openssl','req','-new','-key',str(key),
|
||||||
|
'-subj','/CN=discovery-agent']))
|
||||||
|
result = json.loads(post(ctx,'certificates/renew',json.dumps({'csr_pem':csr.read_text()}),'application/json'))
|
||||||
|
if result['agent_id'] != identity['agent_id']:
|
||||||
|
raise ValueError('renewal identity mismatch')
|
||||||
|
candidate = STATE/'candidate.pem'
|
||||||
|
durable_write(candidate,result['certificate_pem'].encode())
|
||||||
|
context().load_cert_chain(candidate,key)
|
||||||
|
durable_write(cert,candidate.read_bytes())
|
||||||
|
candidate.unlink()
|
||||||
|
csr.unlink()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def usage(previous):
|
||||||
|
def counters(*keys):
|
||||||
|
return [int(x) for x in subprocess.check_output(['/sbin/sysctl', '-n', *keys],timeout=3).split()]
|
||||||
|
ticks = counters('kern.cp_time')
|
||||||
|
free, inactive, page, total = counters('vm.stats.vm.v_free_count','vm.stats.vm.v_inactive_count',
|
||||||
|
'hw.pagesize','hw.physmem')
|
||||||
|
sample = pb.SystemUsage(ram_available_bytes=min((free+inactive)*page,total),ram_total_bytes=total)
|
||||||
|
if previous and len(previous) == len(ticks) and all(x >= y for x,y in zip(ticks,previous)):
|
||||||
|
delta = sum(ticks)-sum(previous)
|
||||||
|
if delta > 0:
|
||||||
|
sample.cpu_usage_basis_points = 10000*(delta-ticks[-1]+previous[-1])//delta
|
||||||
|
return sample,ticks
|
||||||
|
|
||||||
|
|
||||||
|
def session(db, identity, boot, instance):
|
||||||
|
ctx = context()
|
||||||
|
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
|
||||||
|
generation = 0
|
||||||
|
|
||||||
|
def send(kind, payload, captured=None):
|
||||||
|
# A lost inventory ACK replays the exact durable envelope, including its
|
||||||
|
# original time, boot and sequence; only the connection fence changes.
|
||||||
|
with db:
|
||||||
|
pending = db.execute('SELECT envelope FROM pending WHERE id=1').fetchone() if kind=='inventory_snapshot' else None
|
||||||
|
if pending:
|
||||||
|
e = pb.Envelope.FromString(pending[0])
|
||||||
|
if e.agent_id != identity['agent_id']:
|
||||||
|
raise ValueError('pending snapshot identity')
|
||||||
|
e.connection_generation = generation
|
||||||
|
else:
|
||||||
|
seq = db.execute('UPDATE sequence SET n=n+1 RETURNING n').fetchone()[0]
|
||||||
|
e = pb.Envelope(protocol_major=1, message_id=str(uuid.uuid4()), agent_id=identity['agent_id'],
|
||||||
|
enrollment_generation=1, connection_generation=generation, boot_id=boot,
|
||||||
|
sequence=seq, observed_at=captured or time.time_ns()//1_000_000)
|
||||||
|
getattr(e, kind).CopyFrom(payload)
|
||||||
|
if kind == 'inventory_snapshot':
|
||||||
|
db.execute('INSERT INTO pending VALUES(1,?,?)',(e.SerializeToString(),e.observed_at))
|
||||||
|
batch = pb.MessageBatch(protocol_major=1, messages=[e])
|
||||||
|
reply = pb.MessageBatch.FromString(post(ctx, 'messages', batch.SerializeToString(), MEDIA))
|
||||||
|
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')
|
||||||
|
if kind == 'client_hello':
|
||||||
|
if (r.WhichOneof('payload') != 'server_hello' or r.connection_generation == 0 or
|
||||||
|
r.connection_generation != r.server_hello.connection_generation or
|
||||||
|
r.server_hello.max_message_bytes != 1024*1024):
|
||||||
|
raise ValueError('invalid server hello')
|
||||||
|
return r.connection_generation
|
||||||
|
if (r.connection_generation != generation or r.WhichOneof('payload') != 'ack'
|
||||||
|
or r.ack.message_id != e.message_id):
|
||||||
|
raise ValueError('unconfirmed message')
|
||||||
|
if kind == 'inventory_snapshot':
|
||||||
|
with db:
|
||||||
|
db.execute('DELETE FROM pending WHERE id=1')
|
||||||
|
|
||||||
|
if renew(ctx, identity):
|
||||||
|
ctx = context()
|
||||||
|
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
|
||||||
|
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=['heartbeat/1','opnsense.base/1']))
|
||||||
|
last = None
|
||||||
|
previous = None
|
||||||
|
check_cert = time.monotonic()+12*3600
|
||||||
|
while True:
|
||||||
|
if time.monotonic() >= check_cert:
|
||||||
|
if renew(ctx, identity):
|
||||||
|
return
|
||||||
|
check_cert = time.monotonic()+12*3600
|
||||||
|
sample,previous = usage(previous)
|
||||||
|
send('heartbeat',pb.Heartbeat(instance_id=instance,uptime_seconds=int(time.clock_gettime(time.CLOCK_UPTIME)),
|
||||||
|
system_usage=sample))
|
||||||
|
with db:
|
||||||
|
# The ingestion contract accepts observations for 72 hours.
|
||||||
|
db.execute('DELETE FROM pending WHERE observed < ?', (time.time_ns()//1_000_000 - 72*3600*1000,))
|
||||||
|
if db.execute('SELECT 1 FROM pending').fetchone():
|
||||||
|
send('inventory_snapshot',None)
|
||||||
|
file = Path('/var/db/discovery-observations/inventory.json')
|
||||||
|
if file.exists():
|
||||||
|
with file.open('rb') as f:
|
||||||
|
stamp = os.fstat(f.fileno()).st_mtime_ns
|
||||||
|
if stamp != last and 0 <= time.time()-stamp/1e9 <= 120:
|
||||||
|
raw = f.read(384*1024+1)
|
||||||
|
if len(raw) > 384*1024:
|
||||||
|
raise ValueError('snapshot size')
|
||||||
|
send('inventory_snapshot',pb.InventorySnapshot(snapshot_id=str(uuid.uuid4()),
|
||||||
|
scope='opnsense.base',schema_version=1,chunk_count=1,data=raw,
|
||||||
|
sha256=hashlib.sha256(raw).digest(),completeness='partial'),stamp//1_000_000)
|
||||||
|
last = stamp
|
||||||
|
time.sleep(20)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
os.umask(0o077)
|
||||||
|
if sys.argv[1:] == ['enroll']:
|
||||||
|
return enroll()
|
||||||
|
identity = json.loads((STATE/'identity.json').read_bytes())
|
||||||
|
db = sqlite3.connect(STATE/'channel.sqlite')
|
||||||
|
with db:
|
||||||
|
db.execute('CREATE TABLE IF NOT EXISTS sequence(id INTEGER PRIMARY KEY CHECK(id=1),n INTEGER NOT NULL)')
|
||||||
|
db.execute('CREATE TABLE IF NOT EXISTS pending(id INTEGER PRIMARY KEY CHECK(id=1),envelope BLOB NOT NULL,observed INTEGER NOT NULL)')
|
||||||
|
db.execute('INSERT OR IGNORE INTO sequence VALUES(1,0)')
|
||||||
|
started = subprocess.check_output(['/sbin/sysctl','-n','kern.boottime']).decode().split('}')[0]
|
||||||
|
boot = str(uuid.uuid5(uuid.UUID(identity['agent_id']),started))
|
||||||
|
instance = str(uuid.uuid4())
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
session(db, identity, boot, instance)
|
||||||
|
except Exception as exc:
|
||||||
|
print('OPNsense channel:', type(exc).__name__, str(exc)[:160], flush=True)
|
||||||
|
time.sleep(30)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Build two FreeBSD Python zipapps; use grpcio-tools 1.76.0 + protobuf 6.33.5."""
|
||||||
|
import importlib.metadata as metadata
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import zipapp
|
||||||
|
|
||||||
|
here = Path(__file__).resolve().parent
|
||||||
|
out = Path(sys.argv[1])
|
||||||
|
out.mkdir(exist_ok=True, parents=True)
|
||||||
|
if metadata.version('protobuf') != '6.33.5' or metadata.version('grpcio-tools') != '1.76.0':
|
||||||
|
sys.exit('Unexpected protocol builder dependencies')
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
work = Path(tmp)
|
||||||
|
proto = here.parents[1]/'proto'
|
||||||
|
subprocess.run([sys.executable,'-m','grpc_tools.protoc','-I'+str(proto),'--python_out='+tmp,
|
||||||
|
str(proto/'agent.proto')],check=True)
|
||||||
|
dist = metadata.distribution('protobuf')
|
||||||
|
for f in dist.files:
|
||||||
|
if str(f).startswith('google/protobuf/') and f.suffix == '.py':
|
||||||
|
dst = work/f
|
||||||
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(dist.locate_file(f), dst)
|
||||||
|
(work/'google/__init__.py').touch()
|
||||||
|
license_file = next(f for f in dist.files if f.name=='LICENSE' and '.dist-info/' in str(f))
|
||||||
|
shutil.copyfile(dist.locate_file(license_file),work/'LICENSE-protobuf')
|
||||||
|
shutil.copyfile(here/'agent.py',work/'__main__.py')
|
||||||
|
zipapp.create_archive(work,out/'agent.pyz',compressed=True)
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
shutil.copyfile(here/'collect.py',Path(tmp)/'__main__.py')
|
||||||
|
zipapp.create_archive(tmp,out/'collect.pyz',compressed=True)
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""Bounded local inventory projection. Runs independently of the network agent."""
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import resource
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
CACHE = Path('/var/db/discovery-observations')
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
# Appliance commands may produce much more than one snapshot. Cap the
|
||||||
|
# producer before reading its output, including on a misconfigured host.
|
||||||
|
def limits():
|
||||||
|
resource.setrlimit(resource.RLIMIT_FSIZE, (2**21, 2**21))
|
||||||
|
with tempfile.TemporaryFile() as out:
|
||||||
|
subprocess.run(args, stdout=out, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
|
||||||
|
check=True, timeout=10, preexec_fn=limits)
|
||||||
|
out.seek(0)
|
||||||
|
return out.read(2**21).decode('utf8', errors='replace').strip()
|
||||||
|
|
||||||
|
|
||||||
|
def sysctl(name):
|
||||||
|
return run('/sbin/sysctl', '-n', name)
|
||||||
|
|
||||||
|
|
||||||
|
def rows(provider):
|
||||||
|
entries = []
|
||||||
|
partial = False
|
||||||
|
try:
|
||||||
|
for text in provider():
|
||||||
|
if len(entries) == 128:
|
||||||
|
partial = True
|
||||||
|
break
|
||||||
|
text = ' '.join(text.split())
|
||||||
|
if len(text.encode()) > 512:
|
||||||
|
partial = True
|
||||||
|
text = text.encode()[:509].decode(errors='ignore') + '…'
|
||||||
|
if text:
|
||||||
|
entries.append(text)
|
||||||
|
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.SubprocessError):
|
||||||
|
return dict(status='partial' if entries else 'unavailable', entries=entries)
|
||||||
|
return dict(status='partial' if partial else 'ok', entries=entries)
|
||||||
|
|
||||||
|
|
||||||
|
def configured(config_path='/conf/config.xml'):
|
||||||
|
# Project only these model paths and display fields. Never serialize XML.
|
||||||
|
with open(config_path, 'rb') as f:
|
||||||
|
data = f.read(8 * 1024 * 1024 + 1)
|
||||||
|
if len(data) > 8 * 1024 * 1024:
|
||||||
|
raise ValueError('config size')
|
||||||
|
root = ET.fromstring(data)
|
||||||
|
for title, path, field in [
|
||||||
|
('WireGuard-Instanz', 'wireguard/server/servers/server', 'name'),
|
||||||
|
('WireGuard-Peer', 'wireguard/client/clients/client', 'name'),
|
||||||
|
('IPsec', 'Swanctl/Connections/Connection', 'description'),
|
||||||
|
('OpenVPN', 'OpenVPN/Instances/Instance', 'description'),
|
||||||
|
]:
|
||||||
|
for item in root.findall('OPNsense/' + path):
|
||||||
|
enabled = {'0': 'deaktiviert', '1': 'aktiviert'}.get(item.findtext('enabled'), 'Status unbekannt')
|
||||||
|
yield f"{title} · {item.findtext(field) or item.get('uuid') or '–'} · {enabled}"
|
||||||
|
|
||||||
|
|
||||||
|
def wireguard():
|
||||||
|
for line in run('/usr/bin/wg', 'show', 'all', 'latest-handshakes').splitlines():
|
||||||
|
interface, public_key, epoch = line.split()
|
||||||
|
stamp = datetime.datetime.fromtimestamp(int(epoch), datetime.timezone.utc).isoformat() if int(epoch) else 'nie'
|
||||||
|
yield f'{interface} · {public_key} · {stamp}'
|
||||||
|
|
||||||
|
|
||||||
|
def openvpn():
|
||||||
|
data = json.loads(run('/usr/local/opnsense/scripts/openvpn/ovpn_status.py', '--options', 'client,server'))
|
||||||
|
for role in ('server', 'client'):
|
||||||
|
for instance, status in data.get(role, {}).items():
|
||||||
|
yield f"{role} {instance} · {status.get('status', 'unbekannt')}"
|
||||||
|
for peer in status.get('client_list', []):
|
||||||
|
yield f"{instance} · {peer.get('common_name', '–')} · {peer.get('real_address', '–')}"
|
||||||
|
|
||||||
|
|
||||||
|
def ipsec():
|
||||||
|
# Only IKE summary lines, not CHILD_SA details or authentication settings.
|
||||||
|
for line in run('/usr/local/sbin/swanctl', '--list-sas').splitlines():
|
||||||
|
if re.match(r'^\S.*: #\d+, ', line):
|
||||||
|
yield line
|
||||||
|
|
||||||
|
|
||||||
|
def interfaces():
|
||||||
|
item = None
|
||||||
|
for line in run('/sbin/ifconfig','-f','inet:cidr,inet6:cidr','-a').splitlines():
|
||||||
|
if line and not line[0].isspace():
|
||||||
|
if item:
|
||||||
|
yield item
|
||||||
|
item = dict(name=line.split(':',1)[0],mac=None,addresses=[])
|
||||||
|
elif item:
|
||||||
|
fields = line.split()
|
||||||
|
if len(fields)>1 and fields[0]=='ether':
|
||||||
|
item['mac'] = fields[1]
|
||||||
|
elif len(fields)>1 and fields[0] in ('inet','inet6'):
|
||||||
|
item['addresses'].append(fields[1])
|
||||||
|
if item:
|
||||||
|
yield item
|
||||||
|
|
||||||
|
|
||||||
|
def packages():
|
||||||
|
for line in run('/usr/sbin/pkg','query','%n\t%v').splitlines():
|
||||||
|
name,version = line.split('\t',1)
|
||||||
|
yield dict(name=name,version=version)
|
||||||
|
|
||||||
|
|
||||||
|
def inventory_rows(fn, limit):
|
||||||
|
entries = []
|
||||||
|
try:
|
||||||
|
for item in fn():
|
||||||
|
if len(entries) >= limit:
|
||||||
|
return dict(status='partial',entries=entries)
|
||||||
|
entries.append(item)
|
||||||
|
return dict(status='ok',entries=entries)
|
||||||
|
except (OSError,ValueError,subprocess.SubprocessError):
|
||||||
|
return dict(status='partial' if entries else 'unavailable',entries=entries)
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot():
|
||||||
|
disk = os.statvfs('/')
|
||||||
|
boot = int(re.search(r'sec = (\d+)',sysctl('kern.boottime'))[1])
|
||||||
|
hardware = {'device_type':'physical' if sysctl('kern.vm_guest')=='none' else 'virtual',
|
||||||
|
'booted_at':datetime.datetime.fromtimestamp(boot,datetime.timezone.utc).isoformat()}
|
||||||
|
for key,name in [('smbios.system.maker','manufacturer'),('smbios.system.serial','bios_serial_number')]:
|
||||||
|
try:
|
||||||
|
value = run('/bin/kenv',key)
|
||||||
|
if value and value.lower() not in ('none','unknown','not specified','default string'):
|
||||||
|
hardware[name]=value[:128]
|
||||||
|
except (OSError,subprocess.SubprocessError):
|
||||||
|
pass
|
||||||
|
return dict(os=run('/usr/local/sbin/opnsense-version'), hostname=socket.gethostname(),
|
||||||
|
architecture=os.uname().machine, root_total_bytes=disk.f_blocks*disk.f_frsize,
|
||||||
|
root_available_bytes=max(0,disk.f_bavail)*disk.f_frsize, cpu_model=sysctl('hw.model'),
|
||||||
|
logical_processors=int(sysctl('hw.ncpu')), memory_total_bytes=int(sysctl('hw.physmem')),
|
||||||
|
firewall=rows(lambda: run('/sbin/pfctl', '-sr').splitlines()), vpn_configured=rows(configured),
|
||||||
|
wireguard=rows(wireguard), openvpn=rows(openvpn), ipsec=rows(ipsec),
|
||||||
|
hardware=hardware, interfaces=inventory_rows(interfaces,128), software=inventory_rows(packages,1024),
|
||||||
|
users=rows(lambda:sorted(set(run('/usr/bin/users').split()))))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with tempfile.NamedTemporaryFile(dir=CACHE, delete=False) as f:
|
||||||
|
f.write(json.dumps(snapshot(), ensure_ascii=False).encode())
|
||||||
|
os.fchmod(f.fileno(), 0o640)
|
||||||
|
os.replace(f.name, CACHE/'inventory.json')
|
||||||
|
except Exception as exc:
|
||||||
|
print('OPNsense collection:', type(exc).__name__, flush=True)
|
||||||
|
if 'f' in locals():
|
||||||
|
Path(f.name).unlink(missing_ok=True)
|
||||||
|
time.sleep(60)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# PROVIDE: discovery_agent
|
||||||
|
# REQUIRE: NETWORKING
|
||||||
|
# KEYWORD: shutdown
|
||||||
|
. /etc/rc.subr
|
||||||
|
name=discovery_agent
|
||||||
|
rcvar=discovery_agent_enable
|
||||||
|
load_rc_config "$name"
|
||||||
|
: "${discovery_agent_enable:=NO}"
|
||||||
|
start_cmd=discovery_start
|
||||||
|
stop_cmd=discovery_stop
|
||||||
|
|
||||||
|
discovery_start() {
|
||||||
|
for part in collect agent; do
|
||||||
|
pid=/var/run/discovery-$part.pid
|
||||||
|
[ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue
|
||||||
|
user=root
|
||||||
|
[ "$part" != agent ] || user=discovery
|
||||||
|
/usr/sbin/daemon -f -r -R 10 -P "$pid" -u "$user" -S -T "discovery-$part" \
|
||||||
|
/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/"$part".pyz || return 1
|
||||||
|
done
|
||||||
|
}
|
||||||
|
discovery_stop() {
|
||||||
|
for part in agent collect; do
|
||||||
|
pid=$(check_pidfile "/var/run/discovery-$part.pid" /usr/sbin/daemon)
|
||||||
|
[ -z "$pid" ] || kill -TERM "$pid"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
run_rc_command "$1"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Direct artifact deployment in the test guest. Enrollment is a separate step.
|
||||||
|
set -eu
|
||||||
|
[ "$(id -u)" = 0 ] && [ "$(uname -s)" = FreeBSD ] && [ -x /usr/local/sbin/opnsense-version ]
|
||||||
|
[ "$#" = 1 ] || { echo 'Usage: install-dev.sh /path/to/staged-artifacts' >&2; exit 2; }
|
||||||
|
src=$1
|
||||||
|
for f in agent.pyz collect.pyz discovery_agent ca.pem; do [ -f "$src/$f" ]; done
|
||||||
|
/usr/bin/openssl x509 -in "$src/ca.pem" -noout -checkend 0 >/dev/null
|
||||||
|
pw groupshow discovery >/dev/null 2>&1 || pw groupadd discovery
|
||||||
|
pw usershow discovery >/dev/null 2>&1 || pw useradd discovery -g discovery -d /var/db/discovery-agent -s /usr/sbin/nologin
|
||||||
|
[ "$(id -gn discovery)" = discovery ] && [ "$(id -u discovery)" != 0 ]
|
||||||
|
app=/usr/local/libexec/discovery-agent
|
||||||
|
conf=/usr/local/etc/discovery-agent
|
||||||
|
rc=/usr/local/etc/rc.d/discovery_agent
|
||||||
|
install -d -o root -g wheel -m 0755 "$app" "$conf"
|
||||||
|
install -d -o discovery -g discovery -m 0700 /var/db/discovery-agent
|
||||||
|
install -d -o root -g discovery -m 2750 /var/db/discovery-observations
|
||||||
|
if [ -e "$conf/ca.pem" ]; then
|
||||||
|
cmp -s "$conf/ca.pem" "$src/ca.pem" || { echo 'Existing trust anchor differs' >&2; exit 1; }
|
||||||
|
fi
|
||||||
|
for part in collect agent; do
|
||||||
|
install -o root -g wheel -m 0444 "$src/$part.pyz" "$app/$part.next"
|
||||||
|
done
|
||||||
|
if [ -x "$rc" ]; then
|
||||||
|
"$rc" onestop
|
||||||
|
for _ in 1 2 3 4 5; do
|
||||||
|
[ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || break
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ]; then
|
||||||
|
echo 'Existing service still running' >&2; exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
for part in collect agent; do mv -f "$app/$part.next" "$app/$part.pyz"; done
|
||||||
|
install -o root -g wheel -m 0444 "$src/ca.pem" "$conf/ca.pem"
|
||||||
|
install -o root -g wheel -m 0555 "$src/discovery_agent" "$rc"
|
||||||
|
sysrc -f /etc/rc.conf.local discovery_agent_enable=YES >/dev/null
|
||||||
|
if [ -s /var/db/discovery-agent/identity.json ]; then
|
||||||
|
"$rc" start
|
||||||
|
else
|
||||||
|
echo 'Ready for enrollment under the discovery service account.'
|
||||||
|
fi
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Run from the protocol-builder venv: python test_agent.py <built agent.pyz>."""
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
sys.path.insert(0,sys.argv.pop(1))
|
||||||
|
spec = importlib.util.spec_from_file_location('opn_channel', Path(__file__).with_name('agent.py'))
|
||||||
|
a = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(a)
|
||||||
|
|
||||||
|
|
||||||
|
class Reconnect(unittest.TestCase):
|
||||||
|
def test_lost_ack_keeps_original_identity_after_restart(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
db = sqlite3.connect(':memory:')
|
||||||
|
db.executescript('CREATE TABLE sequence(id INTEGER PRIMARY KEY,n INTEGER);INSERT INTO sequence VALUES(1,0);'
|
||||||
|
'CREATE TABLE pending(id INTEGER PRIMARY KEY,envelope BLOB,observed INTEGER);')
|
||||||
|
cache = Path(temp)/'inventory.json'
|
||||||
|
cache.write_text('{}')
|
||||||
|
identity = {'agent_id':str(uuid.uuid4())}
|
||||||
|
instance = str(uuid.uuid4())
|
||||||
|
captures = []
|
||||||
|
generation = 0
|
||||||
|
|
||||||
|
def gateway(_ctx,path,data,media):
|
||||||
|
nonlocal generation
|
||||||
|
req = a.pb.MessageBatch.FromString(data).messages[0]
|
||||||
|
reply = a.pb.Envelope()
|
||||||
|
reply.CopyFrom(req)
|
||||||
|
kind = req.WhichOneof('payload')
|
||||||
|
if kind == 'client_hello':
|
||||||
|
generation += 1
|
||||||
|
reply.connection_generation = generation
|
||||||
|
reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=generation,max_message_bytes=1024*1024))
|
||||||
|
else:
|
||||||
|
if kind == 'inventory_snapshot':
|
||||||
|
captures.append(req)
|
||||||
|
if len(captures)==1: raise OSError('lost ACK')
|
||||||
|
reply.ack.CopyFrom(a.pb.Ack(message_id=req.message_id))
|
||||||
|
return a.pb.MessageBatch(protocol_major=1,messages=[reply]).SerializeToString()
|
||||||
|
|
||||||
|
with patch.object(a,'context'), patch.object(a,'renew',return_value=False), \
|
||||||
|
patch.object(a,'post',gateway), patch.object(a,'Path',return_value=cache), \
|
||||||
|
patch.object(a,'usage',return_value=(a.pb.SystemUsage(),[])), \
|
||||||
|
patch.object(a.time,'clock_gettime',return_value=100), \
|
||||||
|
patch.object(a.time,'CLOCK_UPTIME',1,create=True), patch.object(a.time,'sleep',side_effect=StopIteration):
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
a.session(db,identity,str(uuid.uuid4()),instance)
|
||||||
|
self.assertIsNotNone(db.execute('SELECT 1 FROM pending').fetchone())
|
||||||
|
os.unlink(cache)
|
||||||
|
with self.assertRaises(StopIteration):
|
||||||
|
a.session(db,identity,str(uuid.uuid4()),instance)
|
||||||
|
self.assertIsNone(db.execute('SELECT 1 FROM pending').fetchone())
|
||||||
|
self.assertEqual(len(captures),2)
|
||||||
|
self.assertNotEqual(captures[0].connection_generation,captures[1].connection_generation)
|
||||||
|
captures[0].connection_generation=captures[1].connection_generation
|
||||||
|
self.assertEqual(captures[0],captures[1])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
import collect
|
||||||
|
|
||||||
|
|
||||||
|
class ApplianceProjection(unittest.TestCase):
|
||||||
|
def test_configured_disabled_is_not_a_connection_and_secrets_stay_local(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
p = Path(root)/'config.xml'
|
||||||
|
p.write_text('<opnsense><OPNsense><wireguard><server><servers><server uuid="uuid">'
|
||||||
|
'<name>Test</name><enabled>0</enabled><privkey>do-not-export</privkey>'
|
||||||
|
'</server></servers></server></wireguard><OpenVPN><Instances><Instance>'
|
||||||
|
'<enabled>1</enabled><description>Lab</description><tlskey>do-not-export</tlskey>'
|
||||||
|
'</Instance></Instances></OpenVPN></OPNsense></opnsense>')
|
||||||
|
self.assertEqual(collect.rows(lambda:collect.configured(p)), {
|
||||||
|
'status':'ok','entries':['WireGuard-Instanz · Test · deaktiviert','OpenVPN · Lab · aktiviert']})
|
||||||
|
p.write_text('<broken')
|
||||||
|
self.assertEqual(collect.rows(lambda:collect.configured(p)),{'status':'unavailable','entries':[]})
|
||||||
|
|
||||||
|
def test_truncation_is_explicit_and_utf8_stays_within_the_wire_limit(self):
|
||||||
|
result = collect.rows(lambda:iter(['ü'*1000]*200))
|
||||||
|
self.assertEqual((result['status'],len(result['entries'])),('partial',128))
|
||||||
|
self.assertTrue(all(len(s.encode())<=512 for s in result['entries']))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"rules": 91,
|
||||||
|
"source": "opnsense.base",
|
||||||
|
"tenant": "Ease Testserver - For development",
|
||||||
|
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
|
||||||
|
"asset_id": "1d0b9642-9f31-4fba-95f3-8cc15a11aa34",
|
||||||
|
"tenant_id": "9d730e0a-ba31-402c-8b82-8995c2585f59",
|
||||||
|
"transport": "https",
|
||||||
|
"cpu_reported": true,
|
||||||
|
"inventory_at": "2026-11-19T19:11:42.453+00:00",
|
||||||
|
"ram_reported": true,
|
||||||
|
"agent_version": "0.1.0-opnsense.4",
|
||||||
|
"last_contact_at": "2026-11-19T19:12:03.492329+00:00",
|
||||||
|
"wireguard_after_cleanup": 0,
|
||||||
|
"current_certificate_authenticated": true,
|
||||||
|
"vm": "discovery-opnsense",
|
||||||
|
"native_runtime_checks": {
|
||||||
|
"rust_freebsd_toolchain": "1.99.1",
|
||||||
|
"shared_contract_and_reconciliation_tests_passed": 71,
|
||||||
|
"qualified_clock_and_step_rejection": true,
|
||||||
|
"owned_process_group_tests_as_service_account_passed": 2,
|
||||||
|
"approved_rmm_script_executed": false,
|
||||||
|
"signed_agent_self_update_verified": false
|
||||||
|
},
|
||||||
|
"native_os": "OPNsense 26.7 (amd64), FreeBSD 15.1-RELEASE-p1",
|
||||||
|
"agent_sha256": "1e545467e0e96b87210aa39c4ab7e0f3e0ca5bf0bbbf3cb0140e2f229875e1a4",
|
||||||
|
"server_revision": "b7d9046996fdf4778d04b24a8ab2effd19647db7",
|
||||||
|
"public_browser": {
|
||||||
|
"rules_rendered": 91,
|
||||||
|
"wireguard_loopback_test_peer_handshakes_rendered": 2,
|
||||||
|
"test_interfaces_removed": true,
|
||||||
|
"vpn_section_rendered": true,
|
||||||
|
"native_interface_rendered": true,
|
||||||
|
"native_package_search_verified": true
|
||||||
|
},
|
||||||
|
"packages": 169,
|
||||||
|
"interfaces": 6,
|
||||||
|
"device_type": "virtual",
|
||||||
|
"collector_sha256": "6c4b2fd8a6d2bb9d435a00e40bca63bd53b6430006f044b3edac3655efad30db"
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
{
|
||||||
|
"windows": {
|
||||||
|
"sample_ended_utc": "2026-11-18T20:14:29.0871148Z",
|
||||||
|
"source": "Win32_Process cumulative UserModeTime, KernelModeTime and ReadTransferCount",
|
||||||
|
"duration_seconds": 20.141969,
|
||||||
|
"logical_cpus": 2,
|
||||||
|
"version": "0.1.19",
|
||||||
|
"target": "x86_64-pc-windows-gnu",
|
||||||
|
"build_revision": "aea2d5b37979fc2c039f88e96e7c070e2337cc98",
|
||||||
|
"processes": {
|
||||||
|
"agent": {
|
||||||
|
"pid": 3164,
|
||||||
|
"image_bytes": 31698869,
|
||||||
|
"image_sha256": "10ae59a18e1f6aa765d68e739dc10aa5156d06e9c131f09fea948c24508e1a54",
|
||||||
|
"cpu_seconds_delta": 6.125,
|
||||||
|
"read_bytes_delta": 6280095709,
|
||||||
|
"cpu_percent_of_guest": 15.2,
|
||||||
|
"read_mib_per_second": 297.35
|
||||||
|
},
|
||||||
|
"helper": {
|
||||||
|
"pid": 1600,
|
||||||
|
"image_bytes": 27260060,
|
||||||
|
"image_sha256": "f3f1cda6531ee695936442fc24404387a550f43b3b1afb337a709a6a59694060",
|
||||||
|
"cpu_seconds_delta": 6.3125,
|
||||||
|
"read_bytes_delta": 7294039909,
|
||||||
|
"cpu_percent_of_guest": 15.67,
|
||||||
|
"read_mib_per_second": 345.36
|
||||||
|
},
|
||||||
|
"updater": {
|
||||||
|
"pid": 2384,
|
||||||
|
"cpu_seconds_delta": 0,
|
||||||
|
"read_bytes_delta": 0,
|
||||||
|
"cpu_percent_of_guest": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"local_readiness_utc": "2026-11-18T20:15:08.153963300Z",
|
||||||
|
"clock_qualified": true,
|
||||||
|
"agent_sync_ready": true,
|
||||||
|
"helper_sync_ready": true,
|
||||||
|
"nonterminal_local_attempts": 0,
|
||||||
|
"authenticated_server_contact_utc": "2026-11-18T20:14:59.659919Z",
|
||||||
|
"active_server_jobs": 0,
|
||||||
|
"transport": "https"
|
||||||
|
},
|
||||||
|
"cloud_linux": {
|
||||||
|
"source": "process CPU counters from /proc for the enrolled agent and its managed script helper",
|
||||||
|
"duration_seconds": 20.046738,
|
||||||
|
"logical_cpus": 2,
|
||||||
|
"agent_cpu_percent_of_guest": 0.074825,
|
||||||
|
"helper_cpu_percent_of_guest": 0
|
||||||
|
},
|
||||||
|
"source_findings": {
|
||||||
|
"successful_helper_time_refresh_delay_ms": 20,
|
||||||
|
"successful_enrolled_agent_time_refresh_delay_ms": 5000,
|
||||||
|
"max_held_time_evidence_age_seconds": 300,
|
||||||
|
"pipe_calls_per_successful_helper_time_refresh": 2,
|
||||||
|
"agent_reads_per_second_in_units_of_helper_image": 11.44,
|
||||||
|
"helper_reads_per_second_in_units_of_agent_image": 11.42
|
||||||
|
},
|
||||||
|
"limits": "ReadTransferCount includes logical I/O, including cached reads. Dividing by peer image size estimates operation frequency. No file-level trace or CPU stack sampling was taken. No corrected build was deployed or measured.",
|
||||||
|
"fix": {
|
||||||
|
"build_revision": "a4bcebf4406c8dc6c0c4e0dcaceedb37683710e2",
|
||||||
|
"release_id": "ec1c16b2-7cdb-4c7e-babb-ab8eb51ec740",
|
||||||
|
"release_sequence": 21,
|
||||||
|
"version": "0.1.20",
|
||||||
|
"successful_helper_time_refresh_delay_ms": 5000,
|
||||||
|
"failed_helper_time_refresh_delay_ms": 500,
|
||||||
|
"passive_helper_time_refresh_delay_ms": 30000,
|
||||||
|
"checks": {
|
||||||
|
"windows_gnu_release_built": true,
|
||||||
|
"windows_library_test_binary_built": true,
|
||||||
|
"cadence_test_passed_as_standalone_rust_test": true,
|
||||||
|
"full_windows_unit_test_binary_executed": false,
|
||||||
|
"full_suite_limit": "Linux compilation needs Windows inventory APIs and installed Wine could not load the Windows test binary."
|
||||||
|
},
|
||||||
|
"activation": {
|
||||||
|
"method": "signed normal release pull for Windows GNU in Development A",
|
||||||
|
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
|
||||||
|
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
|
||||||
|
"observed_at_utc": "2026-11-18T20:25:45.3055012Z",
|
||||||
|
"services": [
|
||||||
|
{
|
||||||
|
"name": "RmmDiscoveryReleasePull",
|
||||||
|
"pid": 2384,
|
||||||
|
"state": "Running",
|
||||||
|
"sha256": "575ceb6a0b76c835d28646a498dfa73e88fb5de6343b77bf11d5eefea3fc68b1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RmmDiscoverySystemHelper",
|
||||||
|
"pid": 5832,
|
||||||
|
"state": "Running",
|
||||||
|
"sha256": "990616a6f879d65268ef5a0d31fbf2313af6ae48e70e9a6ed1b2077ea66a194b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RmmDiscoveryWindows",
|
||||||
|
"pid": 4112,
|
||||||
|
"state": "Running",
|
||||||
|
"sha256": "0db90e56ddfc262bd25fd0389a52002611e50be2ae242392b9cecf18fc1e962c"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updater_pid_retained": true,
|
||||||
|
"boot_restarted": false,
|
||||||
|
"clock_qualified": true,
|
||||||
|
"transition_pending": false
|
||||||
|
},
|
||||||
|
"cpu_after_activation": {
|
||||||
|
"start_utc": "2026-11-18T20:26:12.8649479Z",
|
||||||
|
"end_utc": "2026-11-18T20:27:13.6089619Z",
|
||||||
|
"duration_seconds": 60.508365,
|
||||||
|
"logical_cpus": 2,
|
||||||
|
"processes": {
|
||||||
|
"rmm-updater-windows.exe": {
|
||||||
|
"pid": 2384,
|
||||||
|
"cpu_seconds_delta": 0.0,
|
||||||
|
"cpu_percent_of_guest": 0.0,
|
||||||
|
"read_bytes_delta": 0,
|
||||||
|
"read_mib_s": 0.0
|
||||||
|
},
|
||||||
|
"rmm-helper-windows.exe": {
|
||||||
|
"pid": 5832,
|
||||||
|
"cpu_seconds_delta": 4.40625,
|
||||||
|
"cpu_percent_of_guest": 3.641,
|
||||||
|
"read_bytes_delta": 2134329196,
|
||||||
|
"read_mib_s": 33.639
|
||||||
|
},
|
||||||
|
"rmm-agent-windows.exe": {
|
||||||
|
"pid": 4112,
|
||||||
|
"cpu_seconds_delta": 4.25,
|
||||||
|
"cpu_percent_of_guest": 3.5119,
|
||||||
|
"read_bytes_delta": 1136185938,
|
||||||
|
"read_mib_s": 17.907
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cpu_steady_after_test_order": {
|
||||||
|
"start_utc": "2026-11-18T20:29:25.5814828Z",
|
||||||
|
"end_utc": "2026-11-18T20:30:26.1736831Z",
|
||||||
|
"duration_seconds": 60.386439,
|
||||||
|
"logical_cpus": 2,
|
||||||
|
"processes": {
|
||||||
|
"rmm-updater-windows.exe": {
|
||||||
|
"pid": 2384,
|
||||||
|
"cpu_seconds_delta": 0.0,
|
||||||
|
"cpu_percent_of_guest": 0.0,
|
||||||
|
"read_bytes_delta": 0,
|
||||||
|
"read_mib_s": 0.0
|
||||||
|
},
|
||||||
|
"rmm-helper-windows.exe": {
|
||||||
|
"pid": 5832,
|
||||||
|
"cpu_seconds_delta": 3.28125,
|
||||||
|
"cpu_percent_of_guest": 2.7169,
|
||||||
|
"read_bytes_delta": 2126724397,
|
||||||
|
"read_mib_s": 33.587
|
||||||
|
},
|
||||||
|
"rmm-agent-windows.exe": {
|
||||||
|
"pid": 4112,
|
||||||
|
"cpu_seconds_delta": 2.78125,
|
||||||
|
"cpu_percent_of_guest": 2.3029,
|
||||||
|
"read_bytes_delta": 1140038852,
|
||||||
|
"read_mib_s": 18.004
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"system_order": {
|
||||||
|
"operation_id": "6760c9b2-e005-437d-8ae6-1191e5c7972e",
|
||||||
|
"job_id": "778e34f6-e4cc-44d9-b6c0-75e2a559e3a7",
|
||||||
|
"attempt_id": "2a4d1878-74db-43c5-a5ad-202e4bee2e43",
|
||||||
|
"plan_hash": "669a2934ab1e07dbe290bd6adea8c321415ffcf2731a1e4800e305b94a6b1c21",
|
||||||
|
"stdout": "Windows-Konto S-1-5-18",
|
||||||
|
"exit_code": 0,
|
||||||
|
"state": "succeeded",
|
||||||
|
"observed_at": "2026-11-18T20:29:13.872Z",
|
||||||
|
"script_sha256": "8a0c76004a480aa11f6c768b2984e2cf2c01431009ccdbfb1607825133fcbc4f",
|
||||||
|
"runtime_limit_seconds": 30,
|
||||||
|
"preapproval": {
|
||||||
|
"jobs": 0,
|
||||||
|
"outbox": 0,
|
||||||
|
"grants": 0
|
||||||
|
},
|
||||||
|
"approval": {
|
||||||
|
"principal": "simulated-testprincipal-a",
|
||||||
|
"approval_origin": "dev_test_browser_simulation",
|
||||||
|
"testsimulation": true,
|
||||||
|
"plan_hash": "669a2934ab1e07dbe290bd6adea8c321415ffcf2731a1e4800e305b94a6b1c21"
|
||||||
|
},
|
||||||
|
"jobs": 1,
|
||||||
|
"grants": 1
|
||||||
|
},
|
||||||
|
"policy_verification": {
|
||||||
|
"scope_pins_temporarily_rebound": 3,
|
||||||
|
"existing_release_anchor_restored": true,
|
||||||
|
"same_fixed_system_script_accepted_in_preview_with_restored_anchor": true,
|
||||||
|
"preview_submitted": false
|
||||||
|
},
|
||||||
|
"final_gateway": {
|
||||||
|
"auth_contact": "2026-11-18T20:30:25.083449+00:00",
|
||||||
|
"contact": "2026-11-18T20:30:04.483106+00:00",
|
||||||
|
"generation": 74,
|
||||||
|
"active_jobs": 0,
|
||||||
|
"helper_ready": true,
|
||||||
|
"ready": true,
|
||||||
|
"transport": "https",
|
||||||
|
"system_run_script": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,13 @@
|
|||||||
| Windows | `discwindowstest`, Windows 11 Pro x64, Agent `0.1.16` aus dem offiziellen GNU-Kanal |
|
| Windows | `discwindowstest`, Windows 11 Pro x64, Agent `0.1.16` aus dem offiziellen GNU-Kanal |
|
||||||
| Quellstand mit Dokumentation | Gitea-Branch `main` |
|
| Quellstand mit Dokumentation | Gitea-Branch `main` |
|
||||||
|
|
||||||
|
## Ergänzungen zur Geräteansicht
|
||||||
|
|
||||||
|
- **OPNsense-Testgerät:** OPNsense 26.7/FreeBSD 15.1 nativ in der Notebook-VM gestartet; Aufnahme per Kunden-Einmalcode, lokaler P-256-Schlüssel, ausgehendes mTLS. Die öffentliche Geräteansicht zeigte 91 aktive PF-Regeln und beide tatsächlichen Handshakes eines vorübergehenden lokalen WireGuard-Testpaars. Beide Testinterfaces wurden danach entfernt. OpenVPN ohne Verbindungen, IPsec-Dienst nicht erreichbar. Heartbeats, Inventar, CPU und RAM mit derselben Installation nach Agentwechsel geprüft. Version `0.1.0-opnsense.4` meldete Gerätetyp `virtual`, sechs Interfaces und 169 Pakete; Netzwerkkarte und Paketsuche wurden im öffentlichen Browser nachgelesen. Im Gast bestanden 71 Rust-Vertrags-/Abgleichtests, der Test der FreeBSD-Kerneluhr und zwei Prozessgruppenprüfungen als Dienstkonto. Noch offen: durchgängiger Skript-/Root-Jobpfad, signierter OPNsense-Releasekanal und öffentliche Erstinstallation. [Betrieb](../deploy/opnsense/README.md) · [Nachweis](evidence/opnsense-test-device-20261119.json)
|
||||||
|
|
||||||
|
- **RAM-Balken:** Der alte Balken hob bei „RAM frei / gesamt“ den belegten Anteil hervor. Der neue Balken färbt verfügbare Kapazität grün und belegte grau und beschriftet den freien Anteil direkt. Bei fehlenden oder ungültigen Werten wird kein Balken gezeichnet. Build, 80 Komponententests und sechs Browserprüfungen einschließlich 0 %, 75 % und 100 % frei bestanden. WebUI `577a6ee` am 19. November 2026 um 18:38 UTC ausgeliefert. Angemeldetes Chromium bestätigte für neun reale Geräte die gerenderten Segmentbreiten und Beschriftungen bei 1280, 900 und 390 px. API, Datenbank und Agenten mussten nicht geändert werden. [Browserregression](../tests/browser/customer-management.spec.ts)
|
||||||
|
- **Zweck je Gerät:** Optionale Spalte im Bestand und in der Historie, Freitextpflege im Gerätedetail. WebUI-Build, 80 Komponententests, fünf Browserprüfungen und HTTP-Rundlauf auf isoliertem PostgreSQL mit Schreib-, Lese- und Fremdkundenfällen bestanden. Am 19. November 2026 um 14:10 UTC wurde `2070ae9` mit [Migration 45](../migrations/0045_device_purpose.sql) aktiviert. API, öffentliche API und Gateway bestanden die TLS-Healthchecks; der öffentliche WebUI-Index entsprach dem Build. Angemeldetes Chromium zeigte die Zweck-Spalte für sechs Geräte, den Editor im Gerätedetail und die Spalte bei 390 px Breite. Bei der Live-Sichtprüfung wurde nichts gespeichert; kein Agentwechsel. [Bedienung](public-access.md#zweck-eines-geräts-pflegen) · [Browserregression](../tests/browser/device-purpose.spec.ts)
|
||||||
|
|
||||||
## Geräteaktionen über MCP
|
## 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.
|
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.
|
||||||
@@ -27,13 +34,15 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
|
|||||||
| Funktion | Beobachtung und Beleg |
|
| Funktion | Beobachtung und Beleg |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Öffentliche Verwaltung und Kundengrenzen | HTTPS-WebUI mit Passwort/TOTP, MCP mit widerrufbarem Token. Gerätebestand, Historie, eingeschränkter und kundenübergreifender Zugriff sowie Widerruf sind geprüft. [Öffentlicher Zugang](evidence/public-access-20261117.json) · [Kunden und Geräte](evidence/customer-fleet-20261117.json) |
|
| Öffentliche Verwaltung und Kundengrenzen | HTTPS-WebUI mit Passwort/TOTP, MCP mit widerrufbarem Token. Gerätebestand, Historie, eingeschränkter und kundenübergreifender Zugriff sowie Widerruf sind geprüft. [Öffentlicher Zugang](evidence/public-access-20261117.json) · [Kunden und Geräte](evidence/customer-fleet-20261117.json) |
|
||||||
| Kundenwechsel bestehender Geräte | Vormerken und abschließen unter „Gerät verwalten → Kunden wechseln“. Ein nativer Linux-Agent übernahm im isolierten TLS-/PostgreSQL-Test eine neue signierte Kopplung mit neuer Geräte- und Agent-ID. Ein Agentneustart mit der ursprünglichen Installationskonfiguration behielt die neue Kopplung bei. Die alte Kopplung blieb bis zur Bestätigung erhalten. Nach Abschluss sperrte das Gateway ihr Zertifikat, und die Historie war beim bisherigen Kunden weiterhin lesbar. Der Browser prüfte Zugangsbeschränkung, Status, Bestätigung und den Link zum Zielgerät in Mobilbreite. Beschränkte und globale Tokens wurden für Bestandslisten, direkte IDs und Widerruf geprüft. Ein nativer Windows-Test bestätigte die signierte Übernahme nach unterbrochener lokaler Zustandsumstellung und die Trennung der alten lokalen Daten. Die vollständige Windows-Feldabnahme eines Kundenwechsels steht aus. Revision `5253a9f` wurde am 18. November um 20:39 UTC mit Schema 42 bereitgestellt. Interne API, öffentliche API und Gateway bestanden ihre Healthchecks. Der öffentliche WebUI-Index entsprach dem Build. Die signierten Linux-Versionen `0.1.0-mvp.13` und `0.1.0-arm64.7` stammen aus derselben Revision. Windows `0.1.22` stammt aus `9e957e6` und enthält die zuvor veröffentlichte Korrektur der Helper-Zeitabfragen. Die drei Versionen sind Installer-Starter. Linux x64 und Windows sind zusätzlich im zweiten Entwicklungskatalog veröffentlicht. Um 20:46 UTC meldeten Linux x64, Linux ARM64 und Windows die neuen Versionen und die Fähigkeit zum Kundenwechsel bei denselben Geräte-IDs. Auf allen drei Geräten war die Zielkundenauswahl in der öffentlichen WebUI am Desktop und bei 390 px Breite bedienbar. In der produktiven Prüfung wurden null Wechsel vorgemerkt. [Ablauf](public-access.md#kunden-eines-bestehenden-geräts-wechseln) · [TLS-/Datenbanktest](../tests/customer_transfer.py) |
|
| Kundenwechsel bestehender Geräte | Vormerken und abschließen unter „Gerät verwalten → Kunden wechseln“. Ein nativer Linux-Agent übernahm im isolierten TLS-/PostgreSQL-Test eine neue signierte Kopplung mit neuer Geräte- und Agent-ID. Ein Agentneustart mit der ursprünglichen Installationskonfiguration behielt die neue Kopplung bei. Die alte Kopplung blieb bis zur Bestätigung erhalten. Nach Abschluss sperrte das Gateway ihr Zertifikat, und die Historie war beim bisherigen Kunden weiterhin lesbar. Der Browser prüfte Zugangsbeschränkung, Status, Bestätigung und den Link zum Zielgerät in Mobilbreite. Beschränkte und globale Tokens wurden für Bestandslisten, direkte IDs und Widerruf geprüft. Ein nativer Windows-Test bestätigte die signierte Übernahme nach unterbrochener lokaler Zustandsumstellung und die Trennung der alten lokalen Daten. Die vollständige Windows-Feldabnahme eines Kundenwechsels steht aus. Revision `5253a9f` wurde am 18. November um 20:39 UTC mit Schema 42 bereitgestellt. Interne API, öffentliche API und Gateway bestanden ihre Healthchecks. Der öffentliche WebUI-Index entsprach dem Build. Die signierten Linux-Versionen `0.1.0-mvp.13` und `0.1.0-arm64.7` stammen aus derselben Revision. Windows `0.1.22` stammt aus `9e957e6` und enthält die zuvor veröffentlichte Korrektur der Helper-Zeitabfragen. Die drei Versionen sind Installer-Starter. Linux x64 und Windows sind zusätzlich im zweiten Entwicklungskatalog veröffentlicht. Um 20:46 UTC meldeten Linux x64, Linux ARM64 und Windows die neuen Versionen und die Fähigkeit zum Kundenwechsel bei denselben Geräte-IDs. Auf allen drei Geräten war die Zielkundenauswahl in der öffentlichen WebUI am Desktop und bei 390 px Breite bedienbar. In der produktiven Prüfung wurden null Wechsel vorgemerkt. Der damalige Ablauf mit zweiter Bestätigung konnte zwei aktive Einträge erzeugen. Schema 44 schaltet mit der ersten gültigen Inventarmeldung atomar auf den Zielkunden um. Der Browser prüfte, dass nach dem Start keine zweite Aktion erforderlich ist. Ein isolierter Datenbanktest schloss einen bereits gemeldeten Wechsel ab und ließ einen Wechsel ohne Zielinventar offen. Der native Linux-Test bestätigte automatisch genau eine aktive Kopplung, den Widerruf des alten Zertifikats, die erhaltene Historie, den Neustart und die Rechteprüfung für beschränkte und globale Tokens. Revision `480e374` mit Schema 44 wurde am 18. November um 22:00 UTC bereitgestellt. API und Gateway meldeten gesunden Betrieb. Die produktive WebUI zeigte das betroffene Gerät genau einmal im Bestand des Zielkunden; die alte Kopplung blieb mit widerrufener Identität in der Historie des bisherigen Kunden. [Ablauf](public-access.md#kunden-eines-bestehenden-geräts-wechseln) · [TLS-/Datenbanktest](../tests/customer_transfer.py) |
|
||||||
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbares Garantieende, Netzwerkkarten mit IP-Adressen, durchsuchbare Software und angemeldete Benutzer. Beide Linux-Geräte melden den Zeitstempel des Root-Dateisystems als geschätztes Installationsdatum. Quelle `1f60183` wurde am 18. November um 19:23 UTC mit Serverhash `8a821863…` und Schema 41 aktiviert. Interne API, öffentliche API und Gateway wurden mit bestandenem Healthcheck gestartet. Der öffentliche WebUI-Index stimmte mit dem Build überein. 80 WebUI-Tests, 73 Linux- und Domänentests, 15 Bootstrap-Tests und zwei native Windows-Inventartests bestanden. Die vorhandene Windows-Kopplung meldet mit `0.1.19` neun Netzwerkkarten und drei systemweit registrierte Programme. Um 19:29 UTC meldete dieselbe Linux-x64-Kopplung nach dem regulären signierten Update auf `0.1.0-mvp.12` zwei Netzwerkkarten und alle 1.372 erfassten DEB-Pakete. Das Agent- und Helperpaar meldete sich bereit. Die Linux-Inventur holt durch ausstehende Meldungen verschobene Erfassungen nach. Die ARM64-Kopplung meldet mit `0.1.0-arm64.6` drei Netzwerkkarten und 893 DEB-Pakete. Beide Linux-Geräte melden ihre BIOS-Seriennummer. Der Windows-Gast meldet keine Seriennummer. Alle drei Geräte meldeten keine angemeldeten Benutzer und keine Garantiedaten. Für eine automatische Garantieabfrage fehlt eine Herstellerquelle. Die öffentliche WebUI zeigte die Details und fand jeweils einen tatsächlichen Softwareeintrag über die Suche auf dem Desktop und bei 390 px Breite. Die drei signierten Releases sind als Installer-Starter veröffentlicht. Linux x64 und Windows sind auch im Katalog von Development B veröffentlicht. [Geräteansicht](../web/src/device-inventory.tsx) · [Linux-Inventar](../crates/agent-linux/src/inventory.rs) · [Windows-Inventar](../crates/agent-windows/src/inventory.rs) |
|
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbares Garantieende, Netzwerkkarten mit IP-Adressen, durchsuchbare Software und angemeldete Benutzer. Beide Linux-Geräte melden den Zeitstempel des Root-Dateisystems als geschätztes Installationsdatum. Quelle `1f60183` wurde am 18. November um 19:23 UTC mit Serverhash `8a821863…` und Schema 41 aktiviert. Interne API, öffentliche API und Gateway wurden mit bestandenem Healthcheck gestartet. Der öffentliche WebUI-Index stimmte mit dem Build überein. 80 WebUI-Tests, 73 Linux- und Domänentests, 15 Bootstrap-Tests und zwei native Windows-Inventartests bestanden. Die vorhandene Windows-Kopplung meldet mit `0.1.19` neun Netzwerkkarten und drei systemweit registrierte Programme. Um 19:29 UTC meldete dieselbe Linux-x64-Kopplung nach dem regulären signierten Update auf `0.1.0-mvp.12` zwei Netzwerkkarten und alle 1.372 erfassten DEB-Pakete. Das Agent- und Helperpaar meldete sich bereit. Die Linux-Inventur holt durch ausstehende Meldungen verschobene Erfassungen nach. Die ARM64-Kopplung meldet mit `0.1.0-arm64.6` drei Netzwerkkarten und 893 DEB-Pakete. Beide Linux-Geräte melden ihre BIOS-Seriennummer. Der Windows-Gast meldet keine Seriennummer. Alle drei Geräte meldeten keine angemeldeten Benutzer und keine Garantiedaten. Für eine automatische Garantieabfrage fehlt eine Herstellerquelle. Die öffentliche WebUI zeigte die Details und fand jeweils einen tatsächlichen Softwareeintrag über die Suche auf dem Desktop und bei 390 px Breite. Die drei signierten Releases sind als Installer-Starter veröffentlicht. Linux x64 und Windows sind auch im Katalog von Development B veröffentlicht. [Geräteansicht](../web/src/device-inventory.tsx) · [Linux-Inventar](../crates/agent-linux/src/inventory.rs) · [Windows-Inventar](../crates/agent-windows/src/inventory.rs) |
|
||||||
| 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) |
|
| 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) |
|
| 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) |
|
||||||
| 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) |
|
| 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) |
|
| Frische Installation und periodisches Agentupdate | Beide VMs wurden über HTTPS aufgenommen und übernahmen anschließend ein signiertes Folgepaket mit derselben Geräteidentität. Auf Windows ist der öffentliche GNU-Kanal einschließlich Prüfung des offiziellen Schlüssels belegt. [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows GNU](evidence/windows-gnu-official-vm-20261118.json). ARM64 erweitert denselben HTTPS-Installer mit automatischer Architekturerkennung. Release `0.1.0-arm64.1` ist veröffentlicht und als Starter verfügbar. Auf Ubuntu 22.04.5 ARM64 wurden die öffentlichen Downloads, die Signaturprüfung, die Ablehnung einer veränderten Agentdatei und der native Start aller drei Dateien im Prüfmodus beobachtet. OTRS ist mit Gerätezertifikat aufgenommen und meldet authentisierte Heartbeats. Die erste Kontaktprüfung wartet seit der Korrektur auf das Zertifikat. Der öffentliche Installer lief auf OTRS erneut ohne Traceback und ohne neuen Einmalcode. Der ARM64-Katalogabruf ist bestätigt. Ein späterer Versionswechsel auf ARM64 steht aus. [ARM64-Release](evidence/linux-arm64-installer-20261118.json) · [Geräteaufnahme und Nachtest](evidence/linux-arm64-enrollment-heartbeat-20261118.json) |
|
||||||
| Betriebssystemupdate per PowerShell | Die Windows-Updatevorlage installierte KB890830 v5.147 als SYSTEM. Ergebnis und Windows-Ereignis 19 bestätigen die Installation. [Installationsbeleg](evidence/windows-update-installation-20261117.json) |
|
| 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) |
|
||||||
| 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) |
|
| 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) |
|
| 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) |
|
||||||
|
|
||||||
|
|||||||
+12
-2
@@ -8,11 +8,21 @@ Die öffentliche WebUI verwendet ein lokales Benutzerkonto mit Passwort und eine
|
|||||||
|
|
||||||
Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1)
|
Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1)
|
||||||
|
|
||||||
|
### Zweck eines Geräts pflegen
|
||||||
|
|
||||||
|
Unter **Geräte** den Hostnamen öffnen und im Abschnitt **Zweck** auf **Zweck bearbeiten** klicken. Der Freitext darf bis zu 500 Zeichen enthalten. Speichern übernimmt ihn auch in die Übersicht. Zum Entfernen das Feld leeren und erneut speichern. Das Bearbeiten erfordert `inventory:read` und `devices:revoke` im betreffenden Kunden.
|
||||||
|
|
||||||
|
### Hypervisor einer VM zuordnen
|
||||||
|
|
||||||
|
Eine VM unter **Geräte** öffnen und unter **Gerät verwalten → Hypervisor zuordnen** einen Host aus demselben Kundenbestand auswählen. Die Zuordnung speichern. Der Hostname erscheint unter dem VM-Namen in der Übersicht und öffnet die Details des Hypervisors. **Kein konkreter Hypervisor** entfernt die gespeicherte Zuordnung.
|
||||||
|
|
||||||
|
Bei einer VM mit dem gemeldeten Hersteller Hetzner erscheint ohne verfügbaren konkreten Host **Hetzner Cloud · Platzhalter**. Die Anzeige steht für den Anbieter. Die Auswahl eines echten Hypervisors hat Vorrang.
|
||||||
|
|
||||||
### Kunden eines bestehenden Geräts wechseln
|
### Kunden eines bestehenden Geräts wechseln
|
||||||
|
|
||||||
1. In **Geräte** den Hostnamen öffnen und **Gerät verwalten → Kunden wechseln** wählen. Der Agent benötigt eine Version mit Unterstützung für den Kundenwechsel.
|
1. In **Geräte** den Hostnamen öffnen und **Gerät verwalten → Kunden wechseln** wählen. Der Agent benötigt eine Version mit Unterstützung für den Kundenwechsel.
|
||||||
2. Den Zielkunden auswählen und **Kundenwechsel vormerken**. Hierfür braucht die angemeldete Person Geräteverwaltungsrechte beim bisherigen Kunden sowie Inventar- und Aufnahmerechte beim Zielkunden. Offene Aufträge und Genehmigungen vor dem Wechsel abschließen.
|
2. Den Zielkunden auswählen und **Kundenwechsel starten**. Hierfür braucht die angemeldete Person Geräteverwaltungsrechte beim bisherigen Kunden sowie Inventar- und Aufnahmerechte beim Zielkunden. Offene Aufträge und Genehmigungen vor dem Wechsel abschließen.
|
||||||
3. Sobald der Agent über seine bestehende Verbindung die neue Kopplung übernommen und Inventar gemeldet hat, zeigt die WebUI den Hostnamen beim Zielkunden. Den Wechsel bestätigen und **Kundenwechsel abschließen** wählen. Bei einem Offline-Gerät bleibt der Wechsel bis zum nächsten verfügbaren Kontakt vorgemerkt. Die Vormerkung kann vor der Zertifikatsausstellung abgebrochen werden.
|
3. Mit der ersten gültigen Inventarmeldung der neuen Kopplung wechselt der Eintrag automatisch in den Bestand des Zielkunden. Bei einem Offline-Gerät bleibt der Wechsel bis zum nächsten verfügbaren Kontakt vorgemerkt. Die Vormerkung kann vor der Zertifikatsausstellung abgebrochen werden.
|
||||||
|
|
||||||
Der gesamte Ablauf findet in der WebUI statt. Bisheriges Inventar und gespeicherte Aufträge stehen beim bisherigen Kunden in der Historie. Beim Zielkunden beginnen die Meldungen mit der neuen Kopplung. Gerätegebundene Administratorrechte sind an die jeweilige Kopplung gebunden und erfordern eine eigene Freigabe und Bindung.
|
Der gesamte Ablauf findet in der WebUI statt. Bisheriges Inventar und gespeicherte Aufträge stehen beim bisherigen Kunden in der Historie. Beim Zielkunden beginnen die Meldungen mit der neuen Kopplung. Gerätegebundene Administratorrechte sind an die jeweilige Kopplung gebunden und erfordern eine eigene Freigabe und Bindung.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
ALTER TABLE assets
|
||||||
|
ADD COLUMN hypervisor_asset_id uuid,
|
||||||
|
ADD CONSTRAINT assets_hypervisor_not_self CHECK (hypervisor_asset_id <> asset_id),
|
||||||
|
ADD CONSTRAINT assets_same_customer_hypervisor
|
||||||
|
FOREIGN KEY (tenant_id, hypervisor_asset_id) REFERENCES assets(tenant_id, asset_id)
|
||||||
|
ON DELETE SET NULL (hypervisor_asset_id);
|
||||||
|
|
||||||
|
CREATE INDEX assets_hypervisor_reference ON assets (tenant_id, hypervisor_asset_id)
|
||||||
|
WHERE hypervisor_asset_id IS NOT NULL;
|
||||||
|
GRANT UPDATE (hypervisor_asset_id) ON assets TO rmm_app;
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
ALTER TABLE agent_installations
|
||||||
|
ADD COLUMN customer_transfer_pending boolean NOT NULL DEFAULT false,
|
||||||
|
ADD COLUMN customer_transfer_activated_at timestamptz;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX device_customer_transfers_target ON device_customer_transfers
|
||||||
|
(target_tenant_id,target_agent_id) WHERE target_agent_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- The target has tenant-scoped access to its inventory. Only this function
|
||||||
|
-- can use that evidence to close the exact transfer in the source tenant.
|
||||||
|
CREATE FUNCTION finish_device_customer_transfer(target_tenant uuid, target_agent uuid)
|
||||||
|
RETURNS boolean
|
||||||
|
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$
|
||||||
|
DECLARE
|
||||||
|
move public.device_customer_transfers%ROWTYPE;
|
||||||
|
cutover timestamptz;
|
||||||
|
BEGIN
|
||||||
|
IF current_setting('app.tenant_id', true) IS DISTINCT FROM target_tenant::text THEN
|
||||||
|
RETURN false;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
SELECT t.* INTO move
|
||||||
|
FROM public.device_customer_transfers t
|
||||||
|
JOIN public.agent_installations a ON (a.tenant_id,a.asset_id,a.agent_id)
|
||||||
|
= (t.target_tenant_id,t.target_asset_id,t.target_agent_id)
|
||||||
|
WHERE t.target_tenant_id=target_tenant AND t.target_agent_id=target_agent
|
||||||
|
AND t.completed_at IS NULL AND t.cancelled_at IS NULL
|
||||||
|
AND a.customer_transfer_pending AND a.revoked_at IS NULL AND a.last_authenticated_at IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT FROM public.observations o
|
||||||
|
WHERE (o.tenant_id,o.agent_id)=(a.tenant_id,a.agent_id)
|
||||||
|
AND o.received_at>=a.created_at AND o.quality='valid'
|
||||||
|
AND o.source_id IN ('linux.base','windows.base')
|
||||||
|
AND NULLIF(btrim(o.data->>'hostname'),'') IS NOT NULL
|
||||||
|
)
|
||||||
|
FOR UPDATE OF a,t;
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RETURN false;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
-- Serialize with source-side job planning and device controls. Pending
|
||||||
|
-- transfers already prevent new work from being submitted to the source.
|
||||||
|
PERFORM set_config('app.tenant_id',move.source_tenant_id::text,true);
|
||||||
|
PERFORM FROM public.agent_installations
|
||||||
|
WHERE (tenant_id,asset_id,agent_id)=(move.source_tenant_id,move.source_asset_id,move.source_agent_id)
|
||||||
|
FOR UPDATE;
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT FROM public.jobs WHERE tenant_id=move.source_tenant_id AND agent_id=move.source_agent_id
|
||||||
|
AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')
|
||||||
|
) OR EXISTS (
|
||||||
|
SELECT FROM public.approval_requests r JOIN public.operation_plans p USING(tenant_id,plan_id)
|
||||||
|
WHERE r.tenant_id=move.source_tenant_id AND r.approval_state='pending_approval' AND p.expires_at>now()
|
||||||
|
AND convert_from(p.payload,'UTF8')::jsonb->'jobs'
|
||||||
|
@> jsonb_build_array(jsonb_build_object('payload',jsonb_build_object('agent_id',move.source_agent_id)))
|
||||||
|
) THEN
|
||||||
|
PERFORM set_config('app.tenant_id',target_tenant::text,true);
|
||||||
|
RETURN false;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
cutover := clock_timestamp();
|
||||||
|
UPDATE public.agent_installations
|
||||||
|
SET revoked_at=cutover, connection_generation=connection_generation+1,
|
||||||
|
previous_certificate_sha256=NULL, previous_certificate_until=NULL
|
||||||
|
WHERE (tenant_id,asset_id,agent_id)=(move.source_tenant_id,move.source_asset_id,move.source_agent_id)
|
||||||
|
AND revoked_at IS NULL;
|
||||||
|
|
||||||
|
UPDATE public.device_customer_transfers SET completed_at=cutover WHERE transfer_id=move.transfer_id;
|
||||||
|
|
||||||
|
INSERT INTO public.audit_events (tenant_id,event_id,principal,event_type,data)
|
||||||
|
VALUES (move.source_tenant_id,gen_random_uuid(),move.requested_by,'device_customer_transfer_completed',
|
||||||
|
jsonb_build_object('completion_origin','automatic_after_target_inventory','decision',
|
||||||
|
jsonb_build_object('transfer_id',move.transfer_id,'asset_id',move.source_asset_id,
|
||||||
|
'agent_id',move.source_agent_id,'target_tenant_id',move.target_tenant_id,
|
||||||
|
'target_asset_id',move.target_asset_id,'target_agent_id',move.target_agent_id)));
|
||||||
|
|
||||||
|
PERFORM set_config('app.tenant_id',target_tenant::text,true);
|
||||||
|
UPDATE public.agent_installations
|
||||||
|
SET customer_transfer_pending=false, customer_transfer_activated_at=cutover,
|
||||||
|
last_contact_at=COALESCE(last_contact_at,cutover)
|
||||||
|
WHERE (tenant_id,asset_id,agent_id)=(move.target_tenant_id,move.target_asset_id,move.target_agent_id);
|
||||||
|
RETURN true;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
REVOKE ALL ON FUNCTION finish_device_customer_transfer(uuid,uuid) FROM PUBLIC;
|
||||||
|
GRANT EXECUTE ON FUNCTION finish_device_customer_transfer(uuid,uuid) TO rmm_app;
|
||||||
|
|
||||||
|
-- Existing enrollments can already have proved their new identity under the
|
||||||
|
-- old workflow. Finish only transfers with that evidence and preserve history.
|
||||||
|
UPDATE agent_installations a SET customer_transfer_pending=true
|
||||||
|
FROM device_customer_transfers t
|
||||||
|
WHERE (a.tenant_id,a.asset_id,a.agent_id)=(t.target_tenant_id,t.target_asset_id,t.target_agent_id)
|
||||||
|
AND t.completed_at IS NULL AND t.cancelled_at IS NULL;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
destination record;
|
||||||
|
BEGIN
|
||||||
|
FOR destination IN SELECT target_tenant_id,target_agent_id FROM device_customer_transfers
|
||||||
|
WHERE target_agent_id IS NOT NULL AND completed_at IS NULL AND cancelled_at IS NULL
|
||||||
|
ORDER BY created_at,transfer_id
|
||||||
|
LOOP
|
||||||
|
PERFORM set_config('app.tenant_id',destination.target_tenant_id::text,true);
|
||||||
|
PERFORM finish_device_customer_transfer(destination.target_tenant_id,destination.target_agent_id);
|
||||||
|
END LOOP;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- Operator metadata belongs to the asset, not the installation or its inventory.
|
||||||
|
ALTER TABLE assets ADD COLUMN purpose text CHECK (char_length(purpose) BETWEEN 1 AND 500);
|
||||||
|
GRANT UPDATE(purpose) ON assets TO rmm_app;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
SET LOCAL lock_timeout = '3s';
|
||||||
|
SET LOCAL statement_timeout = '30s';
|
||||||
|
ALTER TABLE observations DROP CONSTRAINT observations_source_id_check;
|
||||||
|
ALTER TABLE observations ADD CONSTRAINT observations_source_id_check
|
||||||
|
CHECK (source_id IN ('linux.base','windows.base','agent.update','opnsense.base')) NOT VALID;
|
||||||
|
ALTER TABLE observations VALIDATE CONSTRAINT observations_source_id_check;
|
||||||
@@ -20,6 +20,63 @@ test.beforeAll(async () => {
|
|||||||
|
|
||||||
test.afterAll(async () => { await server?.close(); });
|
test.afterAll(async () => { await server?.close(); });
|
||||||
|
|
||||||
|
test('draws the free RAM share accurately on desktop and mobile', async ({ page }) => {
|
||||||
|
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'RAM-Test' };
|
||||||
|
const gib = 2 ** 30;
|
||||||
|
const readings = [
|
||||||
|
['mostly-free', 12 * gib, 16 * gib],
|
||||||
|
['all-used', 0, 16 * gib],
|
||||||
|
['all-free', 16 * gib, 16 * gib],
|
||||||
|
['missing-available', null, 16 * gib],
|
||||||
|
['invalid-range', 17 * gib, 16 * gib],
|
||||||
|
['invalid-total', 0, 0],
|
||||||
|
] as const;
|
||||||
|
const listing = (items: unknown[]) => ({
|
||||||
|
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-19T12:00:00Z'
|
||||||
|
});
|
||||||
|
await page.route(`${origin}/auth/config`, route => route.fulfill({
|
||||||
|
json: { local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }
|
||||||
|
}));
|
||||||
|
await page.route(`${origin}/auth/session`, route => route.fulfill({
|
||||||
|
json: { principal: 'ram-reader', testsimulation: false, tenant_id: customer.tenant_id,
|
||||||
|
csrf_token: 'ram-fixture', permissions: ['inventory:read'] }
|
||||||
|
}));
|
||||||
|
await page.route(`${origin}/api/v1/**`, route => {
|
||||||
|
const pathname = new URL(route.request().url()).pathname;
|
||||||
|
if (pathname === '/api/v1/tenants') return route.fulfill({ json: listing([customer]) });
|
||||||
|
if (pathname === '/api/v1/devices') return route.fulfill({
|
||||||
|
json: listing(readings.map(([hostname, free, total]) => ({
|
||||||
|
tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: hostname, agent_id: hostname,
|
||||||
|
lifecycle: 'current', status: 'online', hostname, ram_available_bytes: free, ram_total_bytes: total,
|
||||||
|
disk_free_bytes: 12 * gib, disk_total_bytes: 16 * gib
|
||||||
|
})))
|
||||||
|
});
|
||||||
|
return route.fulfill({ status: 404 });
|
||||||
|
});
|
||||||
|
await page.goto(`${origin}/#geraete`);
|
||||||
|
const row = (host: string) => page.getByRole('row').filter({ has: page.getByRole('button', { name: host, exact: true }) });
|
||||||
|
const ram = (host: string) => row(host).locator('[data-label="RAM frei / gesamt"]');
|
||||||
|
await expect(ram('mostly-free')).toContainText('12 / 16 GiB');
|
||||||
|
await expect(ram('mostly-free').locator('.capacity-caption')).toHaveText('75 % frei');
|
||||||
|
await expect(row('mostly-free').locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
|
||||||
|
.toHaveAttribute('style', 'width: 25%;');
|
||||||
|
for (const width of [1280, 900, 390]) {
|
||||||
|
await page.setViewportSize({ width, height: 844 });
|
||||||
|
for (const [host, free] of [['mostly-free', 75], ['all-used', 0], ['all-free', 100]] as const) {
|
||||||
|
const bar = ram(host).getByRole('img', { name: `${free} % frei, ${100 - free} % belegt` });
|
||||||
|
await expect(bar).toBeVisible();
|
||||||
|
const [track = 0, freeWidth = 0, usedWidth = 0] = await bar.evaluate(el => [el, ...Array.from(el.children)]
|
||||||
|
.map(part => part.getBoundingClientRect().width));
|
||||||
|
expect(track).toBeGreaterThan(0);
|
||||||
|
expect(freeWidth / track).toBeCloseTo(free / 100, 2);
|
||||||
|
expect(usedWidth / track).toBeCloseTo((100 - free) / 100, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) {
|
||||||
|
await expect(ram(host).locator('.capacity-track')).toHaveCount(0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('creates and renames a customer, opens its inventory, and hides editing for a reader', async ({ page }) => {
|
test('creates and renames a customer, opens its inventory, and hides editing for a reader', async ({ page }) => {
|
||||||
const home = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Testzentrale' };
|
const home = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Testzentrale' };
|
||||||
const customerId = '22222222-2222-4222-8222-222222222222';
|
const customerId = '22222222-2222-4222-8222-222222222222';
|
||||||
@@ -108,12 +165,12 @@ test('creates and renames a customer, opens its inventory, and hides editing for
|
|||||||
const headers = page.locator('.fleet-table thead th[scope="col"]');
|
const headers = page.locator('.fleet-table thead th[scope="col"]');
|
||||||
await expect(headers.nth(0)).toHaveText('Hostname');
|
await expect(headers.nth(0)).toHaveText('Hostname');
|
||||||
await expect(headers.nth(1)).toHaveText('Type');
|
await expect(headers.nth(1)).toHaveText('Type');
|
||||||
await expect(device.getByRole('cell').nth(2)).toHaveText('hypervisor');
|
await expect(device.locator('[data-label="Type"]')).toHaveText('hypervisor');
|
||||||
await expect(device.getByRole('cell').nth(3)).toHaveText('Proxmox VE');
|
await expect(device.locator('[data-label="OS"]')).toHaveText('Proxmox VE');
|
||||||
const memory = device.locator('[data-label="RAM frei / gesamt"]');
|
const memory = device.locator('[data-label="RAM frei / gesamt"]');
|
||||||
await expect(memory).toHaveText('6 / 16 GiB');
|
await expect(memory).toContainText('6 / 16 GiB');
|
||||||
await expect(memory.locator('.capacity-track')).toHaveAttribute('title', '37,5 % frei');
|
await expect(memory.getByRole('img', { name: '37,5 % frei, 62,5 % belegt' })).toBeVisible();
|
||||||
await expect(memory.locator('.capacity-track i')).toHaveAttribute('style', 'width: 62.5%;');
|
await expect(memory.locator('.capacity-free')).toHaveAttribute('style', 'width: 37.5%;');
|
||||||
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
|
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
|
||||||
.toHaveAttribute('style', 'width: 25%;');
|
.toHaveAttribute('style', 'width: 25%;');
|
||||||
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
|
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
|
||||||
@@ -232,6 +289,7 @@ test('moves an existing pairing through the WebUI and waits for target inventory
|
|||||||
target_asset_id: 'new-asset', target_agent_id: 'new-agent', target_hostname: 'NORD-PC' };
|
target_asset_id: 'new-asset', target_agent_id: 'new-agent', target_hostname: 'NORD-PC' };
|
||||||
let state = '';
|
let state = '';
|
||||||
let canEnroll = false;
|
let canEnroll = false;
|
||||||
|
let posts = 0;
|
||||||
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
|
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
|
||||||
completeness: 'complete', as_of: new Date().toISOString() });
|
completeness: 'complete', as_of: new Date().toISOString() });
|
||||||
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
||||||
@@ -257,14 +315,10 @@ test('moves an existing pairing through the WebUI and waits for target inventory
|
|||||||
expect(req.headers()['x-csrf-token']).toBe('move-csrf');
|
expect(req.headers()['x-csrf-token']).toBe('move-csrf');
|
||||||
expect(req.headers()['x-rmm-tenant']).toBe(source.tenant_id);
|
expect(req.headers()['x-rmm-tenant']).toBe(source.tenant_id);
|
||||||
expect(url.searchParams.get('agent_id')).toBe(device.agent_id);
|
expect(url.searchParams.get('agent_id')).toBe(device.agent_id);
|
||||||
if (url.pathname === move) {
|
expect(url.pathname).toBe(move);
|
||||||
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
|
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
|
||||||
|
posts++;
|
||||||
state = 'pending';
|
state = 'pending';
|
||||||
} else {
|
|
||||||
expect(url.pathname).toBe(move + '/move-fixture/complete');
|
|
||||||
expect(state).toBe('ready');
|
|
||||||
state = 'completed';
|
|
||||||
}
|
|
||||||
return r.fulfill({ json: { state } });
|
return r.fulfill({ json: { state } });
|
||||||
}
|
}
|
||||||
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
||||||
@@ -275,20 +329,99 @@ test('moves an existing pairing through the WebUI and waits for target inventory
|
|||||||
await page.getByText('Kunden wechseln', { exact: true }).click();
|
await page.getByText('Kunden wechseln', { exact: true }).click();
|
||||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
||||||
await expect(page.getByText('Für diesen Zielkunden fehlt das Recht', { exact: false })).toBeVisible();
|
await expect(page.getByText('Für diesen Zielkunden fehlt das Recht', { exact: false })).toBeVisible();
|
||||||
const prepare = page.getByRole('button', { name: 'Kundenwechsel vormerken' });
|
const prepare = page.getByRole('button', { name: 'Kundenwechsel starten' });
|
||||||
await expect(prepare).toBeDisabled();
|
await expect(prepare).toBeDisabled();
|
||||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
|
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
|
||||||
canEnroll = true;
|
canEnroll = true;
|
||||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
||||||
await prepare.click();
|
await prepare.click();
|
||||||
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
|
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
|
||||||
const finish = page.getByRole('button', { name: 'Kundenwechsel abschließen' });
|
const destination = page.getByRole('link', { name: 'Neue Kopplung öffnen' });
|
||||||
await expect(finish).toHaveCount(0);
|
state = 'enrolled';
|
||||||
state = 'ready';
|
await expect(page.getByText('Der Wechsel wird mit der ersten Inventarmeldung', { exact: false }))
|
||||||
await expect(finish).toBeDisabled({ timeout: 10000 });
|
.toBeVisible({ timeout: 10000 });
|
||||||
await page.getByRole('checkbox', { name: 'Ich bestätige den Kundenwechsel für dieses Gerät.' }).check();
|
await expect(destination).toHaveCount(0);
|
||||||
await finish.click();
|
state = 'completed';
|
||||||
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible();
|
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible({ timeout: 10000 });
|
||||||
await expect(page.getByRole('link', { name: 'Neue Kopplung öffnen' })).toHaveAttribute('href',
|
await expect(destination).toHaveAttribute('href',
|
||||||
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
|
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
|
||||||
|
expect(posts).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows real VM hosts and the Hetzner placeholder without adding a device', async ({ page }) => {
|
||||||
|
const tenant = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const path = '/api/v1/tenants/' + tenant;
|
||||||
|
const customer = { tenant_id: tenant, name: 'Testkunde' };
|
||||||
|
const base = { ...customer, customer_name: customer.name,
|
||||||
|
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' };
|
||||||
|
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: 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() });
|
||||||
|
|
||||||
|
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
||||||
|
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
|
||||||
|
} }));
|
||||||
|
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
|
||||||
|
principal: 'inventory-owner', tenant_id: tenant, csrf_token: 'host-assignment-fixture',
|
||||||
|
testsimulation: false, permissions: ['inventory:read', 'devices:revoke']
|
||||||
|
} }));
|
||||||
|
await page.route(origin + '/api/v1/**', r => {
|
||||||
|
const req = r.request(), url = new URL(req.url());
|
||||||
|
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) });
|
||||||
|
if (url.pathname === '/api/v1/devices' || url.pathname === path + '/devices') {
|
||||||
|
return r.fulfill({ json: listing([guest(), pve]) });
|
||||||
|
}
|
||||||
|
if (url.pathname === path + '/devices/' + vm.asset_id) return r.fulfill({ json: guest() });
|
||||||
|
if (url.pathname === path + '/devices/' + pve.asset_id) return r.fulfill({ json: pve });
|
||||||
|
if (url.pathname === path + '/hypervisors') {
|
||||||
|
expect(req.headers()['x-rmm-tenant']).toBe(tenant);
|
||||||
|
return r.fulfill({ json: { items: [pve], truncated: false } });
|
||||||
|
}
|
||||||
|
if (url.pathname === path + '/devices/' + vm.asset_id + '/hypervisor') {
|
||||||
|
expect(req.method()).toBe('POST');
|
||||||
|
expect(req.headers()['x-csrf-token']).toBe('host-assignment-fixture');
|
||||||
|
expect(url.searchParams.get('agent_id')).toBe(vm.agent_id);
|
||||||
|
const target = req.postDataJSON().hypervisor_asset_id;
|
||||||
|
expect(target).toBe(assigned ? null : pve.asset_id);
|
||||||
|
assigned = target === pve.asset_id;
|
||||||
|
return r.fulfill({ json: { asset_id: vm.asset_id, hypervisor_asset_id: target } });
|
||||||
|
}
|
||||||
|
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
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();
|
||||||
|
await page.getByText('Gerät verwalten', { exact: true }).click();
|
||||||
|
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||||
|
const hostInput = page.getByRole('combobox', { name: 'Hypervisor auswählen' });
|
||||||
|
await hostInput.selectOption(pve.asset_id);
|
||||||
|
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
|
||||||
|
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();
|
||||||
|
await expect(page.getByRole('heading', { name: pve.hostname })).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();
|
||||||
|
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||||
|
await hostInput.selectOption('');
|
||||||
|
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');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
|
||||||
|
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
let server: ViteDevServer;
|
||||||
|
let origin: string;
|
||||||
|
test.beforeAll(async () => {
|
||||||
|
server = await createServer({
|
||||||
|
root: resolve(__dirname, '../../web'), configFile: false,
|
||||||
|
server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent'
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const address = server.httpServer!.address();
|
||||||
|
if (!address || typeof address === 'string') throw new Error('Missing local fixture address');
|
||||||
|
origin = `http://127.0.0.1:${address.port}`;
|
||||||
|
});
|
||||||
|
test.afterAll(async () => { await server?.close(); });
|
||||||
|
|
||||||
|
test('shows, edits and clears device purpose without giving readers an editor', async ({ page }) => {
|
||||||
|
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Fixture' };
|
||||||
|
const path = `/api/v1/tenants/${customer.tenant_id}/devices/device-1`;
|
||||||
|
const listing = (items: unknown[]) => ({
|
||||||
|
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-19T12:00:00Z'
|
||||||
|
});
|
||||||
|
let purpose: string | null = null;
|
||||||
|
let writer = true;
|
||||||
|
let reject = true;
|
||||||
|
const writes: string[] = [];
|
||||||
|
const device = () => ({
|
||||||
|
tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: 'device-1', agent_id: 'agent-1',
|
||||||
|
lifecycle: 'current', status: 'online', hostname: 'DATEN-SRV', os: 'Linux', purpose
|
||||||
|
});
|
||||||
|
await page.route(`${origin}/auth/config`, route => route.fulfill({
|
||||||
|
json: { local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }
|
||||||
|
}));
|
||||||
|
await page.route(`${origin}/auth/session`, route => route.fulfill({
|
||||||
|
json: {
|
||||||
|
principal: writer ? 'device-operator' : 'inventory-reader', testsimulation: false,
|
||||||
|
tenant_id: customer.tenant_id, csrf_token: 'purpose-csrf',
|
||||||
|
permissions: writer ? ['inventory:read', 'devices:revoke'] : ['inventory:read']
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
await page.route(`${origin}/api/v1/**`, route => {
|
||||||
|
const request = route.request();
|
||||||
|
const pathname = new URL(request.url()).pathname;
|
||||||
|
if (request.method() === 'GET') {
|
||||||
|
if (pathname === '/api/v1/tenants') return route.fulfill({ json: listing([customer]) });
|
||||||
|
if (pathname === '/api/v1/devices') return route.fulfill({ json: listing([device()]) });
|
||||||
|
if (pathname === path) return route.fulfill({ json: device() });
|
||||||
|
}
|
||||||
|
if (request.method() === 'PATCH' && pathname === `${path}/purpose`) {
|
||||||
|
expect(writer).toBe(true);
|
||||||
|
expect(request.headers()['x-csrf-token']).toBe('purpose-csrf');
|
||||||
|
expect(request.headers()['x-rmm-tenant']).toBe(customer.tenant_id);
|
||||||
|
const text = request.postDataJSON().purpose;
|
||||||
|
writes.push(text);
|
||||||
|
if (reject) return route.fulfill({ status: 403, json: { code: 'FORBIDDEN', message: 'Speichern abgelehnt' } });
|
||||||
|
purpose = text.trim() || null;
|
||||||
|
return route.fulfill({ json: { asset_id: 'device-1', purpose } });
|
||||||
|
}
|
||||||
|
return route.fulfill({ status: 404, json: { code: 'UNEXPECTED_FIXTURE_REQUEST', message: pathname } });
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(`${origin}/#geraete`);
|
||||||
|
await expect(page.getByRole('columnheader', { name: 'Zweck' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('cell', { name: 'Nicht hinterlegt' })).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: 'DATEN-SRV' }).click();
|
||||||
|
await page.getByRole('button', { name: 'Zweck bearbeiten' }).click();
|
||||||
|
const editor = page.getByRole('textbox', { name: 'Zweck des Geräts' });
|
||||||
|
const save = page.getByRole('button', { name: 'Zweck speichern' });
|
||||||
|
await editor.fill('ü'.repeat(501));
|
||||||
|
await expect(save).toBeDisabled();
|
||||||
|
expect(writes).toEqual([]);
|
||||||
|
const text = 'Dateien für Nürnberg\n<intern>';
|
||||||
|
await editor.fill(text);
|
||||||
|
await save.click();
|
||||||
|
await expect(page.getByRole('alert')).toContainText('Speichern abgelehnt');
|
||||||
|
await expect(editor).toHaveValue(text);
|
||||||
|
reject = false;
|
||||||
|
await save.click();
|
||||||
|
await expect(page.getByText('Zweck gespeichert.')).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||||
|
await expect(page.locator('td[data-label="Zweck"]')).toHaveText(text.replace('\n', ' '));
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await expect(page.locator('td[data-label="Zweck"]')).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: 'DATEN-SRV' }).click();
|
||||||
|
await page.getByRole('button', { name: 'Zweck bearbeiten' }).click();
|
||||||
|
await expect(editor).toHaveValue(text);
|
||||||
|
await editor.fill('');
|
||||||
|
await save.click();
|
||||||
|
await expect(page.getByText('Nicht hinterlegt', { exact: true })).toBeVisible();
|
||||||
|
expect(writes).toEqual([text, text, '']);
|
||||||
|
writer = false;
|
||||||
|
purpose = text;
|
||||||
|
await page.reload();
|
||||||
|
await expect(page.locator('.device-purpose .purpose-text')).toHaveText(text.replace('\n', ' '));
|
||||||
|
await expect(page.getByRole('button', { name: 'Zweck bearbeiten' })).toHaveCount(0);
|
||||||
|
});
|
||||||
@@ -20,6 +20,7 @@ import subprocess
|
|||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
import urllib.parse
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from local_access_database import command
|
from local_access_database import command
|
||||||
@@ -40,6 +41,27 @@ def until(probe, seconds=80):
|
|||||||
raise AssertionError(f"Timed out waiting for {probe.__name__}")
|
raise AssertionError(f"Timed out waiting for {probe.__name__}")
|
||||||
|
|
||||||
|
|
||||||
|
def existing_transfer(sql, with_inventory):
|
||||||
|
"""Seed the state left by the old server before the extra confirmation."""
|
||||||
|
asset_a, asset_b, agent_a, agent_b, move = (uuid.uuid4() for _ in range(5))
|
||||||
|
sql(f"""INSERT INTO assets VALUES ('{A}','{asset_a}'),('{B}','{asset_b}');
|
||||||
|
INSERT INTO agent_installations
|
||||||
|
(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,
|
||||||
|
last_authenticated_at,last_authenticated_certificate_sha256)
|
||||||
|
SELECT tenant::uuid,asset::uuid,agent::uuid,pin,now(),now(),pin
|
||||||
|
FROM (VALUES ('{A}','{asset_a}','{agent_a}','{secrets.token_hex(32)}'),
|
||||||
|
('{B}','{asset_b}','{agent_b}','{secrets.token_hex(32)}')) x(tenant,asset,agent,pin);
|
||||||
|
INSERT INTO device_customer_transfers (transfer_id,source_tenant_id,source_asset_id,source_agent_id,
|
||||||
|
target_tenant_id,target_asset_id,target_agent_id,requested_by,csr_sha256)
|
||||||
|
VALUES ('{move}','{A}','{asset_a}','{agent_a}','{B}','{asset_b}','{agent_b}','fixture',repeat('a',64));""")
|
||||||
|
if with_inventory:
|
||||||
|
sql(f"""INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,
|
||||||
|
observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256)
|
||||||
|
VALUES ('{B}','{agent_b}',gen_random_uuid(),gen_random_uuid(),1,now(),'linux.base','valid',
|
||||||
|
'partial',gen_random_uuid(),'{{"hostname":"Legacy ready VM"}}',repeat('b',64));""")
|
||||||
|
return str(agent_a), str(asset_b), str(agent_b)
|
||||||
|
|
||||||
|
|
||||||
def run(server, agent, folder, db, api):
|
def run(server, agent, folder, db, api):
|
||||||
pg_password = secrets.token_hex(24)
|
pg_password = secrets.token_hex(24)
|
||||||
command(["docker", "run", "-d", "--name", db, "-p", "127.0.0.1::5432",
|
command(["docker", "run", "-d", "--name", db, "-p", "127.0.0.1::5432",
|
||||||
@@ -58,6 +80,9 @@ def run(server, agent, folder, db, api):
|
|||||||
ALTER DATABASE postgres OWNER TO rmm_migrator;
|
ALTER DATABASE postgres OWNER TO rmm_migrator;
|
||||||
ALTER SCHEMA public OWNER TO rmm_migrator;""")
|
ALTER SCHEMA public OWNER TO rmm_migrator;""")
|
||||||
for migration in sorted((ROOT / "migrations").glob("*.sql")):
|
for migration in sorted((ROOT / "migrations").glob("*.sql")):
|
||||||
|
if migration.name.startswith("0044_"):
|
||||||
|
ready_source, ready_asset, ready_target = existing_transfer(sql, with_inventory=True)
|
||||||
|
waiting_source, waiting_asset, waiting_target = existing_transfer(sql, with_inventory=False)
|
||||||
sql(migration.read_text(), "rmm_migrator")
|
sql(migration.read_text(), "rmm_migrator")
|
||||||
|
|
||||||
users, login_data = [], {}
|
users, login_data = [], {}
|
||||||
@@ -149,6 +174,19 @@ def run(server, agent, folder, db, api):
|
|||||||
return headers
|
return headers
|
||||||
|
|
||||||
owner, source_only, target_only = map(login, ("owner", "sourceonly", "targetonly"))
|
owner, source_only, target_only = map(login, ("owner", "sourceonly", "targetonly"))
|
||||||
|
|
||||||
|
def fleet_ids(headers, hostname=None):
|
||||||
|
query = "" if hostname is None else "&q=" + urllib.parse.quote(hostname)
|
||||||
|
status, listing, _ = request("/api/v1/devices?view=current" + query, headers=headers)
|
||||||
|
assert status == 200, (status, listing)
|
||||||
|
return {row["agent_id"] for row in listing["items"]}
|
||||||
|
|
||||||
|
fleet = fleet_ids(owner)
|
||||||
|
assert {ready_target, waiting_source} <= fleet and {ready_source, waiting_target}.isdisjoint(fleet)
|
||||||
|
for asset, agent_id, expected in [(ready_asset, ready_target, 200), (waiting_asset, waiting_target, 404)]:
|
||||||
|
assert request(f"/api/v1/tenants/{B}/devices/{asset}?agent_id={agent_id}", headers=target_only)[0] == expected
|
||||||
|
print("PASS migration completes an existing reported transfer and hides an authenticated target without inventory")
|
||||||
|
|
||||||
token = secrets.token_hex(32)
|
token = secrets.token_hex(32)
|
||||||
token_path = folder / "enrollment"
|
token_path = folder / "enrollment"
|
||||||
token_path.write_text(token)
|
token_path.write_text(token)
|
||||||
@@ -201,13 +239,15 @@ def run(server, agent, folder, db, api):
|
|||||||
finally:
|
finally:
|
||||||
proc.send_signal(signal.SIGCONT)
|
proc.send_signal(signal.SIGCONT)
|
||||||
|
|
||||||
def target_ready():
|
def target_completed():
|
||||||
status, dto, _ = request(transfer + query, headers=owner)
|
status, dto, _ = request(transfer + query, headers=owner)
|
||||||
assert status == 200, (status, dto)
|
assert status == 200, (status, dto)
|
||||||
move = dto["transfer"]
|
move = dto["transfer"]
|
||||||
return move if move["state"] == "ready" else None
|
ids = fleet_ids(owner, old["hostname"])
|
||||||
|
assert len(ids) == 1, ("fleet during transfer", ids)
|
||||||
|
return move if move["state"] == "completed" else None
|
||||||
|
|
||||||
moved = until(target_ready)
|
moved = until(target_completed)
|
||||||
assert moved["target_hostname"] == old["hostname"]
|
assert moved["target_hostname"] == old["hostname"]
|
||||||
target_agent, target_asset = moved["target_agent_id"], moved["target_asset_id"]
|
target_agent, target_asset = moved["target_agent_id"], moved["target_asset_id"]
|
||||||
assert target_agent != old_agent and target_asset != old_asset
|
assert target_agent != old_agent and target_asset != old_asset
|
||||||
@@ -215,11 +255,16 @@ def run(server, agent, folder, db, api):
|
|||||||
assert local["agent_id"] == target_agent
|
assert local["agent_id"] == target_agent
|
||||||
assert not list(state.glob("customer-move-*-prior-journal.sqlite"))
|
assert not list(state.glob("customer-move-*-prior-journal.sqlite"))
|
||||||
assert proc.poll() is None
|
assert proc.poll() is None
|
||||||
print("PASS the existing Linux process received a signed handoff and reported fresh target inventory")
|
assert target_agent in fleet_ids(owner) and old_agent not in fleet_ids(owner)
|
||||||
|
print("PASS fresh inventory from the running Linux process switches the sole active entry automatically")
|
||||||
|
|
||||||
route = suffix(moved["transfer_id"], "complete")
|
route = suffix(moved["transfer_id"], "complete")
|
||||||
assert request(route, {}, owner)[0] == 200
|
assert request(route, {}, owner)[0] == 200
|
||||||
assert request(route, {}, owner)[0] == 200
|
assert request(route, {}, owner)[0] == 200
|
||||||
|
assert sql(f"""SELECT count(*) FROM audit_events
|
||||||
|
WHERE event_type='device_customer_transfer_completed'
|
||||||
|
AND data->'decision'->>'agent_id'='{old_agent}'
|
||||||
|
AND data->>'completion_origin'='automatic_after_target_inventory';""") == "1"
|
||||||
assert request("/agent/v1/customer-transfer", tls=old_context)[0] == 401
|
assert request("/agent/v1/customer-transfer", tls=old_context)[0] == 401
|
||||||
status, historic, _ = request(f"/api/v1/tenants/{A}/devices?view=history", headers=source_only)
|
status, historic, _ = request(f"/api/v1/tenants/{A}/devices?view=history", headers=source_only)
|
||||||
assert status == 200 and any(x["agent_id"] == old_agent and x["lifecycle"] == "revoked" for x in historic["items"])
|
assert status == 200 and any(x["agent_id"] == old_agent and x["lifecycle"] == "revoked" for x in historic["items"])
|
||||||
@@ -255,6 +300,7 @@ def run(server, agent, folder, db, api):
|
|||||||
status, fleet, _ = request("/api/v1/devices?view=current", headers=bearer)
|
status, fleet, _ = request("/api/v1/devices?view=current", headers=bearer)
|
||||||
assert status == 200
|
assert status == 200
|
||||||
assert (target_agent in {row["agent_id"] for row in fleet["items"]}) == (audience == "all")
|
assert (target_agent in {row["agent_id"] for row in fleet["items"]}) == (audience == "all")
|
||||||
|
assert all(row["agent_id"] != old_agent for row in fleet["items"])
|
||||||
destination = f"/api/v1/tenants/{B}/devices/{target_asset}?agent_id={target_agent}"
|
destination = f"/api/v1/tenants/{B}/devices/{target_asset}?agent_id={target_agent}"
|
||||||
assert request(destination, headers={**bearer, "X-RMM-Tenant": B})[0] == (200 if audience == "all" else 404)
|
assert request(destination, headers={**bearer, "X-RMM-Tenant": B})[0] == (200 if audience == "all" else 404)
|
||||||
assert request(transfer + query, headers={**bearer, "X-RMM-Tenant": A})[0] == 403
|
assert request(transfer + query, headers={**bearer, "X-RMM-Tenant": A})[0] == 403
|
||||||
|
|||||||
@@ -5,11 +5,10 @@ import { allowed } from './safety';
|
|||||||
|
|
||||||
type Transfer = {
|
type Transfer = {
|
||||||
id: string;
|
id: string;
|
||||||
state: 'pending' | 'enrolled' | 'ready' | 'completed';
|
state: 'pending' | 'enrolled' | 'completed';
|
||||||
tenant: string;
|
tenant: string;
|
||||||
asset: string | null;
|
asset: string | null;
|
||||||
agent: string | null;
|
agent: string | null;
|
||||||
hostname: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseTransfer(value: unknown): Transfer | null {
|
function parseTransfer(value: unknown): Transfer | null {
|
||||||
@@ -17,14 +16,13 @@ function parseTransfer(value: unknown): Transfer | null {
|
|||||||
const t = record(value);
|
const t = record(value);
|
||||||
const { transfer_id: id, target_tenant_id: tenant, state } = t;
|
const { transfer_id: id, target_tenant_id: tenant, state } = t;
|
||||||
if (typeof id !== 'string' || typeof tenant !== 'string' ||
|
if (typeof id !== 'string' || typeof tenant !== 'string' ||
|
||||||
(state !== 'pending' && state !== 'enrolled' && state !== 'ready' && state !== 'completed')) {
|
(state !== 'pending' && state !== 'enrolled' && state !== 'completed')) {
|
||||||
throw new Error('Der Server lieferte keinen gültigen Kundenwechsel.');
|
throw new Error('Der Server lieferte keinen gültigen Kundenwechsel.');
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
id, tenant, state,
|
id, tenant, state,
|
||||||
asset: typeof t.target_asset_id === 'string' ? t.target_asset_id : null,
|
asset: typeof t.target_asset_id === 'string' ? t.target_asset_id : null,
|
||||||
agent: typeof t.target_agent_id === 'string' ? t.target_agent_id : null,
|
agent: typeof t.target_agent_id === 'string' ? t.target_agent_id : null
|
||||||
hostname: typeof t.target_hostname === 'string' ? t.target_hostname : null
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +33,6 @@ function transferError(error: unknown) {
|
|||||||
TRANSFER_ALREADY_PENDING: 'Für dieses Gerät ist bereits ein Kundenwechsel vorgemerkt.',
|
TRANSFER_ALREADY_PENDING: 'Für dieses Gerät ist bereits ein Kundenwechsel vorgemerkt.',
|
||||||
TRANSFER_ALREADY_STARTED: 'Der Agent übernimmt bereits die neue Kopplung.',
|
TRANSFER_ALREADY_STARTED: 'Der Agent übernimmt bereits die neue Kopplung.',
|
||||||
TRANSFER_AGENT_UPDATE_REQUIRED: 'Dieses Gerät benötigt eine Agentversion mit Kundenwechsel.',
|
TRANSFER_AGENT_UPDATE_REQUIRED: 'Dieses Gerät benötigt eine Agentversion mit Kundenwechsel.',
|
||||||
TRANSFER_TARGET_NOT_READY: 'Warten Sie auf die erste Inventarmeldung beim Zielkunden.',
|
|
||||||
TRANSFER_SOURCE_INACTIVE: 'Diese Kopplung ist im bisherigen Kunden nicht mehr aktiv.',
|
TRANSFER_SOURCE_INACTIVE: 'Diese Kopplung ist im bisherigen Kunden nicht mehr aktiv.',
|
||||||
FORBIDDEN: 'Für den Kundenwechsel fehlen Rechte beim bisherigen Kunden oder beim Zielkunden.',
|
FORBIDDEN: 'Für den Kundenwechsel fehlen Rechte beim bisherigen Kunden oder beim Zielkunden.',
|
||||||
NOT_FOUND: 'Das Gerät oder der Zielkunde ist für diese Sitzung nicht verfügbar.'
|
NOT_FOUND: 'Das Gerät oder der Zielkunde ist für diese Sitzung nicht verfügbar.'
|
||||||
@@ -56,7 +53,6 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
|||||||
}) {
|
}) {
|
||||||
const [expanded, setExpanded] = useState(false);
|
const [expanded, setExpanded] = useState(false);
|
||||||
const [target, setTarget] = useState('');
|
const [target, setTarget] = useState('');
|
||||||
const [confirmed, setConfirmed] = useState(false);
|
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const base = tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/customer-transfer');
|
const base = tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/customer-transfer');
|
||||||
@@ -80,7 +76,6 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await request(base + suffix + query, { csrf: auth.csrf_token, tenantId: customer, body });
|
await request(base + suffix + query, { csrf: auth.csrf_token, tenantId: customer, body });
|
||||||
setConfirmed(false);
|
|
||||||
status.reload();
|
status.reload();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(transferError(e));
|
setError(transferError(e));
|
||||||
@@ -99,17 +94,9 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
|||||||
<button disabled={busy} className="quiet"
|
<button disabled={busy} className="quiet"
|
||||||
onClick={() => void submit('/' + encodeURIComponent(current.id) + '/cancel', {})}>Vormerkung abbrechen</button>
|
onClick={() => void submit('/' + encodeURIComponent(current.id) + '/cancel', {})}>Vormerkung abbrechen</button>
|
||||||
</>}
|
</>}
|
||||||
{current.state === 'enrolled' && <p role="status">Die neue Kopplung wartet auf ihre erste Inventarmeldung.</p>}
|
{current.state === 'enrolled' && <p role="status">Der Wechsel wird mit der ersten Inventarmeldung beim Zielkunden abgeschlossen.</p>}
|
||||||
{current.state === 'ready' && <>
|
|
||||||
<p role="status"><strong>{current.hostname}</strong> hat sich beim Zielkunden gemeldet.</p>
|
|
||||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />
|
|
||||||
Ich bestätige den Kundenwechsel für dieses Gerät.
|
|
||||||
</label>
|
|
||||||
<button className="primary" disabled={busy || !confirmed}
|
|
||||||
onClick={() => void submit('/' + encodeURIComponent(current.id) + '/complete', {})}>Kundenwechsel abschließen</button>
|
|
||||||
</>}
|
|
||||||
{current.state === 'completed' && <p role="status">Kundenwechsel abgeschlossen. Die frühere Kopplung steht in der Historie.</p>}
|
{current.state === 'completed' && <p role="status">Kundenwechsel abgeschlossen. Die frühere Kopplung steht in der Historie.</p>}
|
||||||
{current.asset && current.agent && ['ready', 'completed'].includes(current.state) &&
|
{current.asset && current.agent && current.state === 'completed' &&
|
||||||
<a href={'#geraete/' + [current.tenant, current.asset, current.agent].map(encodeURIComponent).join('/')}>
|
<a href={'#geraete/' + [current.tenant, current.asset, current.agent].map(encodeURIComponent).join('/')}>
|
||||||
Neue Kopplung öffnen
|
Neue Kopplung öffnen
|
||||||
</a>}
|
</a>}
|
||||||
@@ -126,7 +113,7 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
|||||||
</select></label>
|
</select></label>
|
||||||
{target && (destination.error || destination.data && !canEnroll) &&
|
{target && (destination.error || destination.data && !canEnroll) &&
|
||||||
<p>Für diesen Zielkunden fehlt das Recht zur Geräteaufnahme oder zum Lesen des Inventars.</p>}
|
<p>Für diesen Zielkunden fehlt das Recht zur Geräteaufnahme oder zum Lesen des Inventars.</p>}
|
||||||
<button className="primary" disabled={busy || !canEnroll}>Kundenwechsel vormerken</button>
|
<button className="primary" disabled={busy || !canEnroll}>Kundenwechsel starten</button>
|
||||||
</form>
|
</form>
|
||||||
</> : <p>Für diese Sitzung ist kein weiterer Kunde verfügbar.</p>
|
</> : <p>Für diese Sitzung ist kein weiterer Kunde verfügbar.</p>
|
||||||
: <p>Der Agent benötigt ein Update für den Kundenwechsel.</p>
|
: <p>Der Agent benötigt ein Update für den Kundenwechsel.</p>
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { ApiError, record, request, tenantPath, type RecordValue, type Session } from './api';
|
||||||
|
import { NavIcon } from './navigation';
|
||||||
|
import { ErrorBox, errorText, useResource } from './resource';
|
||||||
|
|
||||||
|
type Host = { asset_id: string; agent_id: string; hostname: string };
|
||||||
|
|
||||||
|
function host(value: unknown): Host | null {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||||
|
const row = record(value);
|
||||||
|
const { asset_id, agent_id, hostname } = row;
|
||||||
|
return typeof asset_id === 'string' && typeof agent_id === 'string' && typeof hostname === 'string'
|
||||||
|
? { asset_id, agent_id, hostname }
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HypervisorLabel({ device }: { device: RecordValue }) {
|
||||||
|
if (device.device_type !== 'virtual' || !device.hypervisor) return null;
|
||||||
|
const info = record(device.hypervisor);
|
||||||
|
if (info.kind === 'device') {
|
||||||
|
const target = host(info);
|
||||||
|
if (!target || typeof device.tenant_id !== 'string') return null;
|
||||||
|
const path = ['geraete', device.tenant_id, target.asset_id, target.agent_id].map(encodeURIComponent).join('/');
|
||||||
|
return <span className="vm-hypervisor">
|
||||||
|
<NavIcon name="geraete" /><span>Hypervisor <a href={'#' + path} onClick={event => event.stopPropagation()}>
|
||||||
|
{target.hostname}
|
||||||
|
</a></span>
|
||||||
|
</span>;
|
||||||
|
}
|
||||||
|
return info.kind === 'placeholder' && info.provider === 'hetzner' ? (
|
||||||
|
<span className="vm-hypervisor">
|
||||||
|
<NavIcon name="geraete" /><span>Hypervisor <strong>Hetzner Cloud</strong> <span className="muted">· Platzhalter</span></span>
|
||||||
|
</span>
|
||||||
|
) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function assignmentError(e: unknown) {
|
||||||
|
if (e instanceof ApiError) {
|
||||||
|
if (e.code === 'HYPERVISOR_UNAVAILABLE') return 'Dieser Hypervisor ist im Kundenbestand derzeit nicht verfügbar.';
|
||||||
|
if (e.code === 'HYPERVISOR_REQUIRES_VM') return 'Die Installation meldet sich derzeit als anderer Gerätetyp.';
|
||||||
|
if (e.code === 'NOT_FOUND') return 'Diese VM-Kopplung ist nicht mehr im Bestand.';
|
||||||
|
}
|
||||||
|
return errorText(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
|
||||||
|
device: RecordValue; customer: string; asset: string; agent: string; auth: Session;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [draft, setDraft] = useState<string | null>(null);
|
||||||
|
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 value = draft ?? assigned;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => setQuery(search.trim()), 220);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [search]);
|
||||||
|
|
||||||
|
const options = useResource(async signal => {
|
||||||
|
if (!open) return null;
|
||||||
|
const data = record(await request(tenantPath(customer, '/hypervisors?q=' + encodeURIComponent(query)),
|
||||||
|
{ tenantId: customer, signal }));
|
||||||
|
if (!Array.isArray(data.items)) throw new Error('Die Hypervisor-Liste konnte nicht gelesen werden.');
|
||||||
|
return { hosts: data.items.map(host).filter((item): item is Host => item !== null), truncated: data.truncated === true };
|
||||||
|
}, [customer, open, query]);
|
||||||
|
const assignedHost = host(device.hypervisor);
|
||||||
|
const hosts = options.data?.hosts ?? [];
|
||||||
|
const selectedMissing = !!value && !hosts.some(item => item.asset_id === value);
|
||||||
|
const canSave = value !== assigned && (!value || !selectedMissing);
|
||||||
|
|
||||||
|
return <details onToggle={e => {
|
||||||
|
setOpen(e.currentTarget.open);
|
||||||
|
if (!e.currentTarget.open) {
|
||||||
|
setDraft(null);
|
||||||
|
setSearch('');
|
||||||
|
setNotice('');
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<summary>Hypervisor zuordnen</summary>
|
||||||
|
{open && <form onSubmit={async e => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!canSave || busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
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 }
|
||||||
|
});
|
||||||
|
setNotice(value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
|
||||||
|
} catch (e) {
|
||||||
|
setError(assignmentError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<label>Hypervisor suchen<input type="search" maxLength={120} value={search}
|
||||||
|
onChange={e => setSearch(e.target.value)} /></label>
|
||||||
|
<ErrorBox error={error ?? options.error} />
|
||||||
|
{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="">Kein konkreter Hypervisor</option>
|
||||||
|
{selectedMissing && <option value={value} disabled>
|
||||||
|
{assignedHost?.asset_id === value ? assignedHost.hostname : 'Zugeordneter Host außerhalb der Treffer'}
|
||||||
|
</option>}
|
||||||
|
{hosts.map(item => <option key={item.asset_id} value={item.asset_id}>{item.hostname}</option>)}
|
||||||
|
</select></label>
|
||||||
|
<button className="primary" disabled={busy || !canSave}>Zuordnung speichern</button>
|
||||||
|
{notice && <p role="status">{notice}</p>}
|
||||||
|
</form>}
|
||||||
|
</details>;
|
||||||
|
}
|
||||||
@@ -14,7 +14,15 @@ function values(value: unknown) {
|
|||||||
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
|
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
function observation(device: RecordValue, name: string) {
|
function observation(device: RecordValue, name: string): RecordValue | undefined {
|
||||||
|
if (device.source_id === 'opnsense.base') {
|
||||||
|
const inv = object(device.inventory);
|
||||||
|
if (name === 'hardware' || name === 'os') return { data: inv.hardware };
|
||||||
|
const report = object(inv[name]);
|
||||||
|
if (report.status === 'ok' || report.status === 'partial')
|
||||||
|
return { data: report.entries, truncated: report.status === 'partial' };
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
const observations = object(device.inventory).observations;
|
const observations = object(device.inventory).observations;
|
||||||
return Array.isArray(observations) ? observations.map(object).find(item =>
|
return Array.isArray(observations) ? observations.map(object).find(item =>
|
||||||
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
|
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
|
||||||
|
|||||||
+110
-18
@@ -17,7 +17,9 @@ import { allowed } from './safety';
|
|||||||
import { CatalogCheckNotice } from './catalog-check';
|
import { CatalogCheckNotice } from './catalog-check';
|
||||||
import { devicePlatform } from './script-catalog';
|
import { devicePlatform } from './script-catalog';
|
||||||
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
||||||
|
import { OPNsenseDetails } from './opnsense';
|
||||||
import { DeviceCustomerTransfer } from './device-customer-transfer';
|
import { DeviceCustomerTransfer } from './device-customer-transfer';
|
||||||
|
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
|
||||||
import { ErrorBox, errorText, useResource } from './resource';
|
import { ErrorBox, errorText, useResource } from './resource';
|
||||||
import { NavIcon, orderDetailRoute } from './navigation';
|
import { NavIcon, orderDetailRoute } from './navigation';
|
||||||
import { orderTitle, Status } from './order-presentation';
|
import { orderTitle, Status } from './order-presentation';
|
||||||
@@ -28,6 +30,7 @@ import { SyncAlignmentReview } from './sync-alignment-review';
|
|||||||
import { SystemNonstartReview } from './system-nonstart-review';
|
import { SystemNonstartReview } from './system-nonstart-review';
|
||||||
|
|
||||||
const unknown = 'Nicht gemeldet';
|
const unknown = 'Nicht gemeldet';
|
||||||
|
const noPurpose = 'Nicht hinterlegt';
|
||||||
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
|
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
|
||||||
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
|
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
|
||||||
function label(value: unknown) {
|
function label(value: unknown) {
|
||||||
@@ -87,24 +90,35 @@ function Presence({ d }: { d: RecordValue }) {
|
|||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function Capacity({ free, total }: { free: unknown; total: unknown }) {
|
function Capacity({ free, total, showBreakdown = false }: {
|
||||||
|
free: unknown;
|
||||||
|
total: unknown;
|
||||||
|
showBreakdown?: boolean;
|
||||||
|
}) {
|
||||||
|
const freePercent = typeof free === 'number' && typeof total === 'number' &&
|
||||||
|
Number.isFinite(total) && free >= 0 && free <= total && total > 0
|
||||||
|
? (free / total) * 100
|
||||||
|
: null;
|
||||||
|
const displayFree = freePercent === null ? null : Math.round(freePercent * 10) / 10;
|
||||||
|
const freeLabel = displayFree === null ? '' : `${number.format(displayFree)} % frei`;
|
||||||
|
const breakdown = displayFree === null ? '' : `${freeLabel}, ${number.format(100 - displayFree)} % belegt`;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<span>{capacity(free, total)}</span>
|
<span>{capacity(free, total)}</span>
|
||||||
{typeof free === 'number' &&
|
{freePercent !== null && (showBreakdown ? (
|
||||||
typeof total === 'number' &&
|
<>
|
||||||
Number.isFinite(total) &&
|
<span className="capacity-track capacity-breakdown" role="img"
|
||||||
free >= 0 &&
|
aria-label={breakdown} title={breakdown}>
|
||||||
free <= total &&
|
<span className="capacity-free" style={{ width: `${freePercent}%` }} />
|
||||||
total > 0 && (
|
<span className="capacity-used" />
|
||||||
<span
|
|
||||||
className="capacity-track"
|
|
||||||
title={`${number.format((100 * free) / total)} % frei`}
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<i style={{ width: `${(100 * (total - free)) / total}%` }} />
|
|
||||||
</span>
|
</span>
|
||||||
)}
|
<small className="capacity-caption" aria-hidden="true">{freeLabel}</small>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="capacity-track" title={freeLabel} aria-hidden="true">
|
||||||
|
<i style={{ width: `${100 - freePercent}%` }} />
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -126,6 +140,64 @@ function devicePath(customer: string, asset: string) {
|
|||||||
return tenantPath(customer, '/devices/' + encodeURIComponent(asset));
|
return tenantPath(customer, '/devices/' + encodeURIComponent(asset));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DevicePurpose({ value, path, customer, editor, success, onSaved }: {
|
||||||
|
value: string;
|
||||||
|
path: string;
|
||||||
|
customer: string;
|
||||||
|
editor: Session | null;
|
||||||
|
success: boolean;
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const tooLong = Array.from(draft?.trim() ?? '').length > 500;
|
||||||
|
const close = () => { setDraft(null); setError(null); };
|
||||||
|
return (
|
||||||
|
<section className="device-purpose">
|
||||||
|
<h2>Zweck</h2>
|
||||||
|
{editor && draft !== null ? (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (busy || tooLong) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await request(path + '/purpose', {
|
||||||
|
method: 'PATCH', tenantId: customer, csrf: editor.csrf_token, body: { purpose: draft }
|
||||||
|
});
|
||||||
|
close();
|
||||||
|
onSaved();
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<label>
|
||||||
|
Zweck des Geräts
|
||||||
|
<textarea autoFocus rows={3} value={draft} disabled={busy}
|
||||||
|
aria-describedby="device-purpose-help" aria-invalid={tooLong}
|
||||||
|
onChange={(e) => setDraft(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<p id="device-purpose-help" className={tooLong ? 'error' : 'muted'}>
|
||||||
|
{tooLong ? 'Der Zweck ist zu lang. ' : ''}Maximal 500 Zeichen. Zum Entfernen das Feld leeren.
|
||||||
|
</p>
|
||||||
|
<ErrorBox error={error} />
|
||||||
|
<button type="submit" disabled={busy || tooLong}>{busy ? 'Speichert …' : 'Zweck speichern'}</button>{' '}
|
||||||
|
<button type="button" className="quiet" disabled={busy} onClick={close}>Abbrechen</button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className={'purpose-text' + (value ? '' : ' muted')}>{value || noPurpose}</p>
|
||||||
|
{editor && <button className="quiet" onClick={() => setDraft(value)}>Zweck bearbeiten</button>}
|
||||||
|
{success && <p role="status">Zweck gespeichert.</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function reportedScriptProfiles(device: RecordValue) {
|
function reportedScriptProfiles(device: RecordValue) {
|
||||||
const os = devicePlatform(device);
|
const os = devicePlatform(device);
|
||||||
if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet';
|
if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet';
|
||||||
@@ -175,6 +247,7 @@ function DeviceDetail({
|
|||||||
[error, setError] = useState<string | null>(null);
|
[error, setError] = useState<string | null>(null);
|
||||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
const [managing, setManaging] = useState(false);
|
const [managing, setManaging] = useState(false);
|
||||||
|
const [purposeSaved, setPurposeSaved] = useState(false);
|
||||||
const d = detail.data;
|
const d = detail.data;
|
||||||
const scoped = membership.data;
|
const scoped = membership.data;
|
||||||
const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : [];
|
const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : [];
|
||||||
@@ -206,6 +279,7 @@ function DeviceDetail({
|
|||||||
<div>
|
<div>
|
||||||
<h1>{label(d.hostname)}</h1>
|
<h1>{label(d.hostname)}</h1>
|
||||||
<Presence d={d} />
|
<Presence d={d} />
|
||||||
|
<HypervisorLabel device={d} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<section>
|
<section>
|
||||||
@@ -219,6 +293,15 @@ function DeviceDetail({
|
|||||||
))}
|
))}
|
||||||
</dl>
|
</dl>
|
||||||
</section>
|
</section>
|
||||||
|
<DevicePurpose
|
||||||
|
value={typeof d.purpose === 'string' ? d.purpose : ''}
|
||||||
|
path={path}
|
||||||
|
customer={customer}
|
||||||
|
editor={scoped && allowed(scoped, 'devices:revoke') && allowed(scoped, 'inventory:read') ? scoped : null}
|
||||||
|
success={purposeSaved}
|
||||||
|
onSaved={() => { setPurposeSaved(true); detail.reload(); }}
|
||||||
|
/>
|
||||||
|
<OPNsenseDetails device={d} />
|
||||||
<DeviceInventoryPanels device={d} />
|
<DeviceInventoryPanels device={d} />
|
||||||
{volumes.length > 0 && (
|
{volumes.length > 0 && (
|
||||||
<section>
|
<section>
|
||||||
@@ -280,6 +363,8 @@ function DeviceDetail({
|
|||||||
<details open={managing} onToggle={e => setManaging(e.currentTarget.open)}>
|
<details open={managing} onToggle={e => setManaging(e.currentTarget.open)}>
|
||||||
<summary>Gerät verwalten</summary>
|
<summary>Gerät verwalten</summary>
|
||||||
<ErrorBox error={error} />
|
<ErrorBox error={error} />
|
||||||
|
{d.device_type === 'virtual' && d.lifecycle === 'current' &&
|
||||||
|
<HypervisorAssignment device={d} customer={customer} asset={asset} agent={agent} auth={scoped} />}
|
||||||
<DeviceCustomerTransfer auth={scoped} customer={customer} asset={asset} agent={agent}
|
<DeviceCustomerTransfer auth={scoped} customer={customer} asset={asset} agent={agent}
|
||||||
customers={customers} active={d.lifecycle === 'current'}
|
customers={customers} active={d.lifecycle === 'current'}
|
||||||
supported={Array.isArray(d.capabilities) && d.capabilities.includes('device.customer_transfer/1')} />
|
supported={Array.isArray(d.capabilities) && d.capabilities.includes('device.customer_transfer/1')} />
|
||||||
@@ -553,9 +638,9 @@ export function Devices({
|
|||||||
<span className="sr-only">Ziel auswählen</span>
|
<span className="sr-only">Ziel auswählen</span>
|
||||||
</th>
|
</th>
|
||||||
)}
|
)}
|
||||||
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
|
{['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
|
||||||
(h) => (
|
(h) => (
|
||||||
<th scope="col" key={h}>
|
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
|
||||||
{h}
|
{h}
|
||||||
</th>
|
</th>
|
||||||
)
|
)
|
||||||
@@ -567,7 +652,8 @@ export function Devices({
|
|||||||
const asset = objectId(d, 'asset'),
|
const asset = objectId(d, 'asset'),
|
||||||
agent = objectId(d, 'agent'),
|
agent = objectId(d, 'agent'),
|
||||||
customer = objectId(d, 'tenant'),
|
customer = objectId(d, 'tenant'),
|
||||||
model = cpu(d);
|
model = cpu(d),
|
||||||
|
purpose = typeof d.purpose === 'string' ? d.purpose : '';
|
||||||
const show = () => {
|
const show = () => {
|
||||||
setDeletionNotice('');
|
setDeletionNotice('');
|
||||||
window.location.hash = ['geraete', customer, asset, agent]
|
window.location.hash = ['geraete', customer, asset, agent]
|
||||||
@@ -601,8 +687,14 @@ export function Devices({
|
|||||||
>
|
>
|
||||||
{label(d.hostname)}
|
{label(d.hostname)}
|
||||||
</button>
|
</button>
|
||||||
|
<HypervisorLabel device={d} />
|
||||||
</td>
|
</td>
|
||||||
<td data-label="Type">{label(d.device_type)}</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="OS">{label(d.os)}</td>
|
||||||
<td data-label="Status" className="device-presence">
|
<td data-label="Status" className="device-presence">
|
||||||
<Presence d={d} />
|
<Presence d={d} />
|
||||||
@@ -614,7 +706,7 @@ export function Devices({
|
|||||||
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} />
|
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} />
|
||||||
</td>
|
</td>
|
||||||
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
|
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
|
||||||
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
|
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} showBreakdown />
|
||||||
</td>
|
</td>
|
||||||
<td data-label="CPU">
|
<td data-label="CPU">
|
||||||
{model.primary}
|
{model.primary}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, it } from 'vitest';
|
||||||
|
import { OPNsenseDetails } from './opnsense';
|
||||||
|
import { DeviceInventoryPanels } from './device-inventory';
|
||||||
|
|
||||||
|
it('keeps missing, empty and partial appliance sources distinct and limits panels to OPNsense', () => {
|
||||||
|
const d = { source_id:'opnsense.base', inventory:{
|
||||||
|
ipsec:{status:'unavailable',entries:[]}, openvpn:{status:'ok',entries:[]},
|
||||||
|
firewall:{status:'partial', entries:['pass in on vtnet0']},
|
||||||
|
interfaces:{status:'ok', entries:[{name:'vtnet0',addresses:['192.0.2.1/24']}]},
|
||||||
|
software:{status:'ok',entries:[{name:'opnsense',version:'26.7'}]},
|
||||||
|
users:{status:'unavailable',entries:[]}
|
||||||
|
}};
|
||||||
|
const view = renderToStaticMarkup(<OPNsenseDetails device={d}/>);
|
||||||
|
expect(view).toMatch(/IPsec[^<]*<\/h3><p>Nicht ermittelbar/);
|
||||||
|
expect(view).toMatch(/OpenVPN[^<]*<\/h3><p>Keine Einträge/);
|
||||||
|
expect(view).toContain('unvollständige Liste');
|
||||||
|
expect(view).toContain('pass in on vtnet0');
|
||||||
|
expect(renderToStaticMarkup(<OPNsenseDetails device={{...d,source_id:'linux.base'}}/>)).toBe('');
|
||||||
|
const system = renderToStaticMarkup(<DeviceInventoryPanels device={d}/>);
|
||||||
|
expect(system).toContain('192.0.2.1/24');
|
||||||
|
expect(system).toContain('26.7');
|
||||||
|
expect(system).not.toContain('Keine Benutzer angemeldet');
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { RecordValue } from './api';
|
||||||
|
|
||||||
|
export function OPNsenseDetails({ device }: { device: RecordValue }) {
|
||||||
|
if (device.source_id !== 'opnsense.base') return null;
|
||||||
|
const inventory = device.inventory as RecordValue | null;
|
||||||
|
function list(key: string, title: string) {
|
||||||
|
const report = inventory?.[key] as RecordValue | undefined;
|
||||||
|
const available = report?.status === 'ok' || report?.status === 'partial';
|
||||||
|
const rows = Array.isArray(report?.entries) ? report.entries.filter((x): x is string => typeof x === 'string') : [];
|
||||||
|
return <div key={key}><h3>{title}</h3>{!available ? <p>Nicht ermittelbar</p> : <>
|
||||||
|
{report?.status === 'partial' && <p>Auszug – unvollständige Liste</p>}
|
||||||
|
{rows.length ? <ol>{rows.map((line, i) => <li key={i}><code>{line}</code></li>)}</ol> : <p>Keine Einträge gemeldet.</p>}
|
||||||
|
</>}</div>;
|
||||||
|
}
|
||||||
|
return <>
|
||||||
|
<section><h2>VPN-Verbindungen</h2>
|
||||||
|
{list('vpn_configured', 'Konfigurierte VPNs')}
|
||||||
|
{list('wireguard', 'WireGuard · letzter Handshake je Peer')}
|
||||||
|
{list('openvpn', 'OpenVPN · Laufzeitstatus')}
|
||||||
|
{list('ipsec', 'IPsec · aktive Sicherheitsassoziationen')}
|
||||||
|
</section>
|
||||||
|
<section><h2>Firewallregeln</h2>{list('firewall', 'Aktive PF-Filterregeln · Hauptregelsatz in Auswertungsreihenfolge')}</section>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
+12
-1
@@ -94,13 +94,23 @@ section.fleet { padding:0; overflow:hidden; }
|
|||||||
.fleet-table th:last-child,.fleet-table td:last-child { padding-right:18px; }
|
.fleet-table th:last-child,.fleet-table td:last-child { padding-right:18px; }
|
||||||
.fleet-table tbody tr { cursor:pointer; } .fleet-table tbody tr:hover,.fleet-table tr:focus-within { background:#f2f7f4; }
|
.fleet-table tbody tr { cursor:pointer; } .fleet-table tbody tr:hover,.fleet-table tr:focus-within { background:#f2f7f4; }
|
||||||
.release-table tbody tr { cursor:auto; }
|
.release-table tbody tr { cursor:auto; }
|
||||||
|
.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 .target-col { width:35px; }
|
||||||
|
.fleet-table th.purpose-col { width:17%; }
|
||||||
|
.purpose-text { white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||||
|
.fleet-table .purpose-text { display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:3; overflow:hidden; }
|
||||||
|
.device-purpose textarea { font-family:inherit; }
|
||||||
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
|
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
|
||||||
.fleet-table input[type=checkbox] { margin:0; }
|
.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; }
|
.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; }
|
.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 { 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-track i { display:block; height:100%; background:#659d84; }
|
||||||
|
.capacity-breakdown { display:flex; height:6px; }
|
||||||
|
.capacity-free { flex:none; background:#2e7657; }
|
||||||
|
.capacity-used { flex:1; background:#b5c2be; }
|
||||||
|
.capacity-caption { display:block; color:var(--subtle); }
|
||||||
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }
|
.presence { 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 i { width:6px; height:6px; border-radius:50%; background:currentColor; }
|
||||||
.presence.online { color:#236343; background:#e6f4e9; }
|
.presence.online { color:#236343; background:#e6f4e9; }
|
||||||
@@ -154,7 +164,8 @@ section.fleet { padding:0; overflow:hidden; }
|
|||||||
.fleet-table td,.fleet-table td:first-child,.fleet-table td:last-child {display:block;padding:0;border:0;font-size:.9rem;}
|
.fleet-table td,.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 td[data-label]::before {content:attr(data-label);display:block;color:var(--subtle);font-size:.73rem;}
|
||||||
.fleet-table .hostname {grid-column:1/-1;padding-right:28px;} .host-link {font-size:1rem;}
|
.fleet-table .hostname {grid-column:1/-1;padding-right:28px;} .host-link {font-size:1rem;}
|
||||||
.fleet-table .target-col {position:absolute;right:14px;top:14px;width:auto;} .capacity-track {width:76px;}
|
.fleet-table .purpose-col {grid-column:1/-1;}
|
||||||
|
.fleet-table .target-col {position:absolute;right:14px;top:14px;width:auto;} .capacity-track {width:min(76px,100%);}
|
||||||
.list-footer {border-top:1px solid var(--line);flex-wrap:wrap;} .facts {grid-template-columns:1fr 1fr;gap:12px;}
|
.list-footer {border-top:1px solid var(--line);flex-wrap:wrap;} .facts {grid-template-columns:1fr 1fr;gap:12px;}
|
||||||
}
|
}
|
||||||
@media(max-width:450px) { .sidebar nav a {flex-direction:column;gap:2px;} .crumb span,.crumb i {display:none;} .login {margin:18px 12px;} .facts {grid-template-columns:1fr;} }
|
@media(max-width:450px) { .sidebar nav a {flex-direction:column;gap:2px;} .crumb span,.crumb i {display:none;} .login {margin:18px 12px;} .facts {grid-template-columns:1fr;} }
|
||||||
|
|||||||
Reference in New Issue
Block a user