Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65d84a19c0 | ||
|
|
cad188aeb7 | ||
|
|
bcd3bd86ad | ||
|
|
08177d8843 | ||
|
|
2378a54bd4 | ||
|
|
9e957e6d8d | ||
|
|
5253a9f596 | ||
|
|
db6325131a | ||
|
|
1f60183b7e | ||
|
|
55d159cab1 |
Generated
+1
@@ -2189,6 +2189,7 @@ dependencies = [
|
||||
"hex",
|
||||
"openssl",
|
||||
"prost",
|
||||
"reqwest",
|
||||
"rmm-domain",
|
||||
"rmm-protocol",
|
||||
"rmm-updater-handoff",
|
||||
|
||||
@@ -10,9 +10,13 @@ Jede Installation ist an Kunde, Gerät und Agentenidentität gebunden. Die Stand
|
||||
|
||||
Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` bezeichnet einen physischen Rechner, `virtual` ein virtualisiertes System und `hypervisor` eine erkannte Hostrolle. Proxmox VE erscheint als `hypervisor` mit `Proxmox VE` in der Spalte OS. Eine erkannte Hostrolle hat Vorrang, auch bei verschachtelter Virtualisierung. Bei fehlender Angabe zeigt die WebUI „Nicht gemeldet“. Die Geräteabfragen in WebUI und MCP verwenden denselben gespeicherten Typ. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät.
|
||||
|
||||
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Wie beim Speicherplatz zeigt ein Balken den belegten Anteil. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
|
||||
|
||||
Kunden lassen sich in der WebUI anlegen und umbenennen. 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)
|
||||
Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Nach der ersten Inventarmeldung beim Zielkunden bestätigt die Person den Abschluss in der WebUI. Der Server sperrt die bisherige Geräteidentität. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung.
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
//! Additive JSON observation mapping inside the existing snapshot payload. This
|
||||
//! does not introduce a protobuf tag or a fabricated receive time.
|
||||
use anyhow::Result;
|
||||
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();
|
||||
@@ -15,17 +27,15 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
|
||||
// Bound each scope independently. Never drop unsupported/error metadata
|
||||
// or imply that absent/truncated rows were deleted from a device.
|
||||
let max_bytes = if name == "software" {
|
||||
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
while serde_json::to_vec(&observation)?.len() > max_bytes {
|
||||
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 {
|
||||
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;
|
||||
@@ -47,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::*;
|
||||
@@ -67,7 +91,7 @@ mod tests {
|
||||
assert!(!observation["source_id"].as_str().unwrap().is_empty());
|
||||
assert!(observation.get("received_at").is_none());
|
||||
let limit = if observation["scope"] == "linux.software" {
|
||||
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
@@ -97,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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,6 +640,7 @@ 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,
|
||||
@@ -1561,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());
|
||||
}
|
||||
@@ -2746,6 +2804,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
|
||||
@@ -2905,7 +2968,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(),
|
||||
@@ -2921,21 +3000,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, 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)?;
|
||||
@@ -2952,7 +3060,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 {
|
||||
@@ -2974,6 +3084,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
config,
|
||||
reported_version: installed_version()?,
|
||||
release_job_guard: None,
|
||||
transfer_gate: None,
|
||||
identity,
|
||||
ca,
|
||||
journal,
|
||||
@@ -3038,6 +3149,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;
|
||||
}
|
||||
@@ -3056,8 +3173,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();
|
||||
|
||||
@@ -811,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,
|
||||
@@ -825,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)?,
|
||||
@@ -972,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 };
|
||||
@@ -1011,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"
|
||||
);
|
||||
@@ -1403,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)]
|
||||
@@ -1423,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
|
||||
}
|
||||
@@ -1449,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?,
|
||||
};
|
||||
@@ -1570,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)]
|
||||
|
||||
+102
-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,9 @@ 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() {
|
||||
@@ -476,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();
|
||||
@@ -513,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)? {
|
||||
@@ -752,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;}}
|
||||
@@ -842,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())?
|
||||
@@ -872,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() {
|
||||
@@ -949,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()?;
|
||||
@@ -977,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,
|
||||
@@ -1008,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!(
|
||||
@@ -1053,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;
|
||||
@@ -1062,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!(
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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());
|
||||
@@ -167,8 +168,8 @@ 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")) | ("windows.base", Some("windows.software")) =>
|
||||
SOFTWARE_OBSERVATION_MAX_BYTES,
|
||||
("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)
|
||||
@@ -269,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;
|
||||
|
||||
@@ -265,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(
|
||||
@@ -602,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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -10,7 +10,7 @@ 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> {
|
||||
|
||||
@@ -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,477 @@
|
||||
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 = target_hostname(&mut tx, &t).await?;
|
||||
let state = if t.completed_at.is_some() {
|
||||
"completed"
|
||||
} else if hostname.is_some() {
|
||||
"ready"
|
||||
} else if t.target_agent_id.is_some() {
|
||||
"enrolled"
|
||||
} else {
|
||||
"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 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?;
|
||||
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
|
||||
let t = transfer(&mut tx, pair.agent_id)
|
||||
.await?
|
||||
.filter(|t| t.transfer_id == id)
|
||||
.ok_or(NOT_FOUND)?;
|
||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||
if t.completed_at.is_some() {
|
||||
return Ok(private_json(json!({"state":"completed"})));
|
||||
}
|
||||
if target_hostname(&mut tx, &t).await?.is_none() {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_TARGET_NOT_READY"));
|
||||
}
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
ensure_idle(&mut tx, pair.agent_id).await?;
|
||||
sqlx::query(
|
||||
"UPDATE agent_installations SET revoked_at=now(), connection_generation=connection_generation+1,
|
||||
previous_certificate_sha256=NULL,previous_certificate_until=NULL
|
||||
WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(asset).bind(pair.agent_id).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE device_customer_transfers SET completed_at=now() WHERE transfer_id=$1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
audit(&mut tx, &p, "device_customer_transfer_completed", json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":t.target_tenant_id,
|
||||
"target_asset_id":t.target_asset_id,"target_agent_id":t.target_agent_id
|
||||
})).await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"state":"completed"})))
|
||||
}
|
||||
|
||||
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)
|
||||
VALUES($1,$2,$3,$4,$5,$6)",
|
||||
).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())
|
||||
}
|
||||
@@ -3,7 +3,7 @@ WITH classified AS (
|
||||
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
|
||||
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
|
||||
a.system_usage,a.system_usage_observed_at,
|
||||
asset.archived_at,t.name AS customer_name,
|
||||
asset.archived_at,asset.hypervisor_asset_id,t.name AS customer_name,
|
||||
CASE
|
||||
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
||||
WHEN asset.archived_at IS NOT NULL THEN 'archived'
|
||||
|
||||
+227
-10
@@ -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,10 +122,7 @@ 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:{}",
|
||||
@@ -180,6 +178,7 @@ pub async fn list(
|
||||
}
|
||||
.rows(&mut tx)
|
||||
.await?;
|
||||
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
|
||||
tx.commit().await?;
|
||||
for row in rows {
|
||||
if items.len() == capacity {
|
||||
@@ -187,7 +186,7 @@ pub async fn list(
|
||||
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;
|
||||
@@ -236,7 +235,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 +294,135 @@ fn device_type(hardware: &Value) -> Option<DeviceType> {
|
||||
DeviceType::deserialize(&hardware["device_type"]).ok()
|
||||
}
|
||||
|
||||
fn inventory_device_type(data: &Value) -> Option<DeviceType> {
|
||||
device_type(observed(data, "linux.hardware"))
|
||||
.or_else(|| device_type(observed(data, "windows.hardware")))
|
||||
}
|
||||
|
||||
fn hostname_filter(query: Option<&str>) -> Result<&str, Error> {
|
||||
let hostname = query.unwrap_or("").trim();
|
||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
Ok(hostname)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Host {
|
||||
asset_id: Uuid,
|
||||
agent_id: Uuid,
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
async fn hypervisors(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
as_of: DateTime<Utc>,
|
||||
ids: Option<&[Uuid]>,
|
||||
hostname: &str,
|
||||
limit: i64,
|
||||
) -> Result<Vec<Host>, Error> {
|
||||
let rows: Vec<(Uuid, Uuid, String)> = sqlx::query_as(include_str!("hypervisors.sql"))
|
||||
.bind(tenant)
|
||||
.bind(as_of)
|
||||
.bind(ids)
|
||||
.bind(hostname)
|
||||
.bind(limit)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
Ok(rows.into_iter().map(|(asset_id, agent_id, hostname)| Host {
|
||||
asset_id, agent_id, hostname,
|
||||
}).collect())
|
||||
}
|
||||
|
||||
async fn assigned_hosts(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
as_of: DateTime<Utc>,
|
||||
rows: &[PgRow],
|
||||
) -> Result<HashMap<Uuid, Host>, Error> {
|
||||
let mut ids: Vec<Uuid> = rows.iter().filter_map(|row| row.get("hypervisor_asset_id")).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
Ok(hypervisors(tx, tenant, as_of, Some(&ids), "", ids.len() as i64)
|
||||
.await?.into_iter().map(|host| (host.asset_id, host)).collect())
|
||||
}
|
||||
|
||||
fn hypervisor_display(data: &Value, assigned: Option<&Host>) -> Value {
|
||||
if inventory_device_type(data) != Some(DeviceType::Virtual) {
|
||||
return Value::Null;
|
||||
}
|
||||
if let Some(host) = assigned {
|
||||
return json!({"kind":"device","asset_id":host.asset_id,
|
||||
"agent_id":host.agent_id,"hostname":host.hostname});
|
||||
}
|
||||
let linux = observed(data, "linux.hardware");
|
||||
let windows = observed(data, "windows.hardware");
|
||||
let manufacturer = linux["manufacturer"].as_str()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| linux["readable_dmi"]["sys_vendor"].as_str())
|
||||
.or_else(|| windows["manufacturer"].as_str());
|
||||
if manufacturer.is_some_and(|name| matches!(name.trim().to_ascii_lowercase().as_str(),
|
||||
"hetzner" | "hetzner cloud" | "hetzner online" | "hetzner online gmbh")) {
|
||||
return json!({"kind":"placeholder","provider":"hetzner","hostname":"Hetzner Cloud"});
|
||||
}
|
||||
Value::Null
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HypervisorFilter {
|
||||
q: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn hypervisor_options(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
Query(query): Query<HypervisorFilter>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = crate::jobs::principal(&s, &h, false).await?;
|
||||
crate::jobs::scope(&p, tenant, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
let mut hosts = hypervisors(&mut tx, tenant, Utc::now(), None,
|
||||
hostname_filter(query.q.as_deref())?, 51).await?;
|
||||
let truncated = hosts.len() > 50;
|
||||
hosts.truncate(50);
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"items":hosts,"truncated":truncated})))
|
||||
}
|
||||
|
||||
pub(crate) async fn validate_vm_host_assignment(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
host: Option<Uuid>,
|
||||
) -> Result<(), Error> {
|
||||
let now = Utc::now();
|
||||
let row = Selection {
|
||||
tenant, asset: Some(asset), agent: Some(agent), view: Some(View::Current),
|
||||
status: None, hostname: "", last: Uuid::nil(), as_of: now, limit: 1,
|
||||
}.rows(tx).await?.pop().ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||
if inventory_device_type(&data) != Some(DeviceType::Virtual) {
|
||||
return Err(Error(StatusCode::CONFLICT, "HYPERVISOR_REQUIRES_VM"));
|
||||
}
|
||||
if let Some(host) = host {
|
||||
if asset == host {
|
||||
return Err(Error(StatusCode::CONFLICT, "INVALID_HYPERVISOR"));
|
||||
}
|
||||
if hypervisors(tx, tenant, now, Some(&[host]), "", 1).await?.is_empty() {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "HYPERVISOR_UNAVAILABLE"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn os_label(data: &Value) -> Option<String> {
|
||||
let linux_hardware = observed(data, "linux.hardware");
|
||||
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
|
||||
@@ -348,7 +477,7 @@ fn os_label(data: &Value) -> Option<String> {
|
||||
Some("Linux".to_owned())
|
||||
}
|
||||
}
|
||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Host>) -> Value {
|
||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||
let cpu = observed(&data, "linux.cpu");
|
||||
let windows = observed(&data, "windows.hardware");
|
||||
@@ -365,8 +494,7 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
.as_u64()
|
||||
.or_else(|| linux_memory["total_bytes"].as_u64())
|
||||
.or_else(|| windows["memory_total_bytes"].as_u64());
|
||||
let device_type =
|
||||
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
|
||||
let device_type = inventory_device_type(&data);
|
||||
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
|
||||
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
||||
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
||||
@@ -397,6 +525,14 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
|
||||
"completeness":"partial","health":"unknown"
|
||||
});
|
||||
if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" {
|
||||
let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id");
|
||||
let assigned = assigned_id.and_then(|id| hosts.get(&id));
|
||||
item["hypervisor"] = hypervisor_display(&data, assigned);
|
||||
if full {
|
||||
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
|
||||
}
|
||||
}
|
||||
if full {
|
||||
item["inventory"] = data;
|
||||
item["capabilities"] = row.get("capabilities");
|
||||
@@ -457,6 +593,87 @@ mod tests {
|
||||
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hetzner_placeholder_requires_a_valid_guest_and_yields_to_a_registered_host() {
|
||||
let mut data = json!({"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||
"data":{"device_type":"virtual","readable_dmi":{"sys_vendor":" Hetzner "}}}]});
|
||||
assert_eq!(hypervisor_display(&data, None)["kind"], "placeholder");
|
||||
let host = Host { asset_id: Uuid::new_v4(), agent_id: Uuid::new_v4(), hostname: "pve01".into() };
|
||||
assert_eq!(hypervisor_display(&data, Some(&host))["asset_id"], json!(host.asset_id));
|
||||
data["observations"][0]["data"]["device_type"] = json!("physical");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
data["observations"][0]["data"]["device_type"] = json!("virtual");
|
||||
data["observations"][0]["quality"] = json!("error");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
data["observations"][0] = json!({"scope":"windows.hardware","quality":"valid",
|
||||
"data":{"device_type":"virtual","manufacturer":"HETZNER ONLINE GMBH"}});
|
||||
assert_eq!(hypervisor_display(&data, None)["hostname"], "Hetzner Cloud");
|
||||
data["observations"][0]["data"]["manufacturer"] = json!("Other company");
|
||||
assert!(hypervisor_display(&data, None).is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn host_links_resolve_outside_the_page_and_stay_inside_the_customer() {
|
||||
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await.unwrap();
|
||||
let app = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await.unwrap();
|
||||
let tenant = Uuid::new_v4();
|
||||
let other = Uuid::new_v4();
|
||||
let mut ids = [Uuid::new_v4(), Uuid::new_v4()];
|
||||
ids.sort_unstable();
|
||||
let [vm, host] = ids;
|
||||
let foreign_host = Uuid::new_v4();
|
||||
for customer in [tenant, other] {
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Hypervisor test')")
|
||||
.bind(customer).execute(&admin).await.unwrap();
|
||||
}
|
||||
for (customer, id, name, kind) in [
|
||||
(tenant, vm, "guest", "virtual"),
|
||||
(tenant, host, "hypervisor-1", "hypervisor"),
|
||||
(other, foreign_host, "hypervisor-2", "hypervisor"),
|
||||
] {
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(customer).bind(id).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,last_authenticated_at,last_authenticated_certificate_sha256) VALUES($1,$2,$2,$3,now(),now(),$3)")
|
||||
.bind(customer).bind(id).bind(rmm_domain::jobs::hash(format!("{customer}:{id}").as_bytes()))
|
||||
.execute(&admin).await.unwrap();
|
||||
let data = json!({"hostname":name,"os":"Ubuntu","root_available_bytes":10,"root_total_bytes":20,
|
||||
"observations":[{"scope":"linux.hardware","quality":"valid",
|
||||
"data":{"device_type":kind,"manufacturer":"Hetzner"}}]});
|
||||
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,1,now(),'linux.base','valid','partial',$5,$6,$7)")
|
||||
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4())
|
||||
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(foreign_host)).await.is_err());
|
||||
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(vm)).await.is_err());
|
||||
validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(host)).await.unwrap();
|
||||
|
||||
sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||
.bind(vm).bind(host).execute(&mut *tx).await.unwrap();
|
||||
let q = Selection { tenant, asset: None, agent: None, view: Some(View::Current), status: None,
|
||||
hostname: "", last: Uuid::nil(), as_of: Utc::now(), limit: 1 };
|
||||
let page = q.rows(&mut tx).await.unwrap();
|
||||
assert_eq!(page[0].get::<Uuid,_>("asset_id"), vm);
|
||||
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["hostname"], "hypervisor-1");
|
||||
let options = hypervisors(&mut tx, tenant, q.as_of, None, "HYPERVISOR", 51).await.unwrap();
|
||||
assert_eq!(options.len(), 1);
|
||||
assert_eq!(options[0].asset_id, host);
|
||||
|
||||
sqlx::query("UPDATE assets SET archived_at=now() WHERE asset_id=$1")
|
||||
.bind(host).execute(&mut *tx).await.unwrap();
|
||||
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
|
||||
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["kind"], "placeholder");
|
||||
|
||||
let result = sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
|
||||
.bind(vm).bind(foreign_host).execute(&mut *tx).await.unwrap_err();
|
||||
assert_eq!(result.as_database_error().unwrap().code().as_deref(), Some("23503"));
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||
@@ -499,7 +716,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,29 @@
|
||||
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 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 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 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
|
||||
|
||||
@@ -27,9 +27,11 @@ 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) |
|
||||
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbare Garantieinformationen, Netzwerk, Software und angemeldete Benutzer. [Geräteansicht](../web/src/device-inventory.tsx) |
|
||||
| Kundenwechsel bestehender Geräte | Vormerken und abschließen unter „Gerät verwalten → Kunden wechseln“. Ein nativer Linux-Agent übernahm im isolierten TLS-/PostgreSQL-Test eine neue signierte Kopplung mit neuer Geräte- und Agent-ID. Ein Agentneustart mit der ursprünglichen Installationskonfiguration behielt die neue Kopplung bei. Die alte Kopplung blieb bis zur Bestätigung erhalten. Nach Abschluss sperrte das Gateway ihr Zertifikat, und die Historie war beim bisherigen Kunden weiterhin lesbar. Der Browser prüfte Zugangsbeschränkung, Status, Bestätigung und den Link zum Zielgerät in Mobilbreite. Beschränkte und globale Tokens wurden für Bestandslisten, direkte IDs und Widerruf geprüft. Ein nativer Windows-Test bestätigte die signierte Übernahme nach unterbrochener lokaler Zustandsumstellung und die Trennung der alten lokalen Daten. Die vollständige Windows-Feldabnahme eines Kundenwechsels steht aus. Revision `5253a9f` wurde am 18. November um 20:39 UTC mit Schema 42 bereitgestellt. Interne API, öffentliche API und Gateway bestanden ihre Healthchecks. Der öffentliche WebUI-Index entsprach dem Build. Die signierten Linux-Versionen `0.1.0-mvp.13` und `0.1.0-arm64.7` stammen aus derselben Revision. Windows `0.1.22` stammt aus `9e957e6` und enthält die zuvor veröffentlichte Korrektur der Helper-Zeitabfragen. Die drei Versionen sind Installer-Starter. Linux x64 und Windows sind zusätzlich im zweiten Entwicklungskatalog veröffentlicht. Um 20:46 UTC meldeten Linux x64, Linux ARM64 und Windows die neuen Versionen und die Fähigkeit zum Kundenwechsel bei denselben Geräte-IDs. Auf allen drei Geräten war die Zielkundenauswahl in der öffentlichen WebUI am Desktop und bei 390 px Breite bedienbar. In der produktiven Prüfung wurden null Wechsel vorgemerkt. [Ablauf](public-access.md#kunden-eines-bestehenden-geräts-wechseln) · [TLS-/Datenbanktest](../tests/customer_transfer.py) |
|
||||
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbares Garantieende, Netzwerkkarten mit IP-Adressen, durchsuchbare Software und angemeldete Benutzer. Beide Linux-Geräte melden den Zeitstempel des Root-Dateisystems als geschätztes Installationsdatum. Quelle `1f60183` wurde am 18. November um 19:23 UTC mit Serverhash `8a821863…` und Schema 41 aktiviert. Interne API, öffentliche API und Gateway wurden mit bestandenem Healthcheck gestartet. Der öffentliche WebUI-Index stimmte mit dem Build überein. 80 WebUI-Tests, 73 Linux- und Domänentests, 15 Bootstrap-Tests und zwei native Windows-Inventartests bestanden. Die vorhandene Windows-Kopplung meldet mit `0.1.19` neun Netzwerkkarten und drei systemweit registrierte Programme. Um 19:29 UTC meldete dieselbe Linux-x64-Kopplung nach dem regulären signierten Update auf `0.1.0-mvp.12` zwei Netzwerkkarten und alle 1.372 erfassten DEB-Pakete. Das Agent- und Helperpaar meldete sich bereit. Die Linux-Inventur holt durch ausstehende Meldungen verschobene Erfassungen nach. Die ARM64-Kopplung meldet mit `0.1.0-arm64.6` drei Netzwerkkarten und 893 DEB-Pakete. Beide Linux-Geräte melden ihre BIOS-Seriennummer. Der Windows-Gast meldet keine Seriennummer. Alle drei Geräte meldeten keine angemeldeten Benutzer und keine Garantiedaten. Für eine automatische Garantieabfrage fehlt eine Herstellerquelle. Die öffentliche WebUI zeigte die Details und fand jeweils einen tatsächlichen Softwareeintrag über die Suche auf dem Desktop und bei 390 px Breite. Die drei signierten Releases sind als Installer-Starter veröffentlicht. Linux x64 und Windows sind auch im Katalog von Development B veröffentlicht. [Geräteansicht](../web/src/device-inventory.tsx) · [Linux-Inventar](../crates/agent-linux/src/inventory.rs) · [Windows-Inventar](../crates/agent-windows/src/inventory.rs) |
|
||||
| RAM und CPU-Auslastung in der Übersicht | RAM als verfügbar / gesamt in GiB mit demselben Belegungsbalken wie beim Speicherplatz. Die CPU-Spalte zeigt die letzte gemessene Auslastung in Prozent. Am 18. November wurde `6ed57c4` mit Schema 41 produktiv aktiviert. Beide TLS-Healthchecks und der öffentliche WebUI-Index stimmten mit dem Build überein. Die öffentliche Übersicht zeigte die RAM-Balken auf Desktop und bei 390 px Breite für alle drei Geräte. Die Detailansicht und die automatische Aktualisierung wurden in Chromium auf Linux x64 und ARM64 nachgelesen. OTRS meldete um 18:05 UTC nach dem signierten Wechsel auf `0.1.0-arm64.3` `6,2 / 7,6 GiB` und `1,1 %`. Um 18:06 UTC meldeten Linux x64 `0.1.0-mvp.9`, Windows `0.1.18` und ARM64 frische CPU-Werte und waren authentisiert erreichbar. [Geräteansicht](../web/src/devices.tsx) · [Geräteprojektion](../crates/server/src/devices.rs) |
|
||||
| Gerätetyp in der Übersicht | Spalte „Type“ nach „Hostname“ mit `physical`, `virtual` und `hypervisor`. Erkannte Proxmox-VE-Hosts zeigen `Proxmox VE` als OS. Am 18. November wurde `c599baa` auf dem öffentlichen Server aktiviert. Der Serverrunner bestätigte API, Gateway und öffentlichen API-Dienst mit Binärhash `4f9c8c60…`. Der öffentliche WebUI-Index stimmte mit dem gebauten Bundle überein. Die unveränderten Geräteidentitäten meldeten nach regulärem signierten Update `virtual` auf Linux mit `0.1.0-mvp.7` um 16:45 UTC und Windows mit `0.1.17` um 16:47 UTC. Geräteliste, Details, Mobilansicht mit 390 px und Historie sind in der öffentlichen WebUI geprüft. Beide Pakete sind in Development A und B und als Starter für leere Kataloge veröffentlicht. Die Typen `physical` und `hypervisor` sind mit Testdaten geprüft. Die Feldabnahme auf einem physischen Gerät und einem Proxmox-VE-Host steht aus. [Inventarprojektion](../crates/server/src/devices.rs) · [Geräteansicht](../web/src/devices.tsx) |
|
||||
| Hostzuordnung bei VMs | Die WebUI zeigt einen zugeordneten Hypervisor direkt an der VM. Der Browsertest prüfte Zuordnung, Verlinkung, Entfernen und den Hetzner-Platzhalter bei 390 px Breite. In PostgreSQL wurden die Page-Grenze, archivierte Hypervisoren und die Trennung der Kunden geprüft. 80 WebUI-Tests, vier Browsertests und fünf Rust-Gerätetests bestanden. Revision `bcd3bd8` wurde am 18. November um 21:43 UTC mit Schema 43 aktiviert. Der Serverrunner bestätigte die TLS-Healthchecks und der öffentliche Index entsprach dem Build. In der öffentlichen WebUI zeigten zwei vorhandene Hetzner-VMs den Platzhalter auf Desktop und Mobil. Die Auswahl war im Gerätedetail verfügbar. Der Bestand enthielt zum Prüfzeitpunkt keinen registrierten Hypervisor. [Geräteansicht](../web/src/device-hypervisor.tsx) · [Hostsuche](../crates/server/src/hypervisors.sql) |
|
||||
| Von der Auswahl zur Ausgabe | Die WebUI bindet die ausgewählte Skriptversion, zeigt den Inhalt vor Genehmigung und verlinkt das Ergebnis je Gerät. Ein abgelehnter Antrag erzeugte null Jobs. [Auftragsablauf](evidence/webui-auftragsablauf-20261117.json) · [Ergebnislinks und Entscheidungen](evidence/webui-order-history-20261118.json) Auf OTRS ARM64 wurde der Root-Skript-Helper nachträglich mit dem HTTPS-Installer aktiviert. Die zentrale Geräteregel bindet das berechtigte WebUI-Konto an diese Installation und den signierten Helper. Die öffentliche WebUI-Vorschau akzeptierte Root für OTRS. Die Probe blieb bei einer Vorschau und erzeugte null Anträge, Jobs, Outbox-Einträge und Startgrants. [OTRS-Nachweis](evidence/linux-arm64-otrs-root-helper-20261118.json) |
|
||||
| Frische Installation und periodisches Agentupdate | Beide VMs wurden über HTTPS aufgenommen und übernahmen anschließend ein signiertes Folgepaket mit derselben Geräteidentität. Auf Windows ist der öffentliche GNU-Kanal einschließlich Prüfung des offiziellen Schlüssels belegt. [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows GNU](evidence/windows-gnu-official-vm-20261118.json). ARM64 erweitert denselben HTTPS-Installer mit automatischer Architekturerkennung. Release `0.1.0-arm64.1` ist veröffentlicht und als Starter verfügbar. Auf Ubuntu 22.04.5 ARM64 wurden die öffentlichen Downloads, die Signaturprüfung, die Ablehnung einer veränderten Agentdatei und der native Start aller drei Dateien im Prüfmodus beobachtet. OTRS ist mit Gerätezertifikat aufgenommen und meldet authentisierte Heartbeats. Die erste Kontaktprüfung wartet seit der Korrektur auf das Zertifikat. Der öffentliche Installer lief auf OTRS erneut ohne Traceback und ohne neuen Einmalcode. Der ARM64-Katalogabruf ist bestätigt. Ein späterer Versionswechsel auf ARM64 steht aus. [ARM64-Release](evidence/linux-arm64-installer-20261118.json) · [Geräteaufnahme und Nachtest](evidence/linux-arm64-enrollment-heartbeat-20261118.json) |
|
||||
| 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) |
|
||||
|
||||
+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 vormerken**. Hierfür braucht die angemeldete Person Geräteverwaltungsrechte beim bisherigen Kunden sowie Inventar- und Aufnahmerechte beim Zielkunden. Offene Aufträge und Genehmigungen vor dem Wechsel abschließen.
|
||||
3. Sobald der Agent über seine bestehende Verbindung die neue Kopplung übernommen und Inventar gemeldet hat, zeigt die WebUI den Hostnamen beim Zielkunden. Den Wechsel bestätigen und **Kundenwechsel abschließen** wählen. Bei einem Offline-Gerät bleibt der Wechsel bis zum nächsten verfügbaren Kontakt vorgemerkt. Die Vormerkung kann vor der Zertifikatsausstellung abgebrochen werden.
|
||||
|
||||
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,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;
|
||||
@@ -218,3 +218,155 @@ 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;
|
||||
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);
|
||||
if (url.pathname === move) {
|
||||
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
|
||||
state = 'pending';
|
||||
} else {
|
||||
expect(url.pathname).toBe(move + '/move-fixture/complete');
|
||||
expect(state).toBe('ready');
|
||||
state = 'completed';
|
||||
}
|
||||
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 vormerken' });
|
||||
await expect(prepare).toBeDisabled();
|
||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
|
||||
canEnroll = true;
|
||||
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
|
||||
await prepare.click();
|
||||
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
|
||||
const finish = page.getByRole('button', { name: 'Kundenwechsel abschließen' });
|
||||
await expect(finish).toHaveCount(0);
|
||||
state = 'ready';
|
||||
await expect(finish).toBeDisabled({ timeout: 10000 });
|
||||
await page.getByRole('checkbox', { name: 'Ich bestätige den Kundenwechsel für dieses Gerät.' }).check();
|
||||
await finish.click();
|
||||
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible();
|
||||
await expect(page.getByRole('link', { name: 'Neue Kopplung öffnen' })).toHaveAttribute('href',
|
||||
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
|
||||
});
|
||||
|
||||
test('shows real VM hosts and the Hetzner placeholder without adding a device', async ({ page }) => {
|
||||
const tenant = '11111111-1111-4111-8111-111111111111';
|
||||
const path = '/api/v1/tenants/' + tenant;
|
||||
const customer = { tenant_id: tenant, name: 'Testkunde' };
|
||||
const base = { ...customer, customer_name: customer.name,
|
||||
lifecycle: 'current', status: 'online', recent_jobs: [], volumes: [] };
|
||||
const vm = { ...base, hostname: 'Test-VM', asset_id: 'vm-asset', agent_id: 'vm-agent', device_type: 'virtual' };
|
||||
const pve = { ...base, hostname: 'pve-01', asset_id: 'pve-asset', agent_id: 'pve-agent',
|
||||
device_type: 'hypervisor', os: 'Proxmox VE' };
|
||||
const placeholder = { kind: 'placeholder', provider: 'hetzner', hostname: 'Hetzner Cloud' };
|
||||
let assigned = false;
|
||||
const guest = () => ({ ...vm, assigned_hypervisor_asset_id: assigned ? pve.asset_id : null,
|
||||
hypervisor: assigned ? { kind: 'device', hostname: pve.hostname, asset_id: pve.asset_id, agent_id: pve.agent_id } : placeholder });
|
||||
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
|
||||
completeness: 'complete', as_of: new Date().toISOString() });
|
||||
|
||||
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
||||
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
|
||||
} }));
|
||||
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
|
||||
principal: 'inventory-owner', tenant_id: tenant, csrf_token: 'host-assignment-fixture',
|
||||
testsimulation: false, permissions: ['inventory:read', 'devices:revoke']
|
||||
} }));
|
||||
await page.route(origin + '/api/v1/**', r => {
|
||||
const req = r.request(), url = new URL(req.url());
|
||||
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) });
|
||||
if (url.pathname === '/api/v1/devices' || url.pathname === path + '/devices') {
|
||||
return r.fulfill({ json: listing([guest(), pve]) });
|
||||
}
|
||||
if (url.pathname === path + '/devices/' + vm.asset_id) return r.fulfill({ json: guest() });
|
||||
if (url.pathname === path + '/devices/' + pve.asset_id) return r.fulfill({ json: pve });
|
||||
if (url.pathname === path + '/hypervisors') {
|
||||
expect(req.headers()['x-rmm-tenant']).toBe(tenant);
|
||||
return r.fulfill({ json: { items: [pve], truncated: false } });
|
||||
}
|
||||
if (url.pathname === path + '/devices/' + vm.asset_id + '/hypervisor') {
|
||||
expect(req.method()).toBe('POST');
|
||||
expect(req.headers()['x-csrf-token']).toBe('host-assignment-fixture');
|
||||
expect(url.searchParams.get('agent_id')).toBe(vm.agent_id);
|
||||
const target = req.postDataJSON().hypervisor_asset_id;
|
||||
expect(target).toBe(assigned ? null : pve.asset_id);
|
||||
assigned = target === pve.asset_id;
|
||||
return r.fulfill({ json: { asset_id: vm.asset_id, hypervisor_asset_id: target } });
|
||||
}
|
||||
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
|
||||
});
|
||||
|
||||
await page.goto(origin + '/#geraete');
|
||||
const vmRow = page.getByRole('row').filter({ has: page.getByRole('button', { name: vm.hostname }) });
|
||||
await expect(vmRow).toContainText('Hetzner Cloud');
|
||||
await expect(vmRow).toContainText('Platzhalter');
|
||||
await expect(page.getByRole('button', { name: 'Hetzner Cloud' })).toHaveCount(0);
|
||||
await expect(page.locator('.fleet-table tbody tr')).toHaveCount(2);
|
||||
await page.getByRole('button', { name: vm.hostname }).click();
|
||||
await page.getByText('Gerät verwalten', { exact: true }).click();
|
||||
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||
const hostInput = page.getByRole('combobox', { name: 'Hypervisor auswählen' });
|
||||
await hostInput.selectOption(pve.asset_id);
|
||||
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
|
||||
await expect(page.getByText('Hypervisor zugeordnet.', { exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const hostLink = vmRow.getByRole('link', { name: pve.hostname });
|
||||
await expect(hostLink).toBeVisible();
|
||||
await expect(vmRow).not.toContainText('Hetzner Cloud');
|
||||
await hostLink.click();
|
||||
await expect(page.getByRole('heading', { name: pve.hostname })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||
await page.getByRole('button', { name: vm.hostname }).click();
|
||||
await page.getByText('Gerät verwalten', { exact: true }).click();
|
||||
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
|
||||
await hostInput.selectOption('');
|
||||
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
|
||||
await expect(page.getByText('Hostzuordnung entfernt.', { exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
|
||||
await expect(vmRow).toContainText('Hetzner Cloud');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
#!/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 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 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")):
|
||||
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"))
|
||||
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_ready():
|
||||
status, dto, _ = request(transfer + query, headers=owner)
|
||||
assert status == 200, (status, dto)
|
||||
move = dto["transfer"]
|
||||
return move if move["state"] == "ready" else None
|
||||
|
||||
moved = until(target_ready)
|
||||
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
|
||||
print("PASS the existing Linux process received a signed handoff and reported fresh target inventory")
|
||||
|
||||
route = suffix(moved["transfer_id"], "complete")
|
||||
assert request(route, {}, owner)[0] == 200
|
||||
assert request(route, {}, owner)[0] == 200
|
||||
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")
|
||||
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)
|
||||
@@ -0,0 +1,136 @@
|
||||
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' | 'ready' | 'completed';
|
||||
tenant: string;
|
||||
asset: string | null;
|
||||
agent: string | null;
|
||||
hostname: 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 !== 'ready' && state !== 'completed')) {
|
||||
throw new Error('Der Server lieferte keinen gültigen Kundenwechsel.');
|
||||
}
|
||||
return {
|
||||
id, tenant, state,
|
||||
asset: typeof t.target_asset_id === 'string' ? t.target_asset_id : null,
|
||||
agent: typeof t.target_agent_id === 'string' ? t.target_agent_id : null,
|
||||
hostname: typeof t.target_hostname === 'string' ? t.target_hostname : null
|
||||
};
|
||||
}
|
||||
|
||||
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_TARGET_NOT_READY: 'Warten Sie auf die erste Inventarmeldung beim Zielkunden.',
|
||||
TRANSFER_SOURCE_INACTIVE: 'Diese Kopplung ist im bisherigen Kunden nicht mehr aktiv.',
|
||||
FORBIDDEN: 'Für den Kundenwechsel fehlen Rechte beim bisherigen Kunden oder beim Zielkunden.',
|
||||
NOT_FOUND: 'Das Gerät oder der Zielkunde ist für diese Sitzung nicht verfügbar.'
|
||||
};
|
||||
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 [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const base = tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/customer-transfer');
|
||||
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 });
|
||||
setConfirmed(false);
|
||||
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">Die neue Kopplung wartet auf ihre erste Inventarmeldung.</p>}
|
||||
{current.state === 'ready' && <>
|
||||
<p role="status"><strong>{current.hostname}</strong> hat sich beim Zielkunden gemeldet.</p>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />
|
||||
Ich bestätige den Kundenwechsel für dieses Gerät.
|
||||
</label>
|
||||
<button className="primary" disabled={busy || !confirmed}
|
||||
onClick={() => void submit('/' + encodeURIComponent(current.id) + '/complete', {})}>Kundenwechsel abschließen</button>
|
||||
</>}
|
||||
{current.state === 'completed' && <p role="status">Kundenwechsel abgeschlossen. Die frühere Kopplung steht in der Historie.</p>}
|
||||
{current.asset && current.agent && ['ready', 'completed'].includes(current.state) &&
|
||||
<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 vormerken</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>;
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import { allowed } from './safety';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import { devicePlatform } from './script-catalog';
|
||||
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
|
||||
import { 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';
|
||||
@@ -146,6 +148,7 @@ function DeviceDetail({
|
||||
asset,
|
||||
agent,
|
||||
auth,
|
||||
customers,
|
||||
back,
|
||||
openOperation,
|
||||
changed
|
||||
@@ -154,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;
|
||||
@@ -203,6 +207,7 @@ function DeviceDetail({
|
||||
<div>
|
||||
<h1>{label(d.hostname)}</h1>
|
||||
<Presence d={d} />
|
||||
<HypervisorLabel device={d} />
|
||||
</div>
|
||||
</div>
|
||||
<section>
|
||||
@@ -277,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}
|
||||
@@ -437,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) => {
|
||||
@@ -594,6 +605,7 @@ export function Devices({
|
||||
>
|
||||
{label(d.hostname)}
|
||||
</button>
|
||||
<HypervisorLabel device={d} />
|
||||
</td>
|
||||
<td data-label="Type">{label(d.device_type)}</td>
|
||||
<td data-label="OS">{label(d.os)}</td>
|
||||
|
||||
@@ -94,6 +94,8 @@ section.fleet { padding:0; overflow:hidden; }
|
||||
.fleet-table th:last-child,.fleet-table td:last-child { padding-right:18px; }
|
||||
.fleet-table tbody tr { cursor:pointer; } .fleet-table tbody tr:hover,.fleet-table tr:focus-within { background:#f2f7f4; }
|
||||
.release-table tbody tr { cursor:auto; }
|
||||
.vm-hypervisor { display:flex; align-items:baseline; gap:6px; margin-top:5px; color:var(--subtle); font-size:.78rem; overflow-wrap:anywhere; }
|
||||
.vm-hypervisor .nav-icon { width:13px; height:13px; flex:none; align-self:flex-start; margin-top:2px; }
|
||||
.fleet-table .target-col { width:35px; }
|
||||
.fleet-table td[data-label="Type"] { overflow-wrap:anywhere; }
|
||||
.fleet-table input[type=checkbox] { margin:0; }
|
||||
|
||||
Reference in New Issue
Block a user