Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a9eafbff1 | ||
|
|
f01e81418e | ||
|
|
d4cbc40979 | ||
|
|
478ee1fc1a | ||
|
|
01960477f8 | ||
|
|
480e3749a6 | ||
|
|
65d84a19c0 | ||
|
|
cad188aeb7 | ||
|
|
bcd3bd86ad | ||
|
|
08177d8843 | ||
|
|
2378a54bd4 | ||
|
|
9e957e6d8d | ||
|
|
5253a9f596 | ||
|
|
dd59052e7c | ||
|
|
a4bcebf440 | ||
|
|
db6325131a | ||
|
|
1f60183b7e | ||
|
|
55d159cab1 | ||
|
|
aea2d5b379 | ||
|
|
38f43f887a | ||
|
|
915e126f24 | ||
|
|
abad2022e2 | ||
|
|
6ed57c4d0b | ||
|
|
7006ce7420 | ||
|
|
b3fe35b86b | ||
|
|
fb2376443c | ||
|
|
f2a2d44d84 | ||
|
|
7215ea9733 | ||
|
|
b5907d681d | ||
|
|
4b3d0136e9 | ||
|
|
bfdc3da8af | ||
|
|
6d15f1b3f5 | ||
|
|
8b5365f4bc | ||
|
|
247646a2ba |
@@ -8,6 +8,7 @@ Der abgenommene MVP liegt auf dem Branch `main`. Der [Produktvertrag](Rust_RMM_I
|
||||
2. In der [Übergabe](docs/handover.md) den betroffenen Einstiegspunkt finden. Vor Änderungen den tatsächlichen Aufrufer, die Berechtigungsprüfung und die vorhandenen Tests lesen. Ein datierter Beleg in `docs/evidence/` dokumentiert das Ereignis zu seinem Messzeitpunkt.
|
||||
3. Den normalen Bedienweg und den konkreten Fehlerfall prüfen. Bei einem Linux- oder Windows-spezifischen Verhalten den betreffenden Gast verwenden. Ein Build belegt die Erzeugung des Artefakts. Das Ergebnis des Zielgeräts belegt seine Wirkung.
|
||||
4. Verändert sich das Produktverhalten, die zuständige Anleitung und den Produktvertrag abgleichen. Eine neue Abnahme im [Prüfstand](docs/mvp-completion-plan.md) mit Quelle, Ziel und beobachtetem Ergebnis nachtragen.
|
||||
5. Nach jeder abgeschlossenen Änderung die zugehörigen Dateien committen und auf den passenden Branch in Gitea pushen. Das gilt auch für reine Dokuänderungen. Den gepushten Commit in Gitea prüfen. [Entwicklungsablauf](docs/development.md#änderungen-in-gitea-sichern)
|
||||
|
||||
## Regeln für Änderungen
|
||||
|
||||
|
||||
Generated
+1
@@ -2189,6 +2189,7 @@ dependencies = [
|
||||
"hex",
|
||||
"openssl",
|
||||
"prost",
|
||||
"reqwest",
|
||||
"rmm-domain",
|
||||
"rmm-protocol",
|
||||
"rmm-updater-handoff",
|
||||
|
||||
@@ -10,7 +10,15 @@ Jede Installation ist an Kunde, Gerät und Agentenidentität gebunden. Die Stand
|
||||
|
||||
Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` bezeichnet einen physischen Rechner, `virtual` ein virtualisiertes System und `hypervisor` eine erkannte Hostrolle. Proxmox VE erscheint als `hypervisor` mit `Proxmox VE` in der Spalte OS. Eine erkannte Hostrolle hat Vorrang, auch bei verschachtelter Virtualisierung. Bei fehlender Angabe zeigt die WebUI „Nicht gemeldet“. Die Geräteabfragen in WebUI und MCP verwenden denselben gespeicherten Typ. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
Kunden lassen sich in der WebUI anlegen und umbenennen. Beim Kundenwechsel erhält das Gerät eine 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)
|
||||
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. 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)
|
||||
|
||||
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
|
||||
|
||||
## Vom Skript zum Ergebnis
|
||||
|
||||
@@ -24,7 +32,7 @@ Kunden lassen sich in der WebUI anlegen und umbenennen. Beim Kundenwechsel erhä
|
||||
|
||||
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)
|
||||
|
||||
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. Dieser Abschluss erteilt keine Freigabe für einen weiteren Versuch.
|
||||
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
|
||||
|
||||
@@ -38,6 +46,6 @@ Für administrative Skripte gilt zusätzlich das Plattformrecht `root:execute` o
|
||||
|
||||
Die WebUI erzeugt einen kundengebundenen Einmalcode und zeigt die HTTPS-Installationsanleitung für die verfügbare Plattform. Zum Erstbezug braucht das Gerät eine vertrauenswürdige TLS-Verbindung. Der Installer prüft Vertrauensmaterial und Release, richtet die lokalen Dienste ein und nimmt das Gerät auf. Anschließend verwendet die Installation ihre eigene Identität. Der lokale Administrator richtet den privilegierten Skript-Helper ein, wenn das Gerät auch Administratoraufträge erhalten soll. [Serverseitiger Bootstrap](crates/server/src/bootstrap)
|
||||
|
||||
Der Server stellt je Kunde und Plattform Agent und Helper mit einem gemeinsam signierten Manifest bereit. Das Manifest bindet die Hashes und Größen der Binärdateien. Für die Erstaufnahme liefert der Server auch den passenden Bootstrap-Updater. Linux x64 verwendet den GNU/Linux-Kanal, Windows x64 offiziell `x86_64-pc-windows-gnu`. Der lokale Updater fragt regelmäßig nach einer neueren veröffentlichten Generation, prüft die Bindung an Plattform, Schlüsselring, Releasefolge und Binärhashes und aktiviert das geprüfte Paar unter derselben Geräteidentität. Auf Linux steuert ein systemd-Timer den Abruf, auf Windows ein eigener Updatedienst.
|
||||
Der Server stellt je Kunde und Plattform Agent und Helper mit einem gemeinsam signierten Manifest bereit. Das Manifest bindet die Hashes und Größen der Binärdateien. Für die Erstaufnahme liefert der Server auch den passenden Bootstrap-Updater. Das gemeinsame Linux-Installationsskript erkennt x86-64 und ARM64 auf dem Zielgerät. Beide GNU/Linux-Architekturen haben einen eigenen Releasekanal, Signierschlüssel und Bootstrap-Pin. Windows x64 verwendet offiziell `x86_64-pc-windows-gnu`. Der lokale Updater fragt regelmäßig nach einer neueren veröffentlichten Generation, prüft die Bindung an Plattform, Schlüsselring, Releasefolge und Binärhashes und aktiviert das geprüfte Paar unter derselben Geräteidentität. Auf Linux steuert ein systemd-Timer den Abruf, auf Windows ein eigener Updatedienst.
|
||||
|
||||
Für Erstinstallation und Update muss das Manifest zum Prüfzeitpunkt gültig sein. Beim bereits installierten Administrator-Helper prüft der Server die Gültigkeit zum gespeicherten Registrierungszeitpunkt des Releases und die Signatur gegen den aktuellen Schlüsselring. Der Ablauf des Manifests allein blockiert daher keinen Adminauftrag auf diesem Client. [Releaseprüfung](crates/server/src/agent_updates.rs) · [Build und Veröffentlichung](docs/development.md)
|
||||
|
||||
@@ -20,6 +20,7 @@ rmm-domain = { path = "../domain" }
|
||||
rmm-protocol = { path = "../protocol" }
|
||||
rmm-updater-handoff = { path = "../updater-handoff" }
|
||||
rusqlite.workspace = true
|
||||
reqwest.workspace = true
|
||||
ed25519-dalek = "=2.2.0"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
//! A handoff changes the installation, not the old journal or its trust.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use reqwest::Client;
|
||||
use rmm_domain::customer_transfer::{CertificateRequest, CertificateResponse, Offer};
|
||||
use rmm_protocol::EnrollmentResponse;
|
||||
use serde::{Deserialize, de::DeserializeOwned};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
const PREFIX: &str = "customer-move-";
|
||||
const INTENT: &str = "customer-move-intent.json";
|
||||
const MAX_RECORD: usize = 32768;
|
||||
|
||||
pub fn idle(journal: &rusqlite::Connection, ledger: &rusqlite::Connection) -> Result<bool> {
|
||||
let busy: bool = journal.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN (
|
||||
'accepted','requesting','running','verifying','unknown','awaiting_reboot'))",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let consumed: bool = ledger.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM consumed WHERE result IS NULL)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
// The new customer executes under the same service account. Retire
|
||||
// local history only after the old installation has delivered its work.
|
||||
if busy || consumed {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(crate::jobs::events(journal)?.iter().all(|event| {
|
||||
matches!(
|
||||
event.payload,
|
||||
Some(rmm_protocol::Payload::InventorySnapshot(_))
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<Vec<u8>> {
|
||||
let info = fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
info.is_file() && !info.file_type().is_symlink() && info.len() <= MAX_RECORD as u64,
|
||||
"TRANSFER_RECORD"
|
||||
);
|
||||
let mut data = Vec::new();
|
||||
File::open(path)?
|
||||
.take(MAX_RECORD as u64 + 1)
|
||||
.read_to_end(&mut data)?;
|
||||
ensure!(data.len() <= MAX_RECORD, "TRANSFER_RECORD");
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn sync_dir(path: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
File::open(path)?.sync_all()?;
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
if path.try_exists()? {
|
||||
ensure!(read(path)? == bytes, "TRANSFER_RECORD_CONFLICT");
|
||||
return Ok(());
|
||||
}
|
||||
let dir = path.parent().context("TRANSFER_RECORD_PARENT")?;
|
||||
let temporary = dir.join(format!("{PREFIX}tmp-{}", Uuid::new_v4()));
|
||||
let result = (|| {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)?;
|
||||
sync_dir(dir)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(temporary);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn file(dir: &Path, id: Uuid, role: &str) -> PathBuf {
|
||||
dir.join(format!("{PREFIX}{id}-{role}"))
|
||||
}
|
||||
|
||||
fn verify(response: &CertificateResponse, signer: &str) -> Result<()> {
|
||||
let binding = &response.receipt.binding;
|
||||
let signature = Signature::from_slice(&hex::decode(&response.receipt.signature_hex)?)?;
|
||||
let public: [u8; 32] = hex::decode(signer)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("TRANSFER_SIGNER"))?;
|
||||
VerifyingKey::from_bytes(&public)?.verify_strict(&binding.signing_bytes()?, &signature)?;
|
||||
ensure!(
|
||||
binding.offer.source_tenant_id != binding.offer.target_tenant_id
|
||||
&& binding.agent_id != binding.offer.source_agent_id
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.certificate_sha256
|
||||
== rmm_domain::jobs::hash(response.certificate_pem.as_bytes()),
|
||||
"TRANSFER_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn json<T: DeserializeOwned>(mut response: reqwest::Response) -> Result<T> {
|
||||
ensure!(response.status().is_success(), "TRANSFER_HTTP");
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
ensure!(
|
||||
bytes.len() + chunk.len() <= MAX_RECORD,
|
||||
"TRANSFER_RESPONSE_SIZE"
|
||||
);
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
pub async fn stage(
|
||||
client: &Client,
|
||||
origin: &str,
|
||||
dir: &Path,
|
||||
current: &crate::auth::Binding,
|
||||
key_and_csr: impl FnOnce(Option<&[u8]>) -> Result<(Vec<u8>, String)>,
|
||||
) -> Result<bool> {
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
offer: Option<Offer>,
|
||||
}
|
||||
let route = format!("{origin}/agent/v1/customer-transfer");
|
||||
let response = client
|
||||
.get(&route)
|
||||
.timeout(Duration::from_secs(4))
|
||||
.send()
|
||||
.await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(false); // agent updates can precede the server upgrade
|
||||
}
|
||||
let Some(offer) = json::<Response>(response).await?.offer else {
|
||||
return Ok(false);
|
||||
};
|
||||
ensure!(
|
||||
offer.source_agent_id == current.agent_id
|
||||
&& offer.source_tenant_id == current.tenant_id
|
||||
&& offer.target_tenant_id != current.tenant_id
|
||||
&& !offer.transfer_id.is_nil(),
|
||||
"TRANSFER_SOURCE"
|
||||
);
|
||||
let id = offer.transfer_id;
|
||||
let key_path = file(dir, id, "key.pem");
|
||||
let previous = key_path
|
||||
.try_exists()?
|
||||
.then(|| read(&key_path))
|
||||
.transpose()?;
|
||||
let (key, csr_pem) = key_and_csr(previous.as_deref())?;
|
||||
publish(&key_path, &key)?;
|
||||
let response = json::<CertificateResponse>(
|
||||
client
|
||||
.post(format!("{route}/{id}/certificate"))
|
||||
.timeout(Duration::from_secs(10))
|
||||
.json(&CertificateRequest { csr_pem })
|
||||
.send()
|
||||
.await?,
|
||||
)
|
||||
.await?;
|
||||
verify(&response, ¤t.public_key_hex)?;
|
||||
ensure!(
|
||||
response.receipt.binding.offer == offer,
|
||||
"TRANSFER_OFFER_CHANGED"
|
||||
);
|
||||
publish(
|
||||
&file(dir, id, "response.json"),
|
||||
&serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn archive(dir: &Path, id: Uuid) -> Result<()> {
|
||||
for item in fs::read_dir(dir)? {
|
||||
let item = item?;
|
||||
let name = item.file_name();
|
||||
if name.to_string_lossy().starts_with(PREFIX)
|
||||
|| ["agent.lock", "job-signing-key.json"]
|
||||
.iter()
|
||||
.any(|kept| name == *kept)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if name == "jobs" && item.file_type()?.is_dir() {
|
||||
// Keep the installer-owned directory and its Windows ACL.
|
||||
archive(&item.path(), id)?;
|
||||
continue;
|
||||
}
|
||||
let mut backup = std::ffi::OsString::from(format!("{PREFIX}{id}-prior-"));
|
||||
backup.push(name);
|
||||
let target = dir.join(backup);
|
||||
ensure!(!target.try_exists()?, "TRANSFER_ARCHIVE_EXISTS");
|
||||
fs::rename(item.path(), target)?;
|
||||
}
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
fn retire_prior_state(dir: &Path, id: Uuid) -> Result<()> {
|
||||
let prefix = format!("{PREFIX}{id}-prior-");
|
||||
for item in fs::read_dir(dir)? {
|
||||
let item = item?;
|
||||
let name = item.file_name();
|
||||
if name == "jobs" && item.file_type()?.is_dir() {
|
||||
retire_prior_state(&item.path(), id)?;
|
||||
} else if name.to_string_lossy().starts_with(&prefix) {
|
||||
if item.file_type()?.is_dir() {
|
||||
fs::remove_dir_all(item.path())?;
|
||||
} else {
|
||||
fs::remove_file(item.path())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
pub fn pending(dir: &Path) -> Result<bool> {
|
||||
Ok(dir.join(INTENT).try_exists()?)
|
||||
}
|
||||
|
||||
pub fn activate(dir: &Path, signer: &str) -> Result<()> {
|
||||
let intent = dir.join(INTENT);
|
||||
if !intent.try_exists()? {
|
||||
return Ok(());
|
||||
}
|
||||
let id: Uuid = serde_json::from_slice(&read(&intent)?)?;
|
||||
let response_file = file(dir, id, "response.json");
|
||||
let data = read(&response_file)?;
|
||||
let response: CertificateResponse = serde_json::from_slice(&data)?;
|
||||
let binding = &response.receipt.binding;
|
||||
verify(&response, signer)?;
|
||||
ensure!(binding.offer.transfer_id == id, "TRANSFER_INTENT");
|
||||
let relocated = file(dir, id, "relocated");
|
||||
if !relocated.try_exists()? {
|
||||
let current: EnrollmentResponse =
|
||||
serde_json::from_slice(&read(&dir.join("identity.json")).or_else(|error| {
|
||||
let backup = file(dir, id, "prior-identity.json");
|
||||
if backup.exists() {
|
||||
read(&backup)
|
||||
} else {
|
||||
Err(error)
|
||||
}
|
||||
})?)?;
|
||||
ensure!(
|
||||
current.agent_id == binding.offer.source_agent_id.to_string(),
|
||||
"TRANSFER_SOURCE"
|
||||
);
|
||||
archive(dir, id)?;
|
||||
publish(&relocated, b"ok")?;
|
||||
}
|
||||
let key_file = file(dir, id, "key.pem");
|
||||
let identity = EnrollmentResponse {
|
||||
agent_id: binding.agent_id.to_string(),
|
||||
asset_id: binding.asset_id.to_string(),
|
||||
certificate_pem: response.certificate_pem,
|
||||
};
|
||||
publish(&dir.join("device.key"), &read(&key_file)?)?;
|
||||
publish(&dir.join("device.pem"), identity.certificate_pem.as_bytes())?;
|
||||
publish(&dir.join("identity.json"), &serde_json::to_vec(&identity)?)?;
|
||||
publish(&file(dir, binding.agent_id, "active.json"), &data)?;
|
||||
// Do not expose old-tenant credentials or job outputs to scripts running
|
||||
// under this same local service account in the new tenant.
|
||||
retire_prior_state(dir, id)?;
|
||||
fs::remove_file(intent)?;
|
||||
sync_dir(dir)?;
|
||||
// The live private key is durable. This copy only existed for upload retry.
|
||||
let _ = fs::remove_file(key_file);
|
||||
let _ = fs::remove_file(response_file);
|
||||
let _ = fs::remove_file(relocated);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn assigned_tenant(
|
||||
dir: &Path,
|
||||
identity: &EnrollmentResponse,
|
||||
signer: &str,
|
||||
) -> Result<Option<Uuid>> {
|
||||
let path = file(dir, Uuid::parse_str(&identity.agent_id)?, "active.json");
|
||||
if !path.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let response: CertificateResponse = serde_json::from_slice(&read(&path)?)?;
|
||||
verify(&response, signer)?;
|
||||
let binding = response.receipt.binding;
|
||||
ensure!(
|
||||
response.certificate_pem == identity.certificate_pem
|
||||
&& binding.agent_id.to_string() == identity.agent_id
|
||||
&& binding.asset_id.to_string() == identity.asset_id,
|
||||
"TRANSFER_ACTIVE_IDENTITY"
|
||||
);
|
||||
Ok(Some(binding.offer.target_tenant_id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use rmm_domain::customer_transfer::{Binding, Receipt};
|
||||
|
||||
#[test]
|
||||
fn authenticated_handoff_recovers_partial_archive_and_isolates_local_state() -> Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("rmm-transfer-{}", Uuid::new_v4()));
|
||||
fs::create_dir(&dir)?;
|
||||
let result = (|| {
|
||||
let id = Uuid::new_v4();
|
||||
let source = Uuid::new_v4();
|
||||
let target = Uuid::new_v4();
|
||||
let previous = EnrollmentResponse {
|
||||
agent_id: source.to_string(),
|
||||
asset_id: Uuid::new_v4().to_string(),
|
||||
certificate_pem: "old certificate fixture".into(),
|
||||
};
|
||||
publish(&dir.join("identity.json"), &serde_json::to_vec(&previous)?)?;
|
||||
publish(&dir.join("device.key"), b"old key")?;
|
||||
publish(&dir.join("journal.sqlite"), b"old journal")?;
|
||||
let signer = SigningKey::from_bytes(&[7; 32]);
|
||||
let public = hex::encode(signer.verifying_key().as_bytes());
|
||||
let certificate_pem = "new certificate fixture".to_string();
|
||||
let binding = Binding {
|
||||
offer: Offer {
|
||||
transfer_id: id,
|
||||
source_agent_id: source,
|
||||
source_tenant_id: Uuid::new_v4(),
|
||||
target_tenant_id: Uuid::new_v4(),
|
||||
},
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: target,
|
||||
certificate_sha256: rmm_domain::jobs::hash(certificate_pem.as_bytes()),
|
||||
};
|
||||
let tenant = binding.offer.target_tenant_id;
|
||||
let mut response = CertificateResponse {
|
||||
certificate_pem,
|
||||
receipt: Receipt {
|
||||
signature_hex: hex::encode(signer.sign(&binding.signing_bytes()?).to_bytes()),
|
||||
binding,
|
||||
},
|
||||
};
|
||||
publish(&file(&dir, id, "key.pem"), b"new key")?;
|
||||
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
|
||||
response.receipt.binding.offer.target_tenant_id = Uuid::new_v4();
|
||||
fs::write(
|
||||
file(&dir, id, "response.json"),
|
||||
serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
assert!(activate(&dir, &public).is_err());
|
||||
assert_eq!(fs::read(dir.join("device.key"))?, b"old key");
|
||||
response.receipt.binding.offer.target_tenant_id = tenant;
|
||||
fs::write(
|
||||
file(&dir, id, "response.json"),
|
||||
serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
|
||||
// Simulate a stop immediately after relocating the first original file.
|
||||
fs::rename(
|
||||
dir.join("identity.json"),
|
||||
file(&dir, id, "prior-identity.json"),
|
||||
)?;
|
||||
activate(&dir, &public)?;
|
||||
activate(&dir, &public)?;
|
||||
assert!(!pending(&dir)?);
|
||||
assert!(!file(&dir, id, "prior-identity.json").exists());
|
||||
assert!(!file(&dir, id, "prior-device.key").exists());
|
||||
assert!(!file(&dir, id, "prior-journal.sqlite").exists());
|
||||
assert_eq!(fs::read(dir.join("device.key"))?, b"new key");
|
||||
let active: EnrollmentResponse =
|
||||
serde_json::from_slice(&read(&dir.join("identity.json"))?)?;
|
||||
assert_eq!(active.agent_id, target.to_string());
|
||||
assert_eq!(assigned_tenant(&dir, &active, &public)?, Some(tenant));
|
||||
Ok(())
|
||||
})();
|
||||
fs::remove_dir_all(dir)?;
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
@@ -782,10 +804,10 @@ impl<V: Ed25519Verifier> HelperSync<V> {
|
||||
let d = decisions
|
||||
.get(&id)
|
||||
.context("ROOT_ATTEMPT_OMITTED_FROM_DECISION")?;
|
||||
validate_summary(row, local)?;
|
||||
validate_decision(row, local, d)?;
|
||||
let unreported = validate_summary(row, local)?;
|
||||
validate_decision(row, local, d, unreported)?;
|
||||
if d.unlock {
|
||||
let bytes = unlock_outcome(row, d, current_boot)?;
|
||||
let bytes = unlock_outcome(row, d, current_boot, unreported.then_some(local))?;
|
||||
if d.outcome_state == "closed_unknown" {
|
||||
crate::ledger::retain_closure_original(
|
||||
&tx,
|
||||
@@ -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)?;
|
||||
@@ -1636,22 +1662,33 @@ fn definitive(row: &LocalAttempt) -> bool {
|
||||
"succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown"
|
||||
) && !row.outcome_bytes.is_empty()
|
||||
}
|
||||
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> {
|
||||
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<bool> {
|
||||
let unreported = row.state == "unknown"
|
||||
&& row.outcome_sha256.is_empty()
|
||||
&& row.outcome_bytes.is_empty()
|
||||
&& row.update_handoff_bytes.is_empty()
|
||||
&& crate::reconcile::uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
|
||||
ensure!(
|
||||
a.job_payload_hash == row.job_payload_hash
|
||||
&& a.grant_id == row.grant_id.to_string()
|
||||
&& a.consumption == "consumed"
|
||||
&& a.state == row.state
|
||||
&& a.revision >= row.revision
|
||||
&& a.original_boot_id == row.original_boot_id.to_string()
|
||||
&& a.outcome_sha256 == row.outcome_sha256
|
||||
&& a.update_handoff_bytes == row.update_handoff_bytes
|
||||
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes),
|
||||
&& (unreported
|
||||
|| (a.state == row.state
|
||||
&& a.outcome_sha256 == row.outcome_sha256
|
||||
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes))),
|
||||
"ROOT_SNAPSHOT_REQUEST_MISMATCH"
|
||||
);
|
||||
Ok(())
|
||||
Ok(unreported)
|
||||
}
|
||||
fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -> Result<()> {
|
||||
fn validate_decision(
|
||||
row: &LocalAttempt,
|
||||
a: &AttemptView,
|
||||
d: &AttemptDecision,
|
||||
unreported: bool,
|
||||
) -> Result<()> {
|
||||
if !row.update_handoff_bytes.is_empty() {
|
||||
let proof =
|
||||
rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes)
|
||||
@@ -1686,7 +1723,7 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
|
||||
&& d.original_boot_id == Some(row.original_boot_id)
|
||||
&& (d.revision >= a.revision || (!d.unlock && d.outcome_state == "unknown"))
|
||||
&& d.previous_outcome_sha256.as_deref()
|
||||
== (!row.outcome_sha256.is_empty()).then_some(row.outcome_sha256.as_str()),
|
||||
== (!a.outcome_sha256.is_empty()).then_some(a.outcome_sha256.as_str()),
|
||||
"ROOT_SIGNED_ATTEMPT_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
@@ -1697,11 +1734,26 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
|
||||
),
|
||||
"UNKNOWN_CANNOT_UNLOCK"
|
||||
);
|
||||
ensure!(
|
||||
!unreported
|
||||
|| (!d.unlock && d.outcome_state == "unknown")
|
||||
|| (d.unlock
|
||||
&& d.outcome_state == "closed_unknown"
|
||||
&& d.reason == "OPERATOR_CLOSED_UNKNOWN"),
|
||||
"ROOT_UNREPORTED_OUTCOME_CLOSURE_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -> Result<Vec<u8>> {
|
||||
fn unlock_outcome(
|
||||
row: &LocalAttempt,
|
||||
d: &AttemptDecision,
|
||||
current_boot: Uuid,
|
||||
unreported: Option<&AttemptView>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let bytes = if d.outcome_bytes.is_empty() {
|
||||
row.outcome_bytes.clone()
|
||||
unreported
|
||||
.map_or(&row.outcome_bytes, |a| &a.outcome_bytes)
|
||||
.clone()
|
||||
} else {
|
||||
d.outcome_bytes.clone()
|
||||
};
|
||||
@@ -1712,9 +1764,7 @@ fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -
|
||||
&& o.state == d.outcome_state,
|
||||
"ROOT_CANONICAL_UNLOCK_OUTCOME"
|
||||
);
|
||||
if bytes != row.outcome_bytes
|
||||
&& crate::reconcile::operator_closure(&d.reason, &row.state, &o)
|
||||
{
|
||||
if bytes != row.outcome_bytes && crate::reconcile::operator_closure(&d.reason, &row.state, &o) {
|
||||
return Ok(bytes);
|
||||
}
|
||||
if bytes != row.outcome_bytes {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Callers must authenticate their transport, protect/lock their own journals and
|
||||
//! supply a qualified clock. A successful signature is never UI approval itself.
|
||||
pub mod auth;
|
||||
pub mod customer_transfer;
|
||||
pub mod crypto;
|
||||
pub mod helper_reconcile;
|
||||
pub mod jobs;
|
||||
|
||||
@@ -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");
|
||||
@@ -1019,9 +1036,9 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
} else {
|
||||
for d in decision.attempts.iter().filter(|d| d.unlock) {
|
||||
let grant = d.grant_id.context("UNLOCK_GRANT_MISSING")?;
|
||||
let (agent,generation,job,attempt,previous):(String,u64,String,String,Option<Vec<u8>>)=tx.query_row(
|
||||
"SELECT agent,generation,job,attempt,COALESCE((SELECT outcome FROM execution_evidence WHERE execution_evidence.grant_id=consumed.grant_id),result) FROM consumed WHERE grant_id=?1",
|
||||
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
||||
let (agent,generation,job,attempt,previous,start):(String,u64,String,String,Option<Vec<u8>>,Option<Vec<u8>>)=tx.query_row(
|
||||
"SELECT c.agent,c.generation,c.job,c.attempt,COALESCE(e.outcome,c.result),e.start FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
|
||||
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?)))?;
|
||||
ensure!(
|
||||
agent == self.binding.agent_id.to_string()
|
||||
&& generation == self.binding.enrollment_generation
|
||||
@@ -1034,13 +1051,61 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
Some(&self.binding),
|
||||
grant,
|
||||
)?;
|
||||
let previous = resolved
|
||||
.or(previous)
|
||||
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
|
||||
let original = previous.clone();
|
||||
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>(
|
||||
&previous,
|
||||
)?)?;
|
||||
let previous = resolved.or(previous);
|
||||
let summary = gate
|
||||
.request
|
||||
.attempts
|
||||
.iter()
|
||||
.find(|a| a.job_id == job && a.attempt_id == attempt)
|
||||
.context("LOCAL_UNLOCK_ATTEMPT_MISSING")?;
|
||||
let closure = d.reason == "OPERATOR_CLOSED_UNKNOWN"
|
||||
&& d.outcome_state == "closed_unknown"
|
||||
&& summary.consumption == "consumed"
|
||||
&& uncertain_agent_outcome(
|
||||
&summary.state,
|
||||
&summary.outcome_bytes,
|
||||
&summary.outcome_sha256,
|
||||
);
|
||||
let prior = match &previous {
|
||||
Some(bytes) => {
|
||||
let canonical = canonical_outcome_bytes(&serde_json::from_slice(bytes)?)?;
|
||||
if closure
|
||||
&& summary.state == "closed_unknown"
|
||||
&& uncertain_agent_outcome("unknown", &canonical, &hash(&canonical))
|
||||
{
|
||||
summary.outcome_bytes.clone()
|
||||
} else {
|
||||
canonical
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ensure!(closure, "LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING");
|
||||
let start: serde_json::Value = serde_json::from_slice(
|
||||
&start.context("LOCAL_UNLOCK_ORIGINAL_START_MISSING")?,
|
||||
)?;
|
||||
let request: crate::auth::Request =
|
||||
serde_json::from_value(start["request"].clone())?;
|
||||
let permit: rmm_domain::jobs::ExecutionPermitPayload =
|
||||
serde_json::from_slice(&request.permit_bytes)?;
|
||||
let (original, permit) = self.binding.verify_with(
|
||||
&request,
|
||||
permit.not_before,
|
||||
&self.verifier,
|
||||
)?;
|
||||
ensure!(
|
||||
permit.grant_id == grant
|
||||
&& original.job_id == d.job_id
|
||||
&& original.attempt_id == d.attempt_id
|
||||
&& hash(&request.job_bytes) == d.job_payload_hash
|
||||
&& Some(permit.authorization_id) == d.authorization_id
|
||||
&& Some(permit.plan_hash.as_str()) == d.plan_hash.as_deref()
|
||||
&& start["previous_boot_id"].as_str()
|
||||
== d.original_boot_id.map(|id| id.to_string()).as_deref(),
|
||||
"LOCAL_UNLOCK_ORIGINAL_START_BINDING"
|
||||
);
|
||||
summary.outcome_bytes.clone()
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
d.previous_outcome_sha256.as_deref() == Some(hash(&prior).as_str()),
|
||||
"LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISMATCH"
|
||||
@@ -1055,7 +1120,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
terminal(&outcome.state)
|
||||
&& outcome.state == d.outcome_state
|
||||
&& canonical_outcome_bytes(&outcome)? == bytes
|
||||
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()),
|
||||
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str())
|
||||
&& (previous.is_some() || operator_closure(&d.reason, "unknown", &outcome)),
|
||||
"LOCAL_UNLOCK_CANONICAL_OUTCOME"
|
||||
);
|
||||
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
|
||||
@@ -1065,7 +1131,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
|
||||
&bytes,
|
||||
)?;
|
||||
if outcome.state == "closed_unknown" {
|
||||
crate::ledger::retain_closure_original(&tx, grant, &original, &bytes)?;
|
||||
crate::ledger::retain_closure_original(
|
||||
&tx,
|
||||
grant,
|
||||
previous.as_deref().unwrap_or_default(),
|
||||
&bytes,
|
||||
)?;
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
|
||||
@@ -1093,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);
|
||||
@@ -1304,6 +1378,32 @@ pub(crate) fn operator_closure(
|
||||
&& outcome.evidence["closed_by_human"] == true
|
||||
&& outcome.evidence["retry"] == false
|
||||
}
|
||||
|
||||
/// An interrupted agent can record its own uncertainty while the independently
|
||||
/// consumed helper grant has no result. Neither witness establishes an effect.
|
||||
pub(crate) fn uncertain_agent_outcome(state: &str, bytes: &[u8], digest: &str) -> bool {
|
||||
if bytes.is_empty() || hash(bytes) != digest {
|
||||
return false;
|
||||
}
|
||||
let Ok(outcome) = serde_json::from_slice::<ReconciledOutcome>(bytes) else {
|
||||
return false;
|
||||
};
|
||||
canonical_outcome_bytes(&outcome).is_ok_and(|canonical| canonical == bytes)
|
||||
&& outcome.state == state
|
||||
&& !outcome.output_truncated
|
||||
&& !outcome.reboot_required
|
||||
&& (operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &outcome)
|
||||
|| (state == "unknown"
|
||||
&& matches!(
|
||||
outcome.error_code.as_str(),
|
||||
"AGENT_PROCESS_INTERRUPTED" | "HELPER_TRANSPORT_EFFECT_UNKNOWN"
|
||||
)
|
||||
&& outcome.exit_code.is_none()
|
||||
&& outcome.stdout.is_empty()
|
||||
&& outcome.stderr.is_empty()
|
||||
&& outcome.evidence["postconditions_passed"] == false))
|
||||
}
|
||||
|
||||
fn optional_uuid(s: &str) -> Result<Option<Uuid>> {
|
||||
if s.is_empty() {
|
||||
Ok(None)
|
||||
@@ -1452,6 +1552,24 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
|
||||
result_envelope = Some(envelope);
|
||||
}
|
||||
}
|
||||
// The signed closure projection can commit before either consumption
|
||||
// ledger. A fresh signed check may then finish the remaining writes.
|
||||
if state == "closed_unknown"
|
||||
&& consumption == "consumed"
|
||||
&& (canonical.is_empty()
|
||||
|| uncertain_agent_outcome("unknown", &canonical, &hash(&canonical)))
|
||||
{
|
||||
let closed: Vec<u8> = db.query_row(
|
||||
"SELECT outcome FROM reconcile_outcomes WHERE job=?1 AND attempt=?2",
|
||||
params![offer.job_id, offer.attempt_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
uncertain_agent_outcome(&state, &closed, &hash(&closed)),
|
||||
"LOCAL_CLOSURE_OUTCOME_MISMATCH"
|
||||
);
|
||||
canonical = closed;
|
||||
}
|
||||
if !canonical.is_empty() {
|
||||
let o: ReconciledOutcome = serde_json::from_slice(&canonical)?;
|
||||
ensure!(o.state == state, "LOCAL_OUTCOME_STATE_MISMATCH");
|
||||
@@ -1746,6 +1864,15 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
|
||||
"HELPER_ATTEMPT_BINDING"
|
||||
);
|
||||
if h.consumption != "unconsumed" {
|
||||
let unreported = h.state == "unknown"
|
||||
&& h.consumption == "consumed"
|
||||
&& h.outcome_bytes.is_empty()
|
||||
&& h.outcome_sha256.is_empty()
|
||||
&& h.update_handoff_bytes.is_empty()
|
||||
&& a.consumption == "consumed"
|
||||
&& a.grant_id == h.grant_id
|
||||
&& a.original_boot_id == h.original_boot_id
|
||||
&& uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
|
||||
if !h.update_handoff_bytes.is_empty() {
|
||||
ensure!(
|
||||
h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(),
|
||||
@@ -1756,7 +1883,7 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
|
||||
a.grant_id = h.grant_id.clone();
|
||||
a.consumption = h.consumption.clone();
|
||||
ensure!(
|
||||
a.outcome_sha256 == h.outcome_sha256,
|
||||
a.outcome_sha256 == h.outcome_sha256 || unreported,
|
||||
"HELPER_OUTCOME_MISMATCH"
|
||||
);
|
||||
if a.original_boot_id.is_empty() {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1485,6 +1485,207 @@ fn persist_original_fixture_result(
|
||||
fn completion_outcome() -> rmm_agent_core::auth::Outcome {
|
||||
serde_json::from_slice(&canonical_outcome_bytes(&success()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn human_closure_reconciles_agent_interruption_and_a_helper_without_result() {
|
||||
use rmm_agent_core::helper_reconcile::{self, BootSource, ExecutorLedgerGuard, HelperSync};
|
||||
|
||||
struct TestGuard;
|
||||
impl ExecutorLedgerGuard for TestGuard {
|
||||
fn check(&self, db: &Connection) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
db.is_autocommit(),
|
||||
"fixture ledger must be outside a transaction"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct TestBoot(Uuid);
|
||||
impl BootSource for TestBoot {
|
||||
fn current_boot(&self) -> anyhow::Result<Uuid> {
|
||||
Ok(self.0)
|
||||
}
|
||||
}
|
||||
fn map(snapshot: &helper_reconcile::Snapshot) -> HelperSnapshot {
|
||||
HelperSnapshot {
|
||||
journal_id: snapshot.journal_id,
|
||||
checkpoint: snapshot.checkpoint,
|
||||
previous_decision_id: snapshot.previous_decision_id,
|
||||
attempts: snapshot
|
||||
.attempts
|
||||
.iter()
|
||||
.map(|a| SyncAttempt {
|
||||
job_id: a.job_id.to_string(),
|
||||
attempt_id: a.attempt_id.to_string(),
|
||||
job_payload_hash: a.job_payload_hash.clone(),
|
||||
grant_id: a.grant_id.to_string(),
|
||||
consumption: a.consumption.clone(),
|
||||
state: a.state.clone(),
|
||||
revision: a.revision,
|
||||
original_boot_id: a.original_boot_id.to_string(),
|
||||
outcome_sha256: a.outcome_sha256.clone(),
|
||||
outcome_bytes: a.outcome_bytes.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
let closed = canonical_outcome_bytes(&ReconciledOutcome {
|
||||
state: "closed_unknown".into(),
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
exit_code: None,
|
||||
output_truncated: false,
|
||||
reboot_required: false,
|
||||
evidence: serde_json::json!({
|
||||
"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"retry":false
|
||||
}),
|
||||
error_code: "OPERATOR_CLOSED_UNKNOWN".into(),
|
||||
})
|
||||
.unwrap();
|
||||
for interrupt_after_projection in [false, true] {
|
||||
let mut f = Fixture::new();
|
||||
reconcile::initialize(&f.db).unwrap();
|
||||
let (offer, grant, _) = f.add(
|
||||
"running",
|
||||
true,
|
||||
None,
|
||||
Action::SetServiceState {
|
||||
unit: "rmm-acceptance.service".into(),
|
||||
state: "running".into(),
|
||||
},
|
||||
);
|
||||
let grant = grant.unwrap();
|
||||
let archive = persist_original_fixture_result(
|
||||
&mut f,
|
||||
&offer,
|
||||
&grant,
|
||||
rmm_agent_core::auth::Outcome::unknown("AGENT_PROCESS_INTERRUPTED"),
|
||||
);
|
||||
rmm_agent_core::jobs::ack(&mut f.db, &archive.message_id).unwrap();
|
||||
let start: Vec<u8> = f
|
||||
.ledger
|
||||
.query_row("SELECT start FROM execution_evidence", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
let start: serde_json::Value = serde_json::from_slice(&start).unwrap();
|
||||
let request: Request = serde_json::from_value(start["request"].clone()).unwrap();
|
||||
let boot = TestBoot(f.channel.boot_id);
|
||||
let guard = TestGuard;
|
||||
let mut helper_db = Connection::open_in_memory().unwrap();
|
||||
rmm_agent_core::ledger::initialize_ledger(&helper_db).unwrap();
|
||||
rmm_agent_core::ledger::begin_execution(
|
||||
&mut helper_db,
|
||||
&grant,
|
||||
&request,
|
||||
boot.0,
|
||||
f.clock.now,
|
||||
)
|
||||
.unwrap();
|
||||
let mut helper = HelperSync::new(f.binding.clone(), &f.clock).unwrap();
|
||||
let mut client = f.client();
|
||||
|
||||
for round in 0..if interrupt_after_projection { 3 } else { 2 } {
|
||||
let snapshot = map(&helper
|
||||
.snapshot(
|
||||
&mut helper_db,
|
||||
&guard,
|
||||
f.channel.connection_generation,
|
||||
&f.clock,
|
||||
&boot,
|
||||
)
|
||||
.unwrap());
|
||||
assert_eq!(snapshot.attempts[0].state, "unknown");
|
||||
assert!(snapshot.attempts[0].outcome_bytes.is_empty());
|
||||
let prepared = client
|
||||
.prepare(
|
||||
&mut f.db,
|
||||
&f.ledger,
|
||||
f.channel.clone(),
|
||||
Some(&snapshot),
|
||||
&f.clock,
|
||||
)
|
||||
.unwrap();
|
||||
let agent_attempt = &prepared.request.attempts[0];
|
||||
assert!(!agent_attempt.outcome_bytes.is_empty());
|
||||
let mut d = f.decision(&prepared, round != 0);
|
||||
d.issued_at = f.clock.now;
|
||||
if round != 0 {
|
||||
let attempt = &mut d.attempts[0];
|
||||
attempt.revision = 3;
|
||||
attempt.outcome_state = "closed_unknown".into();
|
||||
attempt.reason = "OPERATOR_CLOSED_UNKNOWN".into();
|
||||
attempt.unlock = true;
|
||||
attempt.outcome_sha256 = Some(hash(&closed));
|
||||
if agent_attempt.state == "unknown" {
|
||||
attempt.outcome_bytes = closed.clone();
|
||||
}
|
||||
}
|
||||
let signed = f.sign(&d);
|
||||
client.apply(&mut f.db, &signed, &f.clock).unwrap();
|
||||
if interrupt_after_projection && round == 1 {
|
||||
client = f.client();
|
||||
continue;
|
||||
}
|
||||
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
|
||||
let raw = prepared.request.encode_to_vec();
|
||||
let response = helper_reconcile::SignedResponse {
|
||||
decision_bytes: signed.decision_bytes,
|
||||
signature: signed.signature,
|
||||
};
|
||||
let applied = helper
|
||||
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
|
||||
.unwrap();
|
||||
if round == 0 {
|
||||
assert!(!applied.ready && applied.unlocked_grants.is_empty());
|
||||
assert!(!client.can_start(&f.channel, false, &f.clock));
|
||||
} else {
|
||||
assert!(applied.ready);
|
||||
assert_eq!(applied.unlocked_grants, vec![grant.grant_id]);
|
||||
assert!(
|
||||
helper
|
||||
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
|
||||
.unwrap()
|
||||
.unlocked_grants
|
||||
.is_empty()
|
||||
);
|
||||
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
|
||||
client.confirm_helper(&map(&applied.snapshot)).unwrap();
|
||||
assert!(client.can_start(&f.channel, true, &f.clock));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
f.db.query_row::<String, _, _>("SELECT state FROM job_attempts", [], |rec| rec.get(0))
|
||||
.unwrap(),
|
||||
"closed_unknown"
|
||||
);
|
||||
assert_eq!(
|
||||
f.db.query_row::<Vec<u8>, _, _>("SELECT envelope FROM reconcile_results", [], |rec| {
|
||||
rec.get(0)
|
||||
})
|
||||
.unwrap(),
|
||||
archive.encode_to_vec()
|
||||
);
|
||||
for ledger in [&f.ledger, &helper_db] {
|
||||
assert_eq!(
|
||||
ledger
|
||||
.query_row::<Vec<u8>, _, _>("SELECT result FROM consumed", [], |rec| rec.get(0))
|
||||
.unwrap(),
|
||||
closed
|
||||
);
|
||||
assert_eq!(
|
||||
ledger
|
||||
.query_row::<(Vec<u8>, Vec<u8>), _, _>(
|
||||
"SELECT original_outcome,closure_outcome FROM unknown_closure_originals",
|
||||
[],
|
||||
|rec| Ok((rec.get(0)?, rec.get(1)?))
|
||||
)
|
||||
.unwrap(),
|
||||
(vec![], closed.clone())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes() {
|
||||
let mut f = Fixture::new();
|
||||
|
||||
@@ -4,12 +4,12 @@ use crate::{
|
||||
actions::{ServiceUnit, reboot_required},
|
||||
process,
|
||||
};
|
||||
use rmm_domain::inventory_document::DeviceType;
|
||||
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
ffi::{CStr, CString},
|
||||
fs,
|
||||
io::Read,
|
||||
io::{BufRead, BufReader, Read},
|
||||
mem::MaybeUninit,
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
path::Path,
|
||||
@@ -169,6 +169,9 @@ pub struct OperatingSystem {
|
||||
pub hostname: String,
|
||||
pub boot_id: String,
|
||||
pub uptime_seconds: f64,
|
||||
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub install_date_source: Option<&'static str>,
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Interface {
|
||||
@@ -260,6 +263,8 @@ pub struct Hardware {
|
||||
pub readable_dmi: BTreeMap<String, String>,
|
||||
pub device_type: Option<DeviceType>,
|
||||
pub proxmox_ve: bool,
|
||||
pub manufacturer: Option<String>,
|
||||
pub bios_serial_number: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct LinuxInventory {
|
||||
@@ -271,6 +276,7 @@ pub struct LinuxInventory {
|
||||
pub dns: Observation<Dns>,
|
||||
pub volumes: Observation<Vec<Observation<Volume>>>,
|
||||
pub software: Observation<Vec<SoftwarePackage>>,
|
||||
pub users: Observation<Vec<String>>,
|
||||
pub updates: Observation<UpdateStatus>,
|
||||
pub hardware: Observation<Hardware>,
|
||||
pub smart: Observation<()>,
|
||||
@@ -285,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
|
||||
dns: dns(),
|
||||
volumes: volumes(),
|
||||
software: software(),
|
||||
users: logged_in_users(),
|
||||
updates: updates(),
|
||||
hardware: hardware(),
|
||||
smart: Observation::unavailable(
|
||||
@@ -380,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
|
||||
);
|
||||
result
|
||||
}
|
||||
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
|
||||
for (path, source) in [
|
||||
("/var/log/installer", "installer_directory"),
|
||||
("/", "root_filesystem"),
|
||||
] {
|
||||
if let Some(time) = fs::metadata(path)
|
||||
.ok()
|
||||
.and_then(|data| data.created().ok())
|
||||
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
|
||||
{
|
||||
return Some((time.into(), source));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
let release = read("/etc/os-release", 32 * 1024);
|
||||
let kernel = read("/proc/sys/kernel/osrelease", 4096);
|
||||
@@ -417,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
|
||||
})
|
||||
.collect();
|
||||
let booted_at = read("/proc/stat", 256 * 1024)
|
||||
.data
|
||||
.as_deref()
|
||||
.and_then(|stat| {
|
||||
let seconds = stat
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("btime "))?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()?;
|
||||
chrono::DateTime::from_timestamp(seconds, 0)
|
||||
});
|
||||
let installed = installed_at();
|
||||
Observation::valid(
|
||||
"linux.os:/etc/os-release,/proc",
|
||||
"linux.os:/etc/os-release,/proc,filesystem-birth",
|
||||
OperatingSystem {
|
||||
release,
|
||||
kernel: kernel.trim().into(),
|
||||
@@ -426,12 +462,109 @@ pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
hostname: hostname.trim().into(),
|
||||
boot_id,
|
||||
uptime_seconds,
|
||||
booted_at,
|
||||
installed_at: installed.map(|(time, _)| time),
|
||||
install_date_source: installed.map(|(_, source)| source),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
|
||||
}
|
||||
}
|
||||
|
||||
fn logged_in_users() -> Observation<Vec<String>> {
|
||||
const LOGINCTL: &str = "/usr/bin/loginctl";
|
||||
let listed = command(
|
||||
LOGINCTL,
|
||||
&["--no-legend", "--no-pager", "list-sessions"],
|
||||
16 * 1024,
|
||||
);
|
||||
let Some(rows) = &listed.data else {
|
||||
return map(listed, |_| None);
|
||||
};
|
||||
let mut ids = rows
|
||||
.lines()
|
||||
.filter_map(|line| line.split_whitespace().next());
|
||||
let mut args = vec![
|
||||
"--no-pager",
|
||||
"--all",
|
||||
"--property=Name,Class,State",
|
||||
"show-session",
|
||||
"--",
|
||||
];
|
||||
args.extend(
|
||||
ids.by_ref()
|
||||
.take(64)
|
||||
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
|
||||
);
|
||||
let limited = listed.truncated || ids.next().is_some();
|
||||
if args.len() == 5 {
|
||||
return Observation::valid("linux.logind:loginctl", Vec::new());
|
||||
}
|
||||
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
|
||||
let users: std::collections::BTreeSet<_> = text
|
||||
.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
let fields: BTreeMap<_, _> = block
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once('='))
|
||||
.collect();
|
||||
let class = *fields.get("Class")?;
|
||||
let state = *fields.get("State")?;
|
||||
let name = *fields.get("Name")?;
|
||||
(matches!(
|
||||
class,
|
||||
"user" | "user-early" | "user-light" | "user-early-light"
|
||||
) && matches!(state, "online" | "active")
|
||||
&& !name.is_empty()
|
||||
&& name.len() <= 255)
|
||||
.then(|| name.to_owned())
|
||||
})
|
||||
.collect();
|
||||
Some(users.into_iter().collect())
|
||||
});
|
||||
report.source_id = "linux.logind:loginctl".into();
|
||||
if limited && report.data.is_some() {
|
||||
report = report.partial("SESSION_LIMIT");
|
||||
report.truncated = true;
|
||||
}
|
||||
report
|
||||
}
|
||||
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
|
||||
stat.lines()
|
||||
.find(|line| line.starts_with("cpu "))
|
||||
.and_then(|line| {
|
||||
line.split_whitespace()
|
||||
.skip(1)
|
||||
.map(str::parse)
|
||||
.collect::<Result<_, _>>()
|
||||
.ok()
|
||||
})
|
||||
}
|
||||
|
||||
fn linux_cpu_times(jiffies: &[u64]) -> Option<CpuTimes> {
|
||||
// Linux already includes guest and guest_nice in user and nice.
|
||||
let total = jiffies
|
||||
.iter()
|
||||
.take(8)
|
||||
.try_fold(0_u64, |total, ticks| total.checked_add(*ticks))?;
|
||||
let idle = jiffies
|
||||
.get(3)?
|
||||
.checked_add(jiffies.get(4).copied().unwrap_or_default())?;
|
||||
Some(CpuTimes { total, idle })
|
||||
}
|
||||
|
||||
pub fn cpu_times() -> Option<CpuTimes> {
|
||||
let mut line = String::new();
|
||||
BufReader::new(fs::File::open("/proc/stat").ok()?.take(4096))
|
||||
.read_line(&mut line)
|
||||
.ok()?;
|
||||
if !line.ends_with('\n') {
|
||||
return None;
|
||||
}
|
||||
linux_cpu_times(&aggregate_jiffies(&line)?)
|
||||
}
|
||||
|
||||
pub fn cpu() -> Observation<Cpu> {
|
||||
let info = read("/proc/cpuinfo", 1024 * 1024);
|
||||
let stat = read("/proc/stat", 256 * 1024);
|
||||
@@ -460,15 +593,7 @@ pub fn cpu() -> Observation<Cpu> {
|
||||
.filter(|(k, _)| k.trim() == "model name")
|
||||
.map(|(_, v)| v.trim().to_owned())
|
||||
});
|
||||
let aggregate_jiffies: Option<Vec<u64>> =
|
||||
stat.lines().find(|l| l.starts_with("cpu ")).and_then(|l| {
|
||||
l.split_whitespace()
|
||||
.skip(1)
|
||||
.map(str::parse)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.ok()
|
||||
});
|
||||
match aggregate_jiffies {
|
||||
match aggregate_jiffies(&stat) {
|
||||
Some(aggregate_jiffies) if logical_processors > 0 => Observation::valid(
|
||||
"linux.cpu:/proc/cpuinfo,/proc/stat",
|
||||
Cpu {
|
||||
@@ -556,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
|
||||
}
|
||||
libc::AF_INET6 => {
|
||||
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
|
||||
addresses.push(format!(
|
||||
"{}%{}",
|
||||
Ipv6Addr::from(addr.sin6_addr.s6_addr),
|
||||
addr.sin6_scope_id
|
||||
));
|
||||
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
|
||||
addresses.push(if addr.sin6_scope_id == 0 {
|
||||
ip.to_string()
|
||||
} else {
|
||||
format!("{ip}%{}", addr.sin6_scope_id)
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -1167,7 +1293,20 @@ pub fn hardware() -> Observation<Hardware> {
|
||||
let proxmox_ve =
|
||||
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
|
||||
let device_type = machine_type(proxmox_ve);
|
||||
if readable_dmi.is_empty() && device_type.is_none() {
|
||||
let manufacturer = readable_dmi
|
||||
.get("sys_vendor")
|
||||
.and_then(|value| firmware_identifier(value));
|
||||
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
|
||||
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
|
||||
let bios_serial_number = [
|
||||
Some("/sys/class/dmi/id/product_serial"),
|
||||
Some("/proc/device-tree/serial-number"),
|
||||
serial_credential.as_deref().and_then(Path::to_str),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
|
||||
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
|
||||
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
|
||||
} else {
|
||||
Observation::valid(
|
||||
@@ -1176,6 +1315,8 @@ pub fn hardware() -> Observation<Hardware> {
|
||||
readable_dmi,
|
||||
device_type,
|
||||
proxmox_ve,
|
||||
manufacturer,
|
||||
bios_serial_number,
|
||||
},
|
||||
)
|
||||
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
|
||||
@@ -1400,6 +1541,16 @@ mod tests {
|
||||
assert_eq!(request.since_filter, "@100.123457");
|
||||
assert_eq!(request.until_filter, "@101.987654");
|
||||
}
|
||||
#[test]
|
||||
fn cpu_time_excludes_double_counted_guest_ticks_and_io_wait() {
|
||||
let before = linux_cpu_times(&[10, 0, 5, 60, 10, 0, 0, 0, 4, 0]).unwrap();
|
||||
let after = linux_cpu_times(&[30, 0, 5, 120, 30, 0, 0, 0, 20, 0]).unwrap();
|
||||
assert_eq!(after.usage_since(before), Some(2_000));
|
||||
assert_eq!(after.usage_since(after), None);
|
||||
assert_eq!(before.usage_since(after), None);
|
||||
assert!(linux_cpu_times(&[10, 0, 0]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn machine_types_distinguish_proxmox_guests_and_probe_failures() {
|
||||
assert_eq!(machine_type(true), Some(DeviceType::Hypervisor));
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
//! Additive JSON observation mapping inside the existing snapshot payload. This
|
||||
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
|
||||
use anyhow::Result;
|
||||
//! does not introduce a protobuf tag or a fabricated receive time.
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::inventory_document::LINUX_SOFTWARE_OBSERVATION_MAX_BYTES;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn truncate_rows(observation: &mut Value) -> bool {
|
||||
let Some(rows) = observation["data"].as_array_mut().filter(|v| !v.is_empty()) else {
|
||||
return false;
|
||||
};
|
||||
rows.truncate(rows.len() / 2);
|
||||
observation["truncated"] = json!(true);
|
||||
observation["completeness"] = json!("partial");
|
||||
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
|
||||
true
|
||||
}
|
||||
|
||||
pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<Value>> {
|
||||
let value = serde_json::to_value(inventory)?;
|
||||
let mut result = Vec::new();
|
||||
@@ -14,13 +26,16 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
|
||||
observation["scope"] = json!(format!("linux.{name}"));
|
||||
// Bound each scope independently. Never drop unsupported/error metadata
|
||||
// or imply that absent/truncated rows were deleted from a device.
|
||||
while serde_json::to_vec(&observation)?.len() > 32768 {
|
||||
observation["truncated"] = json!(true);
|
||||
observation["completeness"] = json!("partial");
|
||||
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
|
||||
if let Some(rows) = observation["data"].as_array_mut().filter(|v| !v.is_empty()) {
|
||||
rows.truncate(rows.len() / 2);
|
||||
} else {
|
||||
let max_bytes = if name == "software" {
|
||||
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
while serde_json::to_vec(&observation)?.len() > max_bytes {
|
||||
if !truncate_rows(&mut observation) {
|
||||
observation["truncated"] = json!(true);
|
||||
observation["completeness"] = json!("partial");
|
||||
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
|
||||
observation["data"] = Value::Null;
|
||||
observation["quality"] = json!("unknown");
|
||||
break;
|
||||
@@ -42,6 +57,20 @@ pub fn snapshot(extended: bool) -> Result<Value> {
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
pub fn encode_snapshot(mut inventory: Value) -> Result<Vec<u8>> {
|
||||
let mut bytes = serde_json::to_vec(&inventory)?;
|
||||
// Preserve the other scopes when a large package list fills the snapshot.
|
||||
while bytes.len() > 512 * 1024 {
|
||||
let software = inventory
|
||||
.get_mut("observations")
|
||||
.and_then(Value::as_array_mut)
|
||||
.and_then(|scopes| scopes.iter_mut().find(|scope| scope["scope"] == "linux.software"));
|
||||
ensure!(software.is_some_and(truncate_rows), "INVENTORY_WIRE_LIMIT");
|
||||
bytes = serde_json::to_vec(&inventory)?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -49,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(), 11);
|
||||
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());
|
||||
@@ -61,7 +90,12 @@ mod tests {
|
||||
);
|
||||
assert!(!observation["source_id"].as_str().unwrap().is_empty());
|
||||
assert!(observation.get("received_at").is_none());
|
||||
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
|
||||
let limit = if observation["scope"] == "linux.software" {
|
||||
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
|
||||
}
|
||||
let base = snapshot(false).unwrap();
|
||||
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
|
||||
@@ -87,4 +121,21 @@ mod tests {
|
||||
assert_eq!(software["truncated"], true);
|
||||
assert_eq!(software["completeness"], "partial");
|
||||
}
|
||||
#[test]
|
||||
fn snapshot_limit_shrinks_software_and_preserves_other_scopes() {
|
||||
let network = json!({"scope":"linux.interfaces","data":"x".repeat(280 * 1024)});
|
||||
let data = vec!["x".repeat(1024); 240];
|
||||
let snapshot = json!({"observations":[
|
||||
network,
|
||||
{"scope":"linux.software","completeness":"complete","data":data},
|
||||
]});
|
||||
let bytes = encode_snapshot(snapshot).unwrap();
|
||||
let bounded: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(bounded["observations"][0], network);
|
||||
assert_eq!(bounded["observations"][1]["completeness"], "partial");
|
||||
assert_eq!(
|
||||
bounded["observations"][1]["data"].as_array().unwrap().len(),
|
||||
120
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
|
||||
cc = "=1.11.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
|
||||
|
||||
[[example]]
|
||||
name = "windows_reviewed_recovery"
|
||||
|
||||
@@ -185,6 +185,7 @@ mod native {
|
||||
Payload::Heartbeat(Heartbeat {
|
||||
instance_id: Uuid::new_v4().to_string(),
|
||||
uptime_seconds: 1,
|
||||
system_usage: None,
|
||||
}),
|
||||
)?;
|
||||
let acknowledgement = send(client, &heartbeat).await?;
|
||||
|
||||
@@ -903,9 +903,6 @@ impl SystemHelper {
|
||||
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
|
||||
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
|
||||
let boot = WindowsBoot::capture()?;
|
||||
let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock)
|
||||
.ok()
|
||||
.map(|s| s.with_helper_identity(HelperIdentity::System));
|
||||
Ok(Self {
|
||||
settings,
|
||||
pin,
|
||||
@@ -914,7 +911,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 +1006,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 +1291,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(
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
//! uninstall commands; registry entries are evidence, not verified MSI state.
|
||||
use anyhow::{Result, ensure};
|
||||
use chrono::Utc;
|
||||
use rmm_domain::inventory_document::DeviceType;
|
||||
use rmm_domain::inventory_document::{
|
||||
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
mem::{size_of, zeroed},
|
||||
@@ -10,8 +12,12 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS},
|
||||
System::{Registry::*, SystemInformation::*},
|
||||
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, FILETIME},
|
||||
System::{
|
||||
Registry::*,
|
||||
SystemInformation::*,
|
||||
Threading::{GetActiveProcessorGroupCount, GetSystemTimes},
|
||||
},
|
||||
};
|
||||
|
||||
struct Registry(HKEY);
|
||||
@@ -116,13 +122,77 @@ fn classify_machine(
|
||||
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
|
||||
}
|
||||
|
||||
fn machine_type() -> Option<DeviceType> {
|
||||
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
|
||||
let hyper_v_host = open(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
r"SYSTEM\CurrentControlSet\Services\vmms",
|
||||
KEY_WOW64_64KEY,
|
||||
)
|
||||
.is_ok();
|
||||
classify_machine(
|
||||
hyper_v_host,
|
||||
non_microsoft_hypervisor(),
|
||||
manufacturer,
|
||||
product,
|
||||
)
|
||||
}
|
||||
|
||||
fn memory_status() -> Result<MEMORYSTATUSEX> {
|
||||
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
|
||||
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
|
||||
ensure!(
|
||||
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
|
||||
&& memory.ullTotalPhys > 0
|
||||
&& memory.ullAvailPhys <= memory.ullTotalPhys
|
||||
&& memory.dwMemoryLoad <= 100,
|
||||
"NATIVE_HARDWARE_QUERY"
|
||||
);
|
||||
Ok(memory)
|
||||
}
|
||||
|
||||
pub fn physical_memory() -> Option<(u64, u64)> {
|
||||
let memory = memory_status().ok()?;
|
||||
Some((memory.ullAvailPhys, memory.ullTotalPhys))
|
||||
}
|
||||
|
||||
pub fn cpu_times() -> Option<CpuTimes> {
|
||||
// GetSystemTimes on a multi-group machine only reports the caller's group.
|
||||
if unsafe { GetActiveProcessorGroupCount() } != 1 {
|
||||
return None;
|
||||
}
|
||||
let (mut idle, mut kernel, mut user) = (
|
||||
FILETIME::default(),
|
||||
FILETIME::default(),
|
||||
FILETIME::default(),
|
||||
);
|
||||
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let ticks =
|
||||
|time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
|
||||
// Windows includes idle time in the kernel counter.
|
||||
Some(CpuTimes {
|
||||
total: ticks(kernel).checked_add(ticks(user))?,
|
||||
idle: ticks(idle),
|
||||
})
|
||||
}
|
||||
|
||||
fn hardware() -> Result<Value> {
|
||||
let mut system: SYSTEM_INFO = unsafe { zeroed() };
|
||||
unsafe {
|
||||
GetNativeSystemInfo(&mut system);
|
||||
}
|
||||
ensure!(system.dwNumberOfProcessors > 0, "NATIVE_HARDWARE_QUERY");
|
||||
let memory = memory_status()?;
|
||||
let cpu_model = open(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
|
||||
KEY_WOW64_64KEY,
|
||||
)
|
||||
.ok()
|
||||
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty());
|
||||
let bios = open(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
r"HARDWARE\DESCRIPTION\System\BIOS",
|
||||
@@ -133,48 +203,24 @@ fn machine_type() -> Option<DeviceType> {
|
||||
bios.as_ref()
|
||||
.and_then(|key| text(key.0, name).ok().flatten())
|
||||
};
|
||||
classify_machine(
|
||||
hyper_v_host,
|
||||
non_microsoft_hypervisor(),
|
||||
read("SystemManufacturer").as_deref(),
|
||||
read("SystemProductName").as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
fn hardware() -> Result<Value> {
|
||||
let mut system: SYSTEM_INFO = unsafe { zeroed() };
|
||||
unsafe {
|
||||
GetNativeSystemInfo(&mut system);
|
||||
}
|
||||
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
|
||||
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
|
||||
ensure!(
|
||||
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
|
||||
&& system.dwNumberOfProcessors > 0
|
||||
&& memory.ullTotalPhys > 0
|
||||
&& memory.ullAvailPhys <= memory.ullTotalPhys
|
||||
&& memory.dwMemoryLoad <= 100,
|
||||
"NATIVE_HARDWARE_QUERY"
|
||||
);
|
||||
let cpu_model = open(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
|
||||
KEY_WOW64_64KEY,
|
||||
)
|
||||
.ok()
|
||||
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty());
|
||||
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
|
||||
let product = read("SystemProductName");
|
||||
let bios_serial_number = read("SystemSerialNumber")
|
||||
.and_then(|value| firmware_identifier(&value))
|
||||
.or_else(crate::inventory_sources::bios_serial);
|
||||
Ok(
|
||||
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
|
||||
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
|
||||
"memory_load_percent":memory.dwMemoryLoad,"device_type":machine_type()}),
|
||||
"memory_load_percent":memory.dwMemoryLoad,
|
||||
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
|
||||
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
|
||||
)
|
||||
}
|
||||
|
||||
fn software() -> Result<Value> {
|
||||
let began = Instant::now();
|
||||
let mut entries = Vec::new();
|
||||
let mut entry_bytes = 0;
|
||||
let mut errors = 0u32;
|
||||
let mut scanned = 0u32;
|
||||
let mut truncated = false;
|
||||
@@ -196,7 +242,7 @@ fn software() -> Result<Value> {
|
||||
}
|
||||
};
|
||||
for index in 0..2048 {
|
||||
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
|
||||
if began.elapsed() > Duration::from_millis(250) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
@@ -238,12 +284,12 @@ fn software() -> Result<Value> {
|
||||
})();
|
||||
match entry {
|
||||
Ok(Some(entry)) => {
|
||||
entries.push(entry);
|
||||
if serde_json::to_vec(&entries)?.len() > 12288 {
|
||||
entries.pop();
|
||||
entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
|
||||
if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(_) => errors += 1,
|
||||
@@ -274,7 +320,7 @@ pub fn observations() -> Vec<Value> {
|
||||
[
|
||||
(
|
||||
"windows.hardware",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
|
||||
hardware as Provider,
|
||||
),
|
||||
(
|
||||
@@ -282,6 +328,8 @@ pub fn observations() -> Vec<Value> {
|
||||
"windows.registry:HKLM.Uninstall:64+32",
|
||||
software as Provider,
|
||||
),
|
||||
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
|
||||
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(scope, source, collect)| {
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Local read-only inventory providers. Each result is bounded independently.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::inventory_document::firmware_identifier;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
ffi::c_void,
|
||||
mem::size_of,
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
ptr, slice,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
|
||||
NetworkManagement::IpHelper::*,
|
||||
Networking::WinSock::{
|
||||
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
|
||||
},
|
||||
System::{
|
||||
RemoteDesktop::*,
|
||||
SystemInformation::{GetSystemFirmwareTable, RSMB},
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) fn bios_serial() -> Option<String> {
|
||||
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
|
||||
if !(8..=1024 * 1024).contains(&length) {
|
||||
return None;
|
||||
}
|
||||
let mut data = vec![0; length as usize];
|
||||
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
|
||||
return None;
|
||||
}
|
||||
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
|
||||
smbios_serial(data.get(8..)?.get(..count)?)
|
||||
}
|
||||
|
||||
fn smbios_serial(mut table: &[u8]) -> Option<String> {
|
||||
while let Some(header) = table.get(..4) {
|
||||
let length = usize::from(header[1]);
|
||||
if length < 4 || header[0] == 127 {
|
||||
break;
|
||||
}
|
||||
let strings = table.get(length..)?;
|
||||
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
|
||||
if header[0] == 1 {
|
||||
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
|
||||
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
|
||||
return firmware_identifier(std::str::from_utf8(serial).ok()?);
|
||||
}
|
||||
table = strings.get(end + 2..)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
|
||||
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
|
||||
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
|
||||
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(unsafe { &*pointer })
|
||||
}
|
||||
|
||||
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
|
||||
let mut text = Vec::new();
|
||||
for i in 0..256 {
|
||||
let character = *at(buffer, pointer.wrapping_add(i))?;
|
||||
if character == 0 {
|
||||
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
|
||||
}
|
||||
text.push(character);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
|
||||
let sockaddr = at(buffer, address.lpSockaddr)?;
|
||||
match sockaddr.sa_family {
|
||||
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
|
||||
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
|
||||
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
|
||||
}
|
||||
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
|
||||
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
|
||||
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
|
||||
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
|
||||
Some(if scope == 0 {
|
||||
ip.to_string()
|
||||
} else {
|
||||
format!("{ip}%{scope}")
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn interfaces() -> Result<Value> {
|
||||
let mut bytes = 15360_u32;
|
||||
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
|
||||
let flags = GAA_FLAG_SKIP_ANYCAST
|
||||
| GAA_FLAG_SKIP_MULTICAST
|
||||
| GAA_FLAG_SKIP_DNS_SERVER
|
||||
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
|
||||
let mut status = unsafe {
|
||||
GetAdaptersAddresses(
|
||||
u32::from(AF_UNSPEC),
|
||||
flags,
|
||||
ptr::null(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
|
||||
buffer.resize((bytes as usize).div_ceil(8), 0);
|
||||
status = unsafe {
|
||||
GetAdaptersAddresses(
|
||||
u32::from(AF_UNSPEC),
|
||||
flags,
|
||||
ptr::null(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
}
|
||||
if status == ERROR_NO_DATA {
|
||||
return Ok(json!({"entries":[],"truncated":false}));
|
||||
}
|
||||
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
|
||||
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
|
||||
let mut entries = Vec::new();
|
||||
let mut truncated = false;
|
||||
let mut size = 0;
|
||||
while !current.is_null() && entries.len() < 128 {
|
||||
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
|
||||
let mut next = adapter.FirstUnicastAddress.cast_const();
|
||||
let mut addresses = BTreeSet::new();
|
||||
for _ in 0..64 {
|
||||
if next.is_null() {
|
||||
break;
|
||||
}
|
||||
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
|
||||
if let Some(ip) = ip_address(&buffer, address.Address) {
|
||||
addresses.insert(ip);
|
||||
}
|
||||
next = address.Next.cast_const();
|
||||
}
|
||||
truncated |= !next.is_null();
|
||||
let name = wide_name(&buffer, adapter.FriendlyName)
|
||||
.or_else(|| wide_name(&buffer, adapter.Description))
|
||||
.unwrap_or_else(|| {
|
||||
format!("Adapter {}", unsafe {
|
||||
adapter.Anonymous1.Anonymous.IfIndex
|
||||
})
|
||||
});
|
||||
let mac = adapter
|
||||
.PhysicalAddress
|
||||
.get(..adapter.PhysicalAddressLength as usize)
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.map(|bytes| {
|
||||
bytes
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(":")
|
||||
});
|
||||
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
|
||||
size += serde_json::to_vec(&entry)?.len() + 1;
|
||||
if size > 30 * 1024 {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
entries.push(entry);
|
||||
current = adapter.Next.cast_const();
|
||||
}
|
||||
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
|
||||
}
|
||||
|
||||
struct WtsMemory(*mut c_void);
|
||||
impl Drop for WtsMemory {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe { WTSFreeMemory(self.0) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
|
||||
let mut text = ptr::null_mut();
|
||||
let mut bytes = 0;
|
||||
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
|
||||
== 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let _guard = WtsMemory(text.cast());
|
||||
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
|
||||
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn users() -> Result<Value> {
|
||||
let mut list = ptr::null_mut();
|
||||
let mut count = 0;
|
||||
ensure!(
|
||||
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
|
||||
"SESSION_QUERY"
|
||||
);
|
||||
let _guard = WtsMemory(list.cast());
|
||||
let mut entries = BTreeSet::new();
|
||||
let mut errors = 0;
|
||||
let mut truncated = count > 256;
|
||||
if count != 0 {
|
||||
ensure!(!list.is_null(), "SESSION_LIST");
|
||||
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
|
||||
if session.SessionId == 0
|
||||
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match session_text(session.SessionId, WTSUserName) {
|
||||
Some(name) if !name.is_empty() => {
|
||||
let account = match session_text(session.SessionId, WTSDomainName) {
|
||||
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
|
||||
_ => name,
|
||||
};
|
||||
if entries.len() >= 64 {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
if account.len() <= 255 && !account.chars().any(char::is_control) {
|
||||
entries.insert(account);
|
||||
} else {
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => errors += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
errors == 0 || !entries.is_empty(),
|
||||
"SESSION_INFORMATION_UNAVAILABLE"
|
||||
);
|
||||
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::smbios_serial;
|
||||
|
||||
#[test]
|
||||
fn reads_the_system_serial_and_rejects_incomplete_entries() {
|
||||
assert_eq!(
|
||||
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
|
||||
Some("ABC-123")
|
||||
);
|
||||
assert_eq!(
|
||||
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ pub mod helper_system;
|
||||
pub mod windows_update_setup;
|
||||
#[cfg(windows)]
|
||||
pub mod inventory;
|
||||
mod inventory_sources;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::Utc;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
|
||||
@@ -261,7 +261,23 @@ pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
|
||||
Ok(String::from_utf16(&name[..len as usize])?)
|
||||
}
|
||||
|
||||
fn install_date() -> Option<DateTime<Utc>> {
|
||||
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
|
||||
let name = wide("InstallDate");
|
||||
let mut seconds = 0_u32;
|
||||
let mut bytes = size_of::<u32>() as u32;
|
||||
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
|
||||
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
|
||||
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
|
||||
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
|
||||
.flatten().filter(|time| *time <= Utc::now())
|
||||
}
|
||||
|
||||
pub fn snapshot() -> Result<Value> {
|
||||
snapshot_with_boot(None)
|
||||
}
|
||||
|
||||
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")? + "\\");
|
||||
@@ -281,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
|
||||
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","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
|
||||
{"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.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||
]});
|
||||
@@ -292,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
|
||||
snapshot["collection_completed_at"] = json!(Utc::now());
|
||||
Ok(snapshot)
|
||||
}
|
||||
pub async fn boot_id() -> Result<String> {
|
||||
pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
|
||||
// Fixed passive query only. Never interpolates a job or caller-supplied code.
|
||||
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
|
||||
let executable = Path::new(&std::env::var("SystemRoot")?)
|
||||
@@ -328,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
|
||||
.try_into()?;
|
||||
bytes[6] = (bytes[6] & 15) | 0x80;
|
||||
bytes[8] = (bytes[8] & 63) | 0x80;
|
||||
Ok(uuid::Uuid::from_bytes(bytes).to_string())
|
||||
let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
|
||||
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
|
||||
.context("BOOT_EPOCH")?;
|
||||
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
|
||||
}
|
||||
|
||||
pub async fn boot_id() -> Result<String> {
|
||||
boot_identity().await.map(|(id, _)| id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -8,7 +8,7 @@ use rmm_agent_core::{
|
||||
reconcile::{self, SyncClock},
|
||||
};
|
||||
use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore};
|
||||
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
|
||||
use rmm_agent_windows::{CAPABILITIES, inventory, job_binding::readonly_binding, journal::Journal, native};
|
||||
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
|
||||
use rmm_protocol::*;
|
||||
use rusqlite::{Connection, OptionalExtension};
|
||||
@@ -92,6 +92,11 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
|
||||
])
|
||||
}
|
||||
impl Config {
|
||||
fn supports_customer_transfer(&self) -> bool {
|
||||
cfg!(feature = "system-helper") && self.enable_jobs
|
||||
&& self.localservice_time_policy.is_some() && self.job_binding_file.is_none()
|
||||
&& !self.windows_echo_probe_only && !self.windows_update_helper
|
||||
}
|
||||
fn allows_script_action(&self, action: &Action, identity: &str) -> bool {
|
||||
let Action::RunScript { interpreter, windows_execution_profile, .. } = action else {
|
||||
return false;
|
||||
@@ -183,6 +188,16 @@ fn protected_read(path: &Path, max: usize) -> Result<Vec<u8>> {
|
||||
);
|
||||
Ok(fs::read(path)?)
|
||||
}
|
||||
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
|
||||
let key = match previous {
|
||||
Some(raw) => KeyPair::from_pem(std::str::from_utf8(raw)?)?,
|
||||
None => KeyPair::generate()?,
|
||||
};
|
||||
let mut parameters = CertificateParams::default();
|
||||
parameters.distinguished_name.push(DnType::CommonName, "customer-transfer");
|
||||
let csr = parameters.serialize_request(&key)?.pem()?;
|
||||
Ok((key.serialize_pem().into_bytes(), csr))
|
||||
}
|
||||
async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
|
||||
let state = &config.state_directory;
|
||||
let identity = state.join("identity.json");
|
||||
@@ -625,12 +640,14 @@ struct Agent {
|
||||
config: Config,
|
||||
reported_version: String,
|
||||
release_job_guard: Option<fs::File>,
|
||||
transfer_gate: Option<fs::File>,
|
||||
identity: EnrollmentResponse,
|
||||
ca: Vec<u8>,
|
||||
journal: Journal,
|
||||
certificates: RotationStore,
|
||||
key_files: ProtectedKeyFiles,
|
||||
boot: String,
|
||||
booted_at: chrono::DateTime<Utc>,
|
||||
instance: String,
|
||||
started: Instant,
|
||||
binding: Option<Binding>,
|
||||
@@ -934,7 +951,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;
|
||||
}));
|
||||
@@ -1274,8 +1291,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();
|
||||
@@ -1560,12 +1577,54 @@ impl Agent {
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
async fn stage_customer_transfer(&mut self) -> Result<bool> {
|
||||
if !self.config.supports_customer_transfer() || self.running.is_some()
|
||||
|| self.prepared || self.deferred_sync.is_some() || self.deferred_permit.is_some()
|
||||
|| self.release_job_guard.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let (Some(binding), Some(ledger)) = (&self.binding, &self.ledger) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !rmm_agent_core::customer_transfer::idle(self.journal.connection(), ledger)? {
|
||||
return Ok(false);
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
if self.helper_control_busy_for_sync() || self.update_health.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Keep the release service from replacing the program during the handoff.
|
||||
let binding = binding.clone();
|
||||
if !self.reserve_release_gate()? {
|
||||
return Ok(false);
|
||||
}
|
||||
let result = async {
|
||||
let identity = self.certificates.current(
|
||||
self.journal.connection(), &self.key_files, Utc::now().timestamp(),
|
||||
)?;
|
||||
let client = crate::https_channel::mtls_client(
|
||||
self.config.connect_address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
|
||||
)?;
|
||||
let base = format!("https://{}:{}", self.config.server_name, self.config.connect_address.port());
|
||||
rmm_agent_core::customer_transfer::stage(
|
||||
&client, &base, &self.config.state_directory, &binding, transfer_csr,
|
||||
).await
|
||||
}.await;
|
||||
let gate = self.release_job_guard.take();
|
||||
if matches!(&result, Ok(true)) {
|
||||
self.transfer_gate = gate;
|
||||
}
|
||||
result
|
||||
}
|
||||
fn capabilities(&self) -> Vec<String> {
|
||||
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
|
||||
#[cfg(target_env = "gnu")]
|
||||
caps.push("agent.release.windows.gnu/1".into());
|
||||
// queue_update_observation emits the passive update status in every profile.
|
||||
caps.push("agent.update/1".into());
|
||||
if self.config.supports_customer_transfer() {
|
||||
caps.push(rmm_domain::customer_transfer::CAPABILITY.into());
|
||||
}
|
||||
if self.config.windows_echo_probe_only {
|
||||
caps.push("windows.echo-probe/1".into());
|
||||
}
|
||||
@@ -2420,8 +2479,8 @@ impl Agent {
|
||||
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let data = serde_json::to_vec(&native::snapshot()?)?;
|
||||
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
|
||||
let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
|
||||
ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
|
||||
let envelope = self.envelope(
|
||||
generation,
|
||||
Payload::InventorySnapshot(InventorySnapshot {
|
||||
@@ -2537,7 +2596,7 @@ impl Agent {
|
||||
};
|
||||
self.renew_certificate(admission.as_deref()).await?;
|
||||
}
|
||||
self.boot = native::boot_id().await?;
|
||||
(self.boot, self.booted_at) = native::boot_identity().await?;
|
||||
let advertised = self.capabilities();
|
||||
let hello = self.envelope(
|
||||
0,
|
||||
@@ -2602,9 +2661,11 @@ impl Agent {
|
||||
let mut rotation_at = Instant::now();
|
||||
let mut rotation_after = Duration::from_secs(30);
|
||||
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);
|
||||
@@ -2615,9 +2676,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();}
|
||||
@@ -2649,7 +2720,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)?;
|
||||
@@ -2744,6 +2817,11 @@ impl Agent {
|
||||
if rotation_at.elapsed() >= rotation_after {
|
||||
rotation_at = Instant::now();
|
||||
rotation_after = Duration::from_secs(30);
|
||||
match self.stage_customer_transfer().await {
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) => (),
|
||||
Err(_) => eprintln!("CUSTOMER_TRANSFER_PENDING"),
|
||||
}
|
||||
let now = Utc::now().timestamp();
|
||||
if self
|
||||
.certificates
|
||||
@@ -2776,9 +2854,19 @@ impl Agent {
|
||||
// inventory offline. Retry setup at the next heartbeat.
|
||||
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
|
||||
}
|
||||
let cpu = inventory::cpu_times();
|
||||
let cpu_usage_basis_points = cpu.zip(previous_cpu)
|
||||
.and_then(|(current, previous)| current.usage_since(previous));
|
||||
previous_cpu = cpu;
|
||||
let memory = inventory::physical_memory();
|
||||
let payload = Payload::Heartbeat(Heartbeat {
|
||||
instance_id: self.instance.clone(),
|
||||
uptime_seconds: self.started.elapsed().as_secs(),
|
||||
system_usage: Some(SystemUsage {
|
||||
cpu_usage_basis_points,
|
||||
ram_available_bytes: memory.map(|(available, _)| available),
|
||||
ram_total_bytes: memory.map(|(_, total)| total),
|
||||
}),
|
||||
});
|
||||
let h = self.envelope(generation, payload)?;
|
||||
channel.send(&h).await?;
|
||||
@@ -2788,6 +2876,7 @@ impl Agent {
|
||||
Payload::Heartbeat(Heartbeat {
|
||||
instance_id: self.instance.clone(),
|
||||
uptime_seconds: self.started.elapsed().as_secs(),
|
||||
system_usage: None,
|
||||
}),
|
||||
)?;
|
||||
channel.poll(poll).await?;
|
||||
@@ -2807,7 +2896,7 @@ impl Agent {
|
||||
self.replay(&channel, generation).await?;
|
||||
replay = Instant::now();
|
||||
}
|
||||
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
|
||||
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
|
||||
self.queue_inventory(generation)?;
|
||||
inventory = Instant::now();
|
||||
}
|
||||
@@ -2892,7 +2981,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
);
|
||||
let path = Path::new(&arguments[2]);
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
||||
let config = Config::read(path)?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.worker_threads(2)
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let mut gate = None;
|
||||
loop {
|
||||
match run_service_binding(path, stop, gate.take()).await? {
|
||||
Some(held) => gate = Some(held),
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_guard: Option<fs::File>) -> Result<Option<fs::File>> {
|
||||
let mut config = Config::read(path)?;
|
||||
native::require_local_service()?;
|
||||
ensure!(
|
||||
config.state_directory.is_absolute(),
|
||||
@@ -2908,21 +3013,50 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
let child = child?;
|
||||
native::private_path(&child.path(), child.file_type()?.is_dir())?;
|
||||
}
|
||||
let journal = Journal::open(&config.state_directory)?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.worker_threads(2)
|
||||
.build()?;
|
||||
runtime.block_on(async move {
|
||||
let identity = enrollment(&config, &ca).await?;
|
||||
let mut journal=journal;
|
||||
if rmm_agent_core::customer_transfer::pending(&config.state_directory)? {
|
||||
#[cfg(feature = "system-helper")]
|
||||
{
|
||||
ensure!(config.supports_customer_transfer(), "TRANSFER_CONFIG");
|
||||
let policy = config.localservice_time_policy.as_deref().context("TRANSFER_POLICY")?;
|
||||
let signer = rmm_agent_windows::signed_clock::enrolled_transfer_signer(policy)?;
|
||||
loop {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
return Ok(None);
|
||||
}
|
||||
match rmm_agent_core::customer_transfer::activate(&config.state_directory, &signer) {
|
||||
Ok(()) => break,
|
||||
Err(error) if error.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| matches!(e.raw_os_error(), Some(32 | 33))) => {
|
||||
// Another service can briefly hold a read-only handle.
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "system-helper"))]
|
||||
anyhow::bail!("TRANSFER_CONFIG");
|
||||
}
|
||||
drop(release_guard);
|
||||
let mut journal = Journal::open(&config.state_directory)?;
|
||||
let identity = enrollment(&config, &ca).await?;
|
||||
journal.pin_identity(&identity.agent_id)?;
|
||||
let boot = native::boot_id().await?;
|
||||
let (boot, booted_at) = native::boot_identity().await?;
|
||||
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
|
||||
#[cfg(feature = "system-helper")]
|
||||
let binding = if let Some(policy) = &config.localservice_time_policy {
|
||||
Some(rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?)
|
||||
} else { binding };
|
||||
let (binding, installed_tenant) = if let Some(policy) = &config.localservice_time_policy {
|
||||
let mut enrolled = rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?;
|
||||
let installed = enrolled.tenant_id;
|
||||
if config.supports_customer_transfer()
|
||||
&& let Some(target) = rmm_agent_core::customer_transfer::assigned_tenant(
|
||||
&config.state_directory, &identity, &enrolled.public_key_hex,
|
||||
)? {
|
||||
enrolled.tenant_id = target;
|
||||
// Elevated helpers are bound to the original installation.
|
||||
config.managed_script_helper = false;
|
||||
}
|
||||
(Some(enrolled), Some(installed))
|
||||
} else { (binding, None) };
|
||||
if let Some(binding)=&binding {
|
||||
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
|
||||
native::private_path(&config.state_directory.join("jobs"),true)?;
|
||||
@@ -2939,7 +3073,9 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
#[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()).for_generation(0) }
|
||||
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) }
|
||||
} else { clock };
|
||||
let mut config=config;
|
||||
if config.enable_jobs {
|
||||
@@ -2955,18 +3091,32 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
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,
|
||||
reported_version: installed_version()?,
|
||||
release_job_guard: None,
|
||||
transfer_gate: None,
|
||||
identity,
|
||||
ca,
|
||||
journal,
|
||||
certificates,
|
||||
key_files,
|
||||
boot,
|
||||
booted_at,
|
||||
instance: Uuid::new_v4().to_string(),
|
||||
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
|
||||
#[cfg(feature="system-helper")]
|
||||
@@ -3024,6 +3174,12 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
if let Err(error) = agent.session(stop).await {
|
||||
record_session_error(&agent.config.state_directory, &error);
|
||||
}
|
||||
if let Some(guard) = agent.transfer_gate.take() {
|
||||
if let Some(worker) = agent.readiness_worker.take() {
|
||||
let _ = worker.await;
|
||||
}
|
||||
return Ok(Some(guard));
|
||||
}
|
||||
if start.elapsed() > Duration::from_secs(60) {
|
||||
backoff = 1;
|
||||
}
|
||||
@@ -3042,8 +3198,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
Ok(None)
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
@@ -3063,8 +3218,8 @@ pub fn main() -> Result<()> {
|
||||
}
|
||||
if args == ["--native-probe"] {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let boot = runtime.block_on(native::boot_id())?;
|
||||
let inventory = native::snapshot()?;
|
||||
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
|
||||
let inventory = native::snapshot_with_boot(Some(booted_at))?;
|
||||
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})
|
||||
|
||||
@@ -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]> {
|
||||
@@ -802,10 +811,7 @@ mod installed {
|
||||
tenant_id: Uuid,
|
||||
job_signing_public_key_hex: String,
|
||||
}
|
||||
pub fn enrolled_binding(
|
||||
policy: &Path,
|
||||
registration: &rmm_protocol::EnrollmentResponse,
|
||||
) -> Result<rmm_agent_core::auth::Binding> {
|
||||
fn installed_policy(policy: &Path) -> Result<LocalPolicy> {
|
||||
crate::job_binding::check_admin_readonly(policy)?;
|
||||
ensure!(
|
||||
std::fs::metadata(policy)?.len() <= MAX_CONFIG_BYTES as u64,
|
||||
@@ -816,6 +822,16 @@ mod installed {
|
||||
p.schema_version == 1 && !p.tenant_id.is_nil() && digest(&p.job_signing_public_key_hex),
|
||||
"INSTALLED_JOB_TRUST"
|
||||
);
|
||||
Ok(p)
|
||||
}
|
||||
pub fn enrolled_transfer_signer(policy: &Path) -> Result<String> {
|
||||
Ok(installed_policy(policy)?.job_signing_public_key_hex)
|
||||
}
|
||||
pub fn enrolled_binding(
|
||||
policy: &Path,
|
||||
registration: &rmm_protocol::EnrollmentResponse,
|
||||
) -> Result<rmm_agent_core::auth::Binding> {
|
||||
let p = installed_policy(policy)?;
|
||||
let binding = rmm_agent_core::auth::Binding {
|
||||
tenant_id: p.tenant_id,
|
||||
agent_id: Uuid::parse_str(®istration.agent_id)?,
|
||||
@@ -963,6 +979,7 @@ mod installed {
|
||||
generation: u64,
|
||||
binding: &rmm_agent_core::auth::Binding,
|
||||
policy_file: &Path,
|
||||
installed_tenant: Uuid,
|
||||
helper: Option<&ipc::PeerPin>,
|
||||
) -> Result<Self> {
|
||||
let mut failure_fence = ConstructorFailureFence { armed: true };
|
||||
@@ -1002,7 +1019,7 @@ mod installed {
|
||||
.map(|(id, key)| Ok((id, independent_time_key(&key, &binding.public_key_hex)?)))
|
||||
.collect::<Result<BTreeMap<_, _>>>()?;
|
||||
ensure!(
|
||||
p.tenant_id == binding.tenant_id
|
||||
p.tenant_id == installed_tenant
|
||||
&& p.job_signing_public_key_hex == binding.public_key_hex,
|
||||
"TIME_POLICY_BINDING"
|
||||
);
|
||||
@@ -1394,7 +1411,7 @@ mod installed {
|
||||
pub struct RuntimeClock {
|
||||
role: Role,
|
||||
enrolled_helper: Option<ipc::PeerPin>,
|
||||
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>,
|
||||
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
|
||||
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
@@ -1414,14 +1431,16 @@ mod installed {
|
||||
pub fn enrolled_local_service(
|
||||
binding: rmm_agent_core::auth::Binding,
|
||||
policy: std::path::PathBuf,
|
||||
installed_tenant: Uuid,
|
||||
) -> Self {
|
||||
let mut value = Self::new(Role::Agent);
|
||||
value.local_policy = Some((binding, policy));
|
||||
value.local_policy = Some((binding, policy, installed_tenant));
|
||||
value
|
||||
}
|
||||
pub fn enrolled_windows_update_helper(binding: rmm_agent_core::auth::Binding, helper: ipc::PeerPin) -> Self {
|
||||
let mut value = Self::new(Role::SystemHelper);
|
||||
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json")));
|
||||
let installed_tenant = binding.tenant_id;
|
||||
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json"), installed_tenant));
|
||||
value.enrolled_helper = Some(helper);
|
||||
value
|
||||
}
|
||||
@@ -1440,8 +1459,8 @@ mod installed {
|
||||
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
|
||||
self.close()?;
|
||||
let clock = match &self.local_policy {
|
||||
Some((binding, policy)) => {
|
||||
SignedClock::open_local_service(generation, binding, policy, self.enrolled_helper.as_ref()).await?
|
||||
Some((binding, policy, installed_tenant)) => {
|
||||
SignedClock::open_local_service(generation, binding, policy, *installed_tenant, self.enrolled_helper.as_ref()).await?
|
||||
}
|
||||
None => SignedClock::open(self.role, generation).await?,
|
||||
};
|
||||
@@ -1561,7 +1580,7 @@ mod installed {
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub use installed::{
|
||||
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
|
||||
enrolled_binding,
|
||||
enrolled_binding, enrolled_transfer_signer,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1637,6 +1656,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,
|
||||
|
||||
@@ -103,7 +103,7 @@ impl Observer {
|
||||
}
|
||||
self.cached()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Observation::not_configured(Platform::LinuxX64, chrono::Utc::now()))
|
||||
.unwrap_or_else(|| Observation::not_configured(Platform::NATIVE_LINUX, chrono::Utc::now()))
|
||||
}
|
||||
pub fn catalog_record(&self) -> Option<GuardedRecord> {
|
||||
self.cached()?;
|
||||
|
||||
@@ -15,7 +15,7 @@ use rmm_domain::{
|
||||
};
|
||||
use rmm_privileged_helper::{Binding, TrustedClock};
|
||||
use rmm_updater::{
|
||||
ActiveRelease, Platform as ReleasePlatform, ReleaseRelation, SignedRelease, TrustedContext,
|
||||
ActiveRelease, ReleaseRelation, SignedRelease, TrustedContext,
|
||||
TrustedUpdateKey, UpdateKeyring, verify_release,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
@@ -346,12 +346,12 @@ impl Trust {
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_CATALOG_KEY_SIZE"))?;
|
||||
ensure!(
|
||||
key.platform == Platform::LinuxX64 && key.public_key_hex != binding.public_key_hex,
|
||||
key.platform == Platform::NATIVE_LINUX && key.public_key_hex != binding.public_key_hex,
|
||||
"UPDATE_CATALOG_KEY_SEPARATION"
|
||||
);
|
||||
trusted.push(TrustedUpdateKey::new(
|
||||
public,
|
||||
ReleasePlatform::LinuxX64,
|
||||
Platform::NATIVE_LINUX.into(),
|
||||
key.first_sequence,
|
||||
key.last_sequence,
|
||||
key.revoked,
|
||||
@@ -426,7 +426,7 @@ impl Trust {
|
||||
},
|
||||
&self.keys,
|
||||
&TrustedContext {
|
||||
platform: ReleasePlatform::LinuxX64,
|
||||
platform: Platform::NATIVE_LINUX.into(),
|
||||
now_utc_seconds: now,
|
||||
keyring_generation: self.generation,
|
||||
protocol_major: self.protocol,
|
||||
@@ -522,16 +522,18 @@ async fn request(
|
||||
async fn fetch(client: &reqwest::Client, address: SocketAddr) -> Result<Vec<u8>> {
|
||||
let response = client
|
||||
.get(format!(
|
||||
"https://{}:{}/agent/v1/releases/current?platform=x86_64-unknown-linux-gnu",
|
||||
"https://{}:{}/agent/v1/releases/current?platform={}",
|
||||
crate::https_channel::server_name()?,
|
||||
address.port()
|
||||
address.port(),
|
||||
Platform::NATIVE_LINUX.target_triple()
|
||||
))
|
||||
.send()
|
||||
.await?;
|
||||
crate::https_channel::bounded_body(response, RESPONSE_LIMIT, "application/json").await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
// These fixtures provision the legacy x86-64 manual updater profile.
|
||||
#[cfg(all(test, target_arch = "x86_64"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
|
||||
@@ -319,7 +319,7 @@ pub fn context(
|
||||
let scope = match job.action {
|
||||
rmm_domain::jobs::Action::UpdateAgent { ref update } => {
|
||||
match update.manifest().map_err(anyhow::Error::msg)?.platform {
|
||||
update::Platform::LinuxX64 => "linux.base",
|
||||
update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
|
||||
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
|
||||
}
|
||||
}
|
||||
|
||||
+116
-13
@@ -64,6 +64,8 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
rotation_policy: certificate_rotation::RotationPolicy,
|
||||
catalog: agent_update_catalog::Checker,
|
||||
update_observer: agent_update_apply::Observer,
|
||||
transfer_state: Option<PathBuf>,
|
||||
transfer_gate: Option<fs::File>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct EffectFence {
|
||||
@@ -465,6 +467,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
"heartbeat/1".into(),
|
||||
"agent.update/1".into(),
|
||||
];
|
||||
if self.transfer_state.is_some() {
|
||||
capabilities.push(rmm_domain::customer_transfer::CAPABILITY.into());
|
||||
}
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
capabilities.push(rmm_domain::agent_update::LINUX_ARM64_RELEASE_CAPABILITY.into());
|
||||
if self.binding.is_some() {
|
||||
capabilities.push("rmm.sync.v1".into());
|
||||
}
|
||||
@@ -474,16 +481,43 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
||||
capabilities.push("run_script".into());
|
||||
}
|
||||
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||
if self.helpers.is_some() {
|
||||
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||
}
|
||||
}
|
||||
capabilities.sort();
|
||||
capabilities.dedup();
|
||||
capabilities
|
||||
}
|
||||
fn queue_inventory(&mut self) {
|
||||
async fn stage_customer_transfer(&mut self) -> Result<bool> {
|
||||
let (Some(dir), Some(binding)) = (&self.transfer_state, &self.binding) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !self.running_cancels.is_empty() || self.prepared.is_some()
|
||||
|| !rmm_agent_core::customer_transfer::idle(&self.db, &self.ledger)? {
|
||||
return Ok(false);
|
||||
}
|
||||
let identity = self.certificates.current(Utc::now().timestamp())?;
|
||||
let client = https_channel::mtls_client(
|
||||
self.address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
|
||||
)?;
|
||||
let base = format!("https://{}:{}", https_channel::server_name()?, self.address.port());
|
||||
let guard = fs::File::open(env::var_os("RMM_RELEASE_LOCK").context("RELEASE_LOCK_REQUIRED")?)?;
|
||||
match fs2::FileExt::try_lock_shared(&guard) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => return Ok(false),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
if rmm_agent_core::customer_transfer::stage(&client, &base, dir, binding, transfer_csr).await? {
|
||||
self.transfer_gate = Some(guard);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
fn queue_inventory(&mut self) -> bool {
|
||||
if self.inventory_inflight || !storage::passive_collection_ready(&self.db).unwrap_or(false)
|
||||
{
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
self.inventory_inflight = true;
|
||||
let sender = self.inventory_tx.clone();
|
||||
@@ -511,12 +545,12 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.push(agent_update_catalog::observation(report, Utc::now()));
|
||||
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
|
||||
}
|
||||
let bytes = serde_json::to_vec(&inventory)?;
|
||||
ensure!(bytes.len() <= 512 * 1024, "INVENTORY_WIRE_LIMIT");
|
||||
let bytes = rmm_agent_linux::wire::encode_snapshot(inventory)?;
|
||||
Ok((bytes, Utc::now().timestamp_millis()))
|
||||
});
|
||||
let _ = sender.blocking_send(result);
|
||||
});
|
||||
true
|
||||
}
|
||||
fn queue_update_observation(&mut self, generation: u64) -> Result<()> {
|
||||
if !storage::passive_collection_ready(&self.db)? {
|
||||
@@ -647,6 +681,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
let mut inventory_at = Instant::now();
|
||||
let mut update_at = Instant::now();
|
||||
let mut heartbeat_at = Instant::now();
|
||||
let mut previous_cpu = None;
|
||||
let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(5));
|
||||
let mut sync_at = Instant::now();
|
||||
@@ -749,10 +784,10 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
let decoded=proof.decode().map_err(anyhow::Error::msg)?;
|
||||
let event:Option<rmm_updater_handoff::Event>=decoded.events.last().map(|raw|serde_json::from_slice(raw)).transpose()?;
|
||||
if event.is_some_and(|event|matches!(event.evidence,rmm_updater_handoff::Evidence::ServicesStarted{..}|rmm_updater_handoff::Evidence::RollbackServicesStarted{..})) {
|
||||
if health_inventory_prefix.as_deref()!=Some(proof.head_sha256.as_str()) {
|
||||
if health_inventory_prefix.as_deref()!=Some(proof.head_sha256.as_str()) && self.queue_inventory() {
|
||||
// Fixed update health includes one genuinely new
|
||||
// normal base sample, never a fresh timestamp on old data.
|
||||
self.queue_inventory();health_inventory_prefix=Some(proof.head_sha256.clone());
|
||||
health_inventory_prefix=Some(proof.head_sha256.clone());
|
||||
}
|
||||
if health_task.is_none() && self.prepared.is_none() {
|
||||
match self.start_update_health(proof) {Ok(task)=>health_task=task,Err(error)=>{report_closed_gate(&error);self.close_gate();needs_sync=true;}}
|
||||
@@ -807,11 +842,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
if first_heartbeat || heartbeat_at.elapsed() >= heartbeat_after {
|
||||
first_heartbeat = false;
|
||||
let cpu = rmm_agent_linux::inventory::cpu_times();
|
||||
let cpu_usage_basis_points = cpu.zip(previous_cpu)
|
||||
.and_then(|(current, previous)| current.usage_since(previous));
|
||||
previous_cpu = cpu;
|
||||
let memory = rmm_agent_linux::inventory::memory().data;
|
||||
let heartbeat = self.envelope(
|
||||
generation,
|
||||
Payload::Heartbeat(Heartbeat {
|
||||
instance_id: self.instance.clone(),
|
||||
uptime_seconds: self.started.elapsed().as_secs(),
|
||||
system_usage: Some(SystemUsage {
|
||||
cpu_usage_basis_points,
|
||||
ram_available_bytes: memory.as_ref().and_then(|m| m.available_bytes),
|
||||
ram_total_bytes: memory.map(|m| m.total_bytes),
|
||||
}),
|
||||
}),
|
||||
)?;
|
||||
ws.send(&heartbeat).await?;
|
||||
@@ -821,6 +866,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
Payload::Heartbeat(Heartbeat {
|
||||
instance_id: self.instance.clone(),
|
||||
uptime_seconds: self.started.elapsed().as_secs(),
|
||||
system_usage: None,
|
||||
}),
|
||||
)?;
|
||||
ws.poll(poll).await?;
|
||||
@@ -828,12 +874,18 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
heartbeat_at = Instant::now();
|
||||
heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
|
||||
}
|
||||
if inventory_at.elapsed() >= Duration::from_secs(60) {
|
||||
self.queue_inventory();
|
||||
// A simultaneous update report can fill the durable queue. Keep
|
||||
// inventory due until collection actually starts.
|
||||
if inventory_at.elapsed() >= Duration::from_secs(60) && self.queue_inventory() {
|
||||
inventory_at = Instant::now();
|
||||
}
|
||||
if rotation_at.elapsed() >= Duration::from_secs(30) {
|
||||
rotation_at = Instant::now();
|
||||
match self.stage_customer_transfer().await {
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) => (),
|
||||
Err(_) => eprintln!("customer transfer waiting for a valid handoff"),
|
||||
}
|
||||
if self
|
||||
.certificates
|
||||
.due(self.rotation_policy, Utc::now().timestamp())?
|
||||
@@ -858,6 +910,27 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
|
||||
let key = match previous {
|
||||
Some(raw) => PKey::private_key_from_pem(raw)?,
|
||||
None => {
|
||||
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
|
||||
PKey::from_ec_key(EcKey::generate(&group)?)?
|
||||
}
|
||||
};
|
||||
let mut csr = X509Req::builder()?;
|
||||
let mut name = X509NameBuilder::new()?;
|
||||
name.append_entry_by_text("CN", "customer-transfer")?;
|
||||
csr.set_subject_name(&name.build())?;
|
||||
csr.set_pubkey(&key)?;
|
||||
csr.sign(&key, MessageDigest::sha256())?;
|
||||
Ok((key.private_key_to_pem_pkcs8()?, String::from_utf8(csr.build().to_pem()?)?))
|
||||
}
|
||||
|
||||
fn customer_transfer_signer(dir: &Path) -> Result<rmm_privileged_helper::SigningKey> {
|
||||
rmm_privileged_helper::SigningKey::read(&dir.join("job-signing-key.json"), unsafe { libc::geteuid() })
|
||||
}
|
||||
|
||||
async fn enrollment(dir: &Path, address: std::net::SocketAddr, ca: &[u8]) -> Result<String> {
|
||||
let identity = dir.join("identity.json");
|
||||
if identity.exists() {
|
||||
@@ -935,6 +1008,18 @@ async fn main() -> Result<()> {
|
||||
PathBuf::from(env::var("RMM_AGENT_STATE").unwrap_or_else(|_| "devstate/agent".into()));
|
||||
storage::prepare_dir(&dir)?;
|
||||
let _lock = storage::lock(&dir)?;
|
||||
let mut release_guard = None;
|
||||
loop {
|
||||
if rmm_agent_core::customer_transfer::pending(&dir)? {
|
||||
let signer = customer_transfer_signer(&dir)?;
|
||||
rmm_agent_core::customer_transfer::activate(&dir, &signer.public_key_hex)?;
|
||||
}
|
||||
drop(release_guard.take());
|
||||
release_guard = Some(run_agent(&dir).await?);
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_agent(dir: &Path) -> Result<fs::File> {
|
||||
let address = env::var("RMM_CONNECT_ADDR")
|
||||
.unwrap_or_else(|_| "127.0.0.1:18443".into())
|
||||
.parse()?;
|
||||
@@ -963,6 +1048,20 @@ async fn main() -> Result<()> {
|
||||
enrollment_generation: 1, assignment_version: 1, public_key_hex: String::new(),
|
||||
});
|
||||
}
|
||||
let transfer_state = (env::var_os("RMM_JOB_BINDING_FILE").is_none()
|
||||
&& env::var_os("RMM_ENROLLMENT_TENANT").is_some()
|
||||
&& env::var("RMM_JOB_SIGNING_KEY_BOOTSTRAP").as_deref() == Ok("1")
|
||||
&& env::var_os("RMM_RELEASE_LOCK").is_some()).then(|| dir.to_owned());
|
||||
let mut moved = false;
|
||||
if transfer_state.is_some() && let Some(binding) = binding.as_mut()
|
||||
&& dir.join("job-signing-key.json").try_exists()? {
|
||||
let identity: EnrollmentResponse = serde_json::from_slice(&fs::read(dir.join("identity.json"))?)?;
|
||||
let signer = customer_transfer_signer(dir)?;
|
||||
if let Some(tenant) = rmm_agent_core::customer_transfer::assigned_tenant(dir, &identity, &signer.public_key_hex)? {
|
||||
binding.tenant_id = tenant;
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
let certificate_dir = dir.join("certificates");
|
||||
let certificates = certificate_rotation::RotationStore::open(
|
||||
&certificate_dir,
|
||||
@@ -994,10 +1093,9 @@ async fn main() -> Result<()> {
|
||||
let sync = binding
|
||||
.as_ref()
|
||||
.map(|b| reconcile::ClientSync::new(b.clone()));
|
||||
let helpers = binding
|
||||
.as_ref()
|
||||
.map(helper_sync::Helpers::configured)
|
||||
.transpose()?;
|
||||
let helpers = if moved { None } else {
|
||||
binding.as_ref().map(helper_sync::Helpers::configured).transpose()?
|
||||
};
|
||||
let mut rotation_policy = certificate_rotation::RotationPolicy::default();
|
||||
if let Ok(after) = env::var("RMM_ROTATION_TEST_AFTER_SECONDS") {
|
||||
ensure!(
|
||||
@@ -1039,6 +1137,8 @@ async fn main() -> Result<()> {
|
||||
rotation_policy,
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state,
|
||||
transfer_gate: None,
|
||||
};
|
||||
agent.recover_interrupted()?;
|
||||
let mut backoff = 1_u64;
|
||||
@@ -1048,6 +1148,9 @@ async fn main() -> Result<()> {
|
||||
report_closed_gate(&error);
|
||||
}
|
||||
agent.close_gate();
|
||||
if let Some(guard) = agent.transfer_gate.take() {
|
||||
return Ok(guard);
|
||||
}
|
||||
eprintln!("channel unavailable; retrying with jitter (no jobs can execute)");
|
||||
if started.elapsed() > Duration::from_secs(60) {
|
||||
backoff = 1;
|
||||
|
||||
@@ -152,6 +152,8 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state: None,
|
||||
transfer_gate: None,
|
||||
};
|
||||
// A forged local consumption/start cannot become a purported grant result.
|
||||
agent
|
||||
@@ -541,6 +543,8 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state: None,
|
||||
transfer_gate: None,
|
||||
};
|
||||
for _ in 0..rounds {
|
||||
assert!(
|
||||
|
||||
@@ -42,7 +42,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
|
||||
signature: URL_SAFE_NO_PAD.encode([1_u8; 64]),
|
||||
};
|
||||
let transition = match platform {
|
||||
Platform::LinuxX64 if full => PeerPinTransition::LinuxGeneralFullV1 {
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 if full => PeerPinTransition::LinuxGeneralFullV1 {
|
||||
general_pin_sha256: "10".repeat(32),
|
||||
full: LinuxFullTransition {
|
||||
schema_version: 1,
|
||||
@@ -57,7 +57,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
|
||||
effective_signing_key_id: "17".repeat(32),
|
||||
},
|
||||
},
|
||||
Platform::LinuxX64 => PeerPinTransition::UnchangedGeneralPinV1 {
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 => PeerPinTransition::UnchangedGeneralPinV1 {
|
||||
general_pin_sha256: "10".repeat(32),
|
||||
},
|
||||
Platform::WindowsX64 | Platform::WindowsGnuX64 => PeerPinTransition::WindowsCodePairV1 {
|
||||
@@ -110,7 +110,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
|
||||
update: Box::new(update),
|
||||
},
|
||||
execution_identity: match platform {
|
||||
Platform::LinuxX64 => "root",
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
|
||||
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
|
||||
}
|
||||
.into(),
|
||||
|
||||
@@ -50,11 +50,34 @@ impl UpdateKeyringFile {
|
||||
pub enum Platform {
|
||||
#[serde(rename = "x86_64-unknown-linux-gnu")]
|
||||
LinuxX64,
|
||||
#[serde(rename = "aarch64-unknown-linux-gnu")]
|
||||
LinuxArm64,
|
||||
#[serde(rename = "x86_64-pc-windows-msvc")]
|
||||
WindowsX64,
|
||||
#[serde(rename = "x86_64-pc-windows-gnu")]
|
||||
WindowsGnuX64,
|
||||
}
|
||||
pub const LINUX_ARM64_RELEASE_CAPABILITY: &str = "agent.release.linux.arm64/1";
|
||||
|
||||
impl Platform {
|
||||
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
|
||||
pub const NATIVE_LINUX: Self = Self::LinuxArm64;
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
pub const NATIVE_LINUX: Self = Self::LinuxX64;
|
||||
|
||||
pub const fn is_linux(self) -> bool {
|
||||
matches!(self, Self::LinuxX64 | Self::LinuxArm64)
|
||||
}
|
||||
|
||||
pub const fn target_triple(self) -> &'static str {
|
||||
match self {
|
||||
Self::LinuxX64 => "x86_64-unknown-linux-gnu",
|
||||
Self::LinuxArm64 => "aarch64-unknown-linux-gnu",
|
||||
Self::WindowsX64 => "x86_64-pc-windows-msvc",
|
||||
Self::WindowsGnuX64 => "x86_64-pc-windows-gnu",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ArtifactRole {
|
||||
@@ -708,7 +731,7 @@ impl ResolvedAgentUpdate {
|
||||
}
|
||||
pub fn execution_identity(&self) -> Option<&'static str> {
|
||||
self.manifest().ok().map(|m| match m.platform {
|
||||
Platform::LinuxX64 => "root",
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
|
||||
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const CAPABILITY: &str = "device.customer_transfer/1";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Offer {
|
||||
pub transfer_id: Uuid,
|
||||
pub source_tenant_id: Uuid,
|
||||
pub source_agent_id: Uuid,
|
||||
pub target_tenant_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Binding {
|
||||
pub offer: Offer,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub certificate_sha256: String,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
pub fn signing_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
|
||||
let mut bytes = b"rust-discovery:customer-transfer:1\0".to_vec();
|
||||
bytes.extend(serde_json::to_vec(self)?);
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Receipt {
|
||||
pub binding: Binding,
|
||||
pub signature_hex: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CertificateRequest {
|
||||
pub csr_pem: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CertificateResponse {
|
||||
pub certificate_pem: String,
|
||||
pub receipt: Receipt,
|
||||
}
|
||||
@@ -3,6 +3,21 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
|
||||
pub const LINUX_SOFTWARE_OBSERVATION_MAX_BYTES: usize = 256 * 1024;
|
||||
|
||||
pub fn firmware_identifier(value: &str) -> Option<String> {
|
||||
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
|
||||
let lower = value.to_ascii_lowercase();
|
||||
(!value.is_empty()
|
||||
&& value.len() <= 255
|
||||
&& !value.chars().any(char::is_control)
|
||||
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
|
||||
| "default string" | "to be filled by o.e.m." | "system serial number")
|
||||
&& !value.bytes().all(|b| b == b'0'))
|
||||
.then(|| value.to_owned())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeviceType {
|
||||
@@ -11,6 +26,22 @@ pub enum DeviceType {
|
||||
Hypervisor,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CpuTimes {
|
||||
pub total: u64,
|
||||
pub idle: u64,
|
||||
}
|
||||
|
||||
impl CpuTimes {
|
||||
pub fn usage_since(self, previous: Self) -> Option<u32> {
|
||||
let total = self.total.checked_sub(previous.total)?;
|
||||
let idle = self.idle.checked_sub(previous.idle)?;
|
||||
let busy = total.checked_sub(idle)?;
|
||||
(total != 0)
|
||||
.then(|| ((u128::from(busy) * 10_000 + u128::from(total / 2)) / u128::from(total)) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Observation {
|
||||
@@ -75,7 +106,7 @@ pub fn validate_for_scope(
|
||||
.map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?
|
||||
!= update
|
||||
|| !typed.agent_update.validate()
|
||||
|| (typed.agent_update.platform == crate::agent_update::Platform::LinuxX64) != (scope == "linux.base")
|
||||
|| typed.agent_update.platform.is_linux() != (scope == "linux.base")
|
||||
|| typed.agent_update.observed_at - now > chrono::Duration::seconds(45)
|
||||
|| now - typed.agent_update.observed_at > chrono::Duration::hours(72)
|
||||
{
|
||||
@@ -136,10 +167,15 @@ pub fn validate_for_scope(
|
||||
}
|
||||
let mut scopes = std::collections::BTreeSet::new();
|
||||
for item in observations {
|
||||
let max_bytes = match (scope, item["scope"].as_str()) {
|
||||
("linux.base", Some("linux.software")) => LINUX_SOFTWARE_OBSERVATION_MAX_BYTES,
|
||||
("windows.base", Some("windows.software")) => SOFTWARE_OBSERVATION_MAX_BYTES,
|
||||
_ => 32768,
|
||||
};
|
||||
if serde_json::to_vec(item)
|
||||
.map_err(|_| "INVALID_OBSERVATION")?
|
||||
.len()
|
||||
> 32768
|
||||
> max_bytes
|
||||
{
|
||||
return Err("OBSERVATION_SIZE");
|
||||
}
|
||||
@@ -234,6 +270,23 @@ mod tests {
|
||||
assert!(validate(&serde_json::to_vec(&unknown).unwrap(), now).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn larger_linux_package_lists_fit_the_software_scope() {
|
||||
let now = Utc::now();
|
||||
let mut v = base();
|
||||
let package = json!({"name":"some-package","version":"1.0","architecture":"amd64"});
|
||||
v["collection_started_at"] = json!(now);
|
||||
v["collection_completed_at"] = json!(now);
|
||||
v["observations"] = json!([{"scope":"linux.software","source_id":"dpkg-query","observed_at":now,"quality":"valid","completeness":"complete","truncated":false,"error_code":null,"data":vec![package; 2200]}]);
|
||||
let bytes = serde_json::to_vec(&v).unwrap();
|
||||
assert!(bytes.len() > SOFTWARE_OBSERVATION_MAX_BYTES);
|
||||
assert!(validate(&bytes, now).is_ok());
|
||||
v["observations"][0]["scope"] = json!("linux.hardware");
|
||||
assert_eq!(
|
||||
validate(&serde_json::to_vec(&v).unwrap(), now).unwrap_err(),
|
||||
"OBSERVATION_SIZE"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn windows_scope_does_not_weaken_linux_or_accept_platform_spoofing() {
|
||||
let now = Utc::now();
|
||||
let mut v = base();
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod agent_update;
|
||||
pub mod agent_update_provisioning;
|
||||
pub mod apt_transaction;
|
||||
pub mod checkpoint_repair;
|
||||
pub mod customer_transfer;
|
||||
pub mod inventory_document;
|
||||
pub mod jobs;
|
||||
pub mod reconciliation;
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn observe_record(
|
||||
&& response.ledger_inode != 0
|
||||
&& response.lock_inode != 0
|
||||
&& response.observation.validate()
|
||||
&& response.observation.platform == Platform::LinuxX64,
|
||||
&& response.observation.platform == Platform::NATIVE_LINUX,
|
||||
"UPDATE_OBSERVER_RESPONSE_BINDING"
|
||||
);
|
||||
let record = rmm_domain::agent_update_provisioning::InstalledReleaseRecord::from_bytes(
|
||||
@@ -346,7 +346,7 @@ pub fn collect(db: &Connection, local: Local<'_>, request: &Request) -> Result<R
|
||||
));
|
||||
let observation = AgentUpdateObservation {
|
||||
schema_version: 1,
|
||||
platform: Platform::LinuxX64,
|
||||
platform: Platform::NATIVE_LINUX,
|
||||
observed_at,
|
||||
quality: ObservationQuality::Valid,
|
||||
predecessor: Some(trust.predecessor().clone()),
|
||||
|
||||
@@ -81,6 +81,17 @@ pub struct Heartbeat {
|
||||
pub instance_id: String,
|
||||
#[prost(uint64, tag = "2")]
|
||||
pub uptime_seconds: u64,
|
||||
#[prost(message, optional, tag = "3")]
|
||||
pub system_usage: Option<SystemUsage>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub struct SystemUsage {
|
||||
#[prost(uint32, optional, tag = "1")]
|
||||
pub cpu_usage_basis_points: Option<u32>,
|
||||
#[prost(uint64, optional, tag = "2")]
|
||||
pub ram_available_bytes: Option<u64>,
|
||||
#[prost(uint64, optional, tag = "3")]
|
||||
pub ram_total_bytes: Option<u64>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub struct InventorySnapshot {
|
||||
@@ -156,6 +167,7 @@ mod tests {
|
||||
payload: Some(Payload::Heartbeat(Heartbeat {
|
||||
instance_id: "x".into(),
|
||||
uptime_seconds: 1,
|
||||
system_usage: None,
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ use chrono::{DateTime, Utc};
|
||||
use prost::Message;
|
||||
use rmm_domain::MAX_MESSAGE;
|
||||
use rmm_protocol::*;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
@@ -104,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;
|
||||
@@ -146,7 +147,14 @@ pub async fn ingest(
|
||||
match &e.payload {
|
||||
Some(Payload::Heartbeat(h)) => {
|
||||
Uuid::parse_str(&h.instance_id)?;
|
||||
sqlx::query("UPDATE agent_installations SET last_contact_at=now() WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).execute(&mut *tx).await?;
|
||||
let usage = h.system_usage.as_ref().and_then(|sample| system_usage(sample, observed));
|
||||
sqlx::query("UPDATE agent_installations SET last_contact_at=now(),
|
||||
system_usage=CASE WHEN $2::jsonb IS NULL THEN system_usage
|
||||
ELSE COALESCE(system_usage,'{}'::jsonb) || $2 END,
|
||||
system_usage_observed_at=CASE WHEN $2::jsonb ? 'ram_available_bytes'
|
||||
THEN $3 ELSE system_usage_observed_at END
|
||||
WHERE agent_id=$1 AND revoked_at IS NULL")
|
||||
.bind(agent).bind(usage).bind(observed).execute(&mut *tx).await?;
|
||||
}
|
||||
Some(Payload::InventorySnapshot(s)) => {
|
||||
ensure!(
|
||||
@@ -188,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,
|
||||
@@ -197,3 +215,49 @@ pub async fn ingest(
|
||||
e.connection_generation,
|
||||
))
|
||||
}
|
||||
|
||||
fn system_usage(sample: &SystemUsage, observed: DateTime<Utc>) -> Option<Value> {
|
||||
let cpu = sample
|
||||
.cpu_usage_basis_points
|
||||
.filter(|&value| value <= 10_000);
|
||||
let memory = sample
|
||||
.ram_available_bytes
|
||||
.zip(sample.ram_total_bytes)
|
||||
.filter(|&(available, total)| total > 0 && available <= total);
|
||||
let mut usage = serde_json::Map::new();
|
||||
if let Some(cpu) = cpu {
|
||||
usage.insert("cpu_usage_percent".into(), json!(f64::from(cpu) / 100.0));
|
||||
usage.insert("cpu_usage_observed_at".into(), json!(observed));
|
||||
}
|
||||
if let Some((available, total)) = memory {
|
||||
usage.insert("ram_available_bytes".into(), json!(available));
|
||||
usage.insert("ram_total_bytes".into(), json!(total));
|
||||
}
|
||||
(!usage.is_empty()).then_some(Value::Object(usage))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_zero_usage_and_ignores_invalid_metrics_without_losing_the_heartbeat() {
|
||||
let mut sample = SystemUsage {
|
||||
cpu_usage_basis_points: Some(0),
|
||||
ram_available_bytes: Some(0),
|
||||
ram_total_bytes: Some(1),
|
||||
};
|
||||
let now = Utc::now();
|
||||
let measured = system_usage(&sample, now).unwrap();
|
||||
assert_eq!(measured["cpu_usage_percent"], json!(0.0));
|
||||
assert_eq!(measured["cpu_usage_observed_at"], json!(now));
|
||||
assert_eq!(measured["ram_available_bytes"], json!(0));
|
||||
assert_eq!(measured["ram_total_bytes"], json!(1));
|
||||
sample.cpu_usage_basis_points = Some(10_001);
|
||||
let partial = system_usage(&sample, now).unwrap();
|
||||
assert!(partial.get("cpu_usage_percent").is_none());
|
||||
assert!(partial.get("cpu_usage_observed_at").is_none());
|
||||
sample.ram_available_bytes = Some(2);
|
||||
assert_eq!(system_usage(&sample, now), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,7 +418,7 @@ async fn issue(
|
||||
&& snapshot.sha256 == hex::decode(hash(&snapshot.data)).map_err(|_| denied())?,
|
||||
)?;
|
||||
let scope = match action.manifest().map_err(|_| denied())?.platform {
|
||||
update::Platform::LinuxX64 => "linux.base",
|
||||
update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
|
||||
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
|
||||
};
|
||||
// Health requires a fresh real base inventory of the restarted platform;
|
||||
|
||||
@@ -17,7 +17,7 @@ use axum::{
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::StreamExt;
|
||||
use rmm_domain::{
|
||||
agent_update::{ArtifactDescriptor, Platform, ReleaseEnvelope, ReleaseManifest},
|
||||
agent_update::{ArtifactDescriptor, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseEnvelope, ReleaseManifest},
|
||||
jobs::{ArtifactReference, encode, hash},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
@@ -42,11 +42,7 @@ fn invalid() -> Error {
|
||||
Error(StatusCode::BAD_REQUEST, "INVALID_AGENT_RELEASE")
|
||||
}
|
||||
pub fn platform_name(platform: Platform) -> &'static str {
|
||||
match platform {
|
||||
Platform::LinuxX64 => "x86_64-unknown-linux-gnu",
|
||||
Platform::WindowsX64 => "x86_64-pc-windows-msvc",
|
||||
Platform::WindowsGnuX64 => "x86_64-pc-windows-gnu",
|
||||
}
|
||||
platform.target_triple()
|
||||
}
|
||||
pub fn protected_file(path: &FsPath, maximum: u64) -> Result<Vec<u8>, Error> {
|
||||
let key_path =
|
||||
@@ -139,13 +135,6 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
|
||||
metadata.uid(),
|
||||
)?)
|
||||
}
|
||||
fn verifier_platform(platform: Platform) -> rmm_updater::Platform {
|
||||
match platform {
|
||||
Platform::LinuxX64 => rmm_updater::Platform::LinuxX64,
|
||||
Platform::WindowsX64 => rmm_updater::Platform::WindowsX64,
|
||||
Platform::WindowsGnuX64 => rmm_updater::Platform::WindowsGnuX64,
|
||||
}
|
||||
}
|
||||
/// Network input can choose only among statically named protected
|
||||
/// configuration slots. It never supplies a path or introduces update trust.
|
||||
fn keyring_path_with(
|
||||
@@ -154,6 +143,7 @@ fn keyring_path_with(
|
||||
) -> Result<std::path::PathBuf, Error> {
|
||||
let name = match platform {
|
||||
Platform::LinuxX64 => "RMM_AGENT_UPDATE_LINUX_KEYRING_FILE",
|
||||
Platform::LinuxArm64 => "RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE",
|
||||
Platform::WindowsX64 => "RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE",
|
||||
Platform::WindowsGnuX64 => {
|
||||
// The shared device gateway and both management APIs must select the same
|
||||
@@ -177,7 +167,7 @@ fn keyring_path_with(
|
||||
}
|
||||
// Exact legacy compatibility only when the platform-specific slot is
|
||||
// absent. An invalid explicit slot must never silently choose other trust.
|
||||
if platform == Platform::WindowsGnuX64 {
|
||||
if matches!(platform, Platform::LinuxArm64 | Platform::WindowsGnuX64) {
|
||||
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
|
||||
}
|
||||
lookup("RMM_AGENT_UPDATE_KEYRING_FILE")?
|
||||
@@ -239,7 +229,7 @@ fn verify_envelope_with_keyring(
|
||||
rmm_updater::TrustedUpdateKey::new(
|
||||
raw.try_into()
|
||||
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?,
|
||||
verifier_platform(key.platform),
|
||||
key.platform.into(),
|
||||
key.first_sequence,
|
||||
key.last_sequence,
|
||||
key.revoked,
|
||||
@@ -250,7 +240,7 @@ fn verify_envelope_with_keyring(
|
||||
let keyring = rmm_updater::UpdateKeyring::new(config.generation, keys)
|
||||
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?;
|
||||
let context = rmm_updater::TrustedContext {
|
||||
platform: verifier_platform(decoded.manifest.platform),
|
||||
platform: decoded.manifest.platform.into(),
|
||||
now_utc_seconds,
|
||||
keyring_generation: config.generation,
|
||||
protocol_major: 1,
|
||||
@@ -275,6 +265,12 @@ fn verify_envelope_with_keyring(
|
||||
}
|
||||
Ok(decoded.manifest)
|
||||
}
|
||||
pub(crate) async fn ensure_customer_starters(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
bootstrap::publish_starters(tx, tenant).await
|
||||
}
|
||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route(
|
||||
@@ -612,7 +608,7 @@ async fn list(
|
||||
pub struct Current {
|
||||
platform: Platform,
|
||||
}
|
||||
async fn device(
|
||||
pub(crate) async fn device(
|
||||
s: &crate::State,
|
||||
peer: crate::Peer,
|
||||
headers: &HeaderMap,
|
||||
@@ -658,18 +654,21 @@ async fn check_device_platform(
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
let caps: Vec<String> = serde_json::from_value(caps)?;
|
||||
let expected = match platform {
|
||||
Platform::LinuxX64 => "linux.base/1",
|
||||
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => {
|
||||
return Err(missing());
|
||||
}
|
||||
Platform::WindowsX64 => "windows.base/1",
|
||||
Platform::WindowsGnuX64 => "agent.release.windows.gnu/1",
|
||||
};
|
||||
if !caps.iter().any(|c| c == expected) {
|
||||
return Err(missing());
|
||||
if device_supports_release(platform, &caps) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(missing())
|
||||
}
|
||||
}
|
||||
|
||||
fn device_supports_release(platform: Platform, caps: &[String]) -> bool {
|
||||
let has = |expected: &str| caps.iter().any(|capability| capability == expected);
|
||||
match platform {
|
||||
Platform::LinuxX64 => has("linux.base/1") && !has(LINUX_ARM64_RELEASE_CAPABILITY),
|
||||
Platform::LinuxArm64 => has("linux.base/1") && has(LINUX_ARM64_RELEASE_CAPABILITY),
|
||||
Platform::WindowsX64 => has("windows.base/1") && !has("agent.release.windows.gnu/1"),
|
||||
Platform::WindowsGnuX64 => has("agent.release.windows.gnu/1"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A published release grants access to its two fixed binaries for authenticated
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Usage: sudo sh linux.sh https://bootstrap.example [--enable-admin-scripts]
|
||||
# Linux x86-64 / ARM64. Usage: sudo sh linux.sh https://bootstrap.example [--enable-admin-scripts]
|
||||
set -eu
|
||||
umask 077
|
||||
file=$(mktemp)
|
||||
|
||||
@@ -32,7 +32,6 @@ TIMER = 'rmm-discovery-update.timer'
|
||||
HELPER = 'rmm-discovery-managed-script-helper.service'
|
||||
HELPER_SOCKET = Path('/run/rmm-discovery-script-helper/control.sock')
|
||||
OLD_HELPER_CONFIG = Path('/etc/rmm-discovery-managed-scripts')
|
||||
PLATFORM = 'x86_64-unknown-linux-gnu'
|
||||
MAX_BINARY = 256 * 1024 * 1024
|
||||
UNIT_DIR = Path('/etc/systemd/system')
|
||||
|
||||
@@ -42,6 +41,13 @@ def require(condition, message):
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def release_platform():
|
||||
machine = platform.machine()
|
||||
require(platform.system() == 'Linux' and machine in ('x86_64', 'aarch64'),
|
||||
'Linux x86-64 or ARM64 required')
|
||||
return machine + '-unknown-linux-gnu'
|
||||
|
||||
|
||||
def origin(value):
|
||||
parsed = urlsplit(value)
|
||||
require(parsed.scheme == 'https' and parsed.hostname and parsed.username is None
|
||||
@@ -151,7 +157,9 @@ def pair(folder, doc, source, updater):
|
||||
manifest = doc['manifest']
|
||||
release_id = canonical_id(manifest['release_id'])
|
||||
prefix = '/agent/v1/bootstrap/releases' if source else '/agent/v1/releases'
|
||||
suffix = '?platform=' + PLATFORM if source else ''
|
||||
target = release_platform()
|
||||
require(manifest['platform'] == target, 'release architecture differs from this device')
|
||||
suffix = '?platform=' + target if source else ''
|
||||
save(folder / 'envelope.json', doc['release_envelope'])
|
||||
for artifact, role in zip(manifest['artifacts'], ('agent', 'helper'), strict=True):
|
||||
require(artifact['role'] == role, 'incorrect artifact role')
|
||||
@@ -186,7 +194,12 @@ def installed():
|
||||
def healthy(version, baseline, duration=90, pin=None):
|
||||
until = time.monotonic() + duration
|
||||
started = time.time()
|
||||
certificate_pointer = STATE / 'certificates/current.json'
|
||||
while time.monotonic() < until:
|
||||
# The agent writes this pointer after obtaining its first device certificate.
|
||||
if not certificate_pointer.is_file():
|
||||
time.sleep(2)
|
||||
continue
|
||||
try:
|
||||
record = installed()
|
||||
contact = record.get('last_contact_at')
|
||||
@@ -457,6 +470,30 @@ WantedBy=timers.target
|
||||
}
|
||||
|
||||
|
||||
def provision_serial_credential():
|
||||
# DMI serial files usually require root. Pass this one value to the agent
|
||||
# through systemd's read-only per-service credentials directory.
|
||||
source = Path('/sys/class/dmi/id/product_serial')
|
||||
try:
|
||||
with source.open('rb') as stream:
|
||||
serial = stream.read(256).strip()
|
||||
except OSError:
|
||||
return
|
||||
if not serial or len(serial) >= 255:
|
||||
return
|
||||
target = ROOT / 'bios-serial'
|
||||
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
|
||||
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
|
||||
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
|
||||
if dropin.exists() or dropin.is_symlink():
|
||||
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
|
||||
else:
|
||||
dropin.parent.mkdir(mode=0o755, exist_ok=True)
|
||||
save(target, serial, 0o600)
|
||||
if not dropin.exists():
|
||||
save(dropin, content)
|
||||
|
||||
|
||||
def enable():
|
||||
for name, data in units().items():
|
||||
path = UNIT_DIR / name
|
||||
@@ -464,6 +501,7 @@ def enable():
|
||||
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
|
||||
else:
|
||||
save(path, data.encode())
|
||||
provision_serial_credential()
|
||||
service('daemon-reload')
|
||||
service('enable', '--now', SERVICE)
|
||||
|
||||
@@ -481,7 +519,7 @@ def save_token(base, token, gid):
|
||||
|
||||
|
||||
def install(base, token_file, enable_admin_scripts=False):
|
||||
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
|
||||
target = release_platform()
|
||||
base = origin(base)
|
||||
if ROOT.exists():
|
||||
config = read(ROOT / 'config.json')
|
||||
@@ -491,7 +529,7 @@ def install(base, token_file, enable_admin_scripts=False):
|
||||
token = enrollment_token(token_file)
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
metadata = Path(work) / 'bootstrap.json'
|
||||
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, metadata)
|
||||
remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, metadata)
|
||||
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
|
||||
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
|
||||
# An operator rerunning the HTTPS installer can update the lifecycle
|
||||
@@ -524,7 +562,7 @@ def install(base, token_file, enable_admin_scripts=False):
|
||||
with tempfile.TemporaryDirectory(prefix='.rmm-', dir=ROOT.parent) as work:
|
||||
staging = Path(work) / 'installation'
|
||||
staging.mkdir()
|
||||
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, staging / 'bootstrap.json')
|
||||
remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, staging / 'bootstrap.json')
|
||||
doc = read(staging / 'bootstrap.json')
|
||||
require(doc['schema_version'] == 1, 'unknown bootstrap profile')
|
||||
save(staging / 'keyring.json', doc['keyring'])
|
||||
@@ -532,7 +570,7 @@ def install(base, token_file, enable_admin_scripts=False):
|
||||
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
|
||||
'tenant': canonical_id(doc['tenant_id'])})
|
||||
updater = staging / 'updater'
|
||||
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
|
||||
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + target + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
|
||||
updater.chmod(0o755)
|
||||
releases = staging / 'releases'
|
||||
releases.mkdir()
|
||||
@@ -599,6 +637,7 @@ def revert(intent, report_failure=True):
|
||||
|
||||
|
||||
def update():
|
||||
target = release_platform()
|
||||
with (ROOT / 'release.lock').open('rb') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
pending = ROOT / 'pending.json'
|
||||
@@ -608,7 +647,7 @@ def update():
|
||||
with tempfile.TemporaryDirectory(prefix='.incoming-', dir=ROOT / 'releases') as work:
|
||||
staging = Path(work) / 'generation'
|
||||
staging.mkdir()
|
||||
remote(None, '/agent/v1/releases/current?platform=' + PLATFORM, staging / 'current.json')
|
||||
remote(None, '/agent/v1/releases/current?platform=' + target, staging / 'current.json')
|
||||
response = read(staging / 'current.json')
|
||||
if response['status'] == 'not_configured':
|
||||
return
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
use super::*;
|
||||
mod starter;
|
||||
|
||||
pub(super) use starter::publish_missing as publish_starters;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Config {
|
||||
@@ -31,6 +33,7 @@ fn official_windows(platform: Platform) -> bool {
|
||||
async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
|
||||
let slot = match platform {
|
||||
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
|
||||
Platform::LinuxArm64 => "RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE",
|
||||
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
|
||||
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
|
||||
};
|
||||
|
||||
@@ -10,11 +10,13 @@ struct Starter {
|
||||
worker: Pin,
|
||||
}
|
||||
|
||||
pub(super) async fn publish_missing(
|
||||
pub(in crate::agent_updates) async fn publish_missing(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE") else {
|
||||
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE")
|
||||
.or_else(|| std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE"))
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(config_dir) = FsPath::new(&slot).parent() else {
|
||||
@@ -29,6 +31,7 @@ pub(super) async fn publish_missing(
|
||||
}
|
||||
for platform in [
|
||||
Platform::LinuxX64,
|
||||
Platform::LinuxArm64,
|
||||
Platform::WindowsGnuX64,
|
||||
Platform::WindowsX64,
|
||||
] {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
use crate::{auth::Principal, jobs::Error};
|
||||
use axum::{
|
||||
Extension, Json, Router,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_domain::{customer_transfer as wire, jobs::hash};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
const NOT_FOUND: Error = Error(StatusCode::NOT_FOUND, "NOT_FOUND");
|
||||
|
||||
fn private_json(body: Value) -> Response {
|
||||
([("cache-control", "private, no-store")], Json(body)).into_response()
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/agent/v1/customer-transfer", get(device_offer))
|
||||
.route(
|
||||
"/agent/v1/customer-transfer/{transfer}/certificate",
|
||||
post(device_certificate),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer",
|
||||
get(status).post(begin),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/complete",
|
||||
post(complete),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/cancel",
|
||||
post(cancel),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pairing {
|
||||
agent_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Destination {
|
||||
target_tenant_id: Uuid,
|
||||
}
|
||||
|
||||
struct Transfer {
|
||||
transfer_id: Uuid,
|
||||
target_tenant_id: Uuid,
|
||||
target_asset_id: Option<Uuid>,
|
||||
target_agent_id: Option<Uuid>,
|
||||
csr_sha256: Option<String>,
|
||||
requested_by: String,
|
||||
completed_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
async fn source<'a>(
|
||||
s: &'a crate::State,
|
||||
headers: &HeaderMap,
|
||||
tenant: Uuid,
|
||||
write: bool,
|
||||
) -> Result<(Principal, Transaction<'a, Postgres>), Error> {
|
||||
let p = crate::jobs::principal(s, headers, write).await?;
|
||||
crate::jobs::scope(&p, tenant, write)?;
|
||||
if p.session_hash.is_none() {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "devices:revoke").await?;
|
||||
Ok((p, tx))
|
||||
}
|
||||
|
||||
async fn select_tenant(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
|
||||
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||
.bind(tenant.to_string())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn destination(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
target: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
if target == p.tenant || !p.tenants.contains(&target) {
|
||||
return Err(NOT_FOUND);
|
||||
}
|
||||
select_tenant(tx, target).await?;
|
||||
crate::permissions::require_principal(tx, p, "inventory:read").await?;
|
||||
crate::permissions::require_principal(tx, p, "devices:enroll").await
|
||||
}
|
||||
|
||||
async fn transfer(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
agent: Uuid,
|
||||
) -> Result<Option<Transfer>, Error> {
|
||||
let row = sqlx::query(
|
||||
"SELECT transfer_id,target_tenant_id,target_asset_id,target_agent_id,csr_sha256,requested_by,completed_at
|
||||
FROM device_customer_transfers WHERE source_agent_id=$1 AND cancelled_at IS NULL",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
Ok(row.map(|row| Transfer {
|
||||
transfer_id: row.get("transfer_id"),
|
||||
target_tenant_id: row.get("target_tenant_id"),
|
||||
target_asset_id: row.get("target_asset_id"),
|
||||
target_agent_id: row.get("target_agent_id"),
|
||||
csr_sha256: row.get("csr_sha256"),
|
||||
requested_by: row.get("requested_by"),
|
||||
completed_at: row.get("completed_at"),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn target_hostname(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
t: &Transfer,
|
||||
) -> Result<Option<String>, Error> {
|
||||
let (Some(asset), Some(agent)) = (t.target_asset_id, t.target_agent_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(sqlx::query_scalar(
|
||||
"SELECT o.data->>'hostname' FROM agent_installations a
|
||||
JOIN LATERAL (
|
||||
SELECT data FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base')
|
||||
ORDER BY observed_at DESC, received_at DESC, sequence DESC LIMIT 1
|
||||
) o ON true
|
||||
WHERE a.asset_id=$1 AND a.agent_id=$2 AND a.revoked_at IS NULL
|
||||
AND a.last_authenticated_at IS NOT NULL AND length(o.data->>'hostname')>0",
|
||||
)
|
||||
.bind(asset).bind(agent)
|
||||
.fetch_optional(&mut **tx).await?)
|
||||
}
|
||||
|
||||
async fn status(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, false).await?;
|
||||
verify_pairing(&mut tx, asset, pair.agent_id).await?;
|
||||
let Some(t) = transfer(&mut tx, pair.agent_id).await? else {
|
||||
return Ok(private_json(json!({"transfer":null})));
|
||||
};
|
||||
destination(&mut tx, &p, t.target_tenant_id).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 t.target_agent_id.is_some() {
|
||||
"enrolled"
|
||||
} else {
|
||||
"pending"
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"transfer":{
|
||||
"transfer_id":t.transfer_id, "state":state,
|
||||
"target_tenant_id":t.target_tenant_id, "target_asset_id":t.target_asset_id,
|
||||
"target_agent_id":t.target_agent_id, "target_hostname":hostname
|
||||
}})))
|
||||
}
|
||||
|
||||
async fn lock_source(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
) -> Result<bool, Error> {
|
||||
crate::agent_service::control_lock(tx, tenant, agent).await?;
|
||||
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 AND NOT i.customer_transfer_pending FOR UPDATE OF i",
|
||||
)
|
||||
.bind(asset)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn ensure_idle(tx: &mut Transaction<'_, Postgres>, agent: Uuid) -> Result<(), Error> {
|
||||
let busy: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT FROM jobs WHERE agent_id=$1
|
||||
AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))
|
||||
OR EXISTS(SELECT FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
||||
WHERE 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',$1::uuid))))",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if busy {
|
||||
return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn audit(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
event: &str,
|
||||
details: Value,
|
||||
) -> Result<(), Error> {
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,$4,$5,now())")
|
||||
.bind(p.tenant).bind(Uuid::new_v4()).bind(&p.name).bind(event)
|
||||
.bind(json!({"decision":details,"session_hash":p.session_hash,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}))
|
||||
.execute(&mut **tx).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn begin(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
Json(input): Json<Destination>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||
destination(&mut tx, &p, input.target_tenant_id).await?;
|
||||
crate::agent_updates::ensure_customer_starters(&mut tx, input.target_tenant_id).await?;
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
if !lock_source(&mut tx, tenant, asset, pair.agent_id).await? {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_SOURCE_INACTIVE"));
|
||||
}
|
||||
ensure_idle(&mut tx, pair.agent_id).await?;
|
||||
let supported: bool =
|
||||
sqlx::query_scalar("SELECT capabilities ? $2 FROM agent_installations WHERE agent_id=$1")
|
||||
.bind(pair.agent_id)
|
||||
.bind(wire::CAPABILITY)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !supported {
|
||||
return Err(Error(
|
||||
StatusCode::CONFLICT,
|
||||
"TRANSFER_AGENT_UPDATE_REQUIRED",
|
||||
));
|
||||
}
|
||||
if transfer(&mut tx, pair.agent_id).await?.is_some() {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_PENDING"));
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query(
|
||||
"INSERT INTO device_customer_transfers(transfer_id,source_tenant_id,source_asset_id,source_agent_id,target_tenant_id,requested_by)
|
||||
VALUES($1,$2,$3,$4,$5,$6)",
|
||||
).bind(id).bind(tenant).bind(asset).bind(pair.agent_id).bind(input.target_tenant_id).bind(&p.name)
|
||||
.execute(&mut *tx).await?;
|
||||
audit(&mut tx, &p, "device_customer_transfer_prepared", json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":input.target_tenant_id
|
||||
})).await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"transfer_id":id,"state":"pending"})))
|
||||
}
|
||||
|
||||
async fn verify_pairing(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
sqlx::query_scalar::<_, Uuid>(
|
||||
"SELECT agent_id FROM agent_installations WHERE asset_id=$1 AND agent_id=$2",
|
||||
)
|
||||
.bind(asset)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cancel(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<StatusCode, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
|
||||
let changed = sqlx::query(
|
||||
"UPDATE device_customer_transfers SET cancelled_at=now()
|
||||
WHERE transfer_id=$1 AND source_agent_id=$2 AND target_agent_id IS NULL AND cancelled_at IS NULL",
|
||||
).bind(id).bind(pair.agent_id).execute(&mut *tx).await?.rows_affected();
|
||||
if changed == 0 {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_STARTED"));
|
||||
}
|
||||
audit(
|
||||
&mut tx,
|
||||
&p,
|
||||
"device_customer_transfer_cancelled",
|
||||
json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn complete(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).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?;
|
||||
// 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"));
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"state":"completed"})))
|
||||
}
|
||||
|
||||
async fn device_offer(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let offer = transfer(&mut tx, agent)
|
||||
.await?
|
||||
.filter(|t| t.completed_at.is_none())
|
||||
.map(|t| offer(tenant, agent, &t));
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"offer":offer})))
|
||||
}
|
||||
|
||||
fn offer(tenant: Uuid, agent: Uuid, t: &Transfer) -> wire::Offer {
|
||||
wire::Offer {
|
||||
transfer_id: t.transfer_id,
|
||||
source_tenant_id: tenant,
|
||||
source_agent_id: agent,
|
||||
target_tenant_id: t.target_tenant_id,
|
||||
}
|
||||
}
|
||||
|
||||
async fn device_certificate(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(input): Json<wire::CertificateRequest>,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
|
||||
let invalid = || Error(StatusCode::BAD_REQUEST, "INVALID_CSR");
|
||||
if input.csr_pem.len() > 8192 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let csr = openssl::x509::X509Req::from_pem(input.csr_pem.as_bytes()).map_err(|_| invalid())?;
|
||||
let public = csr.public_key().map_err(|_| invalid())?;
|
||||
if !csr.verify(&public).map_err(|_| invalid())? {
|
||||
return Err(invalid());
|
||||
}
|
||||
let digest = hash(&public.public_key_to_der().map_err(|_| invalid())?);
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::agent_service::control_lock(&mut tx, tenant, agent).await?;
|
||||
let (asset, generation): (Uuid, i64) = sqlx::query_as(
|
||||
"SELECT asset_id,connection_generation FROM agent_installations
|
||||
WHERE agent_id=$1 AND revoked_at IS NULL FOR UPDATE",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)?;
|
||||
let t = transfer(&mut tx, agent)
|
||||
.await?
|
||||
.filter(|t| t.transfer_id == id && t.completed_at.is_none())
|
||||
.ok_or(NOT_FOUND)?;
|
||||
ensure_idle(&mut tx, agent).await?;
|
||||
if t.target_agent_id.is_none() {
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "devices:revoke").await?;
|
||||
}
|
||||
select_tenant(&mut tx, t.target_tenant_id).await?;
|
||||
let (new_asset, new_agent, certificate_pem) = if let (Some(target_asset), Some(target_agent)) =
|
||||
(t.target_asset_id, t.target_agent_id)
|
||||
{
|
||||
if t.csr_sha256.as_deref() != Some(&digest) {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_KEY_MISMATCH"));
|
||||
}
|
||||
let pem: String = sqlx::query_scalar(
|
||||
"SELECT certificate_pem FROM agent_installations WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
|
||||
).bind(target_asset).bind(target_agent).fetch_optional(&mut *tx).await?.ok_or(NOT_FOUND)?;
|
||||
sqlx::query(
|
||||
"UPDATE agent_installations SET connection_generation=GREATEST(connection_generation,$2)
|
||||
WHERE agent_id=$1 AND last_authenticated_at IS NULL",
|
||||
).bind(target_agent).bind(generation).execute(&mut *tx).await?;
|
||||
(target_asset, target_agent, pem)
|
||||
} else {
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "devices:enroll").await?;
|
||||
let new_asset = Uuid::new_v4();
|
||||
let new_agent = Uuid::new_v4();
|
||||
let certificate =
|
||||
crate::tls::issue(&s, &input.csr_pem, new_agent).map_err(|_| invalid())?;
|
||||
let pem = String::from_utf8(certificate.to_pem().map_err(anyhow::Error::from)?)
|
||||
.map_err(anyhow::Error::from)?;
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(t.target_tenant_id)
|
||||
.bind(new_asset)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"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?;
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
sqlx::query(
|
||||
"UPDATE device_customer_transfers SET target_asset_id=$2,target_agent_id=$3,csr_sha256=$4
|
||||
WHERE transfer_id=$1 AND source_asset_id=$5",
|
||||
).bind(id).bind(new_asset).bind(new_agent).bind(digest).bind(asset).execute(&mut *tx).await?;
|
||||
(new_asset, new_agent, pem)
|
||||
};
|
||||
let binding = wire::Binding {
|
||||
offer: offer(tenant, agent, &t),
|
||||
asset_id: new_asset,
|
||||
agent_id: new_agent,
|
||||
certificate_sha256: hash(certificate_pem.as_bytes()),
|
||||
};
|
||||
let signature_hex = hex::encode(s.job_signer.sign(&binding.signing_bytes()?)?);
|
||||
tx.commit().await?;
|
||||
Ok((
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(wire::CertificateResponse {
|
||||
certificate_pem,
|
||||
receipt: wire::Receipt {
|
||||
binding,
|
||||
signature_hex,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
@@ -2,7 +2,8 @@ WITH classified AS (
|
||||
SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at,
|
||||
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
|
||||
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
|
||||
asset.archived_at,t.name AS customer_name,
|
||||
a.system_usage,a.system_usage_observed_at,
|
||||
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'
|
||||
@@ -24,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)
|
||||
)
|
||||
|
||||
+273
-14
@@ -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,12 +501,24 @@ 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");
|
||||
let device_type =
|
||||
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
|
||||
let linux_memory = observed(&data, "linux.memory");
|
||||
let usage = row
|
||||
.get::<Option<Value>, _>("system_usage")
|
||||
.unwrap_or(Value::Null);
|
||||
let usage_at: Option<DateTime<Utc>> = row.get("system_usage_observed_at");
|
||||
let inventory_at: Option<DateTime<Utc>> = row.get("observed_at");
|
||||
let cpu_observed_at = usage["cpu_usage_observed_at"].as_str();
|
||||
let cpu_usage = cpu_observed_at.and_then(|_| usage["cpu_usage_percent"].as_f64());
|
||||
let ram_available = usage["ram_available_bytes"].as_u64();
|
||||
let ram_total = usage["ram_total_bytes"]
|
||||
.as_u64()
|
||||
.or_else(|| linux_memory["total_bytes"].as_u64())
|
||||
.or_else(|| windows["memory_total_bytes"].as_u64());
|
||||
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())) {
|
||||
@@ -372,13 +537,26 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
|
||||
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
|
||||
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
|
||||
"ram_total_bytes":observed(&data,"linux.memory")["total_bytes"].as_u64().or_else(||windows["memory_total_bytes"].as_u64()),
|
||||
"cpu_usage_percent":cpu_usage,
|
||||
"cpu_usage_observed_at":cpu_observed_at,
|
||||
"ram_total_bytes":ram_total,
|
||||
"ram_available_bytes":ram_available.or_else(|| linux_memory["available_bytes"].as_u64().or_else(||windows["memory_available_bytes"].as_u64())
|
||||
.filter(|available| ram_total.is_some_and(|total| *available <= total))),
|
||||
"ram_observed_at":if ram_available.is_some() {usage_at} else {inventory_at},
|
||||
"last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||
"presence":presence,"observed_at":row.get::<Option<DateTime<Utc>>,_>("observed_at"),
|
||||
"presence":presence,"observed_at":inventory_at,
|
||||
"received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"),
|
||||
"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");
|
||||
@@ -439,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() {
|
||||
@@ -481,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 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 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
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@ mod auth;
|
||||
mod local_auth;
|
||||
mod mcp_tokens;
|
||||
mod customers;
|
||||
mod customer_transfer;
|
||||
mod catalog;
|
||||
mod checkpoint_repair;
|
||||
mod controls;
|
||||
@@ -174,7 +175,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
let mut routes = Router::new().route("/healthz", get(|| async { "ok" }));
|
||||
if role.gateway() {
|
||||
routes = agent_updates::gateway_routes(routes);
|
||||
routes = customer_transfer::gateway_routes(agent_updates::gateway_routes(routes));
|
||||
routes = agent_update_health::gateway_routes(routes);
|
||||
routes = agent_time::gateway_routes(routes);
|
||||
routes = routes
|
||||
@@ -216,12 +217,13 @@ 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));
|
||||
routes = jobs::routes(routes);
|
||||
routes = script_library::routes(routes);
|
||||
routes = controls::routes(routes);
|
||||
routes = customer_transfer::routes(controls::routes(routes));
|
||||
routes = catalog::routes(routes);
|
||||
routes = agent_updates::routes(routes);
|
||||
routes = routes
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
|
||||
use axum::http::StatusCode;
|
||||
use rmm_domain::{
|
||||
agent_update::{ArtifactRole, Platform, ReleaseManifest, digest},
|
||||
agent_update::{ArtifactRole, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseManifest, digest},
|
||||
jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
@@ -60,7 +60,7 @@ impl ReleaseAnchor {
|
||||
};
|
||||
let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#);
|
||||
match manifest.platform {
|
||||
Platform::LinuxX64 => replace(
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 => replace(
|
||||
field("helper_binary_sha256", &self.helper_sha256),
|
||||
field("helper_binary_sha256", next(ArtifactRole::Helper)?),
|
||||
1,
|
||||
@@ -164,6 +164,9 @@ fn check_pair(
|
||||
caps: &[String],
|
||||
) -> Result<(), Error> {
|
||||
let platform = match identity {
|
||||
"root" if caps.iter().any(|cap| cap == LINUX_ARM64_RELEASE_CAPABILITY) => {
|
||||
Platform::LinuxArm64
|
||||
}
|
||||
"root" => Platform::LinuxX64,
|
||||
"system" => Platform::WindowsGnuX64,
|
||||
_ => return Err(binding_error()),
|
||||
|
||||
@@ -218,11 +218,7 @@ fn current_keyring(file: &UpdateKeyringFile) -> Result<UpdateKeyring> {
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?;
|
||||
keys.push(TrustedUpdateKey::new(
|
||||
public,
|
||||
match key.platform {
|
||||
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
|
||||
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
|
||||
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
|
||||
},
|
||||
key.platform.into(),
|
||||
key.first_sequence,
|
||||
key.last_sequence,
|
||||
key.revoked,
|
||||
@@ -307,11 +303,7 @@ fn verify_record_release(
|
||||
.release_envelope
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let platform = match record.platform {
|
||||
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
|
||||
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
|
||||
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
|
||||
};
|
||||
let platform = ReleasePlatform::from(record.platform);
|
||||
let envelope: &ReleaseEnvelope = &record.release_envelope;
|
||||
verify_release(
|
||||
SignedRelease {
|
||||
@@ -403,7 +395,7 @@ fn verify_update(
|
||||
ensure!(
|
||||
job.execution_identity
|
||||
== match record.platform {
|
||||
Platform::LinuxX64 => "root",
|
||||
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
|
||||
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
|
||||
}
|
||||
&& update.release_envelope == record.release_envelope
|
||||
|
||||
@@ -45,7 +45,7 @@ mod linux {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args.first().is_some_and(|arg| arg == "--verify-bootstrap") {
|
||||
let release =
|
||||
rmm_updater::verify_bootstrap_files(rmm_updater::Platform::LinuxX64, &args[1..])?;
|
||||
rmm_updater::verify_bootstrap_files(rmm_domain::agent_update::Platform::NATIVE_LINUX.into(), &args[1..])?;
|
||||
println!("{}", serde_json::to_string(release.manifest())?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::{
|
||||
VerifiedRelease,
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::agent_update::{Platform as WirePlatform, ReleaseEnvelope, UpdateKeyringFile};
|
||||
use rmm_domain::agent_update::{ReleaseEnvelope, UpdateKeyringFile};
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fs::File,
|
||||
@@ -31,18 +31,13 @@ pub fn verify_bootstrap_files(platform: Platform, args: &[OsString]) -> Result<V
|
||||
.keys
|
||||
.into_iter()
|
||||
.map(|key| {
|
||||
let platform = match key.platform {
|
||||
WirePlatform::LinuxX64 => Platform::LinuxX64,
|
||||
WirePlatform::WindowsX64 => Platform::WindowsX64,
|
||||
WirePlatform::WindowsGnuX64 => Platform::WindowsGnuX64,
|
||||
};
|
||||
let raw = hex::decode(key.public_key_hex)?
|
||||
.try_into()
|
||||
.ok()
|
||||
.context("Ed25519 public key length")?;
|
||||
TrustedUpdateKey::new(
|
||||
raw,
|
||||
platform,
|
||||
key.platform.into(),
|
||||
key.first_sequence,
|
||||
key.last_sequence,
|
||||
key.revoked,
|
||||
|
||||
@@ -16,12 +16,26 @@ pub const RELEASE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-release.v1\0";
|
||||
pub enum Platform {
|
||||
#[serde(rename = "x86_64-unknown-linux-gnu")]
|
||||
LinuxX64,
|
||||
#[serde(rename = "aarch64-unknown-linux-gnu")]
|
||||
LinuxArm64,
|
||||
#[serde(rename = "x86_64-pc-windows-msvc")]
|
||||
WindowsX64,
|
||||
#[serde(rename = "x86_64-pc-windows-gnu")]
|
||||
WindowsGnuX64,
|
||||
}
|
||||
|
||||
impl From<rmm_domain::agent_update::Platform> for Platform {
|
||||
fn from(platform: rmm_domain::agent_update::Platform) -> Self {
|
||||
use rmm_domain::agent_update::Platform as WirePlatform;
|
||||
match platform {
|
||||
WirePlatform::LinuxX64 => Self::LinuxX64,
|
||||
WirePlatform::LinuxArm64 => Self::LinuxArm64,
|
||||
WirePlatform::WindowsX64 => Self::WindowsX64,
|
||||
WirePlatform::WindowsGnuX64 => Self::WindowsGnuX64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ArtifactRole {
|
||||
|
||||
@@ -66,11 +66,18 @@ fn manifest() -> ReleaseManifest {
|
||||
}
|
||||
|
||||
fn verify_bytes(payload: &[u8], context: &TrustedContext) -> anyhow::Result<VerifiedRelease> {
|
||||
verify_bytes_with_key(payload, context, key(false, 1, 20))
|
||||
}
|
||||
|
||||
fn verify_bytes_with_key(
|
||||
payload: &[u8],
|
||||
context: &TrustedContext,
|
||||
pinned: TrustedUpdateKey,
|
||||
) -> anyhow::Result<VerifiedRelease> {
|
||||
let signer = SigningKey::from_bytes(&[41; 32]);
|
||||
let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec();
|
||||
message.extend_from_slice(payload);
|
||||
let signature = signer.sign(&message).to_bytes();
|
||||
let pinned = key(false, 1, 20);
|
||||
let key_id = pinned.key_id().to_owned();
|
||||
verify_release(
|
||||
SignedRelease {
|
||||
@@ -166,7 +173,7 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
|
||||
payload.replacen("{", "{\"schema_version\":1,", 1),
|
||||
payload.replacen("\"bytes\":11", "\"bytes\":11,\"path\":\"/etc/passwd\"", 1),
|
||||
payload.replacen("\"release_sequence\":4", "\"release_sequence\":4.0", 1),
|
||||
payload.replacen("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", 1),
|
||||
payload.replacen("x86_64-unknown-linux-gnu", "riscv64gc-unknown-linux-gnu", 1),
|
||||
] {
|
||||
assert!(verify_bytes(changed.as_bytes(), &context()).is_err());
|
||||
}
|
||||
@@ -174,6 +181,25 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
|
||||
assert!(verify_bytes(b"", &context()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arm64_release_requires_arm64_context_and_key() {
|
||||
let mut target = manifest();
|
||||
target.platform = Platform::LinuxArm64;
|
||||
let mut context = context();
|
||||
assert!(verify(&target, &context).is_err());
|
||||
context.platform = Platform::LinuxArm64;
|
||||
assert!(verify(&target, &context).is_err());
|
||||
let arm64_key = TrustedUpdateKey::new(
|
||||
SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes(),
|
||||
Platform::LinuxArm64,
|
||||
1,
|
||||
20,
|
||||
false,
|
||||
).unwrap();
|
||||
let payload = serde_json::to_vec(&target).unwrap();
|
||||
assert!(verify_bytes_with_key(&payload, &context, arm64_key).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected() {
|
||||
let mut ctx = context();
|
||||
|
||||
@@ -21,9 +21,11 @@ services:
|
||||
RMM_BOOTSTRAP_ORIGIN: https://discovery.ease-technologies.de:8443
|
||||
RMM_AGENT_UPDATE_ARTIFACT_DIR: /release-objects
|
||||
RMM_AGENT_UPDATE_LINUX_KEYRING_FILE: /release-config/linux-keyring.json
|
||||
RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE: /release-config/linux-arm64-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE: /release-config/windows-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE: /release-config/windows-gnu-official-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_FILE: /release-config/linux-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE: /release-config/linux-arm64-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_FILE: /release-config/windows-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-official-bootstrap.json
|
||||
ports: ["127.0.0.1:18445:18443"]
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
x-release-environment: &release-environment
|
||||
RMM_AGENT_UPDATE_ARTIFACT_DIR: /release-objects
|
||||
RMM_AGENT_UPDATE_LINUX_KEYRING_FILE: /release-config/linux-keyring.json
|
||||
RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE: /release-config/linux-arm64-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE: /release-config/windows-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_FILE: /release-config/linux-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE: /release-config/linux-arm64-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_FILE: /release-config/windows-bootstrap.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE: /release-config/windows-gnu-official-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-official-bootstrap.json
|
||||
|
||||
+23
-2
@@ -1,15 +1,22 @@
|
||||
# Entwickeln, bauen und ausliefern
|
||||
|
||||
## Änderungen in Gitea sichern
|
||||
|
||||
Nach jeder abgeschlossenen Änderung die geprüften Dateien committen und den Commit auf den zugehörigen Gitea-Branch pushen. Das gilt für Code, Konfiguration und Dokumentation. Bei einem neuen Arbeitsbranch `git push -u origin HEAD` verwenden. Danach prüfen, dass der Commit auf dem Zielbranch in Gitea liegt.
|
||||
|
||||
## Quellen bauen
|
||||
|
||||
Der Buildrunner verpackt die Quellen eines eingecheckten Git-Stands und baut mit den gepinnten Docker-Buildern. Die folgenden Befehle laufen vom Wurzelverzeichnis des Repositorys. `REVISION` durch den zu liefernden Commit ersetzen. Vor dem ersten Frontendbuild `npm --prefix web ci` ausführen. Für den Rust-Build werden Python 3, Git, Docker, tar, rsync und die zum Ziel passenden lokalen Builder-Images benötigt. [Buildrunner](../tools/build.py)
|
||||
|
||||
| Ziel | Befehl | Ergebnis |
|
||||
| --- | --- | --- |
|
||||
| Linux-Client x86-64 | `python3 tools/build.py linux-x64 --ref REVISION` | `rmm-agent`, `rmm-privileged-helper`, `rmm-agent-updater` |
|
||||
| Linux-Client ARM64 | `python3 tools/build.py linux-arm64 --ssh --ref REVISION` | `rmm-agent`, `rmm-privileged-helper`, `rmm-agent-updater` für AArch64 |
|
||||
| Offizieller Windows-Client x64 | `python3 tools/build.py windows-gnu-x64 --ref REVISION` | `rmm-agent-windows.exe`, `rmm-helper-windows.exe`, `rmm-updater-windows.exe` für GNU |
|
||||
| Server auf dem dedizierten ARM64-Host | `python3 tools/build.py server-arm64 --ssh --ref REVISION` | Server und Linux-Zeitbroker im Remote-Buildbereich |
|
||||
| WebUI | `npm --prefix web run build` | TypeScript-Prüfung und Bundle in `web/dist/` |
|
||||
|
||||
`--plan` zeigt den Rust-Build einschließlich Quellenrevision und Ziel an. Der Runner verwendet je Ziel einen gemeinsamen Cargo-Cache, lädt bei Bedarf die gesperrten Abhängigkeiten und kompiliert offline. Er meldet den konkreten Ausgabeordner. Lokal liegt er unter `devstate/build/<Ziel>/artifacts/<Commit>/<Manifesthash>/`, beim SSH-Build unter `~/rmm-dev-build/server-arm64/artifacts/` auf dem Server. Die Buildquittung `manifest.json` bindet Ziel, Git-Revision, Builder und Binärhashes.
|
||||
`--plan` zeigt den Rust-Build einschließlich Quellenrevision und Ziel an. Der Runner verwendet je Ziel einen gemeinsamen Cargo-Cache, lädt bei Bedarf die gesperrten Abhängigkeiten und kompiliert offline. Er meldet den konkreten Ausgabeordner. Lokal liegt er unter `devstate/build/<Ziel>/artifacts/<Commit>/<Manifesthash>/`, beim SSH-Build unter `~/rmm-dev-build/<Ziel>/artifacts/` auf dem Server. Die Buildquittung `manifest.json` bindet Ziel, Git-Revision, Builder und Binärhashes.
|
||||
|
||||
## Entwicklungsserver und WebUI aktualisieren
|
||||
|
||||
@@ -45,7 +52,7 @@ python3 tools/dev_agent_release.py --official-windows \
|
||||
--minimum-updater-version 2 --prepare-only
|
||||
```
|
||||
|
||||
Für Linux gilt derselbe Ablauf mit dem Linux-Buildordner und ohne `--official-windows`. Die Mindestversion entsprechend der vom Paket benötigten Updaterfähigkeit setzen. Der offizielle Windows-Kanal nutzt einen eigenen Signierschlüssel. Private Signierschlüssel verbleiben auf dem Signierhost.
|
||||
Für Linux gilt derselbe Ablauf mit dem Linux-Buildordner und ohne `--official-windows`. Die Mindestversion entsprechend der vom Paket benötigten Updaterfähigkeit setzen. Der offizielle Windows-Kanal nutzt einen eigenen Signierschlüssel. Linux x86-64 und ARM64 haben ebenfalls getrennte Signierschlüssel, Starter und Updater-Pins. Private Signierschlüssel verbleiben auf dem Signierhost.
|
||||
|
||||
Für die Erstaufnahme in neuen Kundenkatalogen kann der Betreiber einen veröffentlichten Release als Starter auswählen. Die Quelle wird anhand ihrer Kunden-, Plattform- und Release-ID geprüft. Bereits befüllte Kataloge werden je Kunde gepflegt. [Starter veröffentlichen](../tools/dev_customer_starters.py)
|
||||
|
||||
@@ -54,8 +61,22 @@ python3 tools/dev_customer_starters.py --tenant "$TENANT_ID" \
|
||||
--platform x86_64-pc-windows-gnu --official-windows --release "$RELEASE_ID"
|
||||
```
|
||||
|
||||
Für ARM64 beim Starter `--platform aarch64-unknown-linux-gnu` verwenden und `--official-windows` weglassen. Die beiden Release-Overlays für den Server und die öffentliche API binden den ARM64-Schlüsselring und den Bootstrap-Pin ein.
|
||||
|
||||
Ein neuer stabiler Updater benötigt eine eigene Rotation des Bootstrap-Hashes. `--rotate-worker-only --rotate-bootstrap-from SHA256` bindet die Umstellung im Zielkunden an den bisherigen Hash. Für den gezielten lokalen Austausch des stabilen Windows-Updaters im Entwicklungsbetrieb prüft der PowerShell-Operator beide Hashes, die Geräteidentität und die installierten Releasepaare. [Releasewerkzeuge](../tools/agent_release.py) · [Windows-Updater austauschen](../deploy/windows/Replace-DevelopmentReleaseUpdater.ps1)
|
||||
|
||||
## Linux-Gerät per HTTPS aufnehmen
|
||||
|
||||
Unter **Verwaltung → Geräteaufnahme** den Kunden wählen und einen Einmalcode erstellen. Den gemeinsamen Linux-Befehl auf dem Zielgerät ausführen. `linux.sh` erkennt `x86_64` und `aarch64` und wählt den passenden signierten Agenten, Helper und Updater.
|
||||
|
||||
```sh
|
||||
curl --fail --show-error --silent 'https://discovery.ease-technologies.de:8443/install/linux.sh' -o linux.sh && sudo sh linux.sh 'https://discovery.ease-technologies.de:8443' --enable-admin-scripts
|
||||
```
|
||||
|
||||
Den Einmalcode auf Nachfrage eingeben. Bei direkter Root-Anmeldung entfällt `sudo`. `--enable-admin-scripts` aktiviert den lokalen Skript-Helper. Zusätzliche zentrale Geräterechte und die WebUI-Genehmigung gelten pro Auftrag.
|
||||
|
||||
Auf einem bereits aufgenommenen Linux-Gerät kann der gleiche HTTPS-Installer den Root-Skript-Helper nachträglich einrichten. Dazu `--enable-admin-scripts` verwenden. Der Installer übernimmt die vorhandene Geräteidentität. Für die WebUI muss die zentrale Geräteregel zusätzlich das berechtigte Konto und die authentisiert gemeldete Helper-Bindung enthalten. [Richtlinie und Berechtigungen](public-access.md#administrator-skripte-anfordern)
|
||||
|
||||
## Ergebnis prüfen
|
||||
|
||||
Die folgenden Rust-Tests laufen lokal mit Testidentitäten. Die Transporttests starten einen TLS-Server auf Loopback.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"date": "2026-11-18",
|
||||
"host": "otrs.ease-technologies.de",
|
||||
"reported_startup_traceback": "FileNotFoundError: /var/lib/rmm-discovery/certificates/current.json",
|
||||
"before_correction": {
|
||||
"device_certificate_present": true,
|
||||
"identity_present": true,
|
||||
"installer_token_file_removed": true,
|
||||
"agent_active": true,
|
||||
"update_timer_active": true,
|
||||
"update_service_last_result": "success",
|
||||
"authenticated_contact_at": "2026-11-18T17:08:51.835840Z",
|
||||
"connection_generation": 1
|
||||
},
|
||||
"deployment": {
|
||||
"revision": "4b3d0136e93e9b6d1de2ddaf3aae2cdade0dbb85",
|
||||
"server_sha256": "e1001b2d82e7cde249cfbdfe1b559a8f33369fa78a49eb894dbc781a8e0c563d",
|
||||
"web_index_sha256": "7486a20e0e570c8059d75be7b847ee35a39680d7bfa93498a8a9d26e6e3c4f87",
|
||||
"image": "sha256:09a5dfb6750dce24f838f393b592bd41ceff22592710df9c308d6909faac49b6",
|
||||
"api_health": "ok",
|
||||
"gateway_health": "ok"
|
||||
},
|
||||
"native_retest": {
|
||||
"version": "0.1.0-arm64.1",
|
||||
"architecture": "aarch64-unknown-linux-gnu",
|
||||
"last_authenticated_contact": "2026-11-18T17:12:57.212990Z",
|
||||
"connection_generation": 2,
|
||||
"identity_preserved": true,
|
||||
"agent_process_preserved": true,
|
||||
"update_timer_active": true,
|
||||
"arm64_release_check": "available",
|
||||
"installer_without_traceback": true,
|
||||
"installer_without_new_code": true,
|
||||
"wait_for_missing_certificate_native_probe": true,
|
||||
"previous_lifecycle_sha256": "70fdfc00dc2126df6b6d6fc58fc0d727fa573f9838e703695c63dda126228e3d",
|
||||
"new_lifecycle_sha256": "552a4ab7fb69b6c2f4a89b01145e866e53d2ae3f61c0db9536fe0b5d355d260c",
|
||||
"public_installer_sha256": "09e1aef51362e2de9e6ce40721acc17df3cace0a9da01560c1ada0c5e1b906a2"
|
||||
},
|
||||
"linux_installer_regressions_passed": 15
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"date": "2026-11-18",
|
||||
"native_host": "otrs.ease-technologies.de",
|
||||
"source": {
|
||||
"client_revision": "247646a2ba74abe4f2d42a2c712e3d3166fd2187",
|
||||
"server_revision": "6d15f1b3f524c11923ec1a5daba1c1903ff63a27",
|
||||
"build_receipt_sha256": "35ee5c49744970e140f3e3156980e7dca950eb88a3346e92b8e497fe16265df7",
|
||||
"maximum_required_glibc": "2.34"
|
||||
},
|
||||
"deployment": {
|
||||
"database_schema": 40,
|
||||
"server_sha256": "5681a387a1cdfe459185106e9bdf61c47103472a9051db4396262721d9d0a7eb",
|
||||
"public_web_index_sha256": "7486a20e0e570c8059d75be7b847ee35a39680d7bfa93498a8a9d26e6e3c4f87",
|
||||
"api_and_gateway_health": "ok",
|
||||
"manifest_sha256": "d0f548d0d0a0c0e29e706089d958928d8e48cea29e61e52637be01938dd5df45",
|
||||
"arm64_customer_starter_published": true,
|
||||
"existing_devices_after_deploy": [
|
||||
{
|
||||
"platform": "linux-x86-64",
|
||||
"version": "0.1.0-mvp.7",
|
||||
"authenticated_contact_at": "2026-11-18T17:05:50.996252Z"
|
||||
},
|
||||
{
|
||||
"platform": "windows-x64",
|
||||
"version": "0.1.17",
|
||||
"authenticated_contact_at": "2026-11-18T17:05:33.93606Z"
|
||||
}
|
||||
]
|
||||
},
|
||||
"public_https_native_probe": {
|
||||
"machine": "aarch64",
|
||||
"os": "Ubuntu 22.04.5 LTS",
|
||||
"glibc": "glibc 2.35",
|
||||
"origin": "https://discovery.ease-technologies.de:8443",
|
||||
"installer_sha256": "f22a93fb33021f49ed9d9e56b89d040751c9505313611c73fd1490b1d0618c61",
|
||||
"tenant_id": "11111111-1111-4111-8111-111111111111",
|
||||
"release_id": "8f9c1558-a9b6-4338-84a7-4cd376201879",
|
||||
"sequence": 1,
|
||||
"version": "0.1.0-arm64.1",
|
||||
"platform": "aarch64-unknown-linux-gnu",
|
||||
"artifacts": [
|
||||
{
|
||||
"artifact_id": "2b8efd81-ed48-5d13-92b0-b5e0fdca49ac",
|
||||
"bytes": 14786512,
|
||||
"role": "agent",
|
||||
"sha256": "67fac33df92bf88223c57d2c641518ce35fd7706f8d5031975b2227ad258c869"
|
||||
},
|
||||
{
|
||||
"artifact_id": "bb4e1fb2-02fa-561c-993c-5c4792493a9a",
|
||||
"bytes": 13055264,
|
||||
"role": "helper",
|
||||
"sha256": "8f64e88b11be8298fc216ccf827787a690419c9e9ebd948a9bd476f7a47dd5b6"
|
||||
}
|
||||
],
|
||||
"updater": {
|
||||
"bytes": 8755912,
|
||||
"sha256": "3a3c272c59fd59ee8b994288372531f9bfb92b7174e31f71bd107542ec044934"
|
||||
},
|
||||
"published_platforms": [
|
||||
"aarch64-unknown-linux-gnu",
|
||||
"x86_64-pc-windows-gnu",
|
||||
"x86_64-unknown-linux-gnu"
|
||||
],
|
||||
"x86_64_version": "0.1.0-mvp.7",
|
||||
"native_checks": {
|
||||
"installer_shell_syntax": true,
|
||||
"invalid_code_stopped_before_install": true,
|
||||
"manifest_and_pair_signature": true,
|
||||
"modified_agent_rejected": true,
|
||||
"wrong_platform_artifact_http_status": 404,
|
||||
"missing_code_http_status": 401,
|
||||
"enrollment_performed": false,
|
||||
"all_three_elf_images_started_with_help": true
|
||||
}
|
||||
},
|
||||
"passed_tests": {
|
||||
"linux_installer": 13,
|
||||
"release_contract_native_arm64": 10,
|
||||
"webui_unit": 78,
|
||||
"webui_enrollment_chromium": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"date": "2026-11-18",
|
||||
"target": "otrs.ease-technologies.de",
|
||||
"evidence_id": "linux-arm64-otrs-root-helper-20261118",
|
||||
"source_revision": "4b3d0136e93e9b6d1de2ddaf3aae2cdade0dbb85",
|
||||
"before": {
|
||||
"managed_helper_unit": "not-found",
|
||||
"root_script_capability": false
|
||||
},
|
||||
"device": {
|
||||
"platform": "aarch64-unknown-linux-gnu",
|
||||
"version": "0.1.0-arm64.1",
|
||||
"release_id": "8f9c1558-a9b6-4338-84a7-4cd376201879",
|
||||
"agent_sha256": "67fac33df92bf88223c57d2c641518ce35fd7706f8d5031975b2227ad258c869",
|
||||
"helper_binary_sha256": "8f64e88b11be8298fc216ccf827787a690419c9e9ebd948a9bd476f7a47dd5b6",
|
||||
"helper_policy_sha256": "40da24bd6ad91817ab6e17e18a1ece89587d53a5bb2578bfd6281de727266deb",
|
||||
"last_authenticated_contact": "2026-11-18T17:18:45.609656Z",
|
||||
"connection_generation": 4,
|
||||
"identity_preserved": true,
|
||||
"services_active": true
|
||||
},
|
||||
"server": {
|
||||
"central_device_rule": true,
|
||||
"release_anchor": true,
|
||||
"planner_scope": "one existing WebUI account",
|
||||
"server_roles_read_back": [
|
||||
"api",
|
||||
"public-api",
|
||||
"gateway"
|
||||
],
|
||||
"helper_sync_ready": true,
|
||||
"mcp_opt_in": false,
|
||||
"approval_granted": false
|
||||
},
|
||||
"preview": {
|
||||
"public_webui_preview": "accepted",
|
||||
"identity": "root",
|
||||
"target_count": 1,
|
||||
"counts": {
|
||||
"plans": 1,
|
||||
"approval_requests": 0,
|
||||
"jobs": 0,
|
||||
"outbox": 0,
|
||||
"start_grants": 0
|
||||
},
|
||||
"testsimulation": false,
|
||||
"approval_required": true
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -27,10 +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. 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) |
|
||||
| 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) |
|
||||
| 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) |
|
||||
| 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) |
|
||||
| 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) |
|
||||
| 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) |
|
||||
|
||||
[Produktvertrag](../Rust_RMM_Implementierungsspezifikation.md) · [Übergabe für die Weiterentwicklung](handover.md)
|
||||
|
||||
+15
-1
@@ -8,9 +8,23 @@ 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 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.
|
||||
|
||||
### Alte Gerätekopplung endgültig löschen
|
||||
|
||||
Archivieren und Zurückholen steuern die Sichtbarkeit. Ein Widerruf sperrt die registrierte Identität. Für einen Kundenwechsel das Gerät im Zielkunden neu aufnehmen. Die bisherige Historie gehört zur Installation im ursprünglichen Kunden.
|
||||
Archivieren und Zurückholen steuern die Sichtbarkeit. Ein Widerruf sperrt die registrierte Identität.
|
||||
|
||||
Das Verwalten und Löschen einer Kopplung erfordert `devices:revoke` im betreffenden Kunden. Das Gerät öffnen und unter **Gerät verwalten** widerrufen. Die widerrufene Installation steht unter **Geräte → Historie**. Dort **Kopplung löschen** wählen, Hostname, Kunde und Kopplungs-ID vergleichen und **Endgültig löschen** bestätigen. Noch gültige offene Genehmigungsanträge und nicht abgeschlossene Jobs dieser Installation sperren das Löschen. Das gilt auch für Jobs mit ungeklärter Wirkung (`unknown`). Gelöscht werden diese Installation, ihr Inventar und ihre eigenen Auftragsergebnisse. Gemeinsame signierte Mehrgerätepläne und Auditdaten bleiben nachvollziehbar.
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE agent_update_releases DROP CONSTRAINT agent_update_releases_platform_check;
|
||||
ALTER TABLE agent_update_releases ADD CHECK (platform IN
|
||||
('x86_64-unknown-linux-gnu','aarch64-unknown-linux-gnu','x86_64-pc-windows-msvc','x86_64-pc-windows-gnu'));
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE agent_installations
|
||||
ADD COLUMN system_usage jsonb,
|
||||
ADD COLUMN system_usage_observed_at timestamptz;
|
||||
|
||||
GRANT UPDATE(system_usage, system_usage_observed_at) ON agent_installations TO rmm_app;
|
||||
@@ -0,0 +1,27 @@
|
||||
CREATE TABLE device_customer_transfers (
|
||||
transfer_id uuid PRIMARY KEY,
|
||||
source_tenant_id uuid NOT NULL REFERENCES tenants,
|
||||
source_asset_id uuid NOT NULL,
|
||||
source_agent_id uuid NOT NULL,
|
||||
target_tenant_id uuid NOT NULL REFERENCES tenants,
|
||||
requested_by text NOT NULL,
|
||||
target_asset_id uuid,
|
||||
target_agent_id uuid,
|
||||
csr_sha256 text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
completed_at timestamptz,
|
||||
cancelled_at timestamptz,
|
||||
CHECK (source_tenant_id <> target_tenant_id),
|
||||
CHECK ((target_asset_id IS NULL) = (target_agent_id IS NULL)),
|
||||
CHECK ((csr_sha256 IS NULL) = (target_agent_id IS NULL)),
|
||||
CHECK (completed_at IS NULL OR target_agent_id IS NOT NULL),
|
||||
CHECK (cancelled_at IS NULL OR target_agent_id IS NULL)
|
||||
);
|
||||
CREATE UNIQUE INDEX device_customer_transfers_source ON device_customer_transfers
|
||||
(source_tenant_id,source_agent_id) WHERE cancelled_at IS NULL;
|
||||
ALTER TABLE device_customer_transfers ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_scope ON device_customer_transfers
|
||||
USING (source_tenant_id::text = current_setting('app.tenant_id', true));
|
||||
GRANT SELECT, INSERT ON device_customer_transfers TO rmm_app;
|
||||
GRANT UPDATE (target_asset_id,target_agent_id,csr_sha256,completed_at,cancelled_at)
|
||||
ON device_customer_transfers TO rmm_app;
|
||||
@@ -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;
|
||||
$$;
|
||||
@@ -9,6 +9,8 @@ Linux- und Windows-Agenten bauen die Verbindung zum Gateway ausgehend auf. Eine
|
||||
| `POST /agent/v1/messages` | Ein `ClientHello` eröffnet die Verbindung. Weitere `MessageBatch`-Anfragen übertragen unter anderem Inventar, Abgleich, Auftragsstatus und Ergebnisse. | Ein `MessageBatch` enthält die Antworten des Servers. |
|
||||
| `POST /agent/v1/poll` | Ein `PollRequest` enthält einen Heartbeat und die gewünschte Wartezeit von 0 bis 25 Sekunden. | Das Gateway bestätigt den Heartbeat und liefert vorhandene Arbeit mit derselben Antwort. Im Leerlauf genügt die Bestätigung. |
|
||||
|
||||
Heartbeats können eine passive Ressourcenmessung übermitteln. `cpu_usage_basis_points` liegt zwischen 0 und 10.000, `ram_available_bytes` und `ram_total_bytes` bilden gemeinsam einen Messwert. Das Gateway speichert je authentisierter Installation den letzten gültigen CPU-Wert und das letzte gültige RAM-Wertepaar mit ihrem jeweiligen Zeitpunkt. Ein zusätzlicher Poll-Heartbeat ohne Ressourcendaten lässt die gespeicherten Messwerte bestehen.
|
||||
|
||||
Beide Endpunkte verwenden `application/x-protobuf` und Protokollversion 1. Eine Nachricht trägt unter anderem die Gerätekennung, die Generationen von Einschreibung und Verbindung, die Boot-ID, Sequenznummer und Nachrichten-ID. Für gespeicherte Meldungen wie ein Skriptergebnis bestätigt der Server die ursprüngliche Nachrichten-ID. [HTTP-Verarbeitung](../crates/server/src/agent_http.rs) · [Speicherung und Bestätigung](../crates/server/src/agent_service.rs)
|
||||
|
||||
## Vom Antrag bis zum Ergebnis
|
||||
|
||||
+10
-1
@@ -31,7 +31,16 @@ message Envelope {
|
||||
}
|
||||
message ClientHello { string agent_version = 1; repeated string capabilities = 2; }
|
||||
message ServerHello { uint64 connection_generation = 1; uint32 max_message_bytes = 2; }
|
||||
message Heartbeat { string instance_id = 1; uint64 uptime_seconds = 2; }
|
||||
message Heartbeat {
|
||||
string instance_id = 1;
|
||||
uint64 uptime_seconds = 2;
|
||||
SystemUsage system_usage = 3;
|
||||
}
|
||||
message SystemUsage {
|
||||
optional uint32 cpu_usage_basis_points = 1;
|
||||
optional uint64 ram_available_bytes = 2;
|
||||
optional uint64 ram_total_bytes = 3;
|
||||
}
|
||||
// Single-chunk root inventory scope only; JSON is schema rmm.linux.base/1.
|
||||
message InventorySnapshot {
|
||||
string snapshot_id = 1;
|
||||
|
||||
@@ -56,7 +56,9 @@ test('creates and renames a customer, opens its inventory, and hides editing for
|
||||
if (!customer) throw new Error('Kunde fehlt im Testbestand');
|
||||
return route.fulfill({ json: listing([{
|
||||
tenant_id: customerId, customer_name: customer.name, asset_id: 'device-1', agent_id: 'agent-1',
|
||||
lifecycle: 'current', status: 'online', hostname: 'NORD-PC', device_type: 'hypervisor', os: 'Proxmox VE'
|
||||
lifecycle: 'current', status: 'online', hostname: 'NORD-PC', device_type: 'hypervisor', os: 'Proxmox VE',
|
||||
ram_available_bytes: 6 * 2 ** 30, ram_total_bytes: 16 * 2 ** 30, cpu_usage_percent: 0,
|
||||
disk_free_bytes: 24 * 2 ** 30, disk_total_bytes: 32 * 2 ** 30
|
||||
}]) });
|
||||
}
|
||||
if (method === 'POST' || method === 'PATCH') {
|
||||
@@ -108,6 +110,13 @@ test('creates and renames a customer, opens its inventory, and hides editing for
|
||||
await expect(headers.nth(1)).toHaveText('Type');
|
||||
await expect(device.getByRole('cell').nth(2)).toHaveText('hypervisor');
|
||||
await expect(device.getByRole('cell').nth(3)).toHaveText('Proxmox VE');
|
||||
const memory = device.locator('[data-label="RAM frei / gesamt"]');
|
||||
await expect(memory).toHaveText('6 / 16 GiB');
|
||||
await expect(memory.locator('.capacity-track')).toHaveAttribute('title', '37,5 % frei');
|
||||
await expect(memory.locator('.capacity-track i')).toHaveAttribute('style', 'width: 62.5%;');
|
||||
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
|
||||
.toHaveAttribute('style', 'width: 25%;');
|
||||
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
|
||||
const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' });
|
||||
await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await expect(page.getByRole('combobox', { name: 'Kunde', exact: true })).toHaveValue(customerId);
|
||||
@@ -209,3 +218,153 @@ test('removes the confirmed historical installation and keeps its successor', as
|
||||
await expect(page.getByText('Gerät verwalten', { exact: true })).toHaveCount(0);
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
test('moves an existing pairing through the WebUI and waits for target inventory', async ({ page }) => {
|
||||
const source = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Nord GmbH' };
|
||||
const target = { tenant_id: '22222222-2222-4222-8222-222222222222', name: 'Süd GmbH' };
|
||||
const device = { tenant_id: source.tenant_id, customer_name: source.name,
|
||||
asset_id: 'existing-asset', agent_id: 'existing-agent', hostname: 'NORD-PC', os: 'Linux',
|
||||
capabilities: ['device.customer_transfer/1'], lifecycle: 'current', status: 'online',
|
||||
recent_jobs: [], volumes: [] };
|
||||
const path = '/api/v1/tenants/' + source.tenant_id + '/devices/' + device.asset_id;
|
||||
const move = path + '/customer-transfer';
|
||||
const transfer = { transfer_id: 'move-fixture', target_tenant_id: target.tenant_id,
|
||||
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: {
|
||||
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
|
||||
} }));
|
||||
await page.route(origin + '/auth/session', r => {
|
||||
const selected = r.request().headers()['x-rmm-tenant'] ?? source.tenant_id;
|
||||
return r.fulfill({ json: { principal: 'fixture-operator', tenant_id: selected,
|
||||
csrf_token: 'move-csrf', testsimulation: false,
|
||||
permissions: ['inventory:read', ...(selected === source.tenant_id ? ['devices:revoke'] :
|
||||
canEnroll ? ['devices:enroll'] : [])] } });
|
||||
});
|
||||
await page.route(origin + '/api/v1/**', async r => {
|
||||
const req = r.request(), url = new URL(req.url());
|
||||
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([source, target]) });
|
||||
if (url.pathname === path) return r.fulfill({ json: {
|
||||
...device, lifecycle: state === 'completed' ? 'revoked' : 'current'
|
||||
} });
|
||||
if (url.pathname === move && req.method() === 'GET') {
|
||||
return r.fulfill({ json: { transfer: state ? { ...transfer, state } : null } });
|
||||
}
|
||||
if (req.method() === 'POST') {
|
||||
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);
|
||||
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' } });
|
||||
});
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto(origin + '/#geraete/' + [source.tenant_id, device.asset_id, device.agent_id].join('/'));
|
||||
await page.getByText('Gerät verwalten', { exact: true }).click();
|
||||
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 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 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');
|
||||
});
|
||||
|
||||
@@ -165,7 +165,7 @@ test('shows the execution stop and prepares the Windows restart through a versio
|
||||
expect(writes).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('offers local admin opt-in on both installer commands and keeps the one-time code outside commands', async ({ page }) => {
|
||||
test('offers one Linux command for x86-64 and ARM64 and keeps the code outside both installer commands', async ({ page }) => {
|
||||
const token = 'f'.repeat(64), api = '/api/v1/tenants/' + tenantId;
|
||||
const requests: string[] = [];
|
||||
await page.route(origin + '/auth/config', r => r.fulfill({ json: { dev_login_enabled: true, oidc_configured: false, oidc_login_url: null } }));
|
||||
@@ -176,7 +176,7 @@ test('offers local admin opt-in on both installer commands and keeps the one-tim
|
||||
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing(auth.tenants) });
|
||||
if (url.pathname === api + '/enrollment-tokens') return r.fulfill({ json: {
|
||||
token, expires_at: new Date(Date.now() + 900000).toISOString(), bootstrap_origin: 'https://bootstrap.example',
|
||||
release_platforms: ['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-gnu']
|
||||
release_platforms: ['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'x86_64-pc-windows-gnu']
|
||||
} });
|
||||
return r.fulfill({ json: { ...listing([]), pending_count: 0 } });
|
||||
});
|
||||
@@ -185,6 +185,7 @@ test('offers local admin opt-in on both installer commands and keeps the one-tim
|
||||
const option = enroll.getByRole('checkbox', { name: /Administratorskripte/ });
|
||||
await expect(option).not.toBeChecked();
|
||||
await enroll.getByRole('button', { name: 'Einmalcode erstellen' }).click();
|
||||
await expect(enroll.getByRole('heading', { name: 'Linux (x86-64 und ARM64)' })).toBeVisible();
|
||||
const commands = enroll.locator('pre');
|
||||
await expect(commands).toHaveCount(2);
|
||||
expect((await commands.allTextContents()).join(' ')).not.toMatch(/enable-admin-scripts|EnableAdministratorScripts/);
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise a Linux pairing switch against isolated PostgreSQL and real TLS.
|
||||
|
||||
Pass the built rmm-server and rmm-agent binaries. Only disposable fixtures,
|
||||
random local login credentials and loopback ports are used.
|
||||
"""
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
from local_access_database import command
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
A = "11111111-1111-4111-8111-111111111111"
|
||||
B = "22222222-2222-4222-8222-222222222222"
|
||||
IMAGE = "postgres:17.6-bookworm"
|
||||
HOST = "rmm-transfer.test"
|
||||
|
||||
|
||||
def until(probe, seconds=80):
|
||||
for _ in range(seconds * 4):
|
||||
value = probe()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.25)
|
||||
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",
|
||||
"-e", "POSTGRES_PASSWORD=" + pg_password, IMAGE])
|
||||
|
||||
def sql(statement, role="postgres"):
|
||||
return command(["docker", "exec", "-i", db, "psql", "-XqAt", "-v",
|
||||
"ON_ERROR_STOP=1", "-U", role, "-d", "postgres"],
|
||||
statement.encode()).decode().strip()
|
||||
|
||||
until(lambda: b"init process complete" in command(["docker", "logs", db]), 30)
|
||||
port = int(command(["docker", "port", db, "5432/tcp"]).decode().strip().split(":")[-1])
|
||||
app_password = secrets.token_hex(24)
|
||||
sql(f"""CREATE ROLE rmm_migrator LOGIN NOSUPERUSER NOBYPASSRLS;
|
||||
CREATE ROLE rmm_app LOGIN NOINHERIT NOSUPERUSER NOBYPASSRLS PASSWORD '{app_password}';
|
||||
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 = [], {}
|
||||
for username, home in [("owner", A), ("sourceonly", A), ("targetonly", B)]:
|
||||
password = secrets.token_urlsafe(26)
|
||||
secret = secrets.token_bytes(20)
|
||||
salt = secrets.token_bytes(32)
|
||||
principal = f"local:{uuid.uuid4()}"
|
||||
digest = hashlib.scrypt(password.encode(), salt=salt, n=2**17, r=8, p=1,
|
||||
maxmem=256 * 1024**2, dklen=64)
|
||||
users.append({"username": username, "principal": principal, "tenant_id": home,
|
||||
"disabled": False, "password_scrypt": {"salt_hex": salt.hex(), "hash_hex": digest.hex()},
|
||||
"totp_secret_base32": base64.b32encode(secret).decode()})
|
||||
login_data[username] = password, secret, home
|
||||
sql(f"""INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES
|
||||
('{home}','{principal}','human',ARRAY['inventory:read','devices:revoke','devices:enroll','tokens:manage']);""")
|
||||
sql(f"SELECT provision_customer_admin('{A}','{users[0]['principal']}');")
|
||||
local_auth = folder / "users.json"
|
||||
local_auth.write_text(json.dumps({"schema_version": 1, "users": users}))
|
||||
local_auth.chmod(0o600)
|
||||
command(["docker", "run", "--rm", "--network=none", "-v", f"{folder}:/fixture",
|
||||
"--entrypoint", "chown", IMAGE, "10001:10001", "/fixture/users.json"])
|
||||
|
||||
pki = folder / "pki"
|
||||
pki.mkdir(mode=0o700)
|
||||
command(["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256",
|
||||
"-nodes", "-days", "1", "-subj", "/CN=Transfer Fixture CA",
|
||||
"-addext", "basicConstraints=critical,CA:TRUE", "-out", str(pki / "ca.pem"), "-keyout", str(pki / "ca.key")])
|
||||
command(["openssl", "req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256",
|
||||
"-nodes", "-subj", f"/CN={HOST}", "-addext", f"subjectAltName=DNS:{HOST}",
|
||||
"-out", str(pki / "server.csr"), "-keyout", str(pki / "server.key")])
|
||||
command(["openssl", "x509", "-req", "-in", str(pki / "server.csr"), "-CA", str(pki / "ca.pem"),
|
||||
"-CAkey", str(pki / "ca.key"), "-set_serial", "2", "-days", "1", "-copy_extensions", "copy", "-out", str(pki / "server.pem")])
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
api_port = listener.getsockname()[1]
|
||||
origin = f"https://{HOST}:{api_port}"
|
||||
command(["docker", "run", "-d", "--name", api, "--network=host",
|
||||
"-v", f"{folder}:/fixture", "-v", f"{server}:/rmm-server:ro",
|
||||
"-e", "RMM_LISTEN_ADDR=127.0.0.1:" + str(api_port), "-e", "RMM_PROFILE=production",
|
||||
"-e", "RMM_SERVER_ROLE=all", "-e", "RMM_TLS_DIR=/fixture/pki",
|
||||
"-e", "RMM_LOCAL_AUTH_FILE=/fixture/users.json", "-e", "RMM_UI_ORIGIN=" + origin,
|
||||
"-e", "RMM_JOB_KEY_FILE=/fixture/ed25519.pem",
|
||||
"-e", f"DATABASE_URL=postgresql://rmm_app:{app_password}@127.0.0.1:{port}/postgres",
|
||||
"--entrypoint", "/rmm-server", IMAGE])
|
||||
context = ssl.create_default_context(cafile=pki / "ca.pem")
|
||||
|
||||
class HTTPS(http.client.HTTPSConnection):
|
||||
def connect(self):
|
||||
sock = socket.create_connection(("127.0.0.1", self.port), self.timeout)
|
||||
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
|
||||
|
||||
def request(path, body=None, headers=None, tls=context):
|
||||
conn = HTTPS(HOST, api_port, timeout=8, context=tls)
|
||||
try:
|
||||
h = {"Origin": origin, **(headers or {})}
|
||||
if body is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
conn.request("POST" if body is not None else "GET", path, json.dumps(body) if body is not None else None, h)
|
||||
result = conn.getresponse()
|
||||
data = result.read()
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except ValueError:
|
||||
pass
|
||||
return result.status, data, result.getheader("Set-Cookie")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def healthy():
|
||||
try:
|
||||
return request("/healthz")[0] == 200
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
until(healthy, 15)
|
||||
|
||||
def login(username):
|
||||
password, secret, tenant = login_data[username]
|
||||
code = hmac.digest(secret, (int(time.time()) // 30).to_bytes(8, "big"), "sha1")
|
||||
offset = code[-1] & 15
|
||||
totp = f"{(int.from_bytes(code[offset:offset+4], 'big') & 0x7fffffff) % 1000000:06d}"
|
||||
status, _, cookie = request("/auth/local/login", {"username": username, "password": password, "totp_code": totp})
|
||||
assert status == 200, ("fixture login", status)
|
||||
headers = {"Cookie": cookie.split(";")[0], "X-RMM-Tenant": tenant}
|
||||
status, session, _ = request("/auth/session", headers=headers)
|
||||
assert status == 200
|
||||
headers["X-CSRF-Token"] = session["csrf_token"]
|
||||
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)
|
||||
token_path.chmod(0o600)
|
||||
sql(f"INSERT INTO enrollment_tokens VALUES('{hashlib.sha256(token.encode()).hexdigest()}','{A}',now()+interval '15 minutes',NULL)")
|
||||
state = folder / "state"
|
||||
state.mkdir(mode=0o700)
|
||||
guard = folder / "release.lock"
|
||||
guard.touch(mode=0o644)
|
||||
config = {
|
||||
**os.environ, "RMM_AGENT_STATE": str(state), "RMM_CA_FILE": str(pki / "ca.pem"),
|
||||
"RMM_CONNECT_ADDR": f"127.0.0.1:{api_port}", "RMM_SERVER_NAME": HOST, "RMM_TRANSPORT": "https",
|
||||
"RMM_ENROLLMENT_TENANT": A, "RMM_ENROLLMENT_TOKEN_FILE": str(token_path),
|
||||
"RMM_JOB_SIGNING_KEY_BOOTSTRAP": "1", "RMM_RELEASE_LOCK": str(guard),
|
||||
"RMM_INSTALLED_RELEASE_VERSION": "transfer-fixture",
|
||||
}
|
||||
with (folder / "agent.log").open("w") as log:
|
||||
proc = subprocess.Popen([agent], env=config, stdout=log, stderr=log)
|
||||
try:
|
||||
def current_source():
|
||||
status, listing, _ = request(f"/api/v1/tenants/{A}/devices?view=current", headers=owner)
|
||||
assert status == 200
|
||||
return next((row for row in listing["items"]
|
||||
if row.get("agent_version") == "transfer-fixture" and row.get("hostname")), None)
|
||||
|
||||
old = until(current_source, 30)
|
||||
old_asset, old_agent = old["asset_id"], old["agent_id"]
|
||||
old_context = ssl.create_default_context(cafile=pki / "ca.pem")
|
||||
old_context.load_cert_chain(state / "device.pem", state / "device.key")
|
||||
path = f"/api/v1/tenants/{A}/devices/{old_asset}"
|
||||
transfer = path + "/customer-transfer"
|
||||
query = "?agent_id=" + old_agent
|
||||
suffix = lambda id, action: transfer + f"/{id}/{action}" + query
|
||||
body = {"target_tenant_id": B}
|
||||
assert request(transfer + query, body, source_only)[0] in (403, 404)
|
||||
assert request(transfer + query, body, target_only)[0] == 404
|
||||
assert request("/agent/v1/customer-transfer")[0] == 401
|
||||
assert request(path.replace(A, B) + query, headers=target_only)[0] == 404
|
||||
print("PASS limited sessions, direct IDs and unauthenticated device route")
|
||||
|
||||
proc.send_signal(signal.SIGSTOP)
|
||||
try:
|
||||
status, pending, _ = request(transfer + query, body, owner)
|
||||
assert status == 200, (status, pending)
|
||||
assert pending["state"] == "pending"
|
||||
assert request(suffix(pending["transfer_id"], "complete"), {}, owner)[0] == 409
|
||||
assert request(suffix(pending["transfer_id"], "cancel"), {}, owner)[0] == 204
|
||||
status, pending, _ = request(transfer + query, body, owner)
|
||||
assert status == 200 and pending["state"] == "pending"
|
||||
finally:
|
||||
proc.send_signal(signal.SIGCONT)
|
||||
|
||||
def target_completed():
|
||||
status, dto, _ = request(transfer + query, headers=owner)
|
||||
assert status == 200, (status, dto)
|
||||
move = dto["transfer"]
|
||||
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_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
|
||||
local = json.loads((state / "identity.json").read_text())
|
||||
assert local["agent_id"] == target_agent
|
||||
assert not list(state.glob("customer-move-*-prior-journal.sqlite"))
|
||||
assert proc.poll() is None
|
||||
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"])
|
||||
status, detail, _ = request(f"/api/v1/tenants/{B}/devices/{target_asset}?agent_id={target_agent}", headers=target_only)
|
||||
assert status == 200 and detail["tenant_id"] == B
|
||||
assert request(path + query, headers=target_only)[0] == 404
|
||||
assert request(f"/api/v1/tenants/{B}/devices/{target_asset}", headers=source_only)[0] == 404
|
||||
assert sql("SELECT count(*) FROM jobs;") == "0"
|
||||
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, {
|
||||
"name": f"transfer fixture {audience}", "audience": audience,
|
||||
"tenant_ids": allowed_tenants, "scopes": ["inventory:read"],
|
||||
}, owner)
|
||||
assert status == 200, ("token issuance", status)
|
||||
bearer = {"Authorization": "Bearer " + issued["token"]}
|
||||
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
|
||||
assert request(f"{tokens}/{issued['token_id']}/revoke", {}, owner)[0] == 200
|
||||
assert request("/api/v1/devices?view=current", headers=bearer)[0] == 401
|
||||
print("PASS scoped and global bearer lists, direct IDs, interactive transfer and token revocation")
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=12)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
server, agent = (Path(arg).resolve(strict=True) for arg in sys.argv[1:])
|
||||
suffix = uuid.uuid4().hex[:10]
|
||||
db, api = f"rmm-transfer-db-{suffix}", f"rmm-transfer-api-{suffix}"
|
||||
with tempfile.TemporaryDirectory(prefix="rmm-transfer-") as tmp:
|
||||
directory = Path(tmp)
|
||||
try:
|
||||
run(server, agent, directory, db, api)
|
||||
except Exception:
|
||||
for name in (api,):
|
||||
log = subprocess.run(["docker", "logs", "--tail", "15", name], capture_output=True, text=True)
|
||||
print(log.stderr)
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
print((directory / "agent.log").read_text()[-1600:])
|
||||
raise
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", api, db], capture_output=True)
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Retry coverage for the HTTPS Linux bootstrap without installing on the test host."""
|
||||
from contextlib import ExitStack, redirect_stdout
|
||||
from datetime import datetime, timezone
|
||||
from importlib.util import module_from_spec, spec_from_file_location
|
||||
import io
|
||||
import json
|
||||
@@ -17,6 +18,40 @@ lifecycle = module_from_spec(spec)
|
||||
spec.loader.exec_module(lifecycle)
|
||||
|
||||
|
||||
class EnrollmentHeartbeat(unittest.TestCase):
|
||||
def test_health_probe_waits_for_the_first_certificate_before_fetching(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
state = Path(folder)
|
||||
certificate = state / 'certificates/current.json'
|
||||
certificate.parent.mkdir()
|
||||
now = datetime(2026, 11, 18, 17, tzinfo=timezone.utc)
|
||||
record = {'last_contact_at': now.isoformat(),
|
||||
'agent_version': '0.1.0-arm64.1', 'connection_generation': 1}
|
||||
|
||||
def finish_enrollment(_seconds):
|
||||
probe.assert_not_called()
|
||||
certificate.touch()
|
||||
|
||||
with patch.object(lifecycle, 'STATE', state), \
|
||||
patch.object(lifecycle.time, 'time', return_value=now.timestamp()), \
|
||||
patch.object(lifecycle.time, 'monotonic', side_effect=[0, 0, 2]), \
|
||||
patch.object(lifecycle.time, 'sleep', side_effect=finish_enrollment) as wait, \
|
||||
patch.object(lifecycle, 'installed', return_value=record) as probe, \
|
||||
patch.object(lifecycle.subprocess, 'run', return_value=SimpleNamespace(returncode=0)):
|
||||
self.assertTrue(lifecycle.healthy('0.1.0-arm64.1', 0))
|
||||
wait.assert_called_once_with(2)
|
||||
probe.assert_called_once_with()
|
||||
|
||||
def test_missing_certificate_still_times_out(self):
|
||||
with tempfile.TemporaryDirectory() as folder, \
|
||||
patch.object(lifecycle, 'STATE', Path(folder)), \
|
||||
patch.object(lifecycle.time, 'monotonic', side_effect=[0, 0, 2]), \
|
||||
patch.object(lifecycle.time, 'sleep'), \
|
||||
patch.object(lifecycle, 'installed', return_value={}) as probe:
|
||||
self.assertFalse(lifecycle.healthy('0.1.0-arm64.1', 0, duration=1))
|
||||
probe.assert_not_called()
|
||||
|
||||
|
||||
class EnrollmentRetry(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.stack = ExitStack()
|
||||
@@ -56,9 +91,11 @@ class EnrollmentRetry(unittest.TestCase):
|
||||
lifecycle.device_idle()
|
||||
self.assertEqual(output.getvalue().strip(), expected)
|
||||
|
||||
def bootstrap_tenant(self, tenant):
|
||||
def bootstrap_tenant(self, tenant, expected_platform=None):
|
||||
def answer(source, route, target):
|
||||
self.assertEqual(source, (self.base,'0' * 64))
|
||||
if expected_platform:
|
||||
self.assertEqual(route, '/agent/v1/bootstrap/current?platform=' + expected_platform)
|
||||
target.write_text(json.dumps({'tenant_id': tenant}))
|
||||
return self.stack.enter_context(patch.object(lifecycle,'remote',side_effect=answer))
|
||||
|
||||
@@ -80,6 +117,29 @@ class EnrollmentRetry(unittest.TestCase):
|
||||
self.save.assert_called_once()
|
||||
self.healthy.assert_called_once_with('1.0',0)
|
||||
|
||||
def test_arm64_install_retry_requests_arm64_release(self):
|
||||
self.bootstrap_tenant(self.tenant, 'aarch64-unknown-linux-gnu')
|
||||
with patch.object(lifecycle.platform, 'machine', return_value='aarch64'):
|
||||
lifecycle.install(self.base, self.token, enable_admin_scripts=True)
|
||||
self.save.assert_called_once()
|
||||
self.provision.assert_called_once_with(True)
|
||||
|
||||
def test_unsupported_architecture_stops_before_enrollment(self):
|
||||
with patch.object(lifecycle.platform, 'machine', return_value='armv7l'), \
|
||||
patch.object(lifecycle, 'enrollment_token') as token:
|
||||
with self.assertRaisesRegex(ValueError, 'Linux x86-64 or ARM64 required'):
|
||||
lifecycle.install(self.base, self.token)
|
||||
token.assert_not_called()
|
||||
self.enable.assert_not_called()
|
||||
|
||||
def test_x64_release_is_rejected_before_downloading_to_arm64(self):
|
||||
doc = {'manifest': {'release_id': self.tenant, 'platform': 'x86_64-unknown-linux-gnu'}}
|
||||
with patch.object(lifecycle.platform, 'machine', return_value='aarch64'), \
|
||||
patch.object(lifecycle, 'remote') as download:
|
||||
with self.assertRaisesRegex(ValueError, 'release architecture differs'):
|
||||
lifecycle.pair(lifecycle.ROOT, doc, (self.base, '0' * 64), lifecycle.ROOT / 'updater')
|
||||
download.assert_not_called()
|
||||
|
||||
def test_timer_starts_only_after_confirmed_first_connection(self):
|
||||
self.bootstrap_tenant(self.tenant)
|
||||
self.healthy.return_value = False
|
||||
|
||||
@@ -19,9 +19,11 @@ from urllib.parse import urlencode, urlsplit
|
||||
import uuid
|
||||
|
||||
LINUX = 'x86_64-unknown-linux-gnu'
|
||||
LINUX_ARM64 = 'aarch64-unknown-linux-gnu'
|
||||
WINDOWS = 'x86_64-pc-windows-msvc'
|
||||
FILES = {LINUX: ('rmm-agent', 'rmm-privileged-helper', 'rmm-agent-updater'),
|
||||
WINDOWS: ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'rmm-updater-windows.exe')}
|
||||
FILES[LINUX_ARM64] = FILES[LINUX]
|
||||
WINDOWS_GNU = 'x86_64-pc-windows-gnu'
|
||||
FILES[WINDOWS_GNU] = FILES[WINDOWS]
|
||||
LIMIT = 256 * 1024 * 1024
|
||||
@@ -55,9 +57,11 @@ def verify_native_image(path, target, size):
|
||||
with path.open('rb') as binary:
|
||||
header = binary.read(64)
|
||||
check(len(header) == 64, 'truncated binary header: ' + path.name)
|
||||
if target == LINUX:
|
||||
if target in (LINUX, LINUX_ARM64):
|
||||
machine = 62 if target == LINUX else 183
|
||||
check(header[:6] == b'\x7fELF\x02\x01' and header[16:18] in (b'\x02\x00', b'\x03\x00')
|
||||
and header[18:20] == b'\x3e\x00', 'Linux x86-64 ELF image required: ' + path.name)
|
||||
and int.from_bytes(header[18:20], 'little') == machine,
|
||||
f'{target} ELF image required: {path.name}')
|
||||
else:
|
||||
pe = int.from_bytes(header[60:64], 'little')
|
||||
check(header[:2] == b'MZ' and 64 <= pe <= size - 26, 'Windows PE image required: ' + path.name)
|
||||
@@ -130,7 +134,7 @@ def release_label(platform, official_windows):
|
||||
if official_windows:
|
||||
check(platform == WINDOWS_GNU, 'official Windows releases require a GNU x64 build receipt')
|
||||
return 'windows-gnu-official'
|
||||
return {LINUX: 'linux', WINDOWS: 'windows', WINDOWS_GNU: 'windows-gnu'}[platform]
|
||||
return {LINUX: 'linux', LINUX_ARM64: 'linux-arm64', WINDOWS: 'windows', WINDOWS_GNU: 'windows-gnu'}[platform]
|
||||
|
||||
|
||||
def prepare(args):
|
||||
|
||||
+18
-11
@@ -22,6 +22,12 @@ TARGETS = {
|
||||
"sha256:30ae3d90753bc39b0a98a897784c662aff9598ffab7a98a6298e8aa79145c2ec",
|
||||
[("rmm-server", "rmm-server"), ("rmm-time-broker-linux", "rmm-time-broker-linux")],
|
||||
),
|
||||
"linux-arm64": (
|
||||
"linux/arm64", "aarch64-unknown-linux-gnu",
|
||||
"sha256:30ae3d90753bc39b0a98a897784c662aff9598ffab7a98a6298e8aa79145c2ec",
|
||||
[("rmm-agent", "rmm-agent"), ("rmm-privileged-helper", "rmm-privileged-helper"),
|
||||
("rmm-updater-worker", "rmm-agent-updater")],
|
||||
),
|
||||
"linux-x64": (
|
||||
"linux/amd64", "x86_64-unknown-linux-gnu",
|
||||
"sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6",
|
||||
@@ -34,6 +40,7 @@ TARGETS = {
|
||||
[("rmm-agent-windows", "rmm-agent-windows"), ("rmm-agent-windows", "rmm-helper-windows")],
|
||||
),
|
||||
}
|
||||
REMOTE_TARGETS = ("server-arm64", "linux-arm64")
|
||||
SOURCE_PATHS = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "crates", "proto",
|
||||
"migrations", "tools/apt-transaction", "deploy/linux", "tests"]
|
||||
|
||||
@@ -140,7 +147,7 @@ def build_archive(work, archive, revision, plan):
|
||||
print(f"Artifacts: {destination}\n{json.dumps(hashes, indent=2)}")
|
||||
|
||||
|
||||
def remote_build(archive, revision, jobs):
|
||||
def remote_build(archive, revision, jobs, target):
|
||||
from dev_stage import ssh_prefix
|
||||
|
||||
# The only SSH payload is this build driver and the selected Git sources.
|
||||
@@ -154,14 +161,14 @@ trap 'rm -rf -- "$stage"' EXIT
|
||||
cd "$stage"
|
||||
tar -xf - build.py source.tar.gz
|
||||
printf '%s build.py\\n%s source.tar.gz\\n' "$1" "$2" | sha256sum -c - >/dev/null
|
||||
python3 -I build.py _server_worker "$3" "$4"
|
||||
python3 -I build.py _server_worker "$3" "$4" "$5"
|
||||
"""
|
||||
with tempfile.TemporaryFile() as bundle:
|
||||
with tarfile.open(fileobj=bundle, mode="w") as package:
|
||||
package.add(worker, arcname="build.py")
|
||||
package.add(archive, arcname="source.tar.gz")
|
||||
bundle.seek(0)
|
||||
command = shlex.join(["sh", "-c", shell, "build", *checksums, revision, str(jobs)])
|
||||
command = shlex.join(["sh", "-c", shell, "build", *checksums, revision, str(jobs), target])
|
||||
result = subprocess.run([*ssh_prefix("server"), command], stdin=bundle)
|
||||
if result.returncode:
|
||||
raise SystemExit(f"ARM64 build via SSH failed (exit {result.returncode}).")
|
||||
@@ -176,13 +183,13 @@ def main():
|
||||
parser.add_argument("target", choices=TARGETS)
|
||||
parser.add_argument("--ref", default="HEAD", help="Git commit or ref (default: HEAD). Uncommitted edits are excluded.")
|
||||
parser.add_argument("--jobs", type=int, default=2, help="Maximum parallel Cargo jobs (default: 2).")
|
||||
parser.add_argument("--ssh", action="store_true", help="Build server-arm64 on the configured server, in ~/rmm-dev-build/.")
|
||||
parser.add_argument("--ssh", action="store_true", help="Build ARM64 binaries on the configured server, in ~/rmm-dev-build/.")
|
||||
parser.add_argument("--plan", action="store_true", help="Show the build plan without connecting, writing or building.")
|
||||
args = parser.parse_args()
|
||||
if args.jobs < 1:
|
||||
parser.error("--jobs must be positive")
|
||||
if args.ssh and args.target != "server-arm64":
|
||||
parser.error("--ssh applies to server-arm64")
|
||||
if args.ssh and args.target not in REMOTE_TARGETS:
|
||||
parser.error("--ssh applies to the ARM64 targets")
|
||||
revision = git("rev-parse", "--verify", "--end-of-options", args.ref + "^{commit}")
|
||||
windows_updater = args.target == "windows-gnu-x64" and git(
|
||||
"ls-tree", "--name-only", revision, "crates/agent-windows/src/bin/rmm-updater-windows.rs")
|
||||
@@ -196,7 +203,7 @@ def main():
|
||||
archive = Path(temporary) / "source.tar.gz"
|
||||
subprocess.run(["git", "archive", "-o", archive, revision, "--", *SOURCE_PATHS], cwd=ROOT, check=True)
|
||||
if args.ssh:
|
||||
remote_build(archive, revision, args.jobs)
|
||||
remote_build(archive, revision, args.jobs, args.target)
|
||||
else:
|
||||
build_archive(ROOT / "devstate" / "build" / args.target, archive, revision, plan)
|
||||
|
||||
@@ -204,12 +211,12 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
if sys.argv[1:2] == ["_server_worker"]:
|
||||
revision, jobs_arg = sys.argv[2:]
|
||||
if (len(revision) not in (40, 64) or any(c not in "0123456789abcdef" for c in revision)
|
||||
revision, jobs_arg, target = sys.argv[2:]
|
||||
if (target not in REMOTE_TARGETS or len(revision) not in (40, 64) or any(c not in "0123456789abcdef" for c in revision)
|
||||
or not jobs_arg.isascii() or not jobs_arg.isdecimal() or int(jobs_arg) < 1):
|
||||
raise SystemExit("Invalid packed build request.")
|
||||
work = Path.home() / "rmm-dev-build" / "server-arm64"
|
||||
build_archive(work, Path("source.tar.gz").resolve(), revision, prepare("server-arm64", int(jobs_arg)))
|
||||
work = Path.home() / "rmm-dev-build" / target
|
||||
build_archive(work, Path("source.tar.gz").resolve(), revision, prepare(target, int(jobs_arg)))
|
||||
else:
|
||||
main()
|
||||
except (OSError, subprocess.CalledProcessError) as error:
|
||||
|
||||
@@ -17,7 +17,8 @@ from dev_stage import ssh_prefix
|
||||
|
||||
def publish(tenant, platform, release, official_windows=False, *, root=Path('/opt/rust-discovery/devstate/mvp-releases'),
|
||||
database_container='rust-discovery-server-postgres-1', service_uid=10001):
|
||||
labels = {'x86_64-pc-windows-gnu': 'windows-gnu', 'x86_64-unknown-linux-gnu': 'linux'}
|
||||
labels = {'x86_64-pc-windows-gnu': 'windows-gnu', 'x86_64-unknown-linux-gnu': 'linux',
|
||||
'aarch64-unknown-linux-gnu': 'linux-arm64'}
|
||||
label = labels[platform]
|
||||
if official_windows:
|
||||
if platform != 'x86_64-pc-windows-gnu':
|
||||
@@ -88,7 +89,7 @@ def publish(tenant, platform, release, official_windows=False, *, root=Path('/op
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--tenant',required=True,type=uuid.UUID)
|
||||
parser.add_argument('--platform',required=True,choices=['x86_64-unknown-linux-gnu','x86_64-pc-windows-gnu'])
|
||||
parser.add_argument('--platform',required=True,choices=['x86_64-unknown-linux-gnu','aarch64-unknown-linux-gnu','x86_64-pc-windows-gnu'])
|
||||
parser.add_argument('--official-windows',action='store_true')
|
||||
parser.add_argument('--release',required=True,type=uuid.UUID)
|
||||
args=parser.parse_args()
|
||||
|
||||
@@ -25,7 +25,7 @@ export function releaseEnvelope(value: unknown): ReleaseView {
|
||||
if (!bytes.length || bytes.length > 16384 || signature.length !== 64) throw new Error('Agentupdate: Manifest-/Signaturlimit');
|
||||
const m = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
exact(m, ['schema_version', 'release_id', 'release_sequence', 'version', 'platform', 'published_at', 'expires_at', 'protocol_major', 'state_schema', 'minimum_updater_version', 'artifacts']);
|
||||
if (m.schema_version !== 1 || !['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-msvc', 'x86_64-pc-windows-gnu'].includes(String(m.platform)) || typeof m.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(m.version)
|
||||
if (m.schema_version !== 1 || !['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'x86_64-pc-windows-msvc', 'x86_64-pc-windows-gnu'].includes(String(m.platform)) || typeof m.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(m.version)
|
||||
|| !Array.isArray(m.artifacts) || m.artifacts.length !== 2) throw new Error('Agentupdate: festes x64-Codepaar erforderlich');
|
||||
const artifacts = m.artifacts.map((value, index) => { const a = record(value); exact(a, ['role', 'artifact_id', 'sha256', 'bytes']); if (a.role !== ['agent', 'helper'][index]) throw new Error('Agentupdate: Agent-/Helperreihenfolge'); return { role: a.role, artifact_id: uuid(a.artifact_id), sha256: digest(a.sha256), bytes: integer(a.bytes, 1, 268435456) }; });
|
||||
if (artifacts[0]!.artifact_id === artifacts[1]!.artifact_id) throw new Error('Agentupdate: doppelte Artefakt-ID');
|
||||
@@ -55,7 +55,7 @@ export function validateAgentUpdateAction(value: unknown, identity: unknown): Re
|
||||
const action = record(value); exact(action, ['action', 'update']); if (action.action !== 'update_agent') throw new Error('Agentupdate: typisierte Aktion erforderlich');
|
||||
const u = record(action.update); exact(u, ['schema_version', 'profile', 'release_envelope', 'release_envelope_sha256', 'manifest_sha256', 'predecessor', 'updater', 'peer_pin_transition', 'recovery', 'health_profile', 'health_timeout_seconds', 'no_reboot']);
|
||||
if (u.schema_version !== 1 || u.profile !== 'fixed_code_pair_v1' || u.recovery !== 'restore_exact_predecessor_once' || u.health_profile !== 'mtls_inventory_sync_v1' || u.health_timeout_seconds !== 180 || u.no_reboot !== true) throw new Error('Agentupdate: fester Apply-/Health-/No-Reboot-Vertrag erforderlich');
|
||||
const release = releaseEnvelope(u.release_envelope), linux = release.manifest.platform === 'x86_64-unknown-linux-gnu';
|
||||
const release = releaseEnvelope(u.release_envelope), linux = ['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu'].includes(String(release.manifest.platform));
|
||||
if (identity !== (linux ? 'root' : 'system')) throw new Error('Agentupdate: Plattform und Root-/SYSTEM-Identität widersprechen sich');
|
||||
const old = record(u.predecessor); exact(old, ['release_id', 'release_sequence', 'manifest_sha256', 'installed_record_sha256', 'agent_sha256', 'helper_sha256']);
|
||||
const predecessor = { release_id: uuid(old.release_id), release_sequence: integer(old.release_sequence), manifest_sha256: digest(old.manifest_sha256), installed_record_sha256: digest(old.installed_record_sha256), agent_sha256: digest(old.agent_sha256), helper_sha256: digest(old.helper_sha256) };
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useState } from 'react';
|
||||
import { ApiError, record, request, session, tenantPath, type Session, type Tenant } from './api';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
import { allowed } from './safety';
|
||||
|
||||
type Transfer = {
|
||||
id: string;
|
||||
state: 'pending' | 'enrolled' | 'completed';
|
||||
tenant: string;
|
||||
asset: string | null;
|
||||
agent: string | null;
|
||||
};
|
||||
|
||||
function parseTransfer(value: unknown): Transfer | null {
|
||||
if (value === null) return 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 !== '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
|
||||
};
|
||||
}
|
||||
|
||||
function transferError(error: unknown) {
|
||||
if (error instanceof ApiError) {
|
||||
const messages: Record<string, string> = {
|
||||
DEVICE_HAS_OPEN_WORK: 'Schließen Sie offene Aufträge und Genehmigungen für dieses Gerät ab.',
|
||||
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_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.'
|
||||
};
|
||||
return messages[error.code] ?? errorText(error);
|
||||
}
|
||||
return errorText(error);
|
||||
}
|
||||
|
||||
export function DeviceCustomerTransfer({ auth, customer, asset, agent, customers, active, supported }: {
|
||||
auth: Session;
|
||||
customer: string;
|
||||
asset: string;
|
||||
agent: string;
|
||||
customers: Tenant[];
|
||||
active: boolean;
|
||||
supported: boolean;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [target, setTarget] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const base = tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/customer-transfer');
|
||||
const query = '?agent_id=' + encodeURIComponent(agent);
|
||||
const status = useResource(async signal => {
|
||||
if (!expanded) return null;
|
||||
const response = record(await request(base + query, { signal, tenantId: customer }));
|
||||
return { transfer: parseTransfer(response.transfer) };
|
||||
}, [base, query, expanded, auth.principal.id], expanded);
|
||||
const destination = useResource(async signal => {
|
||||
if (!target || !expanded || status.data?.transfer) return null;
|
||||
return session(await request('/auth/session', { signal, tenantId: target }));
|
||||
}, [target, expanded, status.data?.transfer?.id, auth.principal.id]);
|
||||
const canEnroll = !!destination.data && allowed(destination.data, 'devices:enroll')
|
||||
&& allowed(destination.data, 'inventory:read');
|
||||
const choices = customers.filter(entry => entry.tenant_id !== customer);
|
||||
const current = status.data?.transfer ?? null;
|
||||
const targetName = choices.find(entry => entry.tenant_id === current?.tenant)?.name;
|
||||
async function submit(suffix: string, body: Record<string, unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await request(base + suffix + query, { csrf: auth.csrf_token, tenantId: customer, body });
|
||||
status.reload();
|
||||
} catch (e) {
|
||||
setError(transferError(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return <details onToggle={event => setExpanded(event.currentTarget.open)}>
|
||||
<summary>Kunden wechseln</summary>
|
||||
{expanded && <>
|
||||
<ErrorBox error={error ?? status.error} />
|
||||
{current ? <>
|
||||
{targetName && <p>Zielkunde <strong>{targetName}</strong></p>}
|
||||
{current.state === 'pending' && <>
|
||||
<p role="status">Der Wechsel ist vorgemerkt. Der Agent übernimmt ihn beim nächsten verfügbaren Kontakt.</p>
|
||||
<button disabled={busy} className="quiet"
|
||||
onClick={() => void submit('/' + encodeURIComponent(current.id) + '/cancel', {})}>Vormerkung abbrechen</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 && current.state === 'completed' &&
|
||||
<a href={'#geraete/' + [current.tenant, current.asset, current.agent].map(encodeURIComponent).join('/')}>
|
||||
Neue Kopplung öffnen
|
||||
</a>}
|
||||
</> : status.data && (active ? supported ? choices.length ? <>
|
||||
<p>Der Agent registriert sich beim Zielkunden. Inventar und Aufträge der bisherigen Kopplung bleiben in dessen Historie.
|
||||
Gerätegebundene Administratorrechte brauchen eine neue Bindung.</p>
|
||||
<form onSubmit={e => {
|
||||
e.preventDefault();
|
||||
if (!busy && canEnroll && target) void submit('', { target_tenant_id: target });
|
||||
}}>
|
||||
<label>Zielkunde<select aria-label="Zielkunde" value={target} onChange={e => setTarget(e.target.value)} required disabled={busy}>
|
||||
<option value="">Kunden auswählen</option>
|
||||
{choices.map(entry => <option key={entry.tenant_id} value={entry.tenant_id}>{entry.name}</option>)}
|
||||
</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 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>
|
||||
: <p>Für einen Kundenwechsel ist eine aktive Kopplung erforderlich.</p>)}
|
||||
</>}
|
||||
</details>;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, it } from 'vitest';
|
||||
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
||||
|
||||
const report = (scope: string, data: unknown, truncated = false, quality = 'valid') =>
|
||||
({ scope, data, truncated, quality, observed_at: '2026-11-18T08:00:00Z' });
|
||||
|
||||
it('reads current and older Linux snapshots, and labels approximate installation time', () => {
|
||||
const device = { inventory: { observations: [
|
||||
report('linux.os', { installed_at: '2025-03-12T10:00:00Z', install_date_source: 'root_filesystem', uptime_seconds: 60 }),
|
||||
report('linux.hardware', { readable_dmi: { sys_vendor: 'Vendor' } }),
|
||||
report('linux.interfaces', [{ name: 'eth0', addresses: ['192.0.2.1', '2001:db8::1%0'] }]),
|
||||
report('linux.users', ['alice']),
|
||||
report('linux.software', [{ name: 'openssh-server', version: '1.2', architecture: 'arm64' }], true)
|
||||
] } };
|
||||
expect(systemDetails(device, value => typeof value === 'string' ? value : 'Nicht gemeldet')).toEqual([
|
||||
['OS installiert am', '2025-03-12T10:00:00Z · geschätzt (Root-Dateisystem)'],
|
||||
['Letzter Neustart', '2026-11-18T07:59:00.000Z'],
|
||||
['Hersteller', 'Vendor'],
|
||||
['BIOS-Seriennummer', 'Nicht gemeldet'],
|
||||
['Garantie bis', 'Nicht gemeldet']
|
||||
]);
|
||||
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
|
||||
expect(view).toContain('192.0.2.1, 2001:db8::1');
|
||||
expect(view).toContain('alice');
|
||||
expect(view).toContain('openssh-server');
|
||||
expect(view).toContain('einen Teil der gefundenen Einträge');
|
||||
});
|
||||
|
||||
it('shows Windows adapters, serial and registry software, with unknown distinct from empty sessions', () => {
|
||||
const device = { inventory: { observations: [
|
||||
report('windows.os', { booted_at: '2026-11-18T08:00:00Z' }),
|
||||
report('windows.hardware', { manufacturer: 'Vendor', bios_serial_number: 'ABC123' }),
|
||||
report('windows.interfaces', { entries: [{ name: 'Ethernet', addresses: ['192.0.2.2'] }] }),
|
||||
report('windows.users', null, false, 'permission_denied'),
|
||||
report('windows.software', { entries: [{ display_name: 'Produkt', publisher: 'Hersteller' }] })
|
||||
] } };
|
||||
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
|
||||
expect(view).toContain('Ethernet');
|
||||
expect(view).toContain('Produkt');
|
||||
expect(view).toContain('Nicht gemeldet');
|
||||
expect(view).not.toContain('Keine Benutzer angemeldet');
|
||||
expect(systemDetails(device, String)).toContainEqual(['BIOS-Seriennummer', 'ABC123']);
|
||||
device.inventory.observations[3] = report('windows.users', { entries: [] });
|
||||
expect(renderToStaticMarkup(<DeviceInventoryPanels device={device} />)).toContain('Keine Benutzer angemeldet');
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import type { RecordValue } from './api';
|
||||
|
||||
const unreported = 'Nicht gemeldet';
|
||||
const pageSize = 25;
|
||||
|
||||
function object(value: unknown): RecordValue {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : {};
|
||||
}
|
||||
function text(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
function values(value: unknown) {
|
||||
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
|
||||
}
|
||||
|
||||
function observation(device: RecordValue, name: string) {
|
||||
const observations = object(device.inventory).observations;
|
||||
return Array.isArray(observations) ? observations.map(object).find(item =>
|
||||
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
|
||||
) : undefined;
|
||||
}
|
||||
|
||||
export function systemDetails(device: RecordValue, formatTime: (value: unknown) => string) {
|
||||
const os = observation(device, 'os');
|
||||
const system = object(os?.data);
|
||||
const hardware = object(observation(device, 'hardware')?.data);
|
||||
const installed = formatTime(system.installed_at);
|
||||
const source = system.install_date_source === 'root_filesystem' ? 'Root-Dateisystem'
|
||||
: system.install_date_source === 'installer_directory' ? 'Installer-Verzeichnis' : null;
|
||||
let booted = formatTime(system.booted_at);
|
||||
if (booted === unreported && os?.scope === 'linux.os' && typeof system.uptime_seconds === 'number') {
|
||||
const captured = Date.parse(text(os.observed_at) ?? '');
|
||||
const estimated = captured - system.uptime_seconds * 1000;
|
||||
if (system.uptime_seconds >= 0 && Number.isFinite(estimated) && estimated >= 0) {
|
||||
booted = formatTime(new Date(estimated).toISOString());
|
||||
}
|
||||
}
|
||||
return [
|
||||
['OS installiert am', source && installed !== unreported ? installed + ' · geschätzt (' + source + ')' : installed],
|
||||
['Letzter Neustart', booted],
|
||||
['Hersteller', text(hardware.manufacturer) ?? text(object(hardware.readable_dmi).sys_vendor) ?? unreported],
|
||||
['BIOS-Seriennummer', text(hardware.bios_serial_number) ?? unreported],
|
||||
['Garantie bis', formatTime(hardware.warranty_expires_at)]
|
||||
];
|
||||
}
|
||||
|
||||
function entries(report: RecordValue | undefined): unknown[] | null {
|
||||
const rows = Array.isArray(report?.data) ? report.data : object(report?.data).entries;
|
||||
return Array.isArray(rows) ? rows : null;
|
||||
}
|
||||
|
||||
function note(report: RecordValue | undefined) {
|
||||
const readErrors = object(report?.data).read_errors;
|
||||
return report?.truncated === true || (typeof readErrors === 'number' && readErrors > 0);
|
||||
}
|
||||
|
||||
function InventoryTable({ headings, children }: { headings: string[]; children: ReactNode }) {
|
||||
return <div className="table"><table>
|
||||
<thead><tr>{headings.map(label => <th scope="col" key={label}>{label}</th>)}</tr></thead>
|
||||
<tbody>{children}</tbody>
|
||||
</table></div>;
|
||||
}
|
||||
|
||||
function Software({ report }: { report: RecordValue | undefined }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [page, setPage] = useState(0);
|
||||
const rows = entries(report)?.flatMap(entry => {
|
||||
const row = object(entry);
|
||||
const name = text(row.name) ?? text(row.display_name);
|
||||
if (!name) return [];
|
||||
return [{ name, version: text(row.version), publisher: text(row.publisher), architecture: text(row.architecture) }];
|
||||
}).sort((left, right) => left.name.localeCompare(right.name, 'de'));
|
||||
const matching = (rows ?? []).filter(row => Object.values(row).some(value =>
|
||||
value?.toLocaleLowerCase('de').includes(query.trim().toLocaleLowerCase('de'))
|
||||
));
|
||||
const lastPage = Math.max(0, Math.ceil(matching.length / pageSize) - 1);
|
||||
const current = Math.min(page, lastPage);
|
||||
|
||||
return <details>
|
||||
<summary>Installierte Software{rows ? ' (' + rows.length + ')' : ''}</summary>
|
||||
{note(report) && <p className="muted">Die Meldung enthält einen Teil der gefundenen Einträge.</p>}
|
||||
{rows === undefined ? <p>{unreported}</p> : rows.length === 0 ? <p>Keine Softwareeinträge gemeldet.</p> : <>
|
||||
<label>Software suchen
|
||||
<input type="search" value={query} maxLength={120} onChange={e => { setQuery(e.target.value); setPage(0); }} />
|
||||
</label>
|
||||
{matching.length ? <InventoryTable headings={['Name', 'Version', 'Herausgeber', 'Architektur']}>
|
||||
{matching.slice(current * pageSize, (current + 1) * pageSize).map((row, index) => <tr key={index}>
|
||||
<td>{row.name}</td>
|
||||
<td>{row.version ?? '–'}</td>
|
||||
<td>{row.publisher ?? '–'}</td>
|
||||
<td>{row.architecture ?? '–'}</td>
|
||||
</tr>)}
|
||||
</InventoryTable> : <p>Keine Treffer.</p>}
|
||||
{lastPage > 0 && <div className="list-footer">
|
||||
<span>Seite {current + 1} von {lastPage + 1}</span>
|
||||
<div>
|
||||
<button className="quiet" disabled={current === 0} onClick={() => setPage(current - 1)}>Zurück</button>
|
||||
<button className="quiet" disabled={current === lastPage} onClick={() => setPage(current + 1)}>Weiter</button>
|
||||
</div>
|
||||
</div>}
|
||||
</>}
|
||||
</details>;
|
||||
}
|
||||
|
||||
export function DeviceInventoryPanels({ device }: { device: RecordValue }) {
|
||||
const network = observation(device, 'interfaces');
|
||||
const interfaces = entries(network)?.map(object).filter(row => text(row.name));
|
||||
const sessions = observation(device, 'users');
|
||||
const users = values(entries(sessions)).sort((a, b) => a.localeCompare(b, 'de'));
|
||||
return <>
|
||||
<section>
|
||||
<h2>Netzwerkkarten und IP-Adressen</h2>
|
||||
{note(network) && <p className="muted">Die Meldung enthält einen Teil der Netzwerkkarten oder Adressen.</p>}
|
||||
{interfaces === undefined ? <p>{unreported}</p> : interfaces.length === 0 ? <p>Keine Netzwerkkarten gemeldet.</p> :
|
||||
<InventoryTable headings={['Netzwerkkarte', 'MAC-Adresse', 'IP-Adressen']}>
|
||||
{interfaces.map((row, index) => <tr key={index}>
|
||||
<td>{text(row.name)}</td>
|
||||
<td>{text(row.mac) ?? '–'}</td>
|
||||
<td>{values(row.addresses).map(address => address.replace(/%0$/, '')).join(', ') || 'Keine Adresse gemeldet'}</td>
|
||||
</tr>)}
|
||||
</InventoryTable>}
|
||||
</section>
|
||||
<section>
|
||||
<h2>Angemeldete Benutzer</h2>
|
||||
{note(sessions) && <p className="muted">Die Meldung enthält einen Teil der Sitzungen.</p>}
|
||||
{users.length ? <ul>{users.map(name => <li key={name}>{name}</li>)}</ul>
|
||||
: <p>{entries(sessions) && !note(sessions) ? 'Keine Benutzer angemeldet.' : unreported}</p>}
|
||||
</section>
|
||||
<section><Software report={observation(device, 'software')} /></section>
|
||||
</>;
|
||||
}
|
||||
+36
-9
@@ -16,6 +16,9 @@ import { AdminControl } from './management';
|
||||
import { allowed } from './safety';
|
||||
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';
|
||||
@@ -43,6 +46,15 @@ function capacity(free: unknown, total: unknown) {
|
||||
t = gib(total);
|
||||
return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`;
|
||||
}
|
||||
function cpuUsage(value: unknown) {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100
|
||||
? `${number.format(value)} %`
|
||||
: unknown;
|
||||
}
|
||||
function measuredAt(value: unknown) {
|
||||
const observed = time(value);
|
||||
return observed === unknown ? undefined : `Gemessen am ${observed}`;
|
||||
}
|
||||
function cpu(d: RecordValue) {
|
||||
const model = label(d.cpu_model),
|
||||
count = d.cpu_logical_count;
|
||||
@@ -76,14 +88,13 @@ function Presence({ d }: { d: RecordValue }) {
|
||||
</span>
|
||||
);
|
||||
}
|
||||
function Storage({ d }: { d: RecordValue }) {
|
||||
const free = d.disk_free_bytes,
|
||||
total = d.disk_total_bytes;
|
||||
function Capacity({ free, total }: { free: unknown; total: unknown }) {
|
||||
return (
|
||||
<>
|
||||
<span>{capacity(free, total)}</span>
|
||||
{typeof free === 'number' &&
|
||||
typeof total === 'number' &&
|
||||
Number.isFinite(total) &&
|
||||
free >= 0 &&
|
||||
free <= total &&
|
||||
total > 0 && (
|
||||
@@ -137,6 +148,7 @@ function DeviceDetail({
|
||||
asset,
|
||||
agent,
|
||||
auth,
|
||||
customers,
|
||||
back,
|
||||
openOperation,
|
||||
changed
|
||||
@@ -145,6 +157,7 @@ function DeviceDetail({
|
||||
asset: string;
|
||||
agent: string;
|
||||
auth: Session;
|
||||
customers: Tenant[];
|
||||
back: () => void;
|
||||
openOperation: (id: string, jobId: string) => void;
|
||||
changed: (notice?: string) => void;
|
||||
@@ -171,8 +184,10 @@ function DeviceDetail({
|
||||
['Kunde', label(d.customer_name)],
|
||||
['Type', label(d.device_type)],
|
||||
['Betriebssystem', label(d.os)],
|
||||
['RAM', gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'],
|
||||
...systemDetails(d, time),
|
||||
['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)],
|
||||
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
|
||||
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
|
||||
['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)],
|
||||
['Letzter Kontakt', time(d.last_contact_at)],
|
||||
['Inventar erhoben', time(d.observed_at)],
|
||||
@@ -192,6 +207,7 @@ function DeviceDetail({
|
||||
<div>
|
||||
<h1>{label(d.hostname)}</h1>
|
||||
<Presence d={d} />
|
||||
<HypervisorLabel device={d} />
|
||||
</div>
|
||||
</div>
|
||||
<section>
|
||||
@@ -205,6 +221,7 @@ function DeviceDetail({
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
<DeviceInventoryPanels device={d} />
|
||||
{volumes.length > 0 && (
|
||||
<section>
|
||||
<h2>Laufwerke</h2>
|
||||
@@ -265,6 +282,11 @@ 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')} />
|
||||
{['archived', 'current'].includes(String(d.lifecycle)) && (
|
||||
<button
|
||||
disabled={busy}
|
||||
@@ -425,6 +447,7 @@ export function Devices({
|
||||
key={detailPath}
|
||||
{...target}
|
||||
auth={auth}
|
||||
customers={customers}
|
||||
back={back}
|
||||
openOperation={(id, jobId) => onOperation(target.customer, id, jobId)}
|
||||
changed={(notice) => {
|
||||
@@ -534,7 +557,7 @@ export function Devices({
|
||||
<span className="sr-only">Ziel auswählen</span>
|
||||
</th>
|
||||
)}
|
||||
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM', 'CPU', 'Kunde'].map(
|
||||
{['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map(
|
||||
(h) => (
|
||||
<th scope="col" key={h}>
|
||||
{h}
|
||||
@@ -582,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>
|
||||
@@ -591,15 +615,18 @@ export function Devices({
|
||||
<small>Zuletzt {time(d.last_contact_at)}</small>
|
||||
)}
|
||||
</td>
|
||||
<td data-label="Speicher frei / gesamt" className="storage">
|
||||
<Storage d={d} />
|
||||
<td data-label="Speicher frei / gesamt" className="capacity-cell">
|
||||
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} />
|
||||
</td>
|
||||
<td data-label="RAM">
|
||||
{gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'}
|
||||
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
|
||||
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
|
||||
</td>
|
||||
<td data-label="CPU">
|
||||
{model.primary}
|
||||
{model.secondary && <small>{model.secondary}</small>}
|
||||
<small title={measuredAt(d.cpu_usage_observed_at)}>
|
||||
Auslastung {cpuUsage(d.cpu_usage_percent)}
|
||||
</small>
|
||||
</td>
|
||||
<td data-label="Kunde">{label(d.customer_name)}</td>
|
||||
</tr>
|
||||
|
||||
+7
-2
@@ -200,7 +200,12 @@ function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string;
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [adminScripts, setAdminScripts] = useState(false);
|
||||
const origin = enrollment?.origin;
|
||||
const linuxInstaller = origin && enrollment.platforms.includes('x86_64-unknown-linux-gnu') ? `${origin}/install/linux.sh` : null;
|
||||
const linuxArchitectures = [
|
||||
['x86_64-unknown-linux-gnu', 'x86-64'],
|
||||
['aarch64-unknown-linux-gnu', 'ARM64'],
|
||||
] as const;
|
||||
const availableLinuxArchitectures = linuxArchitectures.filter(([target]) => enrollment?.platforms.includes(target)).map(([, label]) => label);
|
||||
const linuxInstaller = origin && availableLinuxArchitectures.length > 0 ? `${origin}/install/linux.sh` : null;
|
||||
const windowsPlatforms = ['x86_64-pc-windows-gnu', 'x86_64-pc-windows-msvc'].filter(platform => enrollment?.platforms.includes(platform));
|
||||
const windowsInstaller = origin && windowsPlatforms.length > 0 ? `${origin}/install/windows.ps1` : null;
|
||||
return <section aria-label="Gerät aufnehmen"><h2>Gerät aufnehmen</h2>
|
||||
@@ -241,7 +246,7 @@ function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string;
|
||||
{enrollment && !origin && <p role="status">Für die Geräteaufnahme ist keine HTTPS-Downloadadresse konfiguriert.</p>}
|
||||
{origin && !linuxInstaller && !windowsInstaller && <p role="status">Für diesen Kunden ist derzeit kein Linux- oder Windows-Installer verfügbar.</p>}
|
||||
{linuxInstaller && <>
|
||||
<h4>Linux (x86-64)</h4>
|
||||
<h4>Linux ({availableLinuxArchitectures.join(' und ')})</h4>
|
||||
<p>Installationsskript <a href={linuxInstaller} target="_blank" rel="noopener noreferrer">linux.sh</a></p>
|
||||
<pre>{`curl --fail --show-error --silent '${linuxInstaller}' -o linux.sh && sudo sh linux.sh '${origin}'${adminScripts ? ' --enable-admin-scripts' : ''}`}</pre>
|
||||
</>}
|
||||
|
||||
+3
-1
@@ -94,11 +94,13 @@ 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; }
|
||||
.host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; }
|
||||
.fleet-table .storage { font-variant-numeric:tabular-nums; }
|
||||
.fleet-table .capacity-cell { font-variant-numeric:tabular-nums; }
|
||||
.capacity-track { display:block; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:4px; margin-top:6px; overflow:hidden; }
|
||||
.capacity-track i { display:block; height:100%; background:#659d84; }
|
||||
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }
|
||||
|
||||
Reference in New Issue
Block a user