Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52c352c0d9 | ||
|
|
51ce8cde77 | ||
|
|
037b5e39fa | ||
|
|
5cfa0cfdcf | ||
|
|
b002202d62 | ||
|
|
6aeb618170 | ||
|
|
5a9eafbff1 | ||
|
|
f01e81418e | ||
|
|
d4cbc40979 | ||
|
|
478ee1fc1a | ||
|
|
01960477f8 | ||
|
|
480e3749a6 | ||
|
|
65d84a19c0 | ||
|
|
cad188aeb7 | ||
|
|
bcd3bd86ad | ||
|
|
08177d8843 | ||
|
|
2378a54bd4 | ||
|
|
9e957e6d8d | ||
|
|
dd59052e7c | ||
|
|
a4bcebf440 |
@@ -10,9 +10,11 @@ Jede Installation ist an Kunde, Gerät und Agentenidentität gebunden. Die Stand
|
||||
|
||||
Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` bezeichnet einen physischen Rechner, `virtual` ein virtualisiertes System und `hypervisor` eine erkannte Hostrolle. Proxmox VE erscheint als `hypervisor` mit `Proxmox VE` in der Spalte OS. Eine erkannte Hostrolle hat Vorrang, auch bei verschachtelter Virtualisierung. Bei fehlender Angabe zeigt die WebUI „Nicht gemeldet“. Die Geräteabfragen in WebUI und MCP verwenden denselben gespeicherten Typ. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät.
|
||||
|
||||
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)
|
||||
|
||||
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.
|
||||
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)
|
||||
|
||||
@@ -30,6 +32,8 @@ In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hers
|
||||
|
||||
Linux führt Shellskripte unter dem Dienstkonto oder über den eingerichteten Helper als root aus. Windows führt PowerShell unter LocalService oder über den Helper als SYSTEM aus. Neustart und Installation von Windows-Updates sind Skriptaufträge. Bei einem Neustart kann das Skript bereits vor dem Herunterfahren erfolgreich enden. Der Betriebsnachweis verbindet den neuen Bootbezug mit dem nächsten authentisierten Kontakt und einem Folgeauftrag. [Skriptbibliothek](crates/server/src/script_library.rs) · [Auftragsverarbeitung](crates/server/src/jobs.rs)
|
||||
|
||||
Agent und privilegierter Helper prüfen jeweils den Synchronisationsstatus, eine begrenzte Zeitunsicherheit und die Kontinuität der lokalen Systemzeit. Die serverseitig signierte Starterlaubnis wird an der lokal geprüften Uhr gemessen. Linux liest dafür den Kernelstatus. Auf regulär aufgenommenen Windows-Geräten fragen der Agent und der dauerhaft eingerichtete SYSTEM-Helper den lokalen Windows-Zeitdienst jeweils selbst ab. Beide prüfen die Identität des Zeitdienstes an der Verbindung, die den Status liefert. Sie akzeptieren den zuletzt erfolgreichen Abgleich innerhalb eines Tages und eine geschätzte Unsicherheit bis zu zwei Sekunden. Bei einem erkannten Zeitsprung oder Standby warten sie auf einen neueren erfolgreichen Abgleich. Der bisherige signierte Zeitvergleich wird noch im separaten Windows-Update-Wartungsprofil und bei Installationen mit manueller Auftragsbindung verwendet. [Entscheidung zur Uhrprüfung](docs/project-decisions.md)
|
||||
|
||||
Ein Abbruchwunsch wird am Auftrag gespeichert. Bei unterbrochener Rückmeldung gleichen Server, Agent und gegebenenfalls Helper den gespeicherten Versuch ab. Bei `unknown` bleibt die Wirkung ungeklärt. Die WebUI kann einen solchen Fall dokumentiert abschließen. Agent und Helper übernehmen den Abschluss im signierten Abgleich auch dann, wenn der Agent den Abbruch seiner eigenen Ausführung protokolliert hat und im unabhängig gebundenen Verbrauchsjournal des Helpers ein Ergebnis fehlt. Beide bewahren die ursprünglichen Belege. Der Abschluss erteilt keine Freigabe für einen weiteren Versuch.
|
||||
|
||||
## Öffentliche Verwaltung und Berechtigungen
|
||||
|
||||
@@ -205,6 +205,7 @@ pub struct HelperSync<V = DefaultVerifier> {
|
||||
born: DateTime<Utc>,
|
||||
capture: Option<Capture>,
|
||||
lease: Option<Lease>,
|
||||
integrity: Option<crate::ledger::IntegrityMonitor>,
|
||||
}
|
||||
impl HelperSync<DefaultVerifier> {
|
||||
/// No persisted ready bit can open a newly started helper.
|
||||
@@ -222,6 +223,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
born: clock.now()?,
|
||||
capture: None,
|
||||
lease: None,
|
||||
integrity: None,
|
||||
})
|
||||
}
|
||||
/// Select exactly one protected helper execution identity, closing leases.
|
||||
@@ -230,6 +232,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
self.identity = identity;
|
||||
self
|
||||
}
|
||||
/// Use with one protected SQLite connection retained for this instance.
|
||||
/// The native owner must run a full check before any new host effect.
|
||||
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
|
||||
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
|
||||
self
|
||||
}
|
||||
pub fn close(&mut self) {
|
||||
self.lease = None;
|
||||
self.capture = None;
|
||||
@@ -288,7 +296,8 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
ledger_fingerprint: lease.fingerprint.clone(),
|
||||
captured_at: capture.captured_at,
|
||||
};
|
||||
self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?;
|
||||
let audit_history = self.integrity.is_none();
|
||||
self.verify_no_start_anchor(db, guard, &anchor, clock, boot, audit_history)?;
|
||||
Ok(anchor)
|
||||
}
|
||||
/// Consume exactly the approved update attempt and delegate its ORIGINAL
|
||||
@@ -389,9 +398,9 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
tx.commit()?;
|
||||
return Ok(outcome);
|
||||
}
|
||||
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
|
||||
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
|
||||
let observation = guard.verify_no_dispatch(request, anchor)?;
|
||||
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
|
||||
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot, true)?;
|
||||
ensure!(
|
||||
!observation.intent_id.is_nil()
|
||||
&& digest(&observation.intent_sha256)
|
||||
@@ -421,6 +430,7 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
anchor: &NoStartAnchor,
|
||||
clock: &impl Clock,
|
||||
boot: &impl BootSource,
|
||||
audit_history: bool,
|
||||
) -> Result<DateTime<Utc>> {
|
||||
guard.check(db)?;
|
||||
let now = clock.now()?;
|
||||
@@ -445,15 +455,18 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
&& ledger_fingerprint(db)? == anchor.ledger_fingerprint,
|
||||
"DENIAL_HELPER_LINEAGE_CHANGED"
|
||||
);
|
||||
// Exact equality is deliberate: a first implementation refuses even
|
||||
// legitimate intervening progress rather than inventing lineage links.
|
||||
verify_checkpoint_repair_history_with(
|
||||
db,
|
||||
&self.binding,
|
||||
None,
|
||||
self.identity,
|
||||
&self.verifier,
|
||||
)?;
|
||||
// Idle anchor capture checks the current signed head. The native
|
||||
// executor audits the full history before execution, and abandonment
|
||||
// always audits it under the same transaction before recording evidence.
|
||||
if audit_history {
|
||||
verify_checkpoint_repair_history_with(
|
||||
db,
|
||||
&self.binding,
|
||||
None,
|
||||
self.identity,
|
||||
&self.verifier,
|
||||
)?;
|
||||
}
|
||||
let (response, raw): (Vec<u8>, Vec<u8>) = db.query_row(
|
||||
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
|
||||
[anchor.decision_id.to_string()],
|
||||
@@ -483,8 +496,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
&& decision.helper_journal_id == Some(anchor.journal_id)
|
||||
&& decision.helper_checkpoint == anchor.checkpoint
|
||||
&& decision.connection_generation == anchor.connection_generation
|
||||
&& decision.request_hash == anchor.sync_request_sha256
|
||||
&& capture.journal_id == anchor.journal_id
|
||||
&& capture.checkpoint == anchor.checkpoint
|
||||
&& capture.captured_at == anchor.captured_at
|
||||
&& capture.boot_id == anchor.boot_id
|
||||
&& capture.captured_at <= decision.issued_at
|
||||
&& capture.captured_at <= now,
|
||||
"DENIAL_CONFIRMED_READY_REQUIRED"
|
||||
);
|
||||
@@ -523,7 +540,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
);
|
||||
let boot_id = boot.current_boot()?;
|
||||
ensure!(!boot_id.is_nil(), "BOOT_ID_REQUIRED");
|
||||
initialize(db, &self.binding)?;
|
||||
if let Some(integrity) = &mut self.integrity {
|
||||
integrity.check(db, false, "ROOT_LEDGER_INTEGRITY")?;
|
||||
initialize_schema(db, &self.binding)?;
|
||||
} else {
|
||||
initialize(db, &self.binding)?;
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let meta = metadata(&tx)?;
|
||||
ensure!(meta.fault.is_none(), "HELPER_MANUAL_RECOVERY_REQUIRED");
|
||||
@@ -1031,13 +1053,17 @@ struct Meta {
|
||||
agent_checkpoint: u64,
|
||||
}
|
||||
fn initialize(db: &Connection, binding: &Binding) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "ROOT_LEDGER_INTEGRITY");
|
||||
crate::ledger::check_integrity(db, "ROOT_LEDGER_INTEGRITY")?;
|
||||
initialize_schema(db, binding)
|
||||
}
|
||||
|
||||
fn initialize_schema(db: &Connection, binding: &Binding) -> Result<()> {
|
||||
db.execute_batch("PRAGMA synchronous=FULL;
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,binding_sha256 TEXT NOT NULL,last_decision TEXT,fault TEXT,agent_journal_id TEXT,agent_checkpoint INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,fingerprint TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_captures(checkpoint INTEGER PRIMARY KEY,snapshot BLOB NOT NULL,fingerprint TEXT NOT NULL,captured_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);")?;
|
||||
CREATE TABLE IF NOT EXISTS helper_sync_decisions(decision_id TEXT PRIMARY KEY,checkpoint INTEGER NOT NULL,response BLOB NOT NULL,request BLOB NOT NULL,fingerprint TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS helper_sync_decisions_checkpoint ON helper_sync_decisions(checkpoint);")?;
|
||||
let legacy_captures: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='helper_sync_captures')",
|
||||
[], |row| row.get(0),
|
||||
@@ -1175,23 +1201,23 @@ pub fn verify_checkpoint_repair_history_with(
|
||||
) -> Result<()> {
|
||||
let meta = metadata(db)?;
|
||||
validate_history(db, binding, &meta, meta.generation, verifier)?;
|
||||
let entry_count: u64 = db.query_row(
|
||||
"SELECT count(*) FROM helper_sync_decisions",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
ensure!(entry_count <= 100000, "REPAIR_HISTORY_LIMIT");
|
||||
let mut statement = db.prepare(
|
||||
"SELECT response,request,checkpoint FROM helper_sync_decisions ORDER BY checkpoint",
|
||||
)?;
|
||||
let entries = statement
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, Vec<u8>>(0)?,
|
||||
r.get::<_, Vec<u8>>(1)?,
|
||||
r.get::<_, u64>(2)?,
|
||||
))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(entries.len() <= 100000, "REPAIR_HISTORY_LIMIT");
|
||||
let mut entries = statement.query([])?;
|
||||
let mut previous = None;
|
||||
let mut previous_checkpoint = 0;
|
||||
let mut previous_agent_checkpoint = 0;
|
||||
for (signed, raw, checkpoint) in entries {
|
||||
while let Some(entry) = entries.next()? {
|
||||
let signed: Vec<u8> = entry.get(0)?;
|
||||
let raw: Vec<u8> = entry.get(1)?;
|
||||
let checkpoint: u64 = entry.get(2)?;
|
||||
let response: SignedResponse = serde_json::from_slice(&signed)?;
|
||||
let parsed: ReconcileDecisionPayload = serde_json::from_slice(&response.decision_bytes)?;
|
||||
let decision = verify(verifier, binding, &response, parsed.issued_at)?;
|
||||
|
||||
@@ -7,7 +7,8 @@ use rmm_domain::{
|
||||
jobs::hash,
|
||||
reconciliation::{ReconciledOutcome, canonical_outcome_bytes},
|
||||
};
|
||||
use rusqlite::{OptionalExtension, TransactionBehavior, params};
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use std::time::{Duration, Instant};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
|
||||
@@ -29,11 +30,48 @@ pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
|
||||
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
|
||||
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "JOURNAL_INTEGRITY");
|
||||
check_integrity(db, "JOURNAL_INTEGRITY")
|
||||
}
|
||||
|
||||
pub fn check_integrity(db: &Connection, error_code: &'static str) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |row| row.get(0))?;
|
||||
ensure!(check == "ok", "{error_code}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Full integrity scans for an owner holding one protected, long-lived SQLite
|
||||
/// connection. External commits and schema changes require another scan even
|
||||
/// when the interval has not elapsed. No cached result authorizes an effect.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IntegrityMonitor {
|
||||
checked: Option<(u64, u64, Instant)>,
|
||||
}
|
||||
|
||||
impl IntegrityMonitor {
|
||||
pub(crate) fn check(
|
||||
&mut self,
|
||||
db: &Connection,
|
||||
required: bool,
|
||||
error_code: &'static str,
|
||||
) -> Result<()> {
|
||||
let data: u64 = db.query_row("PRAGMA data_version", [], |row| row.get(0))?;
|
||||
let schema: u64 = db.query_row("PRAGMA schema_version", [], |row| row.get(0))?;
|
||||
if !required
|
||||
&& self.checked.is_some_and(|(previous_data, previous_schema, checked)| {
|
||||
data == previous_data
|
||||
&& schema == previous_schema
|
||||
&& checked.elapsed() < Duration::from_secs(300)
|
||||
})
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
self.checked = None;
|
||||
check_integrity(db, error_code)?;
|
||||
self.checked = Some((data, schema, Instant::now()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a human WebUI closure replaces the unresolved local outcome, keep the
|
||||
/// exact original outcome bytes once. A differing second copy fails closed.
|
||||
pub(crate) fn retain_closure_original(
|
||||
@@ -379,3 +417,34 @@ pub fn start_witness_bytes(
|
||||
"reauthentication_required":true,"postconditions_passed":false});
|
||||
Ok(serde_json::to_vec(&evidence)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod integrity_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn idle_integrity_reuses_the_check_but_reaudits_external_changes_and_expiry() {
|
||||
let path = std::env::temp_dir().join(format!("rmm-integrity-{}.sqlite", Uuid::new_v4()));
|
||||
{
|
||||
let db = Connection::open(&path).unwrap();
|
||||
db.execute_batch("CREATE TABLE sample(id INTEGER PRIMARY KEY);").unwrap();
|
||||
let mut monitor = IntegrityMonitor::default();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
let first = monitor.checked.unwrap();
|
||||
db.execute("INSERT INTO sample VALUES (1)", []).unwrap();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
assert_eq!(monitor.checked, Some(first));
|
||||
|
||||
let peer = Connection::open(&path).unwrap();
|
||||
peer.execute("INSERT INTO sample VALUES (2)", []).unwrap();
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
let changed = monitor.checked.unwrap();
|
||||
assert_ne!(changed.0, first.0);
|
||||
|
||||
monitor.checked = Some((changed.0, changed.1, changed.2 - Duration::from_secs(300)));
|
||||
monitor.check(&db, false, "JOURNAL_INTEGRITY").unwrap();
|
||||
assert!(monitor.checked.unwrap().2 >= changed.2);
|
||||
}
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ pub struct ClientSync<V = DefaultVerifier> {
|
||||
verifier: V,
|
||||
helper_identity: HelperIdentity,
|
||||
pending: Option<PreparedSync>,
|
||||
integrity: Option<crate::ledger::IntegrityMonitor>,
|
||||
channel: Option<Channel>,
|
||||
gate: Option<Gate>,
|
||||
}
|
||||
@@ -117,6 +118,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
verifier,
|
||||
helper_identity: HelperIdentity::Root,
|
||||
pending: None,
|
||||
integrity: None,
|
||||
channel: None,
|
||||
gate: None,
|
||||
}
|
||||
@@ -127,6 +129,11 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
self.helper_identity = identity;
|
||||
self
|
||||
}
|
||||
/// Use with one protected SQLite connection retained for this instance.
|
||||
pub fn with_periodic_idle_integrity_checks(mut self) -> Self {
|
||||
self.integrity = Some(crate::ledger::IntegrityMonitor::default());
|
||||
self
|
||||
}
|
||||
/// Invoke on every authenticated/fenced ServerHello or transport loss.
|
||||
pub fn close(&mut self) {
|
||||
self.gate = None;
|
||||
@@ -606,7 +613,17 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
|
||||
"UNAUTHENTICATED_CHANNEL"
|
||||
);
|
||||
initialize(db)?;
|
||||
if let Some(integrity) = &mut self.integrity {
|
||||
let work_pending: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
integrity.check(db, work_pending, "JOURNAL_INTEGRITY")?;
|
||||
initialize_schema(db)?;
|
||||
} else {
|
||||
initialize(db)?;
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let meta = metadata(&tx)?;
|
||||
ensure!(meta.fault.is_none(), "SYNC_MANUAL_RECOVERY_REQUIRED");
|
||||
@@ -1147,8 +1164,11 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
}
|
||||
|
||||
pub fn initialize(db: &Connection) -> Result<()> {
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "JOURNAL_INTEGRITY");
|
||||
crate::ledger::check_integrity(db, "JOURNAL_INTEGRITY")?;
|
||||
initialize_schema(db)
|
||||
}
|
||||
|
||||
fn initialize_schema(db: &Connection) -> Result<()> {
|
||||
db.execute_batch("PRAGMA synchronous=FULL;
|
||||
CREATE TABLE IF NOT EXISTS reconcile_meta(id INTEGER PRIMARY KEY CHECK(id=1),journal_id TEXT NOT NULL,checkpoint INTEGER NOT NULL DEFAULT 0,high_sequence INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT 0,last_decision TEXT,pending_request TEXT,helper_id TEXT,helper_checkpoint INTEGER NOT NULL DEFAULT 0,fault TEXT);
|
||||
CREATE TABLE IF NOT EXISTS reconcile_requests(id TEXT PRIMARY KEY,request BLOB NOT NULL,envelope BLOB NOT NULL,generation INTEGER NOT NULL,response BLOB);
|
||||
|
||||
@@ -466,6 +466,31 @@ struct Fixture {
|
||||
identity: HelperIdentity,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_anchor_checks_the_head_but_abandonment_rejects_damaged_history() {
|
||||
let (mut f, sync, _, request, mut guard) = denial_case();
|
||||
let mut sync = sync.with_periodic_idle_integrity_checks();
|
||||
f.clock.now += Duration::seconds(1);
|
||||
let capture = f.snapshot(&mut sync, 7);
|
||||
let raw = f.request(&capture);
|
||||
let ready = f.decision(&capture, &raw, 7, true);
|
||||
assert!(f.apply(&mut sync, &ready, &raw).unwrap().ready);
|
||||
guard.intent_recorded_at = f.clock.now;
|
||||
f.db.execute(
|
||||
"UPDATE helper_sync_decisions SET response=X'00' WHERE checkpoint < ?1",
|
||||
[capture.checkpoint],
|
||||
).unwrap();
|
||||
|
||||
let anchor = sync.no_start_anchor(&f.db, &guard, 7, &f.clock, &f.boot).unwrap();
|
||||
guard.anchor_sha256 = hash(&serde_json::to_vec(&anchor).unwrap());
|
||||
let before = denial_ledger_bytes(&f.db);
|
||||
assert!(
|
||||
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(denial_ledger_bytes(&f.db), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor() {
|
||||
let mut f = Fixture::new();
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::{
|
||||
actions::{ServiceUnit, reboot_required},
|
||||
process,
|
||||
};
|
||||
mod disks;
|
||||
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
@@ -201,8 +200,6 @@ pub struct Dns {
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Volume {
|
||||
#[serde(skip)]
|
||||
pub(crate) devno: String,
|
||||
pub mount_point: String,
|
||||
pub filesystem: String,
|
||||
pub device: String,
|
||||
@@ -278,7 +275,6 @@ pub struct LinuxInventory {
|
||||
pub routes: Observation<Vec<Route>>,
|
||||
pub dns: Observation<Dns>,
|
||||
pub volumes: Observation<Vec<Observation<Volume>>>,
|
||||
pub disks: Observation<Vec<disks::Disk>>,
|
||||
pub software: Observation<Vec<SoftwarePackage>>,
|
||||
pub users: Observation<Vec<String>>,
|
||||
pub updates: Observation<UpdateStatus>,
|
||||
@@ -286,8 +282,6 @@ pub struct LinuxInventory {
|
||||
pub smart: Observation<()>,
|
||||
}
|
||||
pub fn collect_native() -> LinuxInventory {
|
||||
let volumes = volumes();
|
||||
let disks = disks::collect(&volumes);
|
||||
LinuxInventory {
|
||||
os: operating_system(),
|
||||
cpu: cpu(),
|
||||
@@ -295,8 +289,7 @@ pub fn collect_native() -> LinuxInventory {
|
||||
interfaces: interfaces(),
|
||||
routes: routes(),
|
||||
dns: dns(),
|
||||
volumes,
|
||||
disks,
|
||||
volumes: volumes(),
|
||||
software: software(),
|
||||
users: logged_in_users(),
|
||||
updates: updates(),
|
||||
@@ -944,7 +937,7 @@ pub fn volumes() -> Observation<Vec<Observation<Volume>>> {
|
||||
));
|
||||
continue;
|
||||
};
|
||||
observations.push(volume(&mount, left[2], right[0], right[1]));
|
||||
observations.push(volume(&mount, right[0], right[1]));
|
||||
}
|
||||
Some(observations)
|
||||
})
|
||||
@@ -962,7 +955,7 @@ impl Observation<Vec<Observation<Volume>>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
fn volume(mount: &str, devno: &str, filesystem: &str, device: &str) -> Observation<Volume> {
|
||||
fn volume(mount: &str, filesystem: &str, device: &str) -> Observation<Volume> {
|
||||
// Remote filesystems can hang statvfs indefinitely; explicitly do not probe.
|
||||
const LOCAL: &[&str] = &[
|
||||
"ext2", "ext3", "ext4", "xfs", "btrfs", "tmpfs", "overlay", "vfat", "exfat", "f2fs", "zfs",
|
||||
@@ -1006,7 +999,6 @@ fn volume(mount: &str, devno: &str, filesystem: &str, device: &str) -> Observati
|
||||
Observation::valid(
|
||||
&source,
|
||||
Volume {
|
||||
devno: devno.to_owned(),
|
||||
mount_point: mount.into(),
|
||||
filesystem: filesystem.into(),
|
||||
device: mount_unescape(device).unwrap_or_else(|| device.into()),
|
||||
|
||||
@@ -1,427 +0,0 @@
|
||||
//! Disk capacity is a hardware measurement. Filesystem usage can only be
|
||||
//! attributed where the block topology and mount identity agree.
|
||||
use super::{Observation, Quality, Volume, command};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs,
|
||||
os::unix::fs::{FileTypeExt, MetadataExt},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
const SOURCE: &str = "linux.sysfs:block;mountinfo;statvfs";
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Disk {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
model: Option<String>,
|
||||
members: BTreeSet<String>,
|
||||
total_bytes: u64,
|
||||
used_bytes: Option<u64>,
|
||||
available_bytes: Option<u64>,
|
||||
}
|
||||
impl Disk {
|
||||
fn new(name: String, kind: &'static str, total_bytes: u64) -> Self {
|
||||
Self {
|
||||
name,
|
||||
kind,
|
||||
model: None,
|
||||
members: BTreeSet::new(),
|
||||
total_bytes,
|
||||
used_bytes: None,
|
||||
available_bytes: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Node {
|
||||
parents: Vec<String>,
|
||||
disk: bool,
|
||||
stacked: bool,
|
||||
label: String,
|
||||
}
|
||||
type Nodes = BTreeMap<String, Node>;
|
||||
type Rows = BTreeMap<String, Disk>;
|
||||
fn attr(path: impl AsRef<Path>) -> Option<String> {
|
||||
fs::read_to_string(path)
|
||||
.ok()
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty() && s.len() <= 256)
|
||||
}
|
||||
fn devno(dev: u64) -> String {
|
||||
format!("{}:{}", libc::major(dev), libc::minor(dev))
|
||||
}
|
||||
fn block_id(path: &str) -> Option<String> {
|
||||
if !path.starts_with("/dev/") {
|
||||
return None;
|
||||
}
|
||||
let m = fs::metadata(path).ok()?;
|
||||
m.file_type().is_block_device().then(|| devno(m.rdev()))
|
||||
}
|
||||
fn topology() -> std::io::Result<(Nodes, BTreeMap<String, String>, Rows)> {
|
||||
let mut nodes = Nodes::new();
|
||||
let mut ids = BTreeMap::new();
|
||||
let mut rows = Rows::new();
|
||||
for entry in fs::read_dir("/sys/class/block")? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Some(id) = attr(path.join("dev")) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(real) = path.canonicalize() else {
|
||||
continue;
|
||||
};
|
||||
let part = path.join("partition").exists();
|
||||
let parents = if part {
|
||||
real.parent()
|
||||
.and_then(Path::file_name)
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.into_iter()
|
||||
.collect()
|
||||
} else {
|
||||
fs::read_dir(path.join("slaves"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// virtio/SCSI/Xen disks in guests have real bus paths too. Exclude
|
||||
// synthetic block devices, optical drives and eMMC boot areas.
|
||||
let disk = !part
|
||||
&& parents.is_empty()
|
||||
&& !real.starts_with("/sys/devices/virtual/block")
|
||||
&& attr(path.join("device/type")).is_none_or(|t| t == "0" || t == "14")
|
||||
&& !name.starts_with("sr")
|
||||
&& !(name.starts_with("mmcblk") && name.contains("boot"));
|
||||
if disk {
|
||||
if let Some(size) = attr(path.join("size"))
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
.and_then(|s| s.checked_mul(512))
|
||||
.filter(|n| *n > 0)
|
||||
{
|
||||
let mut row = Disk::new(name.clone(), "disk", size);
|
||||
row.model =
|
||||
attr(path.join("device/model")).or_else(|| attr(path.join("device/name")));
|
||||
rows.insert(name.clone(), row);
|
||||
}
|
||||
}
|
||||
ids.insert(id, name.clone());
|
||||
nodes.insert(
|
||||
name.clone(),
|
||||
Node {
|
||||
stacked: !part && !parents.is_empty(),
|
||||
disk,
|
||||
parents,
|
||||
label: attr(path.join("dm/name")).unwrap_or(name),
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok((nodes, ids, rows))
|
||||
}
|
||||
fn owners(name: &str, nodes: &Nodes) -> (BTreeSet<String>, bool) {
|
||||
let mut pending = vec![name];
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut disks = BTreeSet::new();
|
||||
let mut stacked = false;
|
||||
while let Some(n) = pending.pop() {
|
||||
if !visited.insert(n) {
|
||||
continue;
|
||||
}
|
||||
if let Some(node) = nodes.get(n) {
|
||||
if node.disk {
|
||||
disks.insert(n.to_owned());
|
||||
}
|
||||
stacked |= node.stacked;
|
||||
pending.extend(node.parents.iter().map(String::as_str));
|
||||
}
|
||||
}
|
||||
(disks, stacked)
|
||||
}
|
||||
fn project(
|
||||
nodes: &Nodes,
|
||||
ids: &BTreeMap<String, String>,
|
||||
rows: &mut Rows,
|
||||
volumes: &[&Volume],
|
||||
btrfs: &BTreeMap<String, (String, BTreeSet<String>, bool)>,
|
||||
) {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut invalid = BTreeSet::new();
|
||||
for v in volumes {
|
||||
if v.total_bytes == 0 || v.available_bytes > v.free_bytes || v.free_bytes > v.total_bytes {
|
||||
continue;
|
||||
}
|
||||
let (members, key, group) = if v.filesystem == "btrfs" {
|
||||
// Subvolumes can have different anonymous st_dev numbers. Group by
|
||||
// the filesystem UUID and never allocate replicated chunks per disk.
|
||||
let Some((uuid, members, single)) = block_id(&v.device).and_then(|id| btrfs.get(&id))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
(
|
||||
members.clone(),
|
||||
format!("btrfs:{uuid}"),
|
||||
(!single).then(|| format!("Btrfs {uuid}")),
|
||||
)
|
||||
} else {
|
||||
let Some(name) = ids.get(&v.devno) else {
|
||||
continue;
|
||||
};
|
||||
let (members, stacked) = owners(name, nodes);
|
||||
if members.is_empty() {
|
||||
continue;
|
||||
}
|
||||
(
|
||||
members,
|
||||
v.devno.clone(),
|
||||
stacked.then(|| nodes[name].label.clone()),
|
||||
)
|
||||
};
|
||||
if !seen.insert(key.clone()) {
|
||||
continue;
|
||||
}
|
||||
let used = v.total_bytes - v.free_bytes;
|
||||
if let Some(name) = group {
|
||||
let mut row = Disk::new(name, "group", v.total_bytes);
|
||||
row.members = members;
|
||||
row.used_bytes = Some(used);
|
||||
row.available_bytes = Some(v.available_bytes);
|
||||
rows.insert(format!("group:{key}"), row);
|
||||
} else if members.len() == 1 {
|
||||
let disk = members.first().unwrap();
|
||||
if invalid.contains(disk) {
|
||||
continue;
|
||||
}
|
||||
let Some(row) = rows.get_mut(disk) else {
|
||||
continue;
|
||||
};
|
||||
let u = row.used_bytes.unwrap_or(0).checked_add(used);
|
||||
let a = row
|
||||
.available_bytes
|
||||
.unwrap_or(0)
|
||||
.checked_add(v.available_bytes);
|
||||
if u.zip(a)
|
||||
.and_then(|(u, a)| u.checked_add(a))
|
||||
.is_some_and(|n| n <= row.total_bytes)
|
||||
{
|
||||
row.used_bytes = u;
|
||||
row.available_bytes = a;
|
||||
} else {
|
||||
invalid.insert(disk.clone());
|
||||
row.used_bytes = None;
|
||||
row.available_bytes = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn btrfs_members(
|
||||
nodes: &Nodes,
|
||||
ids: &BTreeMap<String, String>,
|
||||
) -> BTreeMap<String, (String, BTreeSet<String>, bool)> {
|
||||
let mut result = BTreeMap::new();
|
||||
for fs in fs::read_dir("/sys/fs/btrfs")
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
let mut members = BTreeSet::new();
|
||||
let mut devices = Vec::new();
|
||||
let mut direct = true;
|
||||
for dev in fs::read_dir(fs.path().join("devices"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
if let Some(id) = attr(dev.path().join("dev")) {
|
||||
if let Some(name) = ids.get(&id) {
|
||||
let (disks, stacked) = owners(name, nodes);
|
||||
direct &= !stacked && disks.len() == 1;
|
||||
members.extend(disks);
|
||||
} else {
|
||||
direct = false
|
||||
}
|
||||
devices.push(id);
|
||||
} else {
|
||||
direct = false
|
||||
}
|
||||
}
|
||||
let single = direct && devices.len() == 1;
|
||||
for id in devices {
|
||||
result.insert(
|
||||
id,
|
||||
(
|
||||
fs.file_name().to_string_lossy().into_owned(),
|
||||
members.clone(),
|
||||
single,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn volume(id: &str, total: u64, free: u64, available: u64) -> Volume {
|
||||
Volume {
|
||||
devno: id.into(),
|
||||
mount_point: "/".into(),
|
||||
filesystem: "ext4".into(),
|
||||
device: "".into(),
|
||||
total_bytes: total,
|
||||
free_bytes: free,
|
||||
available_bytes: available,
|
||||
available_percent: None,
|
||||
total_inodes: 0,
|
||||
free_inodes: 0,
|
||||
available_inodes: 0,
|
||||
available_inode_percent: None,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn partitions_count_once_pools_stay_separate_and_unmounted_is_unknown() {
|
||||
let mut nodes = Nodes::new();
|
||||
let mut rows = Rows::new();
|
||||
for name in ["sda", "sdb", "vdc"] {
|
||||
nodes.insert(
|
||||
name.into(),
|
||||
Node {
|
||||
disk: true,
|
||||
stacked: false,
|
||||
parents: vec![],
|
||||
label: name.into(),
|
||||
},
|
||||
);
|
||||
rows.insert(name.into(), Disk::new(name.into(), "disk", 1000));
|
||||
}
|
||||
for (name, parents, stacked) in [
|
||||
("sda1", vec!["sda"], false),
|
||||
("sda2", vec!["sda"], false),
|
||||
("md0", vec!["sda", "sdb"], true),
|
||||
] {
|
||||
nodes.insert(
|
||||
name.into(),
|
||||
Node {
|
||||
disk: false,
|
||||
stacked,
|
||||
parents: parents.into_iter().map(String::from).collect(),
|
||||
label: name.into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let ids = [("8:1", "sda1"), ("8:2", "sda2"), ("9:0", "md0")]
|
||||
.map(|(a, b)| (a.into(), b.into()))
|
||||
.into();
|
||||
let a = volume("8:1", 100, 40, 30);
|
||||
let b = volume("8:2", 200, 100, 80);
|
||||
let raid = volume("9:0", 500, 250, 240);
|
||||
project(
|
||||
&nodes,
|
||||
&ids,
|
||||
&mut rows,
|
||||
&[&a, &a, &b, &raid, &raid],
|
||||
&BTreeMap::new(),
|
||||
);
|
||||
assert_eq!(
|
||||
(rows["sda"].used_bytes, rows["sda"].available_bytes),
|
||||
(Some(160), Some(110))
|
||||
);
|
||||
assert_eq!(rows["sdb"].used_bytes, None);
|
||||
assert_eq!(rows["vdc"].available_bytes, None);
|
||||
assert_eq!(
|
||||
rows["group:9:0"].members,
|
||||
["sda".into(), "sdb".into()].into()
|
||||
);
|
||||
assert_eq!(rows["group:9:0"].used_bytes, Some(250));
|
||||
assert_eq!(rows.len(), 4);
|
||||
}
|
||||
}
|
||||
fn zfs(rows: &mut Rows, nodes: &Nodes, ids: &BTreeMap<String, String>, volumes: &[&Volume]) {
|
||||
let pools: BTreeSet<_> = volumes
|
||||
.iter()
|
||||
.filter(|v| v.filesystem == "zfs")
|
||||
.filter_map(|v| v.device.split('/').next())
|
||||
.collect();
|
||||
if pools.is_empty() {
|
||||
return;
|
||||
}
|
||||
// A pool's root dataset includes its children; don't sum dataset free space.
|
||||
let usage = command(
|
||||
"/usr/sbin/zfs",
|
||||
&[
|
||||
"list",
|
||||
"-Hp",
|
||||
"-t",
|
||||
"filesystem",
|
||||
"-o",
|
||||
"name,used,available",
|
||||
],
|
||||
32768,
|
||||
);
|
||||
let topology = command("/usr/sbin/zpool", &["status", "-LP"], 32768);
|
||||
let mut pool = "";
|
||||
let mut members: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
|
||||
for line in topology
|
||||
.data
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
{
|
||||
if let Some(p) = line.strip_prefix("pool: ") {
|
||||
pool = p;
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = line
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.and_then(block_id)
|
||||
.and_then(|id| ids.get(&id))
|
||||
{
|
||||
members
|
||||
.entry(pool)
|
||||
.or_default()
|
||||
.extend(owners(name, nodes).0);
|
||||
}
|
||||
}
|
||||
for p in pools {
|
||||
let measure = usage
|
||||
.data
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let mut cols = line.split('\t');
|
||||
if cols.next() != Some(p) {
|
||||
return None;
|
||||
}
|
||||
let used = cols.next()?.parse::<u64>().ok()?;
|
||||
let free = cols.next()?.parse::<u64>().ok()?;
|
||||
Some((used, free, used.checked_add(free)?))
|
||||
});
|
||||
let mut row = Disk::new(format!("ZFS {p}"), "group", measure.map_or(0, |m| m.2));
|
||||
row.used_bytes = measure.map(|m| m.0);
|
||||
row.available_bytes = measure.map(|m| m.1);
|
||||
row.members = members.remove(p).unwrap_or_default();
|
||||
rows.insert(format!("group:zfs:{p}"), row);
|
||||
}
|
||||
}
|
||||
pub(super) fn collect(volumes: &Observation<Vec<Observation<Volume>>>) -> Observation<Vec<Disk>> {
|
||||
let Ok((nodes, ids, mut rows)) = topology() else {
|
||||
return Observation::unavailable(SOURCE, Quality::Unknown, "BLOCK_TOPOLOGY_UNAVAILABLE");
|
||||
};
|
||||
let mounted: Vec<_> = volumes
|
||||
.data
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter_map(|o| o.data.as_ref())
|
||||
// An over-mounted or replaced mountpoint may now refer to another device.
|
||||
.filter(|v| fs::metadata(&v.mount_point).is_ok_and(|m| devno(m.dev()) == v.devno))
|
||||
.collect();
|
||||
let btrfs = btrfs_members(&nodes, &ids);
|
||||
project(&nodes, &ids, &mut rows, &mounted, &btrfs);
|
||||
zfs(&mut rows, &nodes, &ids, &mounted);
|
||||
let mut result: Vec<_> = rows.into_values().collect();
|
||||
result.sort_by(|a, b| (a.kind, &a.name).cmp(&(b.kind, &b.name)));
|
||||
Observation::valid(SOURCE, result).partial("FILESYSTEM_COVERAGE_PARTIAL")
|
||||
}
|
||||
@@ -78,7 +78,7 @@ mod tests {
|
||||
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
|
||||
let native = crate::inventory::collect_native();
|
||||
let mapped = observations(&native).unwrap();
|
||||
assert_eq!(mapped.len(), 13);
|
||||
assert_eq!(mapped.len(), 12);
|
||||
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
|
||||
assert_eq!(smart["quality"], "unsupported");
|
||||
assert!(smart["data"].is_null());
|
||||
|
||||
@@ -2,6 +2,8 @@ use std::{env, path::PathBuf, process::Command};
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=native/w32time.idl");
|
||||
println!("cargo:rerun-if-changed=native/clock_rpc.c");
|
||||
println!("cargo:rerun-if-changed=native/clock_local.c");
|
||||
println!("cargo:rerun-if-changed=native/clock_status.h");
|
||||
println!("cargo:rerun-if-changed=native/clock_endpoints.c");
|
||||
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
@@ -52,10 +54,12 @@ fn main() {
|
||||
.include(&out)
|
||||
.file(out.join("w32time_c.c"))
|
||||
.file("native/clock_rpc.c")
|
||||
.file("native/clock_local.c")
|
||||
.file("native/clock_endpoints.c")
|
||||
.compile("rmm_clock_rpc");
|
||||
println!("cargo:rustc-link-lib=rpcrt4");
|
||||
println!("cargo:rustc-link-lib=advapi32");
|
||||
println!("cargo:rustc-link-lib=secur32");
|
||||
return;
|
||||
}
|
||||
assert_eq!(
|
||||
@@ -89,8 +93,10 @@ fn main() {
|
||||
.include(&out)
|
||||
.file(out.join("w32time_c.c"))
|
||||
.file("native/clock_rpc.c")
|
||||
.file("native/clock_local.c")
|
||||
.file("native/clock_endpoints.c")
|
||||
.compile("rmm_clock_rpc");
|
||||
println!("cargo:rustc-link-lib=rpcrt4");
|
||||
println!("cargo:rustc-link-lib=advapi32");
|
||||
println!("cargo:rustc-link-lib=secur32");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
/* MS-W32T 2.2.17 / opnum 6 and MS-RPCE connection-oriented packet privacy.
|
||||
* Keep the status RPC on the same local pipe handle whose server PID we verify
|
||||
* against the Service Control Manager, before exchanging any auth tokens.
|
||||
* SSPI performs the NTLM exchange and protects the RPC headers and payloads.
|
||||
*/
|
||||
#define _WIN32_WINNT 0x0a00
|
||||
#define SECURITY_WIN32
|
||||
#include <windows.h>
|
||||
#include <rpc.h>
|
||||
#include <security.h>
|
||||
#include <string.h>
|
||||
#include "clock_status.h"
|
||||
|
||||
enum {
|
||||
RPC_HEADER = 16, CALL_HEADER = 24, SECURITY_TRAILER = 8, SIGNATURE = 16,
|
||||
FIRST_LAST = 3, HEADER_SIGN = 4, FRAME_LIMIT = 4280, TOKEN_LIMIT = 16384,
|
||||
STATUS_LAYOUT = 120, STATUS_FIXED_WIRE = 112, STATUS_SOURCE_PTR = 60,
|
||||
};
|
||||
enum { REQUEST = 0, RESPONSE = 2, BIND = 11, BIND_ACK = 12, AUTH3 = 16 };
|
||||
enum { BIND_CALL_ID = 1, STATUS_CALL_ID = 2, AUTH_CONTEXT_ID = 1, STATUS_OPNUM = 6 };
|
||||
|
||||
static DWORD w32time_pid(void) {
|
||||
SC_HANDLE manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
|
||||
if (!manager) return 0;
|
||||
SC_HANDLE service = OpenServiceW(manager, L"W32Time", SERVICE_QUERY_STATUS);
|
||||
SERVICE_STATUS_PROCESS status = {0};
|
||||
DWORD needed = 0;
|
||||
BOOL ok = service && QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
|
||||
(BYTE *)&status, sizeof status, &needed);
|
||||
if (service) CloseServiceHandle(service);
|
||||
CloseServiceHandle(manager);
|
||||
return ok && status.dwCurrentState == SERVICE_RUNNING ? status.dwProcessId : 0;
|
||||
}
|
||||
|
||||
static BOOL is_w32time(HANDLE pipe, DWORD expected_pid) {
|
||||
ULONG peer_pid = 0;
|
||||
return expected_pid != 0 && GetNamedPipeServerProcessId(pipe, &peer_pid)
|
||||
&& peer_pid == expected_pid && w32time_pid() == expected_pid;
|
||||
}
|
||||
|
||||
static DWORD pipe_io(HANDLE pipe, BYTE *buffer, DWORD capacity, BOOL writing,
|
||||
DWORD *count, ULONGLONG deadline) {
|
||||
ULONGLONG now = GetTickCount64();
|
||||
if (now >= deadline) return ERROR_TIMEOUT;
|
||||
OVERLAPPED io = {0};
|
||||
io.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
|
||||
if (!io.hEvent) return GetLastError();
|
||||
BOOL ok = writing ? WriteFile(pipe, buffer, capacity, NULL, &io)
|
||||
: ReadFile(pipe, buffer, capacity, NULL, &io);
|
||||
DWORD error = ok ? ERROR_SUCCESS : GetLastError();
|
||||
if (error == ERROR_IO_PENDING) {
|
||||
if (WaitForSingleObject(io.hEvent, (DWORD)(deadline - now)) != WAIT_OBJECT_0) {
|
||||
CancelIoEx(pipe, &io);
|
||||
/* Finish cancellation before releasing the stack buffer. */
|
||||
GetOverlappedResult(pipe, &io, count, TRUE);
|
||||
error = ERROR_TIMEOUT;
|
||||
} else {
|
||||
error = GetOverlappedResult(pipe, &io, count, FALSE)
|
||||
? ERROR_SUCCESS : GetLastError();
|
||||
}
|
||||
} else if (ok) {
|
||||
error = GetOverlappedResult(pipe, &io, count, FALSE)
|
||||
? ERROR_SUCCESS : GetLastError();
|
||||
}
|
||||
CloseHandle(io.hEvent);
|
||||
return error;
|
||||
}
|
||||
|
||||
static void put16(BYTE *p, uint16_t v) { memcpy(p, &v, sizeof v); }
|
||||
static void put32(BYTE *p, uint32_t v) { memcpy(p, &v, sizeof v); }
|
||||
static uint16_t get16(const BYTE *p) { uint16_t v; memcpy(&v, p, sizeof v); return v; }
|
||||
static uint32_t get32(const BYTE *p) { uint32_t v; memcpy(&v, p, sizeof v); return v; }
|
||||
static uint64_t get64(const BYTE *p) { uint64_t v; memcpy(&v, p, sizeof v); return v; }
|
||||
static int64_t get_i64(const BYTE *p) { int64_t v; memcpy(&v, p, sizeof v); return v; }
|
||||
static DWORD align4(DWORD offset) { return (offset + 3) & ~3u; }
|
||||
|
||||
static void write_header(BYTE *p, BYTE type, BYTE flags, WORD length, WORD auth_length, DWORD call) {
|
||||
memset(p, 0, RPC_HEADER);
|
||||
p[0] = 5;
|
||||
p[2] = type;
|
||||
p[3] = flags;
|
||||
p[4] = 0x10; /* little-endian NDR */
|
||||
put16(p + 8, length);
|
||||
put16(p + 10, auth_length);
|
||||
put32(p + 12, call);
|
||||
}
|
||||
|
||||
static void write_security_trailer(BYTE *p) {
|
||||
memset(p, 0, SECURITY_TRAILER);
|
||||
p[0] = RPC_C_AUTHN_WINNT;
|
||||
p[1] = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
|
||||
put32(p + 4, AUTH_CONTEXT_ID);
|
||||
}
|
||||
|
||||
static BOOL valid_security_trailer(const BYTE *p) {
|
||||
return p[0] == RPC_C_AUTHN_WINNT && p[1] == RPC_C_AUTHN_LEVEL_PKT_PRIVACY
|
||||
&& p[3] == 0 && get32(p + 4) == AUTH_CONTEXT_ID;
|
||||
}
|
||||
|
||||
static DWORD send_frame(HANDLE pipe, BYTE *frame, ULONGLONG deadline) {
|
||||
DWORD length = get16(frame + 8);
|
||||
DWORD count = 0;
|
||||
DWORD error = pipe_io(pipe, frame, length, TRUE, &count, deadline);
|
||||
return !error && count != length ? ERROR_INVALID_DATA : error;
|
||||
}
|
||||
|
||||
static DWORD read_frame(HANDLE pipe, BYTE *frame, DWORD *length, BYTE type, DWORD call,
|
||||
ULONGLONG deadline) {
|
||||
DWORD error = pipe_io(pipe, frame, FRAME_LIMIT, FALSE, length, deadline);
|
||||
if (error) return error;
|
||||
if (*length < RPC_HEADER || frame[0] != 5 || frame[1] != 0 || frame[2] != type
|
||||
|| (frame[3] & FIRST_LAST) != FIRST_LAST || get32(frame + 4) != 0x10
|
||||
|| get16(frame + 8) != *length || get32(frame + 12) != call) {
|
||||
return ERROR_INVALID_DATA;
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
static DWORD bind_status_rpc(HANDLE pipe, CredHandle *credentials, CtxtHandle *context,
|
||||
ULONGLONG deadline) {
|
||||
static const BYTE interface_v4_1[20] = {0x84,0xd8,0xb6,0x8f,0x88,0x23,0xd0,0x11,
|
||||
0x8c,0x35,0,0xc0,0x4f,0xda,0x27,0x95,4,0,1,0};
|
||||
static const BYTE ndr32_v2[20] = {0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,
|
||||
0x9f,0xe8,0x08,0,0x2b,0x10,0x48,0x60,2};
|
||||
const ULONG required = ISC_REQ_USE_DCE_STYLE | ISC_REQ_CONFIDENTIALITY
|
||||
| ISC_REQ_INTEGRITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT;
|
||||
ULONG attributes = 0;
|
||||
BYTE out[TOKEN_LIMIT] = {0};
|
||||
BYTE reply[FRAME_LIMIT] = {0};
|
||||
SecBuffer token = {sizeof out - 80, SECBUFFER_TOKEN, out + 80};
|
||||
SecBufferDesc output = {SECBUFFER_VERSION, 1, &token};
|
||||
SECURITY_STATUS status = InitializeSecurityContextW(credentials, NULL, L"", required, 0,
|
||||
SECURITY_NATIVE_DREP, NULL, 0, context, &output, &attributes, NULL);
|
||||
if (status != SEC_I_CONTINUE_NEEDED) return status ? (DWORD)status : ERROR_INVALID_DATA;
|
||||
if (!token.cbBuffer || token.cbBuffer > sizeof out - 80) return ERROR_INVALID_DATA;
|
||||
|
||||
write_header(out, BIND, FIRST_LAST | HEADER_SIGN, (WORD)(80 + token.cbBuffer),
|
||||
(WORD)token.cbBuffer, BIND_CALL_ID);
|
||||
put16(out + 16, FRAME_LIMIT);
|
||||
put16(out + 18, FRAME_LIMIT);
|
||||
out[24] = 1; /* one bind context */
|
||||
out[30] = 1; /* one transfer syntax */
|
||||
memcpy(out + 32, interface_v4_1, sizeof interface_v4_1);
|
||||
memcpy(out + 52, ndr32_v2, sizeof ndr32_v2);
|
||||
write_security_trailer(out + 72);
|
||||
DWORD error = send_frame(pipe, out, deadline);
|
||||
if (error) return error;
|
||||
|
||||
DWORD length = 0;
|
||||
error = read_frame(pipe, reply, &length, BIND_ACK, BIND_CALL_ID, deadline);
|
||||
if (error) return error;
|
||||
DWORD challenge_length = get16(reply + 10);
|
||||
if (reply[3] != (FIRST_LAST | HEADER_SIGN) || length < 56
|
||||
|| !challenge_length || challenge_length > length - 56) return ERROR_INVALID_DATA;
|
||||
DWORD verdict = align4(26 + get16(reply + 24));
|
||||
DWORD trailer = length - SECURITY_TRAILER - challenge_length;
|
||||
if (verdict > trailer || trailer - verdict < 28 || reply[verdict] != 1
|
||||
|| get16(reply + verdict + 4) != 0 || get16(reply + verdict + 6) != 0
|
||||
|| memcmp(reply + verdict + 8, ndr32_v2, sizeof ndr32_v2)
|
||||
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
|
||||
|
||||
SecBuffer challenge = {challenge_length, SECBUFFER_TOKEN, reply + trailer + SECURITY_TRAILER};
|
||||
SecBufferDesc input = {SECBUFFER_VERSION, 1, &challenge};
|
||||
token.pvBuffer = out + 28;
|
||||
token.cbBuffer = sizeof out - 28;
|
||||
status = InitializeSecurityContextW(credentials, context, L"", required, 0,
|
||||
SECURITY_NATIVE_DREP, &input, 0, context, &output, &attributes, NULL);
|
||||
if (status == SEC_I_COMPLETE_NEEDED) status = CompleteAuthToken(context, &output);
|
||||
if (status) return (DWORD)status;
|
||||
if (!token.cbBuffer || token.cbBuffer > sizeof out - 28
|
||||
|| !(attributes & ISC_RET_CONFIDENTIALITY) || !(attributes & ISC_RET_INTEGRITY)) {
|
||||
return ERROR_INVALID_DATA;
|
||||
}
|
||||
|
||||
write_header(out, AUTH3, FIRST_LAST, (WORD)(28 + token.cbBuffer),
|
||||
(WORD)token.cbBuffer, BIND_CALL_ID);
|
||||
memset(out + RPC_HEADER, 0, 4);
|
||||
write_security_trailer(out + 20);
|
||||
return send_frame(pipe, out, deadline);
|
||||
}
|
||||
|
||||
static DWORD decode_status(const BYTE *body, DWORD length, RmmClockStatus *out) {
|
||||
/* Unique NDR32 status pointer, x64 MS-W32T layout ID, no auxiliary entries. */
|
||||
if (length < STATUS_FIXED_WIRE + 4 || !get32(body) || get32(body + 8) != STATUS_LAYOUT
|
||||
|| get32(body + 104) || get32(body + 108)) return RPC_X_BAD_STUB_DATA;
|
||||
DWORD result_offset = STATUS_FIXED_WIRE;
|
||||
if (get32(body + STATUS_SOURCE_PTR)) {
|
||||
/* Skip the optional conformant UTF-16 string without allocating or logging it. */
|
||||
if (length - result_offset < 16) return RPC_X_BAD_STUB_DATA;
|
||||
DWORD maximum = get32(body + result_offset);
|
||||
DWORD offset = get32(body + result_offset + 4);
|
||||
DWORD count = get32(body + result_offset + 8);
|
||||
if (offset || !count || count > maximum || count > (length - result_offset - 16) / 2)
|
||||
return RPC_X_BAD_STUB_DATA;
|
||||
result_offset += 12 + 2 * count;
|
||||
if (get16(body + result_offset - 2)) return RPC_X_BAD_STUB_DATA;
|
||||
result_offset = align4(result_offset);
|
||||
}
|
||||
if (length - 4 != result_offset) return RPC_X_BAD_STUB_DATA;
|
||||
DWORD result = get32(body + result_offset);
|
||||
if (result) return result;
|
||||
*out = (RmmClockStatus){
|
||||
.leap = get32(body + 12), .stratum = get32(body + 16), .size = STATUS_LAYOUT,
|
||||
.last_sync = get64(body + 32), .root_delay = get_i64(body + 40),
|
||||
.root_dispersion = get64(body + 48), .phase = get_i64(body + 64),
|
||||
.state = get32(body + 72), .flags = get32(body + 76),
|
||||
.last_result = get32(body + 88), .sync_age = get64(body + 96),
|
||||
};
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
static DWORD request_status(HANDLE pipe, CtxtHandle *context, ULONGLONG deadline,
|
||||
DWORD expected_pid, RmmClockStatus *out) {
|
||||
SecPkgContext_Sizes sizes = {0};
|
||||
SECURITY_STATUS security = QueryContextAttributesW(context, SECPKG_ATTR_SIZES, &sizes);
|
||||
if (security) return (DWORD)security;
|
||||
if (sizes.cbSecurityTrailer != SIGNATURE) return ERROR_INVALID_DATA;
|
||||
BYTE frame[CALL_HEADER + SECURITY_TRAILER + SIGNATURE] = {0};
|
||||
write_header(frame, REQUEST, FIRST_LAST, sizeof frame, SIGNATURE, STATUS_CALL_ID);
|
||||
put16(frame + 22, STATUS_OPNUM); /* only the read-only operation has an encoding */
|
||||
write_security_trailer(frame + CALL_HEADER);
|
||||
SecBuffer parts[] = {
|
||||
{CALL_HEADER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame},
|
||||
{0, SECBUFFER_DATA, frame + CALL_HEADER},
|
||||
{SECURITY_TRAILER, SECBUFFER_DATA | SECBUFFER_READONLY_WITH_CHECKSUM, frame + CALL_HEADER},
|
||||
{SIGNATURE, SECBUFFER_TOKEN, frame + CALL_HEADER + SECURITY_TRAILER},
|
||||
};
|
||||
SecBufferDesc message = {SECBUFFER_VERSION, 4, parts};
|
||||
security = EncryptMessage(context, 0, &message, 0);
|
||||
if (security) return (DWORD)security;
|
||||
if (parts[3].cbBuffer != SIGNATURE) return ERROR_INVALID_DATA;
|
||||
DWORD error = send_frame(pipe, frame, deadline);
|
||||
if (error) return error;
|
||||
|
||||
BYTE reply[FRAME_LIMIT] = {0};
|
||||
DWORD length = 0;
|
||||
error = read_frame(pipe, reply, &length, RESPONSE, STATUS_CALL_ID, deadline);
|
||||
if (error) return error;
|
||||
if (reply[3] != FIRST_LAST || get16(reply + 10) != SIGNATURE || get16(reply + 20) != 0
|
||||
|| length < sizeof frame) return ERROR_INVALID_DATA;
|
||||
DWORD trailer = length - SECURITY_TRAILER - SIGNATURE;
|
||||
BYTE padding = reply[trailer + 2];
|
||||
if (padding > 15 || padding > trailer - CALL_HEADER
|
||||
|| !valid_security_trailer(reply + trailer)) return ERROR_INVALID_DATA;
|
||||
parts[0].pvBuffer = reply;
|
||||
parts[1].pvBuffer = reply + CALL_HEADER;
|
||||
parts[1].cbBuffer = trailer - CALL_HEADER;
|
||||
parts[2].pvBuffer = reply + trailer;
|
||||
parts[3].pvBuffer = reply + trailer + SECURITY_TRAILER;
|
||||
ULONG qop = 0;
|
||||
security = DecryptMessage(context, &message, 0, &qop);
|
||||
if (security) return (DWORD)security;
|
||||
if (qop != 0) return ERROR_INVALID_DATA;
|
||||
if (!is_w32time(pipe, expected_pid)) return ERROR_ACCESS_DENIED;
|
||||
return decode_status(reply + CALL_HEADER, trailer - CALL_HEADER - padding, out);
|
||||
}
|
||||
|
||||
uint32_t rmm_local_clock_query(RmmClockStatus *out) {
|
||||
memset(out, 0, sizeof *out);
|
||||
DWORD expected_pid = w32time_pid();
|
||||
if (!expected_pid) return ERROR_SERVICE_NOT_ACTIVE;
|
||||
ULONGLONG deadline = GetTickCount64() + 750;
|
||||
HANDLE pipe = CreateFileW(L"\\\\.\\pipe\\W32TIME_ALT", FILE_READ_DATA | FILE_WRITE_DATA
|
||||
| FILE_WRITE_ATTRIBUTES | SYNCHRONIZE, 0, NULL, OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, NULL);
|
||||
if (pipe == INVALID_HANDLE_VALUE) return GetLastError();
|
||||
DWORD mode = PIPE_READMODE_MESSAGE;
|
||||
DWORD error;
|
||||
if (!is_w32time(pipe, expected_pid)) {
|
||||
error = ERROR_ACCESS_DENIED;
|
||||
} else if (!SetNamedPipeHandleState(pipe, &mode, NULL, NULL)) {
|
||||
error = GetLastError();
|
||||
} else {
|
||||
CredHandle credentials;
|
||||
CtxtHandle context;
|
||||
SecInvalidateHandle(&context);
|
||||
error = (DWORD)AcquireCredentialsHandleW(NULL, L"NTLM", SECPKG_CRED_OUTBOUND,
|
||||
NULL, NULL, NULL, NULL, &credentials, NULL);
|
||||
if (!error) {
|
||||
error = bind_status_rpc(pipe, &credentials, &context, deadline);
|
||||
if (!error) error = request_status(pipe, &context, deadline, expected_pid, out);
|
||||
if (SecIsValidHandle(&context)) DeleteSecurityContext(&context);
|
||||
FreeCredentialsHandle(&credentials);
|
||||
}
|
||||
}
|
||||
CloseHandle(pipe);
|
||||
return error;
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "w32time.h"
|
||||
#include "clock_status.h"
|
||||
/* Documented public SDK API; older MinGW headers omit its declaration. */
|
||||
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
|
||||
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
|
||||
@@ -61,15 +62,6 @@ void __RPC_USER MIDL_user_free(void *memory) {
|
||||
static void release_allocations(Arena *arena) {
|
||||
while (arena->head) MIDL_user_free(arena->head + 1);
|
||||
}
|
||||
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
|
||||
typedef struct {
|
||||
uint32_t leap, stratum, state, flags, last_result, size;
|
||||
uint64_t last_sync, sync_age;
|
||||
int64_t root_delay;
|
||||
uint64_t root_dispersion;
|
||||
int64_t phase;
|
||||
} RmmClockStatus;
|
||||
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
||||
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
|
||||
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
|
||||
* leave C. A zero native return is meaningful only when return_present is1.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef RMM_CLOCK_STATUS_H
|
||||
#define RMM_CLOCK_STATUS_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/* Numeric Windows status only. No remote strings or pointers cross the ABI. */
|
||||
typedef struct {
|
||||
uint32_t leap, stratum, state, flags, last_result, size;
|
||||
uint64_t last_sync, sync_age;
|
||||
int64_t root_delay;
|
||||
uint64_t root_dispersion;
|
||||
int64_t phase;
|
||||
} RmmClockStatus;
|
||||
|
||||
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
||||
|
||||
#endif
|
||||
@@ -1,19 +1,20 @@
|
||||
//! Read-only trusted clock gate for Windows 11. All MS-W32T time intervals are
|
||||
//! 100 ns; last_sync alone is a FILETIME (1601 epoch), sync_age is a duration.
|
||||
//! No W32Time reconfiguration, resync, unauthenticated pipe or server-time anchor.
|
||||
//! Policy: <=1h successful sync age, SYNC state, stratum1..15, nonalarm leap,
|
||||
//! <=2s root dispersion + roundtrip/2 + absolute phase + query latency.
|
||||
//! Require a successful sync within one day, SYNC state, stratum 1..15 and no
|
||||
//! leap alarm. Bound dispersion, half the round trip, phase, holdover and
|
||||
//! query latency to two seconds.
|
||||
//! A >1s wall step or suspend invalidates until a post-discontinuity sync.
|
||||
use anyhow::{Result, anyhow, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use std::sync::Mutex;
|
||||
/// Flip only after native account AND service-bound ALPC, positive readiness,
|
||||
/// wrong-account/wrong-service denial and fail-closed qualification.
|
||||
pub const ADAPTER_QUALIFIED: bool = false;
|
||||
const ADAPTER_QUALIFIED: bool = cfg!(windows);
|
||||
const SECOND: u64 = 10_000_000;
|
||||
const MAX_AGE: u64 = 3600 * SECOND;
|
||||
const MAX_AGE: u64 = 24 * 60 * 60 * SECOND;
|
||||
const MAX_ERROR: u64 = 2 * SECOND;
|
||||
const CACHE_AGE: u64 = 5 * SECOND;
|
||||
const RETRY_AGE: u64 = SECOND;
|
||||
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||
@@ -124,9 +125,11 @@ impl Continuity {
|
||||
}
|
||||
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
|
||||
// Like the Linux kernel, retain a still-qualified last good sample when
|
||||
// a poll has no new data. The service's state and age still govern trust.
|
||||
ensure!(
|
||||
status.state == 2
|
||||
&& status.last_result == 0
|
||||
&& matches!(status.last_result, 0..=2)
|
||||
&& status.leap <= 2
|
||||
&& (1..=15).contains(&status.stratum),
|
||||
"CLOCK_UNSYNCHRONIZED"
|
||||
@@ -152,6 +155,7 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
.root_dispersion
|
||||
.checked_add((status.root_delay as u64).div_ceil(2))
|
||||
.and_then(|v| v.checked_add(status.phase.unsigned_abs()))
|
||||
.and_then(|v| v.checked_add(holdover_error(status.sync_age)))
|
||||
.and_then(|v| v.checked_add(query_ticks))
|
||||
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
|
||||
ensure!(
|
||||
@@ -160,8 +164,38 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
);
|
||||
Ok(bound)
|
||||
}
|
||||
fn holdover_error(elapsed: u64) -> u64 {
|
||||
// NTP's nominal dispersion growth (RFC 5905, PHI = 15 ppm).
|
||||
elapsed.saturating_mul(15).div_ceil(1_000_000)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct CachedQualification {
|
||||
sample: Sample,
|
||||
bound: Option<u64>,
|
||||
valid_for: u64,
|
||||
}
|
||||
impl CachedQualification {
|
||||
fn bound_at(self, sample: Sample) -> Option<u64> {
|
||||
let elapsed = sample.interrupt.checked_sub(self.sample.interrupt)?;
|
||||
let awake = sample.unbiased.checked_sub(self.sample.unbiased)?;
|
||||
let wall = sample.wall.checked_sub(self.sample.wall)?;
|
||||
let wall_drift = elapsed.abs_diff(wall);
|
||||
let bound = self
|
||||
.bound?
|
||||
.checked_add(holdover_error(elapsed))?
|
||||
.checked_add(wall_drift)?;
|
||||
(elapsed < self.valid_for
|
||||
&& elapsed.abs_diff(awake) <= SECOND
|
||||
&& wall_drift <= SECOND
|
||||
&& bound <= MAX_ERROR)
|
||||
.then_some(bound)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NativeClock {
|
||||
state: Mutex<Continuity>,
|
||||
cache: Mutex<Option<CachedQualification>>,
|
||||
diagnostic: bool,
|
||||
}
|
||||
impl Default for NativeClock {
|
||||
@@ -173,6 +207,7 @@ impl NativeClock {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Mutex::new(Continuity::default()),
|
||||
cache: Mutex::new(None),
|
||||
diagnostic: false,
|
||||
}
|
||||
}
|
||||
@@ -192,7 +227,7 @@ impl NativeClock {
|
||||
transport: if self.diagnostic {
|
||||
"ncacn_np:W32TIME_ALT:diagnostic_only"
|
||||
} else {
|
||||
"ncalrpc:SID19:W32Time:V5_descriptor:mutual_auth"
|
||||
"local_pipe:W32TIME_ALT:verified_service_pid"
|
||||
},
|
||||
status: None,
|
||||
query_ticks: ticks,
|
||||
@@ -222,7 +257,7 @@ impl NativeClock {
|
||||
report.status = Some(raw);
|
||||
match state.validate(&raw, after, ticks) {
|
||||
Ok(bound) => {
|
||||
report.trusted = !self.diagnostic;
|
||||
report.trusted = ADAPTER_QUALIFIED && !self.diagnostic;
|
||||
report.reason = if self.diagnostic {
|
||||
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
|
||||
} else {
|
||||
@@ -235,26 +270,66 @@ impl NativeClock {
|
||||
}
|
||||
report
|
||||
}
|
||||
pub fn now(&self) -> Result<DateTime<Utc>> {
|
||||
fn qualified_sample(&self) -> Result<(Sample, u64)> {
|
||||
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
|
||||
let mut cache = self
|
||||
.cache
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?;
|
||||
let current = sample();
|
||||
let observed = self
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?
|
||||
.observe(current);
|
||||
if observed.is_err() {
|
||||
*cache = None;
|
||||
observed?;
|
||||
}
|
||||
if let Some(cached) = *cache {
|
||||
if let Some(bound) = cached.bound_at(current) {
|
||||
return Ok((current, bound));
|
||||
}
|
||||
ensure!(
|
||||
cached.bound.is_some()
|
||||
|| current.interrupt.saturating_sub(cached.sample.interrupt) >= RETRY_AGE,
|
||||
"CLOCK_RETRY_PENDING"
|
||||
);
|
||||
}
|
||||
let report = self.report();
|
||||
ensure!(report.trusted, "CLOCK_UNTRUSTED: {}", report.reason);
|
||||
let ticks = report
|
||||
.sample
|
||||
.wall
|
||||
.checked_sub(FILETIME_UNIX)
|
||||
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
|
||||
DateTime::from_timestamp(
|
||||
(ticks / SECOND).try_into()?,
|
||||
((ticks % SECOND) * 100) as u32,
|
||||
)
|
||||
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
|
||||
let bound = report.error_bound_ticks.filter(|_| report.trusted);
|
||||
*cache = Some(CachedQualification {
|
||||
sample: report.sample,
|
||||
bound,
|
||||
valid_for: report.status.map_or(0, |status| {
|
||||
CACHE_AGE.min(MAX_AGE.saturating_sub(status.sync_age))
|
||||
}),
|
||||
});
|
||||
Ok((
|
||||
report.sample,
|
||||
bound.ok_or_else(|| anyhow!("CLOCK_UNTRUSTED: {}", report.reason))?,
|
||||
))
|
||||
}
|
||||
pub fn now(&self) -> Result<DateTime<Utc>> {
|
||||
utc(self.qualified_sample()?.0.wall)
|
||||
}
|
||||
}
|
||||
|
||||
fn utc(wall: u64) -> Result<DateTime<Utc>> {
|
||||
let ticks = wall
|
||||
.checked_sub(FILETIME_UNIX)
|
||||
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
|
||||
DateTime::from_timestamp(
|
||||
(ticks / SECOND).try_into()?,
|
||||
((ticks % SECOND) * 100) as u32,
|
||||
)
|
||||
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
|
||||
}
|
||||
/// Named-pipe diagnostics can never open the production clock gate.
|
||||
pub fn named_pipe_diagnostic() -> ClockReport {
|
||||
NativeClock {
|
||||
state: Mutex::new(Continuity::default()),
|
||||
cache: Mutex::new(None),
|
||||
diagnostic: true,
|
||||
}
|
||||
.report()
|
||||
@@ -376,6 +451,17 @@ impl rmm_agent_core::reconcile::SyncClock for NativeClock {
|
||||
fn now(&self) -> Result<DateTime<Utc>> {
|
||||
NativeClock::now(self)
|
||||
}
|
||||
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
|
||||
let (sample, bound) = self.qualified_sample()?;
|
||||
Ok(rmm_agent_core::reconcile::ClockReading {
|
||||
own_wall: utc(sample.wall)?,
|
||||
upper: utc(sample.wall + bound)?,
|
||||
})
|
||||
}
|
||||
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
|
||||
let (sample, bound) = self.qualified_sample()?;
|
||||
Ok((utc(sample.wall - bound)?, utc(sample.wall + bound)?))
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn sample() -> Sample {
|
||||
@@ -401,7 +487,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
|
||||
#[link(name = "advapi32")]
|
||||
unsafe extern "C" {
|
||||
fn rmm_clock_query(status: *mut Status) -> u32;
|
||||
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
|
||||
fn rmm_local_clock_query(status: *mut Status) -> u32;
|
||||
}
|
||||
let mut status = Status::default();
|
||||
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
|
||||
@@ -409,7 +495,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
|
||||
if diagnostic {
|
||||
rmm_clock_query(&mut status)
|
||||
} else {
|
||||
rmm_clock_alpc_query(&mut status)
|
||||
rmm_local_clock_query(&mut status)
|
||||
}
|
||||
};
|
||||
(code, status)
|
||||
@@ -522,8 +608,9 @@ mod tests {
|
||||
},
|
||||
)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
||||
fn production_windows_clock_is_unavailable_on_other_platforms() {
|
||||
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
|
||||
assert_eq!(
|
||||
NativeClock::new().now().unwrap_err().to_string(),
|
||||
@@ -559,7 +646,7 @@ mod tests {
|
||||
Status { state: 1, ..s },
|
||||
Status { leap: 3, ..s },
|
||||
Status {
|
||||
last_result: 2,
|
||||
last_result: 3,
|
||||
..s
|
||||
},
|
||||
Status { stratum: 16, ..s },
|
||||
@@ -585,6 +672,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn missed_poll_keeps_a_bounded_last_good_sample() {
|
||||
let (s, v) = good();
|
||||
let age = 2 * 3600 * SECOND;
|
||||
for last_result in [1, 2] {
|
||||
let held = Status {
|
||||
last_result,
|
||||
last_sync: v.wall - age,
|
||||
sync_age: age,
|
||||
..s
|
||||
};
|
||||
assert!(evaluate(&held, v.wall, 100).is_ok());
|
||||
}
|
||||
let old = Status {
|
||||
last_result: 2,
|
||||
last_sync: v.wall - MAX_AGE - 1,
|
||||
sync_age: MAX_AGE + 1,
|
||||
..s
|
||||
};
|
||||
assert!(evaluate(&old, v.wall, 100).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn cached_bound_expires_and_rejects_wall_step_and_suspend() {
|
||||
let (_, mut sample) = good();
|
||||
let cache = CachedQualification {
|
||||
sample,
|
||||
bound: Some(SECOND),
|
||||
valid_for: CACHE_AGE,
|
||||
};
|
||||
sample.wall += SECOND;
|
||||
sample.interrupt += SECOND;
|
||||
sample.unbiased += SECOND;
|
||||
assert_eq!(cache.bound_at(sample), Some(SECOND + 150));
|
||||
assert_eq!(
|
||||
cache.bound_at(Sample {
|
||||
wall: sample.wall + 2 * SECOND,
|
||||
..sample
|
||||
}),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
cache.bound_at(Sample {
|
||||
unbiased: sample.unbiased - 2 * SECOND,
|
||||
..sample
|
||||
}),
|
||||
None
|
||||
);
|
||||
let elapsed = CACHE_AGE;
|
||||
let expired = Sample {
|
||||
wall: cache.sample.wall + elapsed,
|
||||
interrupt: cache.sample.interrupt + elapsed,
|
||||
unbiased: cache.sample.unbiased + elapsed,
|
||||
};
|
||||
assert_eq!(cache.bound_at(expired), None);
|
||||
}
|
||||
#[test]
|
||||
fn suspend_closes_until_actual_post_resume_sync() {
|
||||
let (s, v) = good();
|
||||
let mut c = Continuity::default();
|
||||
|
||||
@@ -899,13 +899,15 @@ impl SystemHelper {
|
||||
let pin = settings.pin()?;
|
||||
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
|
||||
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
|
||||
let clock = if settings.windows_update_only() || settings.managed_scripts() {
|
||||
let role = rmm_time_attestation::Role::SystemHelper;
|
||||
let clock = if settings.managed_scripts() {
|
||||
RuntimeClock::local(role)
|
||||
} else if settings.windows_update_only() {
|
||||
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
|
||||
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
|
||||
} else {
|
||||
RuntimeClock::new(role)
|
||||
}.for_generation(0);
|
||||
let boot = WindowsBoot::capture()?;
|
||||
let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock)
|
||||
.ok()
|
||||
.map(|s| s.with_helper_identity(HelperIdentity::System));
|
||||
Ok(Self {
|
||||
settings,
|
||||
pin,
|
||||
@@ -914,7 +916,8 @@ impl SystemHelper {
|
||||
db,
|
||||
clock,
|
||||
boot,
|
||||
sync,
|
||||
// The initial connection creates the reconciler using its own qualified time.
|
||||
sync: None,
|
||||
last_diagnostic: None,
|
||||
last_apply_diagnostic: None,
|
||||
unsettled_msi: None,
|
||||
@@ -1008,14 +1011,17 @@ impl SystemHelper {
|
||||
}
|
||||
fn sync(&mut self) -> Result<&mut HelperSync<DalekVerifier>> {
|
||||
if self.sync.is_none() {
|
||||
self.sync = Some(
|
||||
HelperSync::with_verifier(
|
||||
self.settings.binding.clone(),
|
||||
DalekVerifier,
|
||||
&self.clock,
|
||||
)?
|
||||
.with_helper_identity(HelperIdentity::System),
|
||||
);
|
||||
let sync = HelperSync::with_verifier(
|
||||
self.settings.binding.clone(),
|
||||
DalekVerifier,
|
||||
&self.clock,
|
||||
)?
|
||||
.with_helper_identity(HelperIdentity::System);
|
||||
self.sync = Some(if self.settings.managed_scripts() {
|
||||
sync.with_periodic_idle_integrity_checks()
|
||||
} else {
|
||||
sync
|
||||
});
|
||||
}
|
||||
self.sync.as_mut().context("SYSTEM_SYNC_CLOSED")
|
||||
}
|
||||
@@ -1290,6 +1296,16 @@ impl SystemHelper {
|
||||
}
|
||||
ensure!(self.settings.enable_effects, "SYSTEM_EFFECTS_DISABLED");
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
if self.settings.managed_scripts() {
|
||||
ledger::check_integrity(&self.db, "ROOT_LEDGER_INTEGRITY")?;
|
||||
rmm_agent_core::helper_reconcile::verify_checkpoint_repair_history_with(
|
||||
&self.db,
|
||||
&self.settings.binding,
|
||||
None,
|
||||
HelperIdentity::System,
|
||||
&DalekVerifier,
|
||||
)?;
|
||||
}
|
||||
self.sync()?;
|
||||
ensure!(
|
||||
self.sync.as_ref().unwrap().can_start(
|
||||
@@ -1795,14 +1811,18 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
let result = (|| -> Result<()> {
|
||||
let mut helper = SystemHelper::open()?;
|
||||
let server = ipc::Server::bind(helper.pin().clone())?;
|
||||
let time_server = ipc::Server::bind_time(helper.pin().clone())?;
|
||||
let update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
|
||||
.map(crate::update_control_ipc::Server::bind).transpose()?;
|
||||
let time_pin = helper.pin().clone();
|
||||
let time_clock = helper.clock.source();
|
||||
let time_worker = std::thread::Builder::new()
|
||||
.name("rmm-helper-time-control".into())
|
||||
.spawn(move || time_control(time_server, time_pin, time_clock))?;
|
||||
let time_worker = if time_clock.uses_local_clock() {
|
||||
None
|
||||
} else {
|
||||
let time_pin = helper.pin().clone();
|
||||
let time_server = ipc::Server::bind_time(time_pin.clone())?;
|
||||
Some(std::thread::Builder::new()
|
||||
.name("rmm-helper-time-control".into())
|
||||
.spawn(move || time_control(time_server, time_pin, time_clock))?)
|
||||
};
|
||||
scm_status(SERVICE_RUNNING, 0);
|
||||
let mut next_update_unknown=Instant::now();
|
||||
while !STOP.load(Ordering::SeqCst) {
|
||||
@@ -1879,9 +1899,9 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
}
|
||||
// The time lane has no ledger/job operation and its receive wait is
|
||||
// bounded. Shutdown closes its private evidence before service exit.
|
||||
time_worker
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
|
||||
if let Some(worker) = time_worker {
|
||||
worker.join().map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||
|
||||
@@ -53,6 +53,7 @@ pub fn clock_code(error: &anyhow::Error) -> &'static str {
|
||||
"TIME_RUNTIME_NO_CONNECTION",
|
||||
"TIME_LOCAL_WALL_OUTSIDE_BOUND",
|
||||
"TIME_SOURCE_AGE_AT_CHECK",
|
||||
"TIME_WINDOWS_LOCAL_CLOCK",
|
||||
];
|
||||
error
|
||||
.chain()
|
||||
|
||||
@@ -227,28 +227,51 @@ pub fn private_path(path: &Path, directory: bool) -> Result<()> {
|
||||
}
|
||||
fn registry_string(name: &str) -> Result<String> {
|
||||
let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
|
||||
let name = wide(name);
|
||||
let value_name = wide(name);
|
||||
let mut bytes = vec![0u16; 2048];
|
||||
let mut size = (bytes.len() * 2) as u32;
|
||||
let status = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
value_name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
ptr::null_mut(),
|
||||
bytes.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "OS_REGISTRY {name} (Win32 {status})");
|
||||
ensure!(
|
||||
unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
ptr::null_mut(),
|
||||
bytes.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
} == 0,
|
||||
"OS_REGISTRY"
|
||||
size >= 2 && size % 2 == 0 && size as usize <= bytes.len() * 2,
|
||||
"OS_REGISTRY_SIZE {name}"
|
||||
);
|
||||
ensure!(
|
||||
size >= 2 && size as usize <= bytes.len() * 2,
|
||||
"OS_REGISTRY_SIZE"
|
||||
);
|
||||
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
|
||||
String::from_utf16(&bytes[..size as usize / 2 - 1])
|
||||
.with_context(|| format!("OS_REGISTRY_ENCODING {name}"))
|
||||
}
|
||||
|
||||
fn os_inventory(read: impl Fn(&str) -> Result<String>) -> Result<(String, Value)> {
|
||||
let product = read("ProductName")?;
|
||||
let build = read("CurrentBuildNumber")?;
|
||||
// Older Windows releases can omit DisplayVersion. Both version labels are
|
||||
// optional; the product and build still identify the OS without either.
|
||||
let version = |name| read(name).ok().filter(|s| !s.trim().is_empty());
|
||||
let display = version("DisplayVersion");
|
||||
let release = if display.is_none() {
|
||||
version("ReleaseId")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let os = match (&display, &release) {
|
||||
(Some(display), _) => format!("{product}; DisplayVersion={display}; Build={build}"),
|
||||
(None, Some(release)) => format!("{product}; ReleaseId={release}; Build={build}"),
|
||||
(None, None) => format!("{product}; Build={build}"),
|
||||
};
|
||||
let mut data = json!({"product_name":product,"display_version":display,"build":build});
|
||||
if let Some(release) = release {
|
||||
data["release_id"] = json!(release);
|
||||
}
|
||||
Ok((os, data))
|
||||
}
|
||||
pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
|
||||
let mut name = [0u16; 256];
|
||||
@@ -277,28 +300,45 @@ pub fn snapshot() -> Result<Value> {
|
||||
snapshot_with_boot(None)
|
||||
}
|
||||
|
||||
fn disk_space(root: &[u16]) -> Option<(u64, u64)> {
|
||||
let (mut available, mut total) = (0, 0);
|
||||
(unsafe { GetDiskFreeSpaceExW(root.as_ptr(), &mut available, &mut total, ptr::null_mut()) } != 0
|
||||
&& total > 0 && available <= total).then_some((available, total))
|
||||
}
|
||||
|
||||
fn fixed_volumes(system: &str, available: u64, total: u64) -> Vec<Value> {
|
||||
use windows_sys::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
|
||||
const DRIVE_FIXED: u32 = 3;
|
||||
let mask = unsafe { GetLogicalDrives() };
|
||||
let mut rows = vec![json!({"name":system,"free_bytes":available,"total_bytes":total})];
|
||||
for letter in b'A'..=b'Z' {
|
||||
if mask & (1 << (letter - b'A')) == 0 { continue; }
|
||||
let name = format!("{}:", char::from(letter));
|
||||
if name.eq_ignore_ascii_case(system) { continue; }
|
||||
let root = wide(format!("{name}\\"));
|
||||
if unsafe { GetDriveTypeW(root.as_ptr()) } != DRIVE_FIXED { continue; }
|
||||
// Retain an identified but unreadable volume without claiming zero usage.
|
||||
let sizes = disk_space(&root);
|
||||
rows.push(json!({"name":name,"free_bytes":sizes.map(|s| s.0),"total_bytes":sizes.map(|s| s.1)}));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
|
||||
let started = Utc::now();
|
||||
let hostname = computer_name(ComputerNameDnsHostname)?;
|
||||
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
|
||||
let mut available = 0;
|
||||
let mut total = 0;
|
||||
let mut free = 0;
|
||||
ensure!(
|
||||
unsafe { GetDiskFreeSpaceExW(volume.as_ptr(), &mut available, &mut total, &mut free) } != 0,
|
||||
"VOLUME_QUERY"
|
||||
);
|
||||
ensure!(total > 0 && available <= total, "VOLUME_VALUES");
|
||||
let product = registry_string("ProductName")?;
|
||||
let display = registry_string("DisplayVersion")?;
|
||||
let build = registry_string("CurrentBuildNumber")?;
|
||||
let os = format!("{product}; DisplayVersion={display}; Build={build}");
|
||||
let system = std::env::var("SystemDrive").context("SYSTEM_DRIVE")?.to_ascii_uppercase();
|
||||
let (available, total) = disk_space(&wide(format!("{system}\\"))).context("VOLUME_QUERY")?;
|
||||
let volumes = fixed_volumes(&system, available, total);
|
||||
let (os, mut os_data) = os_inventory(registry_string)?;
|
||||
os_data["installed_at"] = json!(install_date());
|
||||
os_data["booted_at"] = json!(booted_at);
|
||||
let completed = Utc::now();
|
||||
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
|
||||
"collection_started_at":started,"collection_completed_at":completed,
|
||||
"observations":[
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
|
||||
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":os_data},
|
||||
{"scope":"windows.volumes","source_id":"windows.win32:GetLogicalDrives;GetDriveTypeW;GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available,"drives":volumes}},
|
||||
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||
]});
|
||||
snapshot["observations"]
|
||||
@@ -356,6 +396,47 @@ pub async fn boot_id() -> Result<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
fn os_fixture(display: Option<&str>, release: Option<&str>) -> (String, serde_json::Value) {
|
||||
super::os_inventory(|name| {
|
||||
match name {
|
||||
"ProductName" => Some("Windows 10 Enterprise LTSC"),
|
||||
"CurrentBuildNumber" => Some("17763"),
|
||||
"DisplayVersion" => display,
|
||||
"ReleaseId" => release,
|
||||
_ => panic!("unexpected registry value: {name}"),
|
||||
}
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing {name}"))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_prefers_display_version() {
|
||||
let (os, data) = os_fixture(Some("22H2"), Some("2009"));
|
||||
assert!(os.contains("DisplayVersion=22H2"));
|
||||
assert_eq!(data["display_version"], "22H2");
|
||||
assert!(data.get("release_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_uses_legacy_release_id_when_display_version_is_missing() {
|
||||
let (os, data) = os_fixture(None, Some("1809"));
|
||||
assert_eq!(os, "Windows 10 Enterprise LTSC; ReleaseId=1809; Build=17763");
|
||||
assert!(data["display_version"].is_null());
|
||||
assert_eq!(data["release_id"], "1809");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_inventory_keeps_product_and_build_without_version_labels() {
|
||||
for display in [None, Some(" ")] {
|
||||
let (os, data) = os_fixture(display, None);
|
||||
assert_eq!(os, "Windows 10 Enterprise LTSC; Build=17763");
|
||||
assert!(data["display_version"].is_null());
|
||||
assert_eq!(data["build"], "17763");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_inventory_has_real_windows_sources_and_no_fake_inodes() {
|
||||
let v = super::snapshot().unwrap();
|
||||
|
||||
@@ -839,6 +839,10 @@ impl Agent {
|
||||
) -> Result<()> {
|
||||
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
|
||||
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
|
||||
let clock = self.clock.native.source();
|
||||
if clock.uses_local_clock() {
|
||||
return Ok(());
|
||||
}
|
||||
// Presence opts into sampling only. Each role opens and verifies the
|
||||
// protected profile and signed response itself before accepting time.
|
||||
let Some(mode) = SamplingMode::configured(self.config.enable_jobs, Path::new(CONFIG_PATH))?
|
||||
@@ -860,7 +864,6 @@ impl Agent {
|
||||
self.binding.as_ref(),
|
||||
self.helper_lane.clone(),
|
||||
)? };
|
||||
let clock = self.clock.native.source();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut tasks = Vec::new();
|
||||
let own_clock = clock.clone();
|
||||
@@ -951,7 +954,7 @@ impl Agent {
|
||||
let _ = time_helper.time_close(generation).await;
|
||||
}
|
||||
helper_report.record(&helper_state, "system_helper", &result);
|
||||
tokio::time::sleep(mode.interval(result.is_ok())).await;
|
||||
tokio::time::sleep(mode.helper_interval(result.is_ok())).await;
|
||||
}
|
||||
let _ = time_helper.time_close(generation).await;
|
||||
}));
|
||||
@@ -1291,8 +1294,8 @@ impl Agent {
|
||||
&& !self.helper_apply_unconfirmed
|
||||
&& !self.prepared
|
||||
&& self.running.is_none()
|
||||
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
|
||||
&& self.helper_probe_at.elapsed() >= Duration::from_secs(30)
|
||||
&& !self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?
|
||||
{
|
||||
let agent = self.identity.agent_id.clone();
|
||||
let asset = self.identity.asset_id.clone();
|
||||
@@ -2663,8 +2666,9 @@ impl Agent {
|
||||
let mut heartbeat = Instant::now() - Duration::from_secs(60);
|
||||
let mut previous_cpu = None;
|
||||
let mut heartbeat_after = Duration::from_secs(30);
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let active_tick = Duration::from_millis(20);
|
||||
let idle_tick = Duration::from_millis(250);
|
||||
let mut next_tick = tokio::time::Instant::now();
|
||||
let mut readiness_at = Instant::now() - Duration::from_secs(5);
|
||||
#[cfg(feature = "system-helper")]
|
||||
let mut update_control_at = Instant::now() - Duration::from_secs(2);
|
||||
@@ -2675,9 +2679,19 @@ impl Agent {
|
||||
running.cancel.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let control_pending = self.running.is_some()
|
||||
|| self.prepared
|
||||
|| self.deferred_sync.is_some()
|
||||
|| self.deferred_permit.is_some()
|
||||
|| self.helper_control_pending();
|
||||
#[cfg(feature = "system-helper")]
|
||||
let control_pending = control_pending || self.helper_probe.is_some();
|
||||
let cadence = if control_pending { active_tick } else { idle_tick };
|
||||
next_tick = next_tick.min(tokio::time::Instant::now() + cadence);
|
||||
tokio::select! {
|
||||
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
|
||||
_=tick.tick()=>{
|
||||
_=tokio::time::sleep_until(next_tick)=>{
|
||||
next_tick = tokio::time::Instant::now() + cadence;
|
||||
if !stop.load(Ordering::SeqCst) && self.poll_sync_apply(generation,true).is_err(){self.close_gate();needs_sync=true;}
|
||||
#[cfg(feature = "system-helper")]
|
||||
if !stop.load(Ordering::SeqCst) && self.poll_helper(&channel,generation).await.is_err() {self.close_gate();needs_sync=self.sync.is_some();}
|
||||
@@ -2709,7 +2723,9 @@ impl Agent {
|
||||
if self.sync.is_some() && !self.prepared && !self.helper_control_busy_for_sync() && rmm_agent_windows::job_readiness::refresh_due(needs_sync,sync_at.elapsed(),self.sync.as_ref().and_then(|s|s.validity_deadline()),self.clock.reading().ok().map(|r|r.upper)) {
|
||||
if self.start_sync(&channel,generation).await.is_err(){self.close_gate();needs_sync=true;}else{needs_sync=false;}sync_at=Instant::now();
|
||||
}
|
||||
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
|
||||
if Instant::now() >= permit_after && !needs_sync && !self.prepared && self.config.enable_jobs
|
||||
&& self.journal.connection().prepare_cached("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state='accepted' AND cancel_requested=0)")?.query_row([], |row| row.get::<_, bool>(0))?
|
||||
&& self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
|
||||
// A transiently stale clock skips this tick; it must not end the session.
|
||||
if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
|
||||
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
|
||||
@@ -3059,10 +3075,17 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
|
||||
let clock=JobClock::new(config.enable_jobs);
|
||||
#[cfg(feature = "system-helper")]
|
||||
let clock = if let Some(policy) = &config.localservice_time_policy {
|
||||
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
|
||||
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
|
||||
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
|
||||
).for_generation(0) }
|
||||
use rmm_agent_windows::signed_clock::RuntimeClock;
|
||||
let source = if config.windows_update_helper {
|
||||
RuntimeClock::enrolled_local_service(
|
||||
binding.clone().context("JOB_BINDING_REQUIRED")?,
|
||||
policy.clone(),
|
||||
installed_tenant.context("INSTALLED_TENANT_REQUIRED")?,
|
||||
)
|
||||
} else {
|
||||
RuntimeClock::local(rmm_time_attestation::Role::Agent)
|
||||
};
|
||||
JobClock { enabled: true, native: source.for_generation(0) }
|
||||
} else { clock };
|
||||
let mut config=config;
|
||||
if config.enable_jobs {
|
||||
@@ -3078,7 +3101,19 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
|
||||
ensure!(rmm_agent_windows::echo_probe::protected_scope()? == *scope, "WINDOWS_ECHO_CONFIGURATION_CHANGED");
|
||||
}
|
||||
}
|
||||
let sync=if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
|
||||
let sync = if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {
|
||||
binding.clone().map(|binding| {
|
||||
let sync = reconcile::ClientSync::new(binding)
|
||||
.with_helper_identity(reconcile::HelperIdentity::System);
|
||||
if config.localservice_time_policy.is_some() {
|
||||
sync.with_periodic_idle_integrity_checks()
|
||||
} else {
|
||||
sync
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
|
||||
let mut agent = Agent {
|
||||
config,
|
||||
@@ -3195,9 +3230,11 @@ pub fn main() -> Result<()> {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
|
||||
let inventory = native::snapshot_with_boot(Some(booted_at))?;
|
||||
let drives = inventory["observations"].as_array().and_then(|observations|
|
||||
observations.iter().find(|o| o["scope"] == "windows.volumes")).map(|o| &o["data"]["drives"]);
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
|
||||
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"fixed_volumes":drives,"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -31,6 +31,15 @@ impl SamplingMode {
|
||||
(Self::Jobs, false) => Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn helper_interval(self, verified: bool) -> std::time::Duration {
|
||||
match (self, verified) {
|
||||
// Each refresh verifies both service images over the pipe. A held
|
||||
// signed time sample remains usable for up to five minutes.
|
||||
(Self::Jobs, true) => std::time::Duration::from_secs(5),
|
||||
_ => self.interval(verified),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
|
||||
@@ -1401,6 +1410,7 @@ mod installed {
|
||||
#[derive(Clone)]
|
||||
pub struct RuntimeClock {
|
||||
role: Role,
|
||||
native: Option<Arc<crate::clock::NativeClock>>,
|
||||
enrolled_helper: Option<ipc::PeerPin>,
|
||||
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
|
||||
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
|
||||
@@ -1414,11 +1424,20 @@ mod installed {
|
||||
pub fn new(role: Role) -> Self {
|
||||
Self {
|
||||
role,
|
||||
native: None,
|
||||
enrolled_helper: None,
|
||||
local_policy: None,
|
||||
state: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
pub fn local(role: Role) -> Self {
|
||||
let mut clock = Self::new(role);
|
||||
clock.native = Some(Arc::new(crate::clock::NativeClock::new()));
|
||||
clock
|
||||
}
|
||||
pub fn uses_local_clock(&self) -> bool {
|
||||
self.native.is_some()
|
||||
}
|
||||
pub fn enrolled_local_service(
|
||||
binding: rmm_agent_core::auth::Binding,
|
||||
policy: std::path::PathBuf,
|
||||
@@ -1519,6 +1538,10 @@ mod installed {
|
||||
}
|
||||
fn bounds(&self) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
|
||||
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
|
||||
if let Some(native) = &self.source.native {
|
||||
return rmm_agent_core::reconcile::SyncClock::bounds(native.as_ref())
|
||||
.context("TIME_WINDOWS_LOCAL_CLOCK");
|
||||
}
|
||||
let mut state = self
|
||||
.source
|
||||
.state
|
||||
@@ -1535,6 +1558,10 @@ mod installed {
|
||||
}
|
||||
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
|
||||
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
|
||||
if let Some(native) = &self.source.native {
|
||||
return rmm_agent_core::reconcile::SyncClock::reading(native.as_ref())
|
||||
.context("TIME_WINDOWS_LOCAL_CLOCK");
|
||||
}
|
||||
let mut state = self
|
||||
.source
|
||||
.state
|
||||
@@ -1647,6 +1674,26 @@ mod tests {
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_sampling_spaces_successes_and_retries_failures_quickly() {
|
||||
use std::time::Duration;
|
||||
assert_eq!(
|
||||
SamplingMode::Jobs.helper_interval(true),
|
||||
Duration::from_secs(5)
|
||||
);
|
||||
assert_eq!(
|
||||
SamplingMode::Jobs.helper_interval(false),
|
||||
Duration::from_millis(500)
|
||||
);
|
||||
for verified in [false, true] {
|
||||
assert_eq!(
|
||||
SamplingMode::Passive.helper_interval(verified),
|
||||
Duration::from_secs(30)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn sample(ns: u64) -> Sample {
|
||||
Sample {
|
||||
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
|
||||
|
||||
@@ -105,7 +105,7 @@ pub async fn ingest(
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).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()
|
||||
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
|
||||
&& row.get::<String, _>("transport") == transport;
|
||||
@@ -196,6 +196,16 @@ pub async fn ingest(
|
||||
}
|
||||
_ => 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?;
|
||||
Ok(reply(
|
||||
e,
|
||||
|
||||
@@ -26,6 +26,10 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
post(revoke_device),
|
||||
)
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/hypervisor",
|
||||
post(assign_hypervisor),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
||||
post(archive_device),
|
||||
@@ -134,6 +138,51 @@ struct Pairing {
|
||||
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(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
|
||||
@@ -158,11 +158,13 @@ async fn status(
|
||||
return Ok(private_json(json!({"transfer":null})));
|
||||
};
|
||||
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() {
|
||||
"completed"
|
||||
} else if hostname.is_some() {
|
||||
"ready"
|
||||
} else if t.target_agent_id.is_some() {
|
||||
"enrolled"
|
||||
} else {
|
||||
@@ -186,7 +188,7 @@ async fn lock_source(
|
||||
sqlx::query_scalar(
|
||||
"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)
|
||||
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(agent)
|
||||
@@ -320,34 +322,16 @@ async fn complete(
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<Response, Error> {
|
||||
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)
|
||||
.await?
|
||||
.filter(|t| t.transfer_id == id)
|
||||
.ok_or(NOT_FOUND)?;
|
||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||
if t.completed_at.is_some() {
|
||||
return Ok(private_json(json!({"state":"completed"})));
|
||||
}
|
||||
if target_hostname(&mut tx, &t).await?.is_none() {
|
||||
// Older WebUI bundles may still request completion after the atomic cutover.
|
||||
if t.completed_at.is_none() {
|
||||
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?;
|
||||
Ok(private_json(json!({"state":"completed"})))
|
||||
}
|
||||
@@ -443,8 +427,8 @@ async fn device_certificate(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation)
|
||||
VALUES($1,$2,$3,$4,$5,$6)",
|
||||
"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,true)",
|
||||
).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)
|
||||
.execute(&mut *tx).await?;
|
||||
|
||||
@@ -3,7 +3,7 @@ WITH classified AS (
|
||||
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
|
||||
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
|
||||
a.system_usage,a.system_usage_observed_at,
|
||||
asset.archived_at,t.name AS customer_name,
|
||||
asset.archived_at,asset.hypervisor_asset_id,t.name AS customer_name,
|
||||
CASE
|
||||
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
||||
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 tenants t USING(tenant_id)
|
||||
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 ($5::uuid IS NULL OR a.agent_id=$5)
|
||||
)
|
||||
|
||||
+253
-12
@@ -14,6 +14,7 @@ use rmm_domain::inventory_document::DeviceType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
||||
@@ -121,15 +122,13 @@ pub async fn list(
|
||||
};
|
||||
tenants.sort_unstable();
|
||||
tenants.dedup();
|
||||
let hostname = q.q.as_deref().unwrap_or("").trim();
|
||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let hostname = hostname_filter(q.q.as_deref())?;
|
||||
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
|
||||
let scope = format!(
|
||||
"device-fleet:{}",
|
||||
rmm_domain::jobs::hash(binding.to_string().as_bytes())
|
||||
);
|
||||
let first_page = q.cursor.is_none();
|
||||
let mut page = Cursor::parse(
|
||||
s,
|
||||
&p,
|
||||
@@ -145,10 +144,15 @@ pub async fn list(
|
||||
let mut last = None;
|
||||
let mut truncated = false;
|
||||
let mut authorized = false;
|
||||
let mut principals = Vec::new();
|
||||
for customer in tenants {
|
||||
if page.last_tenant.is_some_and(|after| customer < after) {
|
||||
continue;
|
||||
}
|
||||
if customer == p.tenant {
|
||||
principals.push(p.clone());
|
||||
continue;
|
||||
}
|
||||
let mut headers = h.clone();
|
||||
headers.insert(
|
||||
"x-rmm-tenant",
|
||||
@@ -157,7 +161,25 @@ pub async fn list(
|
||||
);
|
||||
let current = crate::jobs::principal(s, &headers, false).await?;
|
||||
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 {
|
||||
Err(Error(StatusCode::FORBIDDEN, _)) if tenant.is_none() => continue,
|
||||
other => other?,
|
||||
@@ -180,19 +202,20 @@ pub async fn list(
|
||||
}
|
||||
.rows(&mut tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
|
||||
for row in rows {
|
||||
if items.len() == capacity {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
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 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
if !authorized {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
@@ -236,7 +259,8 @@ pub async fn detail(
|
||||
.await?
|
||||
.pop()
|
||||
.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["recent_jobs"] = if p.permits_scope("operations:read")
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||
@@ -294,6 +318,135 @@ fn device_type(hardware: &Value) -> Option<DeviceType> {
|
||||
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")))
|
||||
}
|
||||
|
||||
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> {
|
||||
let linux_hardware = observed(data, "linux.hardware");
|
||||
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
|
||||
@@ -348,7 +501,7 @@ fn os_label(data: &Value) -> Option<String> {
|
||||
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 cpu = observed(&data, "linux.cpu");
|
||||
let windows = observed(&data, "windows.hardware");
|
||||
@@ -365,8 +518,7 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
.as_u64()
|
||||
.or_else(|| linux_memory["total_bytes"].as_u64())
|
||||
.or_else(|| windows["memory_total_bytes"].as_u64());
|
||||
let device_type =
|
||||
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 revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
||||
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
||||
@@ -397,6 +549,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"},
|
||||
"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 {
|
||||
item["inventory"] = data;
|
||||
item["capabilities"] = row.get("capabilities");
|
||||
@@ -457,6 +617,87 @@ mod tests {
|
||||
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]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||
@@ -499,7 +740,7 @@ mod tests {
|
||||
limit: 1,
|
||||
};
|
||||
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["ram_total_bytes"], 1024);
|
||||
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 mut jobs = Vec::new();
|
||||
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 {
|
||||
return Err(fail(if rows.is_empty() {
|
||||
"NOT_FOUND"
|
||||
@@ -683,7 +683,7 @@ async fn recheck_for(
|
||||
if job.payload.start_before <= Utc::now() {
|
||||
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
|
||||
|| r.get::<i64, _>("enrollment_generation") as u64 != job.payload.enrollment_generation
|
||||
{
|
||||
|
||||
@@ -217,6 +217,7 @@ async fn main() -> Result<()> {
|
||||
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
|
||||
.route("/api/v1/devices", get(devices::all))
|
||||
.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));
|
||||
routes = mcp_tokens::routes(routes);
|
||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
{
|
||||
"native_method": "Three windows with process CPU and logical I/O counters from Win32_Process, plus existing readiness observations. Percentages use both Windows logical processors. I/O counts include cached reads. The data shows the combined effect of each release.",
|
||||
"source_findings": {
|
||||
"baseline_revision": "9e957e6d8d4254a01fe215b32ecd6bc8c31b6947",
|
||||
"agent": "20 ms timer did journal queries and qualified clock reads even with no accepted attempt. Every sync prepared with a complete SQLite integrity scan.",
|
||||
"helper": "Every snapshot ran a complete SQLite integrity scan. Every ready response rebuilt a denial anchor and revalidated the entire historical decision chain. ORDER BY checkpoint had no supporting index for that replay.",
|
||||
"idle_runtime_tick_ms": 250,
|
||||
"active_runtime_tick_ms": 20,
|
||||
"idle_integrity_audit_interval_seconds": 300,
|
||||
"full_audits_before_new_system_effect": true,
|
||||
"full_lineage_audit_before_no_start_record": true
|
||||
},
|
||||
"local_sqlite_query_plan": {
|
||||
"baseline": [
|
||||
"SCAN helper_sync_decisions",
|
||||
"USE TEMP B-TREE FOR ORDER BY"
|
||||
],
|
||||
"with_checkpoint_index": [
|
||||
"SCAN helper_sync_decisions USING INDEX helper_sync_decisions_checkpoint"
|
||||
]
|
||||
},
|
||||
"measurements": [
|
||||
{
|
||||
"start": "2026-11-19T09:05:49.2782989Z",
|
||||
"end": "2026-11-19T09:07:20.7135402Z",
|
||||
"version": "0.1.22",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 91.127271,
|
||||
"journal_bytes": 452415488,
|
||||
"ledger_bytes": 335908864,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.03125,
|
||||
"cpu_percent": 0.0171,
|
||||
"read_mib_s": 0.0003,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 4700,
|
||||
"cpu_seconds": 21.546875,
|
||||
"cpu_percent": 11.8224,
|
||||
"read_mib_s": 102.0242,
|
||||
"write_mib_s": 34.4732
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 1908,
|
||||
"cpu_seconds": 5.75,
|
||||
"cpu_percent": 3.1549,
|
||||
"read_mib_s": 38.1056,
|
||||
"write_mib_s": 0.0482
|
||||
}
|
||||
},
|
||||
"idle_job_authorizations": 0,
|
||||
"readiness_samples": 19,
|
||||
"signed_decisions_observed": 6,
|
||||
"ready_samples": 14
|
||||
},
|
||||
{
|
||||
"start": "2026-11-19T09:13:22.8803140Z",
|
||||
"end": "2026-11-19T09:14:54.0077643Z",
|
||||
"version": "0.1.23",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.93767,
|
||||
"journal_bytes": 455192576,
|
||||
"ledger_bytes": 337829888,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.015625,
|
||||
"cpu_percent": 0.0086,
|
||||
"read_mib_s": 0.0,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 8036,
|
||||
"cpu_seconds": 10.015625,
|
||||
"cpu_percent": 5.5069,
|
||||
"read_mib_s": 63.7249,
|
||||
"write_mib_s": 13.9068
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 832,
|
||||
"cpu_seconds": 2.640625,
|
||||
"cpu_percent": 1.4519,
|
||||
"read_mib_s": 26.3846,
|
||||
"write_mib_s": 0.0204
|
||||
}
|
||||
},
|
||||
"idle_job_authorizations": 0,
|
||||
"readiness_samples": 18,
|
||||
"signed_decisions_observed": 3,
|
||||
"ready_samples": 10
|
||||
},
|
||||
{
|
||||
"start": "2026-11-19T09:18:45.8146916Z",
|
||||
"end": "2026-11-19T09:20:16.8017398Z",
|
||||
"version": "0.1.24",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.814144,
|
||||
"journal_bytes": 456974336,
|
||||
"ledger_bytes": 339193856,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.0,
|
||||
"cpu_percent": 0.0,
|
||||
"read_mib_s": 0.0,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 4168,
|
||||
"cpu_seconds": 1.53125,
|
||||
"cpu_percent": 0.8431,
|
||||
"read_mib_s": 16.1736,
|
||||
"write_mib_s": 0.0126
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 404,
|
||||
"cpu_seconds": 1.28125,
|
||||
"cpu_percent": 0.7054,
|
||||
"read_mib_s": 12.3686,
|
||||
"write_mib_s": 0.0294
|
||||
}
|
||||
},
|
||||
"idle_job_authorizations": 0,
|
||||
"readiness_samples": 19,
|
||||
"signed_decisions_observed": 4,
|
||||
"ready_samples": 18
|
||||
}
|
||||
],
|
||||
"candidate_0_1_23_revision": "478ee1fc1a8141845427011e566f5225eeebadd0",
|
||||
"final_build_revision": "f01e81418e7b36a86bfb686542bd2f5380ecfe82",
|
||||
"release": {
|
||||
"release_id": "2032b236-4ab7-4dad-8e74-1144c5a5d165",
|
||||
"version": "0.1.24",
|
||||
"platform": "x86_64-pc-windows-gnu",
|
||||
"manifest_sha256": "311e5df4979904907e54d5d1e08205decaf78fa3e3c6e34a68215f4873c2782d"
|
||||
},
|
||||
"activation": {
|
||||
"method": "Signed automatic Windows GNU release pull in Development A",
|
||||
"sequence": 25,
|
||||
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
|
||||
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
|
||||
"services": [
|
||||
{
|
||||
"name": "RmmDiscoveryReleasePull",
|
||||
"pid": 2384,
|
||||
"state": "Running",
|
||||
"sha256": "575ceb6a0b76c835d28646a498dfa73e88fb5de6343b77bf11d5eefea3fc68b1"
|
||||
},
|
||||
{
|
||||
"name": "RmmDiscoverySystemHelper",
|
||||
"pid": 4168,
|
||||
"state": "Running",
|
||||
"sha256": "bcff281db15549381f1fbe530af74ad4b44cefaa94a7c1c30e1f5a6a673ea556"
|
||||
},
|
||||
{
|
||||
"name": "RmmDiscoveryWindows",
|
||||
"pid": 404,
|
||||
"state": "Running",
|
||||
"sha256": "3c4727fd08ffecf3147221826087f125c6d835201b182b8ad1a4280c98ea0954"
|
||||
}
|
||||
],
|
||||
"observed_at_utc": "2026-11-19T09:18:43.8141692Z",
|
||||
"fresh_gateway_contact": "2026-11-19T09:18:40.275768+00:00"
|
||||
},
|
||||
"system_test": {
|
||||
"operation_id": "e6d139c0-7f29-478d-87e8-38f466d8634f",
|
||||
"job_id": "512f9311-4ace-4b64-9c60-24bb40719312",
|
||||
"attempt_id": "d6e4a74a-4a56-4d95-b640-db4267c437eb",
|
||||
"plan_hash": "7aeffea215d916810af3b7748fb3fb7bc715e5d9470d85e7f669bd20526ff2e7",
|
||||
"stdout": "Windows-Konto S-1-5-18",
|
||||
"exit_code": 0,
|
||||
"state": "succeeded",
|
||||
"observed_at": "2026-11-19T09:20:39.711Z",
|
||||
"script_sha256": "8a0c76004a480aa11f6c768b2984e2cf2c01431009ccdbfb1607825133fcbc4f",
|
||||
"approval": {
|
||||
"principal": "simulated-testprincipal-a",
|
||||
"approval_origin": "dev_test_browser_simulation",
|
||||
"testsimulation": true,
|
||||
"plan_hash": "7aeffea215d916810af3b7748fb3fb7bc715e5d9470d85e7f669bd20526ff2e7"
|
||||
},
|
||||
"preapproval": {
|
||||
"jobs": 0,
|
||||
"outbox": 0,
|
||||
"grants": 0
|
||||
},
|
||||
"grants": 1
|
||||
},
|
||||
"final_health": {
|
||||
"auth_contact": "2026-11-19T09:20:39.525258+00:00",
|
||||
"contact": "2026-11-19T09:20:26.027274+00:00",
|
||||
"generation": 80,
|
||||
"active_jobs": 0,
|
||||
"helper_ready": true,
|
||||
"ready": true,
|
||||
"system_run_script": true
|
||||
},
|
||||
"targeted_core_tests_passed": 70
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"device": "discwindowstest",
|
||||
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
|
||||
"service_account_sid": "S-1-5-19",
|
||||
"approval_origin": "dev_test_browser_simulation",
|
||||
"testsimulation": true,
|
||||
"probes": [
|
||||
{
|
||||
"probe": "event_log_access",
|
||||
"operation_id": "a1c51c29-691e-4b70-aa94-d2967ffece45",
|
||||
"job_id": "a94170e7-97e4-4092-9cfb-76394f43b891",
|
||||
"attempt_id": "d01accc7-cb36-4a92-b31a-0a34e5642bd9",
|
||||
"plan_hash": "09b0d80a2ce0c68300f4a2a2639af2dc7a40a7a75b3011e26ae0e0de7e30bded",
|
||||
"observed_at": "2026-11-19T10:25:20.806Z"
|
||||
},
|
||||
{
|
||||
"probe": "w32tm_exit_and_event_260_fields",
|
||||
"operation_id": "9354d97c-dc14-436b-9da5-5c665dbf5ee4",
|
||||
"job_id": "4a2fd66e-2ba8-4414-a19e-38911e08a1ad",
|
||||
"attempt_id": "5e1cb739-aac4-48e1-9a7a-72c52aa3a366",
|
||||
"plan_hash": "e18a81044b5f249709cf18c90df01e6d8a904f9e714ba736341e89a7d3546f14",
|
||||
"observed_at": "2026-11-19T10:26:17.521Z"
|
||||
},
|
||||
{
|
||||
"probe": "w32tm_status_and_instance_creation_acl",
|
||||
"operation_id": "174c88c2-bbf9-4f94-9ac3-c2421205b36c",
|
||||
"job_id": "93546a51-9a55-444d-8a51-0a28b72868a2",
|
||||
"attempt_id": "4767c1d0-574d-4867-abaf-c4fe5540f5f3",
|
||||
"plan_hash": "63a34cfa84f8b6cb2c97685ea4cdf3c5a4833d4f47536d5a9b784cb814657ef2",
|
||||
"observed_at": "2026-11-19T10:27:49.448Z"
|
||||
},
|
||||
{
|
||||
"probe": "w32tm_status_and_pipe_owner_pid",
|
||||
"operation_id": "f5398a75-358b-41df-8891-41a294f03865",
|
||||
"job_id": "e38e9eaf-f987-4fcf-8fe6-38b3e1f213f5",
|
||||
"attempt_id": "89d476f3-de30-48da-8fe9-1259634daa04",
|
||||
"plan_hash": "d37cbf6ff3b705e1d2b9637cc4f357989e774a8b1201892084abfecd42b82399",
|
||||
"observed_at": "2026-11-19T10:29:10.112Z"
|
||||
}
|
||||
],
|
||||
"first_w32tm_invocation_exit_observed": false,
|
||||
"w32time_running": true,
|
||||
"last_w32tm_query_exit_code": 0,
|
||||
"last_w32tm_query": {
|
||||
"leap": 0,
|
||||
"stratum": 5,
|
||||
"state": 2,
|
||||
"root_delay_seconds": 0.0171354,
|
||||
"root_dispersion_seconds": 1.1443877,
|
||||
"phase_offset_seconds": 0.0090787,
|
||||
"last_successful_sync_age_seconds": 6310.7259763
|
||||
},
|
||||
"newest_operational_status_event_260": {
|
||||
"id": 260,
|
||||
"count": 10,
|
||||
"last_age_seconds": 28666,
|
||||
"fields": [
|
||||
"Configuration",
|
||||
"TimeProviders",
|
||||
"LeapIndicator",
|
||||
"Stratum",
|
||||
"Precision",
|
||||
"RootDelay",
|
||||
"RootDispersion",
|
||||
"ReferenceId",
|
||||
"LastSuccessfulSyncTime",
|
||||
"Source",
|
||||
"PollInterval",
|
||||
"PhaseOffset",
|
||||
"ClockRate",
|
||||
"StateMachine",
|
||||
"TimeSourceFlags",
|
||||
"ServerRole",
|
||||
"LastSyncError",
|
||||
"TimeSinceLastGoodSync",
|
||||
"TickCount"
|
||||
]
|
||||
},
|
||||
"direct_local_w32time_alt_pipe": {
|
||||
"owner_sid": "S-1-5-19",
|
||||
"owner_rights": "READ_CONTROL",
|
||||
"create_instance_sid_matches_w32time": true,
|
||||
"peer_pid_matches_service_manager": true
|
||||
},
|
||||
"existing_native_adapter_max_sync_age_seconds": 3600,
|
||||
"native_job_clock_accepted": false,
|
||||
"agent_or_helper_released": false,
|
||||
"workspace_base_revision": "5a9eafbff17b782081bf0ebe67a75b93122e5eac",
|
||||
"w32tm_rpc_peer_identity_verified_in_probe": false,
|
||||
"post_diagnostics": {
|
||||
"checked_at": "2026-11-19T10:32:09.314887+00:00",
|
||||
"release_version": "0.1.24",
|
||||
"release_id": "2032b236-4ab7-4dad-8e74-1144c5a5d165",
|
||||
"active_jobs": 0,
|
||||
"agent_ready": true,
|
||||
"helper_ready": true,
|
||||
"system_script_capability": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"device": "discwindowstest",
|
||||
"agent_id": "239ffa87-642f-40cd-9cbf-d48557dc0193",
|
||||
"asset_id": "fab8b229-4eea-4af8-9362-a3aea4a8f709",
|
||||
"source_revision": "b002202d625720694a3792c3e15d3a94719b7099",
|
||||
"release": {
|
||||
"version": "0.1.25",
|
||||
"id": "2a41f8c8-dd1a-46d9-bef1-9ad5cddf5966",
|
||||
"sequence": 26,
|
||||
"signing_key_id": "0cd5b3f3e2ddf7669df05e759f48e6398548112fc5c6fd9b9128ef3243561b10",
|
||||
"authenticated_contact_at": "2026-11-19T10:54:12.386781+00:00",
|
||||
"local_service_readiness": {
|
||||
"observed_at": "2026-11-19T10:54:13.672532300Z",
|
||||
"ready": true,
|
||||
"helper_ready": true,
|
||||
"clock_qualified": true,
|
||||
"counts": {
|
||||
"accepted": 0,
|
||||
"requesting": 0,
|
||||
"running": 0,
|
||||
"verifying": 0,
|
||||
"unknown": 0,
|
||||
"awaiting_reboot": 0,
|
||||
"events": 0,
|
||||
"legacy_events": 0
|
||||
}
|
||||
},
|
||||
"running_images": {
|
||||
"RmmDiscoverySystemHelper": "b7a6a451647bd840524067270ed96fdfea84cd5b2a60d84445eacc90d544c9f1",
|
||||
"RmmDiscoveryWindows": "a687961919ab30d539105ad7e693666bcd38d26515a11d8d486364ffb156fcf5"
|
||||
}
|
||||
},
|
||||
"direct_pipe_probe_as_localservice": {
|
||||
"job_id": "e6cad92f-6474-4693-bf1a-73cf72ad81bb",
|
||||
"state": 2,
|
||||
"stratum": 5,
|
||||
"sync_age_seconds": 7203.0809513,
|
||||
"root_dispersion_seconds": 1.1443877
|
||||
},
|
||||
"native_clock_tests_passed": 17,
|
||||
"job_approval_origin": "dev_test_browser_simulation",
|
||||
"system_job": {
|
||||
"operation_id": "fee07cb4-a708-41e9-9690-e84a9b960f64",
|
||||
"job_id": "49536eaa-dd7a-4f7e-910d-34a120e5c404",
|
||||
"attempt_id": "cd00f3db-6f57-411f-ad1b-c89e4f83c37d",
|
||||
"plan_hash": "3115b232e66a0766b075f223165e5e32824329ff2fcefd77e09adb7c91eb6920",
|
||||
"stdout": "Windows-Konto S-1-5-18",
|
||||
"exit_code": 0,
|
||||
"observed_at": "2026-11-19T10:54:54.535Z"
|
||||
},
|
||||
"localservice_job": {
|
||||
"operation_id": "3a82b9f8-6b90-403b-bc07-af3fd5577765",
|
||||
"job_id": "ea8fc366-cea5-44e5-aea2-92a614b3d584",
|
||||
"attempt_id": "41915f64-0c33-43b9-a6c2-abe4b5daf2fd",
|
||||
"plan_hash": "61310d106e488185f8dad1490dde0a21878d744b2e3ceefafef8cad98794399b",
|
||||
"stdout": "Windows-Konto S-1-5-19",
|
||||
"exit_code": 0,
|
||||
"observed_at": "2026-11-19T10:55:15.164Z"
|
||||
},
|
||||
"idle_cpu": {
|
||||
"method": "Deltas of accumulated user and kernel CPU time, normalized to all guest logical CPUs. No active jobs at either endpoint of each measurement.",
|
||||
"before": [
|
||||
{
|
||||
"start": "2026-11-19T10:34:46.3830134Z",
|
||||
"end": "2026-11-19T10:36:17.5961401Z",
|
||||
"version": "0.1.24",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.878517,
|
||||
"journal_bytes": 490684416,
|
||||
"ledger_bytes": 364482560,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.0,
|
||||
"cpu_percent": 0.0,
|
||||
"read_mib_s": 0.0,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 4168,
|
||||
"cpu_seconds": 1.71875,
|
||||
"cpu_percent": 0.9456,
|
||||
"read_mib_s": 19.5365,
|
||||
"write_mib_s": 0.0099
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 404,
|
||||
"cpu_seconds": 1.46875,
|
||||
"cpu_percent": 0.8081,
|
||||
"read_mib_s": 12.3542,
|
||||
"write_mib_s": 0.0265
|
||||
}
|
||||
},
|
||||
"signed_sync_decisions": 3,
|
||||
"readiness_samples": 19,
|
||||
"clock_and_both_processes_ready_samples": 18
|
||||
},
|
||||
{
|
||||
"start": "2026-11-19T10:48:29.8083475Z",
|
||||
"end": "2026-11-19T10:50:00.9952167Z",
|
||||
"version": "0.1.24",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.893371,
|
||||
"journal_bytes": 501288960,
|
||||
"ledger_bytes": 371404800,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.015625,
|
||||
"cpu_percent": 0.0086,
|
||||
"read_mib_s": 0.0,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 4168,
|
||||
"cpu_seconds": 1.609375,
|
||||
"cpu_percent": 0.8853,
|
||||
"read_mib_s": 16.8442,
|
||||
"write_mib_s": 0.015
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 404,
|
||||
"cpu_seconds": 2.015625,
|
||||
"cpu_percent": 1.1088,
|
||||
"read_mib_s": 18.2974,
|
||||
"write_mib_s": 0.0426
|
||||
}
|
||||
},
|
||||
"signed_sync_decisions": 5,
|
||||
"readiness_samples": 19,
|
||||
"clock_and_both_processes_ready_samples": 17
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"start": "2026-11-19T10:55:17.1079639Z",
|
||||
"end": "2026-11-19T10:56:48.1011210Z",
|
||||
"version": "0.1.25",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.804969,
|
||||
"journal_bytes": 505876480,
|
||||
"ledger_bytes": 375373824,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.0,
|
||||
"cpu_percent": 0.0,
|
||||
"read_mib_s": 0.0,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 7736,
|
||||
"cpu_seconds": 0.453125,
|
||||
"cpu_percent": 0.2495,
|
||||
"read_mib_s": 3.5594,
|
||||
"write_mib_s": 0.0106
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 6660,
|
||||
"cpu_seconds": 0.515625,
|
||||
"cpu_percent": 0.2839,
|
||||
"read_mib_s": 2.0611,
|
||||
"write_mib_s": 0.0297
|
||||
}
|
||||
},
|
||||
"signed_sync_decisions": 3,
|
||||
"readiness_samples": 19,
|
||||
"clock_and_both_processes_ready_samples": 19
|
||||
},
|
||||
{
|
||||
"start": "2026-11-19T10:56:51.2093465Z",
|
||||
"end": "2026-11-19T10:58:22.2709313Z",
|
||||
"version": "0.1.25",
|
||||
"cpu_count": 2,
|
||||
"duration_seconds": 90.875229,
|
||||
"journal_bytes": 507482112,
|
||||
"ledger_bytes": 376291328,
|
||||
"processes": {
|
||||
"rmm-updater-windows.exe": {
|
||||
"pid": 2384,
|
||||
"cpu_seconds": 0.015625,
|
||||
"cpu_percent": 0.0086,
|
||||
"read_mib_s": 0.0003,
|
||||
"write_mib_s": 0.0
|
||||
},
|
||||
"rmm-helper-windows.exe": {
|
||||
"pid": 7736,
|
||||
"cpu_seconds": 0.984375,
|
||||
"cpu_percent": 0.5416,
|
||||
"read_mib_s": 10.2012,
|
||||
"write_mib_s": 0.0206
|
||||
},
|
||||
"rmm-agent-windows.exe": {
|
||||
"pid": 6660,
|
||||
"cpu_seconds": 0.671875,
|
||||
"cpu_percent": 0.3697,
|
||||
"read_mib_s": 3.283,
|
||||
"write_mib_s": 0.0803
|
||||
}
|
||||
},
|
||||
"signed_sync_decisions": 5,
|
||||
"readiness_samples": 19,
|
||||
"clock_and_both_processes_ready_samples": 18
|
||||
}
|
||||
],
|
||||
"weighted_mean_percent": {
|
||||
"agent": {
|
||||
"before": 0.9584,
|
||||
"after": 0.3268
|
||||
},
|
||||
"system_helper": {
|
||||
"before": 0.9155,
|
||||
"after": 0.3956
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"source_revision": "037b5e39fa5c23689984061efded0628e6914dab",
|
||||
"platform": "x86_64-pc-windows-gnu",
|
||||
"release": {
|
||||
"version": "0.1.26",
|
||||
"sequence": 27,
|
||||
"release_id": "979ff20e-e412-402f-85ea-fa6c50ae4b7b",
|
||||
"manifest_sha256": "31d22becc730eb4a2817dcd9b6aee2924b3416d3956c9a8b1bc6d2f79749499e",
|
||||
"minimum_updater_version": 2,
|
||||
"published_to_affected_customer": true,
|
||||
"official_windows_starter": true
|
||||
},
|
||||
"native_windows_tests": {
|
||||
"display_version_has_priority": "passed",
|
||||
"missing_display_version_uses_release_id": "passed",
|
||||
"missing_version_labels_keep_product_and_build": "passed",
|
||||
"existing_windows_inventory_collection": "passed"
|
||||
},
|
||||
"native_test_vm_self_update": {
|
||||
"previous_sequence": 26,
|
||||
"installed_sequence": 27,
|
||||
"same_agent_identity": true,
|
||||
"new_heartbeat_at_utc": "2026-11-19T15:35:18.825174Z",
|
||||
"updater_status": "ok",
|
||||
"updater_status_at_utc": "2026-11-19T15:35:21.661912200Z",
|
||||
"running_agent_sha256": "a23edbe35c089e1788939c42274dba58ad5b33bf344997fb85b023355b97de64",
|
||||
"running_helper_sha256": "68a952a4d42375bc4119486c72f4714ca47e72348e15ef013eda9892614f088d"
|
||||
},
|
||||
"affected_device": {
|
||||
"enrollment_accepted": true,
|
||||
"last_observed_version": "0.1.22",
|
||||
"local_error": "OS_REGISTRY",
|
||||
"display_version_missing_confirmed_by_operator": true,
|
||||
"updated_and_reported_first_heartbeat": "not yet observed"
|
||||
}
|
||||
}
|
||||
@@ -27,13 +27,16 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
|
||||
| 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) |
|
||||
| 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. 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. Der Windows-Agent ist für den neuen Ablauf gebaut. Die Fachabnahme eines vollständigen Wechsels im Windows-Dienst steht aus. [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) |
|
||||
| RAM und CPU-Auslastung in der Übersicht | RAM als verfügbar / gesamt in GiB mit demselben Belegungsbalken wie beim Speicherplatz. Die CPU-Spalte zeigt die letzte gemessene Auslastung in Prozent. Am 18. November wurde `6ed57c4` mit Schema 41 produktiv aktiviert. Beide TLS-Healthchecks und der öffentliche WebUI-Index stimmten mit dem Build überein. Die öffentliche Übersicht zeigte die RAM-Balken auf Desktop und bei 390 px Breite für alle drei Geräte. Die Detailansicht und die automatische Aktualisierung wurden in Chromium auf Linux x64 und ARM64 nachgelesen. OTRS meldete um 18:05 UTC nach dem signierten Wechsel auf `0.1.0-arm64.3` `6,2 / 7,6 GiB` und `1,1 %`. Um 18:06 UTC meldeten Linux x64 `0.1.0-mvp.9`, Windows `0.1.18` und ARM64 frische CPU-Werte und waren authentisiert erreichbar. [Geräteansicht](../web/src/devices.tsx) · [Geräteprojektion](../crates/server/src/devices.rs) |
|
||||
| Gerätetyp in der Übersicht | Spalte „Type“ nach „Hostname“ mit `physical`, `virtual` und `hypervisor`. Erkannte Proxmox-VE-Hosts zeigen `Proxmox VE` als OS. Am 18. November wurde `c599baa` auf dem öffentlichen Server aktiviert. Der Serverrunner bestätigte API, Gateway und öffentlichen API-Dienst mit Binärhash `4f9c8c60…`. Der öffentliche WebUI-Index stimmte mit dem gebauten Bundle überein. Die unveränderten Geräteidentitäten meldeten nach regulärem signierten Update `virtual` auf Linux mit `0.1.0-mvp.7` um 16:45 UTC und Windows mit `0.1.17` um 16:47 UTC. Geräteliste, Details, Mobilansicht mit 390 px und Historie sind in der öffentlichen WebUI geprüft. Beide Pakete sind in Development A und B und als Starter für leere Kataloge veröffentlicht. Die Typen `physical` und `hypervisor` sind mit Testdaten geprüft. Die Feldabnahme auf einem physischen Gerät und einem Proxmox-VE-Host steht aus. [Inventarprojektion](../crates/server/src/devices.rs) · [Geräteansicht](../web/src/devices.tsx) |
|
||||
| Hostzuordnung bei VMs | Die WebUI zeigt einen zugeordneten Hypervisor direkt an der VM. Der Browsertest prüfte Zuordnung, Verlinkung, Entfernen und den Hetzner-Platzhalter bei 390 px Breite. In PostgreSQL wurden die Page-Grenze, archivierte Hypervisoren und die Trennung der Kunden geprüft. 80 WebUI-Tests, vier Browsertests und fünf Rust-Gerätetests bestanden. Revision `bcd3bd8` wurde am 18. November um 21:43 UTC mit Schema 43 aktiviert. Der Serverrunner bestätigte die TLS-Healthchecks und der öffentliche Index entsprach dem Build. In der öffentlichen WebUI zeigten zwei vorhandene Hetzner-VMs den Platzhalter auf Desktop und Mobil. Die Auswahl war im Gerätedetail verfügbar. Der Bestand enthielt zum Prüfzeitpunkt keinen registrierten Hypervisor. [Geräteansicht](../web/src/device-hypervisor.tsx) · [Hostsuche](../crates/server/src/hypervisors.sql) |
|
||||
| Von der Auswahl zur Ausgabe | Die WebUI bindet die ausgewählte Skriptversion, zeigt den Inhalt vor Genehmigung und verlinkt das Ergebnis je Gerät. Ein abgelehnter Antrag erzeugte null Jobs. [Auftragsablauf](evidence/webui-auftragsablauf-20261117.json) · [Ergebnislinks und Entscheidungen](evidence/webui-order-history-20261118.json) Auf OTRS ARM64 wurde der Root-Skript-Helper nachträglich mit dem HTTPS-Installer aktiviert. Die zentrale Geräteregel bindet das berechtigte WebUI-Konto an diese Installation und den signierten Helper. Die öffentliche WebUI-Vorschau akzeptierte Root für OTRS. Die Probe blieb bei einer Vorschau und erzeugte null Anträge, Jobs, Outbox-Einträge und Startgrants. [OTRS-Nachweis](evidence/linux-arm64-otrs-root-helper-20261118.json) |
|
||||
| Frische Installation und periodisches Agentupdate | Beide VMs wurden über HTTPS aufgenommen und übernahmen anschließend ein signiertes Folgepaket mit derselben Geräteidentität. Auf Windows ist der öffentliche GNU-Kanal einschließlich Prüfung des offiziellen Schlüssels belegt. [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows GNU](evidence/windows-gnu-official-vm-20261118.json). ARM64 erweitert denselben HTTPS-Installer mit automatischer Architekturerkennung. Release `0.1.0-arm64.1` ist veröffentlicht und als Starter verfügbar. Auf Ubuntu 22.04.5 ARM64 wurden die öffentlichen Downloads, die Signaturprüfung, die Ablehnung einer veränderten Agentdatei und der native Start aller drei Dateien im Prüfmodus beobachtet. OTRS ist mit Gerätezertifikat aufgenommen und meldet authentisierte Heartbeats. Die erste Kontaktprüfung wartet seit der Korrektur auf das Zertifikat. Der öffentliche Installer lief auf OTRS erneut ohne Traceback und ohne neuen Einmalcode. Der ARM64-Katalogabruf ist bestätigt. Ein späterer Versionswechsel auf ARM64 steht aus. [ARM64-Release](evidence/linux-arm64-installer-20261118.json) · [Geräteaufnahme und Nachtest](evidence/linux-arm64-enrollment-heartbeat-20261118.json) |
|
||||
| Erste Windows-Meldung ohne `DisplayVersion` | Bei einem betroffenen Gerät nahm das Gateway das Enrollment und die authentisierten Verbindungsaufbauten an, erhielt aber weder Inventar noch Heartbeat. Windows GNU `0.1.26` aus `037b5e3` nutzt bei fehlendem `DisplayVersion` den Registrywert `ReleaseId` oder meldet Produkt und Build ohne Versionsbezeichnung. Drei Regressionen und die Inventarprobe liefen nativ auf der Windows-Test-VM. Das offiziell signierte Paket (Sequenz 27) ist im Katalog des betroffenen Kunden und als Starter für neue Windows-Kataloge verfügbar. Die Test-VM übernahm das reguläre Update, meldete einen neuen Heartbeat mit derselben Identität und startete beide signierten Binärdateien mit den erwarteten Hashes. Die erneute Meldung des betroffenen Geräts mit derselben Identität steht aus. Bei durch den Erstkontakt blockiertem Installer den vorhandenen `RmmDiscoveryReleasePull` lokal starten; nach erfolgreichem Update den Installer mit derselben Identität abschließen. [Nachweis](evidence/windows-missing-display-version-20261119.json) |
|
||||
| Betriebssystemupdate per PowerShell | Die Windows-Updatevorlage installierte KB890830 v5.147 als SYSTEM. Ergebnis und Windows-Ereignis 19 bestätigen die Installation. [Installationsbeleg](evidence/windows-update-installation-20261117.json) |
|
||||
| Windows im Leerlauf | Windows GNU `0.1.20` aus `a4bcebf` aktualisiert den signierten Zeitbeleg des Helpers nach erfolgreicher Abfrage im Abstand von fünf Sekunden. Der Testgast übernahm das Paket mit derselben Geräteidentität. Im Leerlauf sank die CPU-Last des Agenten von 15,20 % auf 2,30 % und die des Helpers von 15,67 % auf 2,72 %. Der in der internen Entwicklungs-WebUI genehmigte PowerShell-Testauftrag meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. Beide Dienste blieben synchron. [Leerlaufmessung und SYSTEM-Test](evidence/windows-idle-cpu-20261118.json) Am 19.11. senkte `0.1.24` im jeweils 91 Sekunden langen Leerlauftest die Gast-CPU-Last von 3,15 % auf 0,71 % beim Agenten und von 11,82 % auf 0,84 % beim Helper. Die Lastspitzen fielen mit wiederholten Vollprüfungen großer SQLite-Dateien und der kompletten signierten Helperhistorie zusammen. Der Agent prüft im Leerlauf alle 250 ms auf Arbeit. Vollprüfungen bleiben für anstehende SYSTEM-Aufträge und den Nachweis unterbliebener Ausführung erhalten. Der Testgast übernahm das signierte Paket mit denselben Geräte- und Agentenkennungen. Der erneut in der Entwicklungs-WebUI genehmigte SYSTEM-Test meldete `S-1-5-18` mit Exitcode 0 und einem Startgrant. [Folgemessung und Abnahme](evidence/windows-idle-cpu-followup-20261119.json) Der lokale Windows-Zeitstatus konnte am 19. November lesend unter LocalService abgefragt werden. Der Testgast meldete Synchronisierung mit Stratum 5 bei rund 105 Minuten seit der letzten erfolgreichen Synchronisierung. Das Betriebsprotokoll lieferte knapp acht Stunden alte Statusdaten. Der direkt geprüfte Pipe-Handle gehörte zu W32Time. Für die tatsächliche Statusverbindung und den SYSTEM-Helper steht die native Qualifikation aus. Die Umstellung war bei dieser Diagnose offen. Agent und SYSTEM-Helper meldeten mit Version `0.1.24` weiterhin Bereitschaft. [Zeitstatus und Prüfergebnis](evidence/windows-local-clock-20261119.json) Windows GNU `0.1.25` aus `b002202` prüft die Systemzeit bei regulär aufgenommenen Geräten lokal über W32Time. Agent und SYSTEM-Helper prüfen unabhängig die Identität der Statusverbindung, den Synchronisationsstatus, den Zeitfehler und die Kontinuität. 17 native Uhrtests bestanden. Der Testgast übernahm das signierte Paket mit unveränderter Geräteidentität und bestätigte beide laufenden Binärhashes. Die in der Entwicklungs-WebUI genehmigten Aufträge lieferten je einen Startgrant, Exitcode 0 und `S-1-5-18` für SYSTEM beziehungsweise `S-1-5-19` für LocalService. Im Mittel aus jeweils zwei rund 91 Sekunden langen Leerlaufmessungen sank die Gast-CPU-Last von 0,96 % auf 0,33 % beim Agenten und von 0,92 % auf 0,40 % beim Helper. [Native Abnahme der lokalen Uhrprüfung](evidence/windows-local-clock-release-20261119.json) |
|
||||
| Wiederanlauf | Nach einem Gatewaywechsel wurde der Windows-Agent ohne manuellen Dienstneustart wieder bereit. Der Helper glich seine bereits quittierte Ergebnismeldung ab. [Gatewaywechsel](evidence/windows-gateway-clock-recovery-20261117.json) · [Helper-Abgleich](evidence/windows-helper-result-recovery-20261118.json) |
|
||||
| WebUI-Abschluss eines ungeklärten Versuchs | Auf OTRS ARM64 war derselbe Versuch zentral als `closed_unknown` abgeschlossen und lokal wegen unterschiedlicher Befunde noch blockiert. Der Agent hatte eine archivierte Unterbrechungsmeldung, beide Verbrauchsjournale hatten den ursprünglichen Start und kein Ergebnis. 71 Tests zu `915e126` prüfen den signierten Abschluss in Agent und Helper, den Erhalt der Originale und den Wiederanlauf nach unterbrochenen Journalaktualisierungen. Am 18. November um 18:05 UTC startete das bestehende Gerät einmal kontrolliert unter exklusiver Startsperre mit dem über mTLS abgerufenen signierten Paar `0.1.0-arm64.3`. Beide Verbrauchsjournale übernahmen den bereits vorhandenen WebUI-Abschluss. Die archivierte Originalmeldung, die Startbelege und die Geräteidentität waren unverändert nachweisbar. Der native Updater meldete `idle`, Agent und Helper waren nach dem Abgleich bereit und der reguläre Updatetimer war aktiv. Linux x64 übernahm `0.1.0-mvp.9` über den regulären Timer. [Geräteabgleich](../crates/agent-core/tests/reconcile.rs) |
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Produktentscheidungen
|
||||
|
||||
## Lokaler Zeitstatus für Windows-Aufträge · 19. November 2026
|
||||
|
||||
Die Uhrprüfung des Windows-Agenten und des SYSTEM-Helpers soll denselben Zweck und dieselbe Vertrauensbasis wie unter Linux haben. Beide Prozesse prüfen vor zeitgebundenen Auftragsentscheidungen die lokale Betriebssystemuhr auf Synchronisierung, Unsicherheit und Zeitsprünge. Die Prüfung muss mit den bestehenden Dienstkonten auskommen. Mit der Umstellung entfallen die separaten signierten RMM-Zeitabfragen für diese Prozesse. Signaturen, Genehmigung sowie Zeit- und Versuchsbindung der Aufträge gelten weiterhin.
|
||||
|
||||
Der signierte Zeitvergleich wurde am 14. November als Windows-Ausweichlösung vereinbart, nachdem der Statusabruf und die Herkunft des abgerufenen Status offen geblieben waren. Die erste Diagnose am 19. November bestätigte die lesende Abfrage als LocalService und die Identität des Zeitdienstes am separat geöffneten Pipe-Handle. Der damalige Kandidat verlangte einen höchstens 60 Minuten alten Abgleich. Der Testgast meldete rund 105 Minuten. [Erste Diagnose](evidence/windows-local-clock-20261119.json)
|
||||
|
||||
Der lokale Adapter verwendet die Pipe, deren Serverprozess er über die Windows-Dienstverwaltung W32Time zuordnet, für die gesamte verschlüsselte und signierte Statusabfrage. Er verwendet die gemeldete Synchronisierung und den Zeitpunkt des letzten erfolgreichen Abgleichs. Ein ausgefallener Abruf oder ein älteres Paket des Zeitservers kann die Synchronisierung weiter gültig lassen, solange der letzte erfolgreiche Abgleich und die Fehlergrenze sie tragen. Die Prüfung berücksichtigt die mit dem Alter wachsende Unsicherheit. Jeder Prozess hält einen gültigen Status höchstens fünf Sekunden im Speicher und prüft bei seiner Verwendung erneut die Kontinuität der lokalen Uhr. Die Auftragsausführung setzt die lokale W32Time-Pipe und die dafür verwendete NTLM-Authentisierung voraus. [Windows-Zeitstatus](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/f60ebce0-df96-4c96-b40b-fdbd34a2c936) · [NTP-Fehlermodell](https://www.rfc-editor.org/rfc/rfc5905#section-9)
|
||||
@@ -8,11 +8,17 @@ 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)
|
||||
|
||||
### 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
|
||||
|
||||
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.
|
||||
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.
|
||||
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. 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.
|
||||
|
||||
|
||||
@@ -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;
|
||||
$$;
|
||||
@@ -232,6 +232,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' };
|
||||
let state = '';
|
||||
let canEnroll = false;
|
||||
let posts = 0;
|
||||
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: {
|
||||
@@ -257,14 +258,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-rmm-tenant']).toBe(source.tenant_id);
|
||||
expect(url.searchParams.get('agent_id')).toBe(device.agent_id);
|
||||
if (url.pathname === move) {
|
||||
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
|
||||
state = 'pending';
|
||||
} else {
|
||||
expect(url.pathname).toBe(move + '/move-fixture/complete');
|
||||
expect(state).toBe('ready');
|
||||
state = 'completed';
|
||||
}
|
||||
expect(url.pathname).toBe(move);
|
||||
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
|
||||
posts++;
|
||||
state = 'pending';
|
||||
return r.fulfill({ json: { state } });
|
||||
}
|
||||
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
||||
@@ -275,20 +272,99 @@ test('moves an existing pairing through the WebUI and waits for target inventory
|
||||
await page.getByText('Kunden wechseln', { exact: true }).click();
|
||||
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();
|
||||
const prepare = page.getByRole('button', { name: 'Kundenwechsel vormerken' });
|
||||
const prepare = page.getByRole('button', { name: 'Kundenwechsel starten' });
|
||||
await expect(prepare).toBeDisabled();
|
||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
|
||||
canEnroll = true;
|
||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
||||
await prepare.click();
|
||||
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
|
||||
const finish = page.getByRole('button', { name: 'Kundenwechsel abschließen' });
|
||||
await expect(finish).toHaveCount(0);
|
||||
state = 'ready';
|
||||
await expect(finish).toBeDisabled({ timeout: 10000 });
|
||||
await page.getByRole('checkbox', { name: 'Ich bestätige den Kundenwechsel für dieses Gerät.' }).check();
|
||||
await finish.click();
|
||||
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible();
|
||||
await expect(page.getByRole('link', { name: 'Neue Kopplung öffnen' })).toHaveAttribute('href',
|
||||
const destination = page.getByRole('link', { name: 'Neue Kopplung öffnen' });
|
||||
state = 'enrolled';
|
||||
await expect(page.getByText('Der Wechsel wird mit der ersten Inventarmeldung', { exact: false }))
|
||||
.toBeVisible({ timeout: 10000 });
|
||||
await expect(destination).toHaveCount(0);
|
||||
state = 'completed';
|
||||
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible({ timeout: 10000 });
|
||||
await expect(destination).toHaveAttribute('href',
|
||||
'#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');
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
from local_access_database import command
|
||||
@@ -40,6 +41,27 @@ def until(probe, seconds=80):
|
||||
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):
|
||||
pg_password = secrets.token_hex(24)
|
||||
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 SCHEMA public OWNER TO rmm_migrator;""")
|
||||
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")
|
||||
|
||||
users, login_data = [], {}
|
||||
@@ -149,6 +174,19 @@ def run(server, agent, folder, db, api):
|
||||
return headers
|
||||
|
||||
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_path = folder / "enrollment"
|
||||
token_path.write_text(token)
|
||||
@@ -201,13 +239,15 @@ def run(server, agent, folder, db, api):
|
||||
finally:
|
||||
proc.send_signal(signal.SIGCONT)
|
||||
|
||||
def target_ready():
|
||||
def target_completed():
|
||||
status, dto, _ = request(transfer + query, headers=owner)
|
||||
assert status == 200, (status, dto)
|
||||
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"]
|
||||
target_agent, target_asset = moved["target_agent_id"], moved["target_asset_id"]
|
||||
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 not list(state.glob("customer-move-*-prior-journal.sqlite"))
|
||||
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")
|
||||
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
|
||||
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"])
|
||||
@@ -231,6 +276,19 @@ def run(server, agent, folder, db, api):
|
||||
assert sql(f"SELECT count(*) FROM observations WHERE tenant_id='{A}' AND agent_id='{old_agent}';") != "0"
|
||||
print("PASS source certificate revoked, source history preserved and target inventory isolated")
|
||||
|
||||
def generation():
|
||||
return int(sql(f"SELECT connection_generation FROM agent_installations WHERE agent_id='{target_agent}';"))
|
||||
|
||||
previous_generation = generation()
|
||||
proc.terminate()
|
||||
proc.wait(timeout=12)
|
||||
proc = subprocess.Popen([agent], env=config, stdout=log, stderr=log)
|
||||
until(lambda: generation() > previous_generation, 30)
|
||||
active = json.loads((state / "identity.json").read_text())
|
||||
assert active["agent_id"] == target_agent
|
||||
assert request("/agent/v1/customer-transfer", tls=old_context)[0] == 401
|
||||
print("PASS restart preserves the new pairing using the original installer configuration")
|
||||
|
||||
tokens = f"/api/v1/tenants/{A}/mcp-tokens"
|
||||
for audience, allowed_tenants in [("selected", [A]), ("all", [])]:
|
||||
status, issued, _ = request(tokens, {
|
||||
@@ -242,6 +300,7 @@ def run(server, agent, folder, db, api):
|
||||
status, fleet, _ = request("/api/v1/devices?view=current", headers=bearer)
|
||||
assert status == 200
|
||||
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}"
|
||||
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
|
||||
|
||||
@@ -5,11 +5,10 @@ import { allowed } from './safety';
|
||||
|
||||
type Transfer = {
|
||||
id: string;
|
||||
state: 'pending' | 'enrolled' | 'ready' | 'completed';
|
||||
state: 'pending' | 'enrolled' | 'completed';
|
||||
tenant: string;
|
||||
asset: string | null;
|
||||
agent: string | null;
|
||||
hostname: string | null;
|
||||
};
|
||||
|
||||
function parseTransfer(value: unknown): Transfer | null {
|
||||
@@ -17,14 +16,13 @@ function parseTransfer(value: unknown): Transfer | null {
|
||||
const t = record(value);
|
||||
const { transfer_id: id, target_tenant_id: tenant, state } = t;
|
||||
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.');
|
||||
}
|
||||
return {
|
||||
id, tenant, state,
|
||||
asset: typeof t.target_asset_id === 'string' ? t.target_asset_id : null,
|
||||
agent: typeof t.target_agent_id === 'string' ? t.target_agent_id : null,
|
||||
hostname: typeof t.target_hostname === 'string' ? t.target_hostname : null
|
||||
agent: typeof t.target_agent_id === 'string' ? t.target_agent_id : null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,7 +33,6 @@ function transferError(error: unknown) {
|
||||
TRANSFER_ALREADY_PENDING: 'Für dieses Gerät ist bereits ein Kundenwechsel vorgemerkt.',
|
||||
TRANSFER_ALREADY_STARTED: 'Der Agent übernimmt bereits die neue Kopplung.',
|
||||
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.',
|
||||
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.'
|
||||
@@ -56,7 +53,6 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [target, setTarget] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const base = tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/customer-transfer');
|
||||
@@ -80,7 +76,6 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
||||
setError(null);
|
||||
try {
|
||||
await request(base + suffix + query, { csrf: auth.csrf_token, tenantId: customer, body });
|
||||
setConfirmed(false);
|
||||
status.reload();
|
||||
} catch (e) {
|
||||
setError(transferError(e));
|
||||
@@ -99,17 +94,9 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
||||
<button disabled={busy} className="quiet"
|
||||
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 === '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 === 'enrolled' && <p role="status">Der Wechsel wird mit der ersten Inventarmeldung beim Zielkunden abgeschlossen.</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('/')}>
|
||||
Neue Kopplung öffnen
|
||||
</a>}
|
||||
@@ -126,7 +113,7 @@ export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers
|
||||
</select></label>
|
||||
{target && (destination.error || destination.data && !canEnroll) &&
|
||||
<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>
|
||||
</> : <p>Für diese Sitzung ist kein weiterer Kunde verfügbar.</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>;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { CatalogCheckNotice } from './catalog-check';
|
||||
import { devicePlatform } from './script-catalog';
|
||||
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
||||
import { DeviceCustomerTransfer } from './device-customer-transfer';
|
||||
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
import { NavIcon, orderDetailRoute } from './navigation';
|
||||
import { orderTitle, Status } from './order-presentation';
|
||||
@@ -206,6 +207,7 @@ function DeviceDetail({
|
||||
<div>
|
||||
<h1>{label(d.hostname)}</h1>
|
||||
<Presence d={d} />
|
||||
<HypervisorLabel device={d} />
|
||||
</div>
|
||||
</div>
|
||||
<section>
|
||||
@@ -280,6 +282,8 @@ function DeviceDetail({
|
||||
<details open={managing} onToggle={e => setManaging(e.currentTarget.open)}>
|
||||
<summary>Gerät verwalten</summary>
|
||||
<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}
|
||||
customers={customers} active={d.lifecycle === 'current'}
|
||||
supported={Array.isArray(d.capabilities) && d.capabilities.includes('device.customer_transfer/1')} />
|
||||
@@ -601,6 +605,7 @@ export function Devices({
|
||||
>
|
||||
{label(d.hostname)}
|
||||
</button>
|
||||
<HypervisorLabel device={d} />
|
||||
</td>
|
||||
<td data-label="Type">{label(d.device_type)}</td>
|
||||
<td data-label="OS">{label(d.os)}</td>
|
||||
|
||||
@@ -94,6 +94,8 @@ section.fleet { padding:0; overflow:hidden; }
|
||||
.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; }
|
||||
.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 td[data-label="Type"] { overflow-wrap:anywhere; }
|
||||
.fleet-table input[type=checkbox] { margin:0; }
|
||||
|
||||
Reference in New Issue
Block a user