From 312da6f39ef3fc84924d9282ead36eb9a1b50271 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Tue, 17 Nov 2026 22:05:44 +0100 Subject: [PATCH] Enforce customer boundaries on token administration and finalize fleet navigation --- AGENTS.md | 2 + Rust_RMM_Implementierungsspezifikation.md | 10 +- crates/server/src/local_auth.rs | 128 ++++ crates/server/src/mcp_tokens.rs | 16 +- deploy/browser/close_unknown_job.cjs | 1 + deploy/browser/cloud_approve.cjs | 1 + deploy/browser/cloud_apt_acceptance.cjs | 6 +- deploy/browser/cloud_apt_diagnostic.cjs | 3 + deploy/browser/cloud_crash_acceptance.cjs | 3 + deploy/browser/cloud_delivery_acceptance.cjs | 1 + deploy/browser/cloud_lifecycle_revoke.cjs | 21 +- deploy/browser/cloud_logs_read.cjs | 4 +- deploy/browser/cloud_offline_acceptance.cjs | 4 +- deploy/browser/cloud_reboot_acceptance.cjs | 6 +- deploy/browser/windows_mvp_approve.cjs | 1 + .../windows_system_nonstart_approve.cjs | 3 +- docs/project-decisions.md | 6 +- docs/public-access.md | 12 +- .../0031_customer_token_administration.sql | 32 + tests/customer_access.sql | 46 +- web/src/devices.tsx | 657 +++++++++++++++--- web/src/main.tsx | 378 ++++++++-- web/src/navigation.tsx | 18 +- web/src/resource.tsx | 52 +- web/src/style.css | 4 +- 25 files changed, 1207 insertions(+), 208 deletions(-) create mode 100644 migrations/0031_customer_token_administration.sql diff --git a/AGENTS.md b/AGENTS.md index 0b3050d..4d1c547 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,8 @@ Ein Server mit WebUI und MCP verwaltet Linux- und Windows-Clients. Die Clients melden Heartbeats und Inventar, holen optionale Skriptaufträge ab und geben Ergebnisse zurück. Eine benannte, versionierte Skriptbibliothek bedient beide Oberflächen. Windows-Updates sind ein PowerShell-Katalogeintrag. Ein frischer Client lässt sich über ein HTTPS-Installationsskript aufnehmen und aktualisiert seinen eigenen Agenten periodisch aus dem signierten Releasebestand des Servers. Die Abnahmekriterien stehen im Plan. +Für Geräte und Kunden gilt Kapitel 0.7. Änderungen an Kundengrenzen mit beschränktem und globalem Token prüfen, einschließlich Listen, direkter Geräte-IDs und Widerruf. Die Trennung von Bestand und Historie beruht auf der bestätigten Geräteidentität. Bei einem Kundenwechsel neu enrollen und die bisherige Historie beim ursprünglichen Kunden belassen. + ## Betrieb und Freigabe - Der dedizierte Server ist `discovery.ease-technologies.de`. Testclients sind die Cloud-Linux-VM und der Windows-11-Gast. Das Notebook dient ausschließlich der Entwicklung. Plattformspezifische Arbeit auf beiden Gästen darf parallel laufen. Plattformfunktionen jeweils nativ nachweisen. diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 53eac6b..7df3599 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.35 · 2026-11-17 · Sprache: Deutsch +Version 1.36 · 2026-11-17 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -114,6 +114,14 @@ Minuten nach Empfang nutzbar (bisher 100 ms). Details Kapitel 0.3. ## 0 Auftrag und verbindliche Produktanforderungen +### 0.7 Kunden, Gerätebestand und MCP-Zugriff (Version 1.36) + +Ein Kunde entspricht einem Tenant. Die Kundenwahl bei der Geräteaufnahme bindet die Identität an diesen Tenant. Bei einem Wechsel wird das Gerät für den Zielkunden neu aufgenommen. Die vorherige Identität und ihre Auftragsdaten gehören weiterhin zum bisherigen Kunden. + +Der Bestand umfasst Geräte mit bestätigtem authentisiertem Kontakt, einschließlich inzwischen offline befindlicher Geräte. Widerrufene, ersetzte, explizit archivierte und unbestätigte Installationen sind über die Historie erreichbar. Gleiche Hostnamen sind kein Identitätsnachweis. Gespeicherte Inventardaten liefern OS, Speicherplatz, RAM und CPU mit Erhebungszeit. Fehlende Werte werden als solche angezeigt. + +Die interaktive Kundenverwaltung pflegt Kundennamen. Bei MCP-Tokens wählt ein berechtigter Verwalter sowohl die Aktionen als auch den Kundenkreis. Eine feste Auswahl enthält einen oder mehrere ausdrücklich gewählte Kunden. Der ausdrücklich globale Zugriff umfasst auch später angelegte Kunden und benötigt Kundenadministratorrechte. Beide Grenzen gelten bei Auflistungen und Direktzugriffen. Die Jobgenehmigung erfolgt weiterhin interaktiv in der WebUI. + ### 0.6 Öffentliche Verwaltung mit lokaler Authentisierung (Version 1.35) Userentscheidung vom 17. November 2026. WebUI und MCP sind über öffentliches HTTPS erreichbar. OAuth ist für diesen Aufbau ausgeschlossen. Die WebUI verwendet lokale Benutzer mit Passwort und TOTP. MCP verwendet individuell widerrufbare zufällige Bearer-Tokens mit Mandantenbindung, festen Scopes und Ablauf. Tokens werden nur gehasht gespeichert und einmal ausgegeben. Die feste WebUI-Genehmigung von Jobs bleibt an die echte interaktive Person gebunden. Die öffentliche Anmeldung verwendet das Produktionsprofil ohne simulierte Testidentität. Der private Entwicklungszugang bleibt für native Abnahmen verfügbar. diff --git a/crates/server/src/local_auth.rs b/crates/server/src/local_auth.rs index 0d71d6c..6d684b4 100644 --- a/crates/server/src/local_auth.rs +++ b/crates/server/src/local_auth.rs @@ -403,6 +403,134 @@ mod tests { assert!(LocalAuth::parse(&serde_json::to_vec(&duplicate).unwrap()).is_err()); } + #[tokio::test] + #[ignore = "requires isolated PostgreSQL with current migrations"] + async fn restricted_token_rejects_foreign_detail_and_plan_routes() { + use axum::{Router, middleware, routing::get}; + use serde_json::Value; + + let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap()) + .await + .unwrap(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(std::time::Duration::from_secs(3)) + .connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap()) + .await + .unwrap(); + let a = Uuid::parse_str(rmm_domain::TENANT_A).unwrap(); + let b = Uuid::parse_str(rmm_domain::TENANT_B).unwrap(); + let issuer = format!("local:{}", Uuid::new_v4()); + let id = Uuid::new_v4(); + let asset = Uuid::new_v4(); + let token = format!("rmm_mcp_{}", "A".repeat(43)); + let scopes = vec!["inventory:read", "operations:plan", "operations:read"]; + sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)") + .bind(a).bind(&issuer).bind([scopes.as_slice(), &["tokens:manage"]].concat()) + .execute(&admin).await.unwrap(); + let mut tx = rmm_persistence::tenant_tx(&pool, a).await.unwrap(); + sqlx::query("SELECT issue_customer_token($1,$2,'Restricted HTTP fixture',$3,$4,now()+interval '1 hour',false,$5)") + .bind(&issuer).bind(id).bind(hash(token.as_bytes())).bind(&scopes).bind(vec![a]).execute(&mut *tx).await.unwrap(); + tx.commit().await.unwrap(); + sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)") + .bind(b) + .bind(asset) + .execute(&admin) + .await + .unwrap(); + let fingerprint = hash(asset.as_bytes()); + sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,last_contact_at,last_authenticated_certificate_sha256,last_authenticated_at) VALUES($1,$2,$3,$4,now(),$4,now())") + .bind(b).bind(Uuid::new_v4()).bind(asset).bind(fingerprint).execute(&admin).await.unwrap(); + let mut config = sample(&issuer, a, &hex::encode([1; 64])); + let mut auth = crate::auth::Auth::from_env("development").await.unwrap(); + auth.local = Some(configured(&config)); + let key_dir = std::env::temp_dir().join(id.to_string()); + let state = crate::State { + pool: pool.clone(), + signer: None, + viewer_a: [0; 32], + viewer_b: [1; 32], + auth: Arc::new(auth), + job_signer: Arc::new( + crate::job_signer::JobSigner::load_or_create(&key_dir.join("http-test.key")) + .unwrap(), + ), + }; + let router = crate::jobs::routes( + Router::new() + .route("/api/v1/tenants", get(crate::api::tenants)) + .route( + "/api/v1/tenants/{tenant}/devices/{asset}", + get(crate::devices::detail), + ), + ) + .layer(middleware::from_fn(crate::auth::context)) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let base = format!("http://{}/api/v1/tenants", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(); + let response = client.get(&base).bearer_auth(&token).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let directory = response.json::().await.unwrap(); + assert_eq!(directory["items"].as_array().unwrap().len(), 1); + assert_eq!(directory["items"][0]["tenant_id"], a.to_string()); + let now = Utc::now(); + let forbidden_plan = json!({"tenant_id":b,"action":"refresh_inventory","targets":{"asset_ids":[asset]}, + "parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"scope":"base"}, + "schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"}, + "rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"}); + for request in [ + client.get(format!("{base}/{b}/devices/{asset}")), + client + .post(format!("{base}/{b}/operation-plans")) + .json(&forbidden_plan), + ] { + let denied = request + .bearer_auth(&token) + .header("x-rmm-tenant", a.to_string()) + .send() + .await + .unwrap(); + assert_eq!(denied.status(), StatusCode::NOT_FOUND); + } + let member = format!("mcp:{id}"); + let created: i64 = sqlx::query_scalar( + "SELECT count(*) FROM operation_plans WHERE tenant_id=$1 AND principal=$2", + ) + .bind(b) + .bind(&member) + .fetch_one(&admin) + .await + .unwrap(); + assert_eq!(created, 0); + server.abort(); + config["users"][0]["disabled"] = json!(true); + let mut disabled = crate::auth::Auth::from_env("development").await.unwrap(); + disabled.local = Some(configured(&config)); + let suspended = crate::State { + auth: Arc::new(disabled), + ..state + }; + assert!(matches!( + crate::mcp_tokens::authenticate(&suspended, &token, None).await, + Err(StatusCode::UNAUTHORIZED) + )); + let mut tx = rmm_persistence::tenant_tx(&pool, a).await.unwrap(); + assert!( + !crate::jobs::requester_enabled(&suspended, &mut tx, &member, a) + .await + .unwrap() + ); + tx.commit().await.unwrap(); + std::fs::remove_dir_all(key_dir).unwrap(); + } + #[tokio::test] #[ignore = "requires isolated PostgreSQL with current migrations"] async fn local_password_totp_database() { diff --git a/crates/server/src/mcp_tokens.rs b/crates/server/src/mcp_tokens.rs index 46ff52f..0d3d16a 100644 --- a/crates/server/src/mcp_tokens.rs +++ b/crates/server/src/mcp_tokens.rs @@ -122,8 +122,10 @@ async fn list( ) -> Result { let (principal, allowed, mut tx) = administration(&state, &headers, tenant, false).await?; let rows = sqlx::query(&format!( - "SELECT {COLUMNS} FROM mcp_tokens ORDER BY created_at DESC,token_id" + "SELECT {COLUMNS} FROM mcp_tokens WHERE can_manage_mcp_token($1,token_id,$2) ORDER BY created_at DESC,token_id" )) + .bind(&principal.name) + .bind(&principal.tenants) .fetch_all(&mut *tx) .await?; let can_select_all = crate::customers::can_manage(&principal, &mut tx).await?; @@ -267,10 +269,11 @@ async fn revoke( Path((tenant, id)): Path<(Uuid, Uuid)>, ) -> Result { let (principal, _, mut tx) = administration(&state, &headers, tenant, true).await?; - let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)") + let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)") .bind(&principal.name) .bind(id) .bind(Uuid::new_v4()) + .bind(&principal.tenants) .fetch_one(&mut *tx) .await?; if !found { @@ -401,7 +404,8 @@ pub async fn issuer_enabled( })) } -pub async fn enabled_in( +#[cfg(test)] +async fn enabled_in( tx: &mut Transaction<'_, Postgres>, principal: &str, ) -> Result { @@ -411,7 +415,8 @@ pub async fn enabled_in( .await } -pub async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool { +#[cfg(test)] +async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool { let Ok(mut tx) = rmm_persistence::tenant_tx(pool, tenant).await else { return false; }; @@ -605,10 +610,11 @@ mod tests { let (revoked_id, revoked) = mint(&app, tenant, &actor, &["inventory:read"]).await; let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap(); - let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)") + let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)") .bind(&actor) .bind(revoked_id) .bind(Uuid::new_v4()) + .bind(vec![tenant]) .fetch_one(&mut *tx) .await .unwrap(); diff --git a/deploy/browser/close_unknown_job.cjs b/deploy/browser/close_unknown_job.cjs index c70c4da..cd6524a 100644 --- a/deploy/browser/close_unknown_job.cjs +++ b/deploy/browser/close_unknown_job.cjs @@ -29,6 +29,7 @@ const assert = (value, code) => { if (!value) throw new Error(code || 'UI contra const session = await (await sessionResponse).json(); assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === 'simulated-testprincipal-a', 'SESSION'); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: operationId, exact: true }).click(); await page.getByRole('button', { name: `Job ${jobId} · unknown`, exact: true }).click(); const job = page.locator('article').filter({ has: page.getByRole('heading', { name: `Job ${jobId}`, exact: true }) }); diff --git a/deploy/browser/cloud_approve.cjs b/deploy/browser/cloud_approve.cjs index 1281c64..4bc7673 100644 --- a/deploy/browser/cloud_approve.cjs +++ b/deploy/browser/cloud_approve.cjs @@ -49,6 +49,7 @@ function checkWindowsHello(job, planBytes) { const session = await (await sessionResponse).json(); assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await op.locator('pre').first().innerText()); diff --git a/deploy/browser/cloud_apt_acceptance.cjs b/deploy/browser/cloud_apt_acceptance.cjs index 5c0dfc3..a433fc5 100644 --- a/deploy/browser/cloud_apt_acceptance.cjs +++ b/deploy/browser/cloud_apt_acceptance.cjs @@ -62,6 +62,8 @@ function checkAction(p, expected) { const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) }); if (expected.phase === 'prepare') { await page.getByRole('checkbox', { name: 'Ziel ' + expected.asset_id, exact: true }).check(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); + await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click(); await page.getByLabel('Aktion', { exact: true }).selectOption(expected.request.action); await page.getByLabel('Aktionsparameter', { exact: true }).fill(JSON.stringify(expected.request.parameters)); await page.getByLabel('Ausführungsidentität', { exact: true }).selectOption('root'); @@ -83,7 +85,9 @@ function checkAction(p, expected) { assert(path.dirname(path.resolve(expected.output_file)) === path.dirname(file)); fs.writeFileSync(expected.output_file, JSON.stringify({ plan, operation }), { flag: 'wx', mode: 0o600 }); } else { - assert(expected.phase === 'approve'); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); + assert(expected.phase === 'approve'); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); + await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await op.locator('pre').first().innerText()); assert(pending.approval_state === 'pending_approval' && pending.job_count === 0 && pending.execution_state === null); diff --git a/deploy/browser/cloud_apt_diagnostic.cjs b/deploy/browser/cloud_apt_diagnostic.cjs index b1e0f63..684ba70 100644 --- a/deploy/browser/cloud_apt_diagnostic.cjs +++ b/deploy/browser/cloud_apt_diagnostic.cjs @@ -39,6 +39,8 @@ function readPrivate(file) { if (expected.phase === 'prepare') { assert(expected.request.parameters.variants[0].script_utf8 === script && expected.request.parameters.expected_stdout === null); await page.getByRole('checkbox', { name: 'Ziel ' + expected.asset_id, exact: true }).check(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); + await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click(); await page.getByLabel('Aktion', { exact: true }).selectOption('run_script'); await page.getByRole('combobox', { name: 'Interpreter', exact: true }).selectOption('posix_sh'); await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill(script); @@ -65,6 +67,7 @@ function readPrivate(file) { fs.writeFileSync(expected.output_file, JSON.stringify({ plan, operation }), { flag: 'wx', mode: 0o600 }); } else { assert(expected.phase === 'approve'); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await op.locator('pre').first().innerText()); diff --git a/deploy/browser/cloud_crash_acceptance.cjs b/deploy/browser/cloud_crash_acceptance.cjs index c7e7be4..dd2e184 100644 --- a/deploy/browser/cloud_crash_acceptance.cjs +++ b/deploy/browser/cloud_crash_acceptance.cjs @@ -53,6 +53,8 @@ function checkJob(plan, expected, script) { assert(expected.request.parameters.variants.length === 1 && expected.request.parameters.variants[0].script_utf8 === script && expected.request.parameters.expected_stdout === 'RMM_CRASH_COUNT=1\n'); await page.getByRole('checkbox', { name: 'Ziel ' + expected.asset_id, exact: true }).check(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); + await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click(); await page.getByLabel('Aktion', { exact: true }).selectOption('run_script'); await page.getByRole('combobox', { name: 'Interpreter', exact: true }).selectOption('posix_sh'); await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill(script); @@ -77,6 +79,7 @@ function checkJob(plan, expected, script) { fs.writeFileSync(expected.output_file, JSON.stringify({ plan, operation: pending }), { flag: 'wx', mode: 0o600 }); } else { assert(expected.phase === 'approve'); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const operation = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await operation.locator('pre').first().innerText()); diff --git a/deploy/browser/cloud_delivery_acceptance.cjs b/deploy/browser/cloud_delivery_acceptance.cjs index 96a3d81..fe7815d 100644 --- a/deploy/browser/cloud_delivery_acceptance.cjs +++ b/deploy/browser/cloud_delivery_acceptance.cjs @@ -47,6 +47,7 @@ function counterScript(id, readOnly) { assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const operation = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await operation.locator('pre').first().innerText()); diff --git a/deploy/browser/cloud_lifecycle_revoke.cjs b/deploy/browser/cloud_lifecycle_revoke.cjs index 4a75d79..3da2e50 100644 --- a/deploy/browser/cloud_lifecycle_revoke.cjs +++ b/deploy/browser/cloud_lifecycle_revoke.cjs @@ -28,20 +28,27 @@ function readPrivate(file) { const session = await (await response).json(); assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal && session.permissions.includes('devices:revoke')); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); - assert(await page.getByLabel('Mandant', { exact: true }).inputValue() === expected.tenant_id); - await page.getByRole('button', { name: expected.asset_id, exact: true }).click(); - const article = page.locator('article').filter({ has: page.getByRole('heading', { name: 'Inventardetail ' + expected.asset_id, exact: true }) }); - await article.locator('pre').waitFor(); const device = JSON.parse(await article.locator('pre').innerText()); + await page.getByLabel('Kunde', { exact: true }).selectOption(expected.tenant_id); + assert(await page.getByLabel('Kunde', { exact: true }).inputValue() === expected.tenant_id); + const row = page.getByRole('row').filter({ has: page.getByLabel('Ziel ' + expected.asset_id, { exact: true }) }); + await row.getByRole('button').click(); + const article = page.locator('.device-detail'); + await article.getByText('Technische Daten', { exact: true }).click(); + const device = JSON.parse(await article.getByLabel('Vollständiges Geräteinventar', { exact: true }).innerText()); assert(device.agent_id === expected.agent_id && device.asset_id === expected.asset_id && device.presence === 'online'); assert(device.capabilities.length === 2 && device.capabilities.includes('linux.base/1') && device.capabilities.includes('heartbeat/1')); - const control = article.locator('details').filter({ has: page.locator('summary').filter({ hasText: /^Geräteidentität widerrufen$/ }) }); - await control.locator('summary').click(); + await article.getByText('Gerät verwalten', { exact: true }).click(); + const summary = article.locator('summary').filter({ hasText: /^Geräteidentität widerrufen$/ }); + await summary.click(); + const control = summary.locator('..'); await control.getByLabel('Grund für Geräteidentität widerrufen', { exact: true }).fill('Native passive Linux MVP lifecycle acceptance; revoke only this separate nonexecuting test identity'); const nonce = await control.locator('code').innerText(); await control.getByLabel('Bestätigungskennung eingeben', { exact: true }).fill(nonce); await control.getByRole('checkbox', { name: 'Ich bestätige diese konkrete administrative Wirkung ausdrücklich.' }).check(); + const revocation = page.waitForResponse(r => new URL(r.url()).pathname === '/api/v1/tenants/' + expected.tenant_id + '/devices/' + expected.asset_id + '/revocation' && r.request().method() === 'POST'); await control.getByRole('button', { name: 'Geräteidentität widerrufen · ausdrücklich ausführen', exact: true }).click(); - await control.locator('pre').filter({ hasText: '"revoked": true' }).waitFor(); + const result = await revocation; + assert(result.ok() && (await result.json()).revoked === true); assert(revocations === 1 && approvals === 0); await page.getByRole('button', { name: 'Abmelden', exact: true }).click(); } finally { await browser.close(); } diff --git a/deploy/browser/cloud_logs_read.cjs b/deploy/browser/cloud_logs_read.cjs index 531d510..e68a653 100644 --- a/deploy/browser/cloud_logs_read.cjs +++ b/deploy/browser/cloud_logs_read.cjs @@ -28,7 +28,9 @@ function privateJson(file) { const session = await (await sessionResponse).json(); assert(session.testsimulation === true && session.principal === 'simulated-testprincipal-a'); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); - assert.equal(await page.getByLabel('Mandant', { exact: true }).inputValue(), expected.tenant_id); + await page.getByLabel('Kunde', { exact: true }).selectOption(expected.tenant_id); + assert.equal(await page.getByLabel('Kunde', { exact: true }).inputValue(), expected.tenant_id); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const response = page.waitForResponse(r => new URL(r.url()).pathname === `/api/v1/tenants/${expected.tenant_id}/jobs/${expected.job_id}` && r.status() === 200); diff --git a/deploy/browser/cloud_offline_acceptance.cjs b/deploy/browser/cloud_offline_acceptance.cjs index 6054fa4..bf582fa 100644 --- a/deploy/browser/cloud_offline_acceptance.cjs +++ b/deploy/browser/cloud_offline_acceptance.cjs @@ -37,7 +37,9 @@ function counterScript(id) { const session = await (await response).json(); assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); - assert(await page.getByLabel('Mandant', { exact: true }).inputValue() === expected.tenant_id); + await page.getByLabel('Kunde', { exact: true }).selectOption(expected.tenant_id); + assert(await page.getByLabel('Kunde', { exact: true }).inputValue() === expected.tenant_id); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const operation = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const state = JSON.parse(await operation.locator('pre').first().innerText()); diff --git a/deploy/browser/cloud_reboot_acceptance.cjs b/deploy/browser/cloud_reboot_acceptance.cjs index 2ee33a5..4ccd519 100644 --- a/deploy/browser/cloud_reboot_acceptance.cjs +++ b/deploy/browser/cloud_reboot_acceptance.cjs @@ -43,7 +43,8 @@ function checkPlan(plan, expected) { assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); - assert(await page.getByLabel('Mandant', { exact: true }).inputValue() === expected.tenant_id); + await page.getByLabel('Kunde', { exact: true }).selectOption(expected.tenant_id); + assert(await page.getByLabel('Kunde', { exact: true }).inputValue() === expected.tenant_id); const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) }); if (expected.phase === 'prepare') { const request = expected.request; @@ -52,6 +53,8 @@ function checkPlan(plan, expected) { && equal(request.parameters, { reason, dependency_group: 'single-test-vm', reconnect_timeout_seconds: 180, execution_identity: 'root', timeout_seconds: 240, max_output_bytes: 65536 })); await page.getByRole('checkbox', { name: 'Ziel ' + expected.asset_id, exact: true }).check(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); + await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click(); await page.getByLabel('Aktion', { exact: true }).selectOption('reboot'); await page.getByLabel('Aktionsparameter', { exact: true }).fill(JSON.stringify(request.parameters)); await page.getByLabel('Ausführungsidentität', { exact: true }).selectOption('root'); @@ -71,6 +74,7 @@ function checkPlan(plan, expected) { assert(path.dirname(path.resolve(expected.output_file)) === path.dirname(file)); fs.writeFileSync(expected.output_file, JSON.stringify({ plan, operation: pending }), { flag: 'wx', mode: 0o600 }); } else { + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const operation = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await operation.locator('pre').first().innerText()); diff --git a/deploy/browser/windows_mvp_approve.cjs b/deploy/browser/windows_mvp_approve.cjs index ebbe6e0..b8beb8f 100644 --- a/deploy/browser/windows_mvp_approve.cjs +++ b/deploy/browser/windows_mvp_approve.cjs @@ -52,6 +52,7 @@ function checkWindowsScript(job, planBytes, expected) { const session = await (await sessionResponse).json(); assert(session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation' && session.principal === expected.expected_principal); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); + await page.getByRole('link', { name: 'Aufträge', exact: true }).click(); await page.getByRole('button', { name: expected.operation_id, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Antrag / Ausführung ' + expected.operation_id, exact: true }) }); const pending = JSON.parse(await op.locator('pre').first().innerText()); diff --git a/deploy/browser/windows_system_nonstart_approve.cjs b/deploy/browser/windows_system_nonstart_approve.cjs index b41963a..87321eb 100644 --- a/deploy/browser/windows_system_nonstart_approve.cjs +++ b/deploy/browser/windows_system_nonstart_approve.cjs @@ -43,7 +43,8 @@ const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const session = await (await sessionResponse).json(); assert(session.principal === 'simulated-testprincipal-a' && session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation'); await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor(); - await page.getByRole('row').filter({ hasText: 'a176520e-8a91-4e93-a78b-8e7620f430e0' }).getByRole('button').click(); + await page.getByRole('row').filter({ has: page.getByLabel('Ziel a176520e-8a91-4e93-a78b-8e7620f430e0', { exact: true }) }).getByRole('button').click(); + await page.getByText('Entwicklungsabnahmen', { exact: true }).click(); const section = page.getByRole('region', { name: 'Administrativer SYSTEM-Nichtstartabschluss 221', exact: true }); await section.waitFor(); if (mode === 'submit') { diff --git a/docs/project-decisions.md b/docs/project-decisions.md index f5416ff..00ceca9 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,10 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-17**, Spezifikation **1.35** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. +Stand: **2026-11-17**, Spezifikation **1.36** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. + +## Kunden und Gerätebestand (Version 1.36) + +Die WebUI startet mit den authentisierten Geräten der berechtigten Kunden. Die Historie bewahrt ausgemusterte und unbestätigte Installationen getrennt auf. Jedes Gerät gehört über seine Aufnahme zu genau einem Kunden. MCP-Berechtigungen bestehen aus Aktionsrechten und einer festen Kundenauswahl oder einem ausdrücklich globalen Kundenkreis einschließlich künftiger Kunden. Die frühere Beschränkung auf genau einen Kunden je Token entfällt. [Produktvertrag](../Rust_RMM_Implementierungsspezifikation.md) ## Öffentliche WebUI und MCP ohne OAuth (Version 1.35) diff --git a/docs/public-access.md b/docs/public-access.md index 963b3cb..854da6a 100644 --- a/docs/public-access.md +++ b/docs/public-access.md @@ -12,16 +12,24 @@ Die Kontokonfiguration liegt auf dem Server unter `/opt/rust-discovery/devstate/ ## MCP-Tokens -Nach der WebUI-Anmeldung im Bereich **MCP-Tokens** einen Namen, die benötigten Rechte und ein Ablaufdatum wählen. Standard sind gespeichertes Inventar, Protokolle und Aufträge/Ergebnisse lesen. Der Tokenwert wird einmal angezeigt. Er kann anschließend im MCP-Client als HTTP-Header hinterlegt werden. +Nach der WebUI-Anmeldung unter **Verwaltung → MCP-Tokens** einen Namen, den Kundenkreis, die benötigten Rechte und ein Ablaufdatum wählen. Ein einzelner Kunde ist vorausgewählt. Weitere Kunden lassen sich einzeln ergänzen. „Alle aktuellen und zukünftigen Kunden“ ist eine eigene Option für Kundenadministratoren. Standard sind gespeichertes Inventar, Protokolle und Aufträge/Ergebnisse lesen. Der Tokenwert wird einmal angezeigt. Er kann anschließend im MCP-Client als HTTP-Header hinterlegt werden. ```http Authorization: Bearer ``` -Ein Token besteht aus einem Präfix und 32 zufälligen Bytes. Der Server speichert ausschließlich dessen SHA-256-Prüfwert. Jedes Token besitzt einen eigenen Principal, Mandanten, feste Scopes, Ablauf und Widerruf. Jede Anfrage wird erneut geprüft. Die wirksamen Rechte sind die Schnittmenge aus Scopes und aktiver Membership. Der Widerruf greift auch bei einer bereits geöffneten MCP-Sitzung. Tokens können mit entsprechenden Rechten Anträge planen und einreichen. Die Jobgenehmigung erfolgt durch die Person in der WebUI. Tokenverwaltung verlangt eine echte interaktive Sitzung mit `tokens:manage` und CSRF-Schutz. +Ein Token besteht aus einem Präfix und 32 zufälligen Bytes. Der Server speichert ausschließlich dessen SHA-256-Prüfwert. Jedes Token besitzt einen eigenen Principal, einen Ausgabekunden, einen Kundenkreis, feste Scopes, Ablauf und Widerruf. Jede Anfrage wird erneut geprüft. Die wirksamen Rechte sind die Schnittmenge aus Scopes und aktiver Membership. Der Widerruf greift auch bei einer bereits geöffneten MCP-Sitzung. Tokens können mit entsprechenden Rechten Anträge planen und einreichen. Die Jobgenehmigung erfolgt durch die Person in der WebUI. Tokenverwaltung verlangt eine echte interaktive Sitzung mit `tokens:manage` und CSRF-Schutz. Der verwendete MCP-Client muss einen manuell konfigurierbaren Bearer-Header unterstützen. Die standardisierte automatische MCP-HTTP-Autorisierung beschreibt einen OAuth-Ablauf. Die hier eingerichtete statische Tokenanmeldung verwendet den vorhandenen HTTP-Transport mit selbst verwalteten Zugangsdaten. [MCP-Autorisierung](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) +## Geräte und Kunden bedienen + +**Geräte → Bestand** zeigt die bestätigten Online- und Offline-Geräte. Über **Historie** sind frühere Installationen erreichbar. Der Hostname öffnet das Inventar mit Laufwerken, Erhebungszeit und den letzten Aufträgen. In der Detailansicht erlaubt **Gerät verwalten** das Archivieren und Zurückholen. Archivieren steuert die Sichtbarkeit, ein Widerruf sperrt die Identität. + +**Kunden** erlaubt berechtigten Personen das Anlegen und Umbenennen. Bei **Gerät aufnehmen** zuerst den Kunden im Kopfbereich wählen und anschließend den Einmalcode ausstellen. Für einen Kundenwechsel die bisherige Identität widerrufen und das Gerät beim Zielkunden neu aufnehmen. Frühere Ergebnisse bleiben beim ursprünglichen Kunden. + +Der Entwicklungsoperator kann dem bereits eingerichteten lokalen Betreiberkonto über `python3 tools/dev_public_access.py grant-customer-admin` die Kundenadministration zuweisen. Ein signierter Release lässt sich mit `python3 tools/dev_customer_starters.py --tenant UUID --platform PLATTFORM --release RELEASE_UUID` als Installationspaket für leere Kundenkataloge bereitstellen. Das Werkzeug prüft die Objektprüfsummen. Bei der ersten Codeausgabe übernimmt der Server das Paket in den Katalog des Zielkunden. Bereits befüllte Kataloge pflegt der Betreiber je Kunde über den regulären Releaseweg. + ## Entwicklung und Deployment Der öffentliche API-Dienst `public-api` läuft unprivilegiert auf `127.0.0.1:18445`, im Produktionsprofil mit lokalem Passwort/TOTP und ohne Entwicklungszugänge. Der private Entwicklungsdienst bleibt auf `127.0.0.1:18443`. PostgreSQL hat keinen veröffentlichten Port. Der Reverseproxy verifiziert das TLS-Zertifikat des jeweiligen internen Dienstes. Öffentliche Anmeldung und MCP gehen an `public-api`, die vorhandenen Bootstrapdownloads an das Gerätegateway. diff --git a/migrations/0031_customer_token_administration.sql b/migrations/0031_customer_token_administration.sql new file mode 100644 index 0000000..1f29f7f --- /dev/null +++ b/migrations/0031_customer_token_administration.sql @@ -0,0 +1,32 @@ +-- Token administrators may see and revoke a credential only when its full +-- audience is within their current customer-management rights. +CREATE FUNCTION can_manage_mcp_token(actor text,id uuid,visible uuid[]) RETURNS boolean +LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ + SELECT EXISTS ( + SELECT FROM mcp_tokens t + JOIN customer_member_index issuer ON issuer.principal=actor AND issuer.customer=t.tenant_id + WHERE t.token_id=id AND t.tenant_id=nullif(current_setting('app.tenant_id',true),'')::uuid + AND issuer.kind='human' AND 'tokens:manage'=ANY(issuer.permissions) AND t.tenant_id=ANY(visible) + AND CASE WHEN t.all_customers THEN is_customer_admin(actor) + ELSE NOT EXISTS ( + SELECT FROM unnest(coalesce(t.customer_ids,ARRAY[t.tenant_id])) AS target(customer_id) + WHERE NOT target.customer_id=ANY(visible) OR NOT EXISTS ( + SELECT FROM customer_member_index m WHERE m.principal=actor AND m.customer=target.customer_id + AND m.kind='human' AND 'tokens:manage'=ANY(m.permissions) + ) + ) END + ); +$$; +REVOKE ALL ON FUNCTION can_manage_mcp_token(text,uuid,uuid[]) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION can_manage_mcp_token(text,uuid,uuid[]) TO rmm_app; + +ALTER FUNCTION revoke_mcp_token(text,uuid,uuid) RENAME TO revoke_mcp_token_data; +REVOKE ALL ON FUNCTION revoke_mcp_token_data(text,uuid,uuid) FROM rmm_app; +CREATE FUNCTION revoke_mcp_token(actor text,id uuid,event uuid,visible uuid[]) RETURNS boolean +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ +BEGIN + IF NOT can_manage_mcp_token(actor,id,visible) THEN RETURN false; END IF; + RETURN revoke_mcp_token_data(actor,id,event); +END $$; +REVOKE ALL ON FUNCTION revoke_mcp_token(text,uuid,uuid,uuid[]) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION revoke_mcp_token(text,uuid,uuid,uuid[]) TO rmm_app; diff --git a/tests/customer_access.sql b/tests/customer_access.sql index 02ada11..8991d2b 100644 --- a/tests/customer_access.sql +++ b/tests/customer_access.sql @@ -4,6 +4,9 @@ SELECT set_config('app.tenant_id','11111111-1111-4111-8111-111111111111',true); INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES ('11111111-1111-4111-8111-111111111111','local:11112222-3333-4444-aaaa-000000000001','human', ARRAY['tokens:manage','inventory:read','operations:read','operations:plan']); +INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES +('11111111-1111-4111-8111-111111111111','local:11112222-3333-4444-aaaa-000000000002','human', + ARRAY['tokens:manage','inventory:read']); SELECT provision_customer_admin('11111111-1111-4111-8111-111111111111','local:11112222-3333-4444-aaaa-000000000001'); SET ROLE rmm_app; DO $$ @@ -12,9 +15,11 @@ DECLARE b constant uuid:='22222222-2222-4222-8222-222222222222'; c uuid:=gen_random_uuid(); actor text:='local:11112222-3333-4444-aaaa-000000000001'; + limited_actor text:='local:11112222-3333-4444-aaaa-000000000002'; selected_id uuid:=gen_random_uuid(); both_id uuid:=gen_random_uuid(); all_id uuid:=gen_random_uuid(); + expired_plan uuid:=gen_random_uuid(); selected_member text:='mcp:'||selected_id::text; all_member text:='mcp:'||all_id::text; scopes text[]:=ARRAY['inventory:read']; @@ -36,6 +41,7 @@ BEGIN PERFORM issue_customer_token(actor,selected_id,'Only B',repeat('1',64),scopes,now()+interval '1 day',false,ARRAY[b]); PERFORM issue_customer_token(actor,both_id,'A+B',repeat('2',64),scopes,now()+interval '1 day',false,ARRAY[a,b]); PERFORM issue_customer_token(actor,all_id,'Global',repeat('3',64),scopes,now()+interval '1 day',true,ARRAY[]::uuid[]); + PERFORM issue_customer_token(actor,gen_random_uuid(),'Global for grant removal',repeat('4',64),scopes,now()+interval '1 day',true,ARRAY[]::uuid[]); IF mcp_credential_customers(repeat('1',64))<>ARRAY[b] OR mcp_principal_permission(selected_member,'inventory:read') OR NOT mcp_principal_permission(all_member,'inventory:read') THEN RAISE EXCEPTION 'unexpected issuing-customer visibility'; END IF; PERFORM manage_customer(actor,c,'New customer',true); @@ -49,12 +55,50 @@ BEGIN OR NOT EXISTS(SELECT 1 FROM tenant_limits) OR NOT EXISTS(SELECT 1 FROM script_revisions) THEN RAISE EXCEPTION 'invalid new customer contents/permissions'; END IF; + INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) + VALUES(c,expired_plan,actor,'{}','test-expired',now()-interval '1 minute'); + INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash) + VALUES(c,gen_random_uuid(),expired_plan,actor,'test-expired','test-request'); + PERFORM set_config('app.tenant_id',a::text,true); + PERFORM maintain_customers(); + IF current_setting('app.tenant_id')<>a::text THEN RAISE EXCEPTION 'scheduler changed tenant context'; END IF; + PERFORM set_config('app.tenant_id',c::text,true); + IF NOT EXISTS(SELECT 1 FROM approval_requests WHERE plan_id=expired_plan AND approval_state='expired') + THEN RAISE EXCEPTION 'scheduler skipped future customer'; END IF; PERFORM set_config('app.tenant_id',b::text,true); IF NOT mcp_principal_permission(selected_member,'inventory:read') THEN RAISE EXCEPTION 'selected customer denied'; END IF; PERFORM set_config('app.tenant_id',a::text,true); - PERFORM revoke_mcp_token(actor,all_id,gen_random_uuid()); + IF can_manage_mcp_token(limited_actor,all_id,ARRAY[a]) + OR can_manage_mcp_token(limited_actor,both_id,ARRAY[a]) + OR can_manage_mcp_token(limited_actor,selected_id,ARRAY[a,b]) + OR revoke_mcp_token(limited_actor,all_id,gen_random_uuid(),ARRAY[a]) + OR revoke_mcp_token(limited_actor,selected_id,gen_random_uuid(),ARRAY[a]) + OR has_function_privilege(current_user,'revoke_mcp_token_data(text,uuid,uuid)','EXECUTE') + THEN RAISE EXCEPTION 'home-only administrator has foreign credential metadata/revocation access'; END IF; + IF NOT revoke_mcp_token(actor,all_id,gen_random_uuid(),ARRAY[a,b,c]) THEN RAISE EXCEPTION 'global revoke denied'; END IF; PERFORM set_config('app.tenant_id',c::text,true); IF cardinality(mcp_credential_customers(repeat('3',64)))<>0 OR cardinality(mcp_current_scopes(all_member))<>0 THEN RAISE EXCEPTION 'revocation failed in foreign customer'; END IF; END $$; +RESET ROLE; +DELETE FROM customer_admins WHERE principal='local:11112222-3333-4444-aaaa-000000000001'; +SET ROLE rmm_app; +DO $$ +DECLARE a constant uuid:='11111111-1111-4111-8111-111111111111'; +BEGIN + IF cardinality(mcp_credential_customers(repeat('1',64)))<>0 + OR mcp_credential_customers(repeat('2',64))<>ARRAY[a] + OR cardinality(mcp_credential_customers(repeat('4',64)))<>0 THEN + RAISE EXCEPTION 'platform-admin removal failed to restrict existing tokens'; + END IF; +END $$; +RESET ROLE; +UPDATE memberships SET revoked_at=now() WHERE tenant_id='11111111-1111-4111-8111-111111111111' + AND principal='local:11112222-3333-4444-aaaa-000000000001'; +SET ROLE rmm_app; +DO $$ BEGIN + IF cardinality(mcp_credential_customers(repeat('2',64)))<>0 THEN + RAISE EXCEPTION 'suspended token issuer still authorizes a credential'; + END IF; +END $$; ROLLBACK; diff --git a/web/src/devices.tsx b/web/src/devices.tsx index 3e9c391..bf1aaf2 100644 --- a/web/src/devices.tsx +++ b/web/src/devices.tsx @@ -1,5 +1,16 @@ import { useEffect, useState } from 'react'; -import { objectId, page, pretty, record, request, session, tenantPath, type RecordValue, type Session, type Tenant } from './api'; +import { + objectId, + page, + pretty, + record, + request, + session, + tenantPath, + type RecordValue, + type Session, + type Tenant +} from './api'; import { AdminControl } from './management'; import { allowed } from './safety'; import { CatalogCheckNotice } from './catalog-check'; @@ -14,130 +25,578 @@ import { SystemNonstartReview } from './system-nonstart-review'; const unknown = 'Nicht gemeldet'; const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 }); const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' }); -function label(value: unknown) { return typeof value === 'string' && value.trim() ? value : unknown; } +function label(value: unknown) { + return typeof value === 'string' && value.trim() ? value : unknown; +} function time(value: unknown) { const t = typeof value === 'string' ? Date.parse(value) : NaN; return Number.isFinite(t) ? date.format(t) : unknown; } -function gib(v: unknown) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null; } +function gib(v: unknown) { + return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null; +} function capacity(free: unknown, total: unknown) { - const f = gib(free), t = gib(total); + const f = gib(free), + t = gib(total); return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`; } function cpu(d: RecordValue) { - const model = label(d.cpu_model), count = d.cpu_logical_count; - const threads = typeof count === 'number' && count > 0 ? `${count} log. CPU${count === 1 ? '' : 's'}` : ''; - return { primary: model === unknown ? threads || unknown : model, secondary: model === unknown ? '' : threads }; + const model = label(d.cpu_model), + count = d.cpu_logical_count; + const threads = + typeof count === 'number' && count > 0 ? `${count} log. CPU${count === 1 ? '' : 's'}` : ''; + return { + primary: model === unknown ? threads || unknown : model, + secondary: model === unknown ? '' : threads + }; } -const states: Record = { online: 'Online', offline: 'Offline', never_seen: 'Ohne Erstkontakt', revoked: 'Widerrufen', archived: 'Archiviert', replaced: 'Ersetzt', unverified: 'Identität unbestätigt' }; +const states: Record = { + online: 'Online', + offline: 'Offline', + never_seen: 'Ohne Erstkontakt', + revoked: 'Widerrufen', + archived: 'Archiviert', + replaced: 'Ersetzt', + unverified: 'Identität unbestätigt' +}; function Presence({ d }: { d: RecordValue }) { - const state = typeof d.lifecycle === 'string' && d.lifecycle !== 'current' ? d.lifecycle : String(d.status); - return {states[state] ?? 'Unbekannt'}; + const state = + typeof d.lifecycle === 'string' && d.lifecycle !== 'current' ? d.lifecycle : String(d.status); + return ( + + + {states[state] ?? 'Unbekannt'} + + ); } function Storage({ d }: { d: RecordValue }) { - const free = d.disk_free_bytes, total = d.disk_total_bytes; - return <>{capacity(free,total)}{typeof free === 'number' && typeof total === 'number' && free >= 0 && free <= total && total > 0 && - }; + const free = d.disk_free_bytes, + total = d.disk_total_bytes; + return ( + <> + {capacity(free, total)} + {typeof free === 'number' && + typeof total === 'number' && + free >= 0 && + free <= total && + total > 0 && ( + + )} + + ); } type Target = { customer: string; ids: string[] }; type Props = { - auth: Session; customers: Tenant[]; filter: string; onFilter: (id: string) => void; - selection: Target; onSelection: (s: Target) => void; - onScripts: () => void; onEnroll: () => void; onOperation: (customer: string, id: string) => void; + detailPath: string; + auth: Session; + customers: Tenant[]; + filter: string; + onFilter: (id: string) => void; + selection: Target; + onSelection: (s: Target) => void; + onScripts: () => void; + onEnroll: () => void; + onOperation: (customer: string, id: string) => void; }; -function devicePath(customer: string, asset: string) { return tenantPath(customer, '/devices/' + encodeURIComponent(asset)); } +function devicePath(customer: string, asset: string) { + return tenantPath(customer, '/devices/' + encodeURIComponent(asset)); +} -function DeviceDetail({ customer, asset, agent, auth, back, openOperation, changed }: { - customer: string; asset: string; agent: string; auth: Session; back: () => void; - openOperation: (id: string) => void; changed: () => void; +function DeviceDetail({ + customer, + asset, + agent, + auth, + back, + openOperation, + changed +}: { + customer: string; + asset: string; + agent: string; + auth: Session; + back: () => void; + openOperation: (id: string) => void; + changed: () => void; }) { const path = devicePath(customer, asset); - const detail = useResource(async signal => record(await request(path+'?agent_id='+encodeURIComponent(agent), { signal })), [customer,asset,agent], true); - const membership = useResource(async signal => session(await request('/auth/session', { signal, tenantId: customer })), [customer,auth.principal.id]); - const [busy, setBusy] = useState(false), [error, setError] = useState(null); + const detail = useResource( + async (signal) => record(await request(path + '?agent_id=' + encodeURIComponent(agent), { signal })), + [customer, asset, agent], + true + ); + const membership = useResource( + async (signal) => session(await request('/auth/session', { signal, tenantId: customer })), + [customer, auth.principal.id] + ); + const [busy, setBusy] = useState(false), + [error, setError] = useState(null); const d = detail.data; const scoped = membership.data; - const volumes = Array.isArray(d?.volumes) ? d.volumes.map(v=>record(v)) : []; - const jobs = Array.isArray(d?.recent_jobs) ? d.recent_jobs.map(v=>record(v)) : null; + const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : []; + const jobs = Array.isArray(d?.recent_jobs) ? d.recent_jobs.map((v) => record(v)) : null; const facts = d && [ - ['Kunde', label(d.customer_name)], ['Betriebssystem',label(d.os)], ['RAM', gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes)+' GiB'], - ['CPU',[cpu(d).primary,cpu(d).secondary].filter(Boolean).join(' · ')], ['Speicher frei / gesamt',capacity(d.disk_free_bytes,d.disk_total_bytes)], - ['Letzter Kontakt',time(d.last_contact_at)], ['Inventar erhoben',time(d.observed_at)], ['Agentversion',label(d.agent_version)] + ['Kunde', label(d.customer_name)], + ['Betriebssystem', label(d.os)], + ['RAM', gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'], + ['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')], + ['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)], + ['Letzter Kontakt', time(d.last_contact_at)], + ['Inventar erhoben', time(d.observed_at)], + ['Agentversion', label(d.agent_version)] ]; - return
- - - {!d && !detail.error &&

Inventar wird geladen …

} - {d && <>

{label(d.hostname)}

-

Geräteinformationen

{facts?.map(([k,v])=>
{k}
{v}
)}
- {volumes.length > 0 &&

Laufwerke

{volumes.map((v,i)=>)}
LaufwerkSpeicher frei / gesamt
{label(v.name)}{capacity(v.free_bytes,v.total_bytes)}
} - {jobs &&

Letzte Aufträge

{jobs.length === 0 ?

Keine Aufträge für dieses Gerät.

:
    {jobs.map(j=>
  • {label(j.state)}
  • )}
}
} -
Technische Daten
{pretty(d)}
- {scoped && allowed(scoped,'devices:revoke') &&
Gerät verwalten - {['archived','current'].includes(String(d.lifecycle)) && } - {d.lifecycle==='current' && } -
}
- {scoped && customer===recoveryTenant && asset===recoveryAsset && allowed(scoped,'inventory:read') &&
Entwicklungsabnahmen
} - } -
; + return ( +
+ + + {!d && !detail.error &&

Inventar wird geladen …

} + {d && ( + <> +
+
+

{label(d.hostname)}

+ +
+
+
+

Geräteinformationen

+
+ {facts?.map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+
+ {volumes.length > 0 && ( +
+

Laufwerke

+
+ + + + + + + + + {volumes.map((v, i) => ( + + + + + ))} + +
LaufwerkSpeicher frei / gesamt
{label(v.name)}{capacity(v.free_bytes, v.total_bytes)}
+
+
+ )} + {jobs && ( +
+

Letzte Aufträge

+ {jobs.length === 0 ? ( +

Keine Aufträge für dieses Gerät.

+ ) : ( +
    + {jobs.map((j) => ( +
  • + + {label(j.state)} +
  • + ))} +
+ )} +
+ )} +
+
+ Technische Daten + +
{pretty(d)}
+
+ {scoped && allowed(scoped, 'devices:revoke') && ( +
+ Gerät verwalten + {['archived', 'current'].includes(String(d.lifecycle)) && ( + + )} + {d.lifecycle === 'current' && ( + + )} +
+ )} +
+ {scoped && + customer === recoveryTenant && + asset === recoveryAsset && + allowed(scoped, 'inventory:read') && ( +
+ Entwicklungsabnahmen + + + + + +
+ )} + + )} +
+ ); } -export function Devices({ auth, customers, filter, onFilter, selection, onSelection, onEnroll, onScripts, onOperation }: Props) { - const [search,setSearch]=useState(''), [query,setQuery]=useState(''), [status,setStatus]=useState(''), [history,setHistory]=useState(false); - const [routes,setRoutes]=useState([]), [target,setTarget]=useState<{customer:string;asset:string;agent:string}|null>(null); - const cursor=routes[routes.length-1]; - useEffect(()=>{ const timer=setTimeout(()=>{ setQuery(search.trim());setRoutes([]); },200);return ()=>clearTimeout(timer); },[search]); - const list=useResource(async signal=>{ - if(target) return null; - const params=new URLSearchParams({view:history?'history':'current',limit:'40'}); - if(query) params.set('q',query);if(status && !history) params.set('status',status);if(cursor) params.set('cursor',cursor); - const path=filter?tenantPath(filter,'/devices'):'/api/v1/devices'; - return page(await request(path+'?'+params, {signal})); - },[filter,query,history,status,cursor,target],true); - function setView(historic:boolean){setRoutes([]);setHistory(historic);onSelection({customer:'',ids:[]});} - function select(d:RecordValue,checked:boolean) { - const asset=objectId(d,'asset'),customer=objectId(d,'tenant'); - if(checked && selection.ids.length && customer!==selection.customer) return; - const ids=checked?[...selection.ids,asset]:selection.ids.filter(id=>id!==asset); - onSelection({ customer:ids.length?customer:'',ids }); +export function Devices({ + detailPath, + auth, + customers, + filter, + onFilter, + selection, + onSelection, + onEnroll, + onScripts, + onOperation +}: Props) { + const [search, setSearch] = useState(''), + [query, setQuery] = useState(''), + [status, setStatus] = useState(''), + [history, setHistory] = useState(false); + const [routes, setRoutes] = useState([]); + const [customerId, assetId, agentId] = detailPath.split('/'); + const target = + customerId && assetId && agentId ? { customer: customerId, asset: assetId, agent: agentId } : null; + const back = () => { + window.location.hash = 'geraete'; + }; + const cursor = routes[routes.length - 1]; + useEffect(() => { + const timer = setTimeout(() => { + setQuery(search.trim()); + setRoutes([]); + }, 200); + return () => clearTimeout(timer); + }, [search]); + const list = useResource( + async (signal) => { + if (target) return null; + const params = new URLSearchParams({ view: history ? 'history' : 'current', limit: '40' }); + if (query) params.set('q', query); + if (status && !history) params.set('status', status); + if (cursor) params.set('cursor', cursor); + const path = filter ? tenantPath(filter, '/devices') : '/api/v1/devices'; + return page(await request(path + '?' + params, { signal })); + }, + [filter, query, history, status, cursor, detailPath], + true + ); + function setView(historic: boolean) { + setRoutes([]); + setHistory(historic); + onSelection({ customer: '', ids: [] }); } - if(target) return setTarget(null)} openOperation={id=>onOperation(target.customer,id)} - changed={()=>{setTarget(null);setRoutes([]);onSelection({customer:'',ids:[]});list.reload();}}/>; - return <> -

Geräte

{allowed(auth,'devices:enroll') && }
-
-
-
- - {!history && } + function select(d: RecordValue, checked: boolean) { + const asset = objectId(d, 'asset'), + customer = objectId(d, 'tenant'); + if (checked && selection.ids.length && customer !== selection.customer) return; + const ids = checked ? [...selection.ids, asset] : selection.ids.filter((id) => id !== asset); + onSelection({ customer: ids.length ? customer : '', ids }); + } + if (target) + return ( + onOperation(target.customer, id)} + changed={() => { + back(); + setRoutes([]); + onSelection({ customer: '', ids: [] }); + list.reload(); + }} + /> + ); + return ( + <> +
+
+

Geräte

+
+ {allowed(auth, 'devices:enroll') && ( + + )}
- - {history &&

Ausgemusterte Geräte und Registrierungen ohne bestätigte Identität.

} - {!list.data && !list.error &&

Geräte werden geladen …

} - {list.data && <>
{!history && }{['Hostname','OS','Status','Speicher frei / gesamt','RAM','CPU','Kunde'].map(h=>)} - {list.data.items.map(d=>{ - const asset=objectId(d,'asset'), agent=objectId(d,'agent'),customer=objectId(d,'tenant'),model=cpu(d); - const show=()=>setTarget({asset,agent,customer}); - const another=selection.ids.length>0 && selection.customer!==customer; - return - {!history && } - - - - - ; - })}
Ziel auswählen{h}
e.stopPropagation()}>select(d,e.target.checked)}/>{label(d.os)}{d.status==='offline' && d.lifecycle==='current' && Zuletzt {time(d.last_contact_at)}}{gib(d.ram_total_bytes)===null?unknown:gib(d.ram_total_bytes)+' GiB'}{model.primary}{model.secondary && {model.secondary}}{label(d.customer_name)}
- {!list.data.items.length &&

{query||filter||status?'Keine passenden Geräte':'Keine Geräte in dieser Ansicht'}

{(query||filter||status) && }
} -
{list.data.items.length} {list.data.items.length===1?'Gerät':'Geräte'}{cursor||list.data.next_cursor?' auf dieser Seite':''} · Stand {time(list.data.as_of)} - {(cursor||list.data.next_cursor) &&
}
- } -
- {!!selection.ids.length &&
{selection.ids.length} {selection.ids.length===1?'Gerät':'Geräte'} ausgewählt{customers.find(c=>c.tenant_id===selection.customer)?.name}
-
} - ; +
+
+ + +
+
+ + + {!history && ( + + )} +
+ + {history && ( +

+ Ausgemusterte Geräte und Registrierungen ohne bestätigte Identität. +

+ )} + {!list.data && !list.error &&

Geräte werden geladen …

} + {list.data && ( + <> +
+ + + + {!history && ( + + )} + {['Hostname', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM', 'CPU', 'Kunde'].map( + (h) => ( + + ) + )} + + + + {list.data.items.map((d) => { + const asset = objectId(d, 'asset'), + agent = objectId(d, 'agent'), + customer = objectId(d, 'tenant'), + model = cpu(d); + const show = () => { + window.location.hash = ['geraete', customer, asset, agent] + .map(encodeURIComponent) + .join('/'); + }; + const another = selection.ids.length > 0 && selection.customer !== customer; + return ( + + {!history && ( + + )} + + + + + + + + + ); + })} + +
+ Ziel auswählen + + {h} +
e.stopPropagation()}> + select(d, e.target.checked)} + /> + + + {label(d.os)} + + {d.status === 'offline' && d.lifecycle === 'current' && ( + Zuletzt {time(d.last_contact_at)} + )} + + + + {gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes) + ' GiB'} + + {model.primary} + {model.secondary && {model.secondary}} + {label(d.customer_name)}
+
+ {!list.data.items.length && ( +
+ +

+ {query || filter || status + ? 'Keine passenden Geräte' + : 'Keine Geräte in dieser Ansicht'} +

+ {(query || filter || status) && ( + + )} +
+ )} +
+ + {list.data.items.length} {list.data.items.length === 1 ? 'Gerät' : 'Geräte'} + {cursor || list.data.next_cursor ? ' auf dieser Seite' : ''} · Stand{' '} + {time(list.data.as_of)} + + {(cursor || list.data.next_cursor) && ( +
+ + +
+ )} +
+ + )} +
+ {!!selection.ids.length && ( +
+
+ + {selection.ids.length} {selection.ids.length === 1 ? 'Gerät' : 'Geräte'} ausgewählt + + {customers.find((c) => c.tenant_id === selection.customer)?.name} +
+ + +
+ )} + + ); } diff --git a/web/src/main.tsx b/web/src/main.tsx index 53c4e70..c73b5e4 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -258,87 +258,319 @@ function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; i await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/unknown-closure`), { csrf: auth.csrf_token, body: { attempt_id: stringField(job, 'attempt_id'), revision: job.revision, reason: reason.trim() } }); setConfirmed(false); done(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Unknown-Job ausdrücklich abschließen' : 'Unknown-Job ausdrücklich abschließen'}; } -const pages: Record = { geraete: 'Geräte', auftraege: 'Aufträge', skripte: 'Skripte', kunden: 'Kunden', verwaltung: 'Verwaltung' }; +const pages: Record = { + geraete: 'Geräte', + auftraege: 'Aufträge', + skripte: 'Skripte', + kunden: 'Kunden', + verwaltung: 'Verwaltung' +}; function currentRoute() { - const [key = 'geraete',tab] = window.location.hash.slice(1).split('/'); - return { page: (Object.hasOwn(pages,key) ? key : 'geraete') as NavKey, tab: tab ?? '' }; + const [key = 'geraete', ...parts] = window.location.hash.slice(1).split('/'); + return { page: (Object.hasOwn(pages, key) ? key : 'geraete') as NavKey, tab: parts.join('/') }; +} +function go(page: NavKey, tab = '') { + window.location.hash = page + (tab ? '/' + tab : ''); } -function go(page: NavKey, tab = '') { window.location.hash = page + (tab ? '/' + tab : ''); } function Workspace({ auth, logout }: { auth: Session; logout: () => void }) { - const [route,setRoute] = useState(currentRoute); - useEffect(()=>{ const change=()=>{setRoute(currentRoute());window.scrollTo(0,0);}; window.addEventListener('hashchange',change);return ()=>window.removeEventListener('hashchange',change); },[]); - useEffect(()=>{document.title=pages[route.page]+' · Rust Discovery';},[route.page]); - const tenants=useResource(async signal=>{ - const data=record(await request('/api/v1/tenants',{signal})); - return {items:page(data).items.map(tenant),canManage:data.can_manage_customers===true}; - },[auth.principal.id]); - const customers=tenants.data?.items ?? auth.tenants; - const [customer,setCustomer]=useState(auth.tenants[0]?.tenant_id ?? ''); - const [fleetFilter,setFleetFilter]=useState(''); - const [selection,setSelection]=useState<{customer:string;ids:string[]}>({customer:'',ids:[]}); - const [error,setError]=useState(null); - const [planId,setPlan]=useState(null), [operationId,setOperation]=useState(null); - function switchCustomer(id:string) { - if(id===customer)return; - setSelection({customer:'',ids:[]});setPlan(null);setOperation(null);setCustomer(id); + const [route, setRoute] = useState(currentRoute); + useEffect(() => { + const change = () => { + setRoute(currentRoute()); + window.scrollTo(0, 0); + }; + window.addEventListener('hashchange', change); + return () => window.removeEventListener('hashchange', change); + }, []); + useEffect(() => { + document.title = pages[route.page] + ' · Rust Discovery'; + }, [route.page]); + const tenants = useResource( + async (signal) => { + const data = record(await request('/api/v1/tenants', { signal })); + return { items: page(data).items.map(tenant), canManage: data.can_manage_customers === true }; + }, + [auth.principal.id] + ); + const customers = tenants.data?.items ?? auth.tenants; + const [customer, setCustomer] = useState(auth.tenants[0]?.tenant_id ?? ''); + const [fleetFilter, setFleetFilter] = useState(''); + const [selection, setSelection] = useState<{ customer: string; ids: string[] }>({ + customer: '', + ids: [] + }); + const [error, setError] = useState(null); + const [planId, setPlan] = useState(null), + [operationId, setOperation] = useState(null); + function switchCustomer(id: string) { + if (id === customer) return; + setSelection({ customer: '', ids: [] }); + setPlan(null); + setOperation(null); + setCustomer(id); } - function selectFleetCustomer(id:string) { - setFleetFilter(id);setSelection({customer:'',ids:[]}); - if(id) switchCustomer(id); + function selectFleetCustomer(id: string) { + setFleetFilter(id); + setSelection({ customer: '', ids: [] }); + if (id) switchCustomer(id); } - const primaryTenant=auth.tenants[0]?.tenant_id; - const current = useResource(async signal=>{ - if(!customer || customer===primaryTenant)return {id:customer,auth}; - const scoped=session(await request('/auth/session',{signal,tenantId:customer})); - return {id:customer,auth:scoped}; - },[customer,auth]); + const primaryTenant = auth.tenants[0]?.tenant_id; + const current = useResource( + async (signal) => { + if (!customer || customer === primaryTenant) return { id: customer, auth }; + const scoped = session(await request('/auth/session', { signal, tenantId: customer })); + return { id: customer, auth: scoped }; + }, + [customer, auth] + ); // Gate rendering during a tenant change; a previously loaded session is scoped to its own customer. - const scoped=current.data?.id===customer ? current.data.auth : null; - const customerName=customers.find(c=>c.tenant_id===customer)?.name ?? ''; - const openOperation=(id:string)=>{setPlan(null);setOperation(id);go('auftraege');}; - const showPlan=(id:string)=>{setOperation(null);setPlan(id);go('auftraege');}; - const selected=selection.customer===customer?selection.ids:[]; - const tabs: [string,string][]= [['zugang','MCP-Tokens'],['aufnahme','Agent-Releases & Aufnahme'],['kataloge','Paketkataloge'],['rechte','Rechte & Ausführungsstopp']]; - const adminTab=tabs.some(([id])=>id===route.tab)?route.tab:'zugang'; - return
- -
Arbeitsbereich{pages[route.page]}
- {route.page!=='geraete' && route.page!=='kunden' && } -
- {auth.principal.simulated && } -
- {route.page==='geraete' && {if(value.customer)switchCustomer(value.customer);setSelection(value);}} - onEnroll={()=>go('verwaltung','aufnahme')} onScripts={()=>go('skripte')} - onOperation={(tenantId,id)=>{switchCustomer(tenantId);openOperation(id);}}/>} - {route.page==='kunden' && <>

Kunden

{selectFleetCustomer(id);go('geraete');}}/>} - {!['geraete','kunden'].includes(route.page) && (!customer || !scoped) && !current.error &&

Kundenbereich wird geladen …

} - {scoped && - {route.page==='skripte' && <> - {selected.length>0 &&

{selected.length} {selected.length===1?'Zielgerät':'Zielgeräte'} für {customerName} ausgewählt

} - } - {route.page==='auftraege' && <>

Aufträge

{route.tab!=='neu' && Auftrag planen}
- {route.tab==='neu' ? <>Geräte auswählen

{selected.length} {selected.length===1?'Zielgerät':'Zielgeräte'} für {customerName} ausgewählt

: <> - {operationId && setPlan(id)}/>} - {planId && } - }} - {route.page==='verwaltung' && <>

Verwaltung

- {adminTab==='zugang' && } - {adminTab==='aufnahme' && } - {adminTab==='kataloge' && <>} - {adminTab==='rechte' && }} -
} -
-
; + const scoped = current.data?.id === customer ? current.data.auth : null; + const customerName = customers.find((c) => c.tenant_id === customer)?.name ?? ''; + const openOperation = (id: string) => { + setPlan(null); + setOperation(id); + go('auftraege'); + }; + const showPlan = (id: string) => { + setOperation(null); + setPlan(id); + go('auftraege'); + }; + const selected = selection.customer === customer ? selection.ids : []; + const tabs: [string, string][] = [ + ['zugang', 'MCP-Tokens'], + ['aufnahme', 'Agent-Releases & Aufnahme'], + ['kataloge', 'Paketkataloge'], + ['rechte', 'Rechte & Ausführungsstopp'] + ]; + const adminTab = tabs.some(([id]) => id === route.tab) ? route.tab : 'zugang'; + return ( +
+ +
+
+
+ Arbeitsbereich + + {pages[route.page]} +
+ {route.page !== 'geraete' && route.page !== 'kunden' && ( + + )} +
+ {auth.principal.simulated && ( + + )} +
+ + + + {route.page === 'geraete' && ( + { + if (value.customer) switchCustomer(value.customer); + setSelection(value); + }} + onEnroll={() => go('verwaltung', 'aufnahme')} + onScripts={() => go('skripte')} + onOperation={(tenantId, id) => { + switchCustomer(tenantId); + openOperation(id); + }} + /> + )} + {route.page === 'kunden' && ( + <> +
+

Kunden

+
+ { + selectFleetCustomer(id); + go('geraete'); + }} + /> + + )} + {!['geraete', 'kunden'].includes(route.page) && (!customer || !scoped) && !current.error && ( +

Kundenbereich wird geladen …

+ )} + {scoped && ( + + {route.page === 'skripte' && ( + <> + + {selected.length > 0 && ( +

+ {selected.length} {selected.length === 1 ? 'Zielgerät' : 'Zielgeräte'} für{' '} + {customerName} ausgewählt +

+ )} + + + )} + {route.page === 'auftraege' && ( + <> +
+

Aufträge

+ {route.tab !== 'neu' && ( + + Auftrag planen + + )} +
+ {route.tab === 'neu' ? ( + <> + + Geräte auswählen + +

+ {selected.length} {selected.length === 1 ? 'Zielgerät' : 'Zielgeräte'} für{' '} + {customerName} ausgewählt +

+ + + ) : ( + <> + {operationId && ( + setPlan(id)} + /> + )} + {planId && ( + + )} + + + )} + + )} + {route.page === 'verwaltung' && ( + <> +
+

Verwaltung

+
+ + {adminTab === 'zugang' && } + {adminTab === 'aufnahme' && ( + + )} + {adminTab === 'kataloge' && ( + <> + + + + )} + {adminTab === 'rechte' && } + + )} +
+ )} +
+
+
+ ); } + function App() { const [auth, setAuth] = useState(null), [loading, setLoading] = useState(true), [error, setError] = useState(null); const config = useResource(async signal => authConfig(await request('/auth/config', { signal })), []); diff --git a/web/src/navigation.tsx b/web/src/navigation.tsx index 55d7768..77d4f0f 100644 --- a/web/src/navigation.tsx +++ b/web/src/navigation.tsx @@ -8,8 +8,22 @@ const glyphs = { suchen: 'M16 16l5 5 M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0', plus: 'M12 5v14 M5 12h14', abmelden: 'M10 4H4v16h6 M8 12h13 M16 7l5 5-5 5', - zurueck: 'M20 12H4 M10 6l-6 6 6 6', + zurueck: 'M20 12H4 M10 6l-6 6 6 6' }; export function NavIcon({ name }: { name: keyof typeof glyphs }) { - return ; + return ( + + ); } diff --git a/web/src/resource.tsx b/web/src/resource.tsx index 1eee2c9..7bd9ddd 100644 --- a/web/src/resource.tsx +++ b/web/src/resource.tsx @@ -1,15 +1,47 @@ import React, { useEffect, useState } from 'react'; -export const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler'; -export function ErrorBox({ error }: { error: string | null }) { return error ?
{error}
: null; } -export function useResource(load: (signal: AbortSignal) => Promise, deps: React.DependencyList, poll = false) { - const [data, setData] = useState(null), [error, setError] = useState(null), [revision, setRevision] = useState(0); +export const errorText = (error: unknown) => + error instanceof Error ? error.message : 'Unbekannter Fehler'; +export function ErrorBox({ error }: { error: string | null }) { + return error ? ( +
+ {error} +
+ ) : null; +} +export function useResource( + load: (signal: AbortSignal) => Promise, + deps: React.DependencyList, + poll = false +) { + const [data, setData] = useState(null), + [error, setError] = useState(null), + [revision, setRevision] = useState(0); useEffect(() => { - let active = true; const controller = new AbortController(); let timer: ReturnType | undefined; - setData(null); setError(null); - const run = async () => { try { const result = await load(controller.signal); if (active) { setData(result); setError(null); } } catch (e) { if (active) setError(errorText(e)); } - finally { if (active && poll) timer = setTimeout(run, 4000); } }; - void run(); return () => { active = false; controller.abort(); clearTimeout(timer); }; + let active = true; + const controller = new AbortController(); + let timer: ReturnType | undefined; + setData(null); + setError(null); + const run = async () => { + try { + const result = await load(controller.signal); + if (active) { + setData(result); + setError(null); + } + } catch (e) { + if (active) setError(errorText(e)); + } finally { + if (active && poll) timer = setTimeout(run, 4000); + } + }; + void run(); + return () => { + active = false; + controller.abort(); + clearTimeout(timer); + }; }, [...deps, revision]); - return { data, error, reload: () => setRevision(v => v + 1) }; + return { data, error, reload: () => setRevision((v) => v + 1) }; } diff --git a/web/src/style.css b/web/src/style.css index 839d95d..26b3a8e 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -46,8 +46,8 @@ thead th { background:#f7f9f8; color:var(--subtle); font-weight:620; font-size:. .login form > button { width:100%; margin-top:12px; } .workbench { display:grid; grid-template-columns:195px minmax(0,1fr); min-height:100vh; } .sidebar { position:sticky; top:0; height:100vh; height:100dvh; background:var(--nav); color:#eef7f3; display:flex; flex-direction:column; padding:25px 12px 15px; } -.brand { display:flex; align-items:center; gap:10px; padding:0 7px; color:white; text-decoration:none; font-weight:675; font-size:1.13rem; letter-spacing:-.035em; white-space:nowrap; } -.brand-mark { width:28px; height:28px; position:relative; transform:rotate(-6deg); display:inline-block; } +.brand { display:flex; align-items:center; gap:9px; padding:0 4px; color:white; text-decoration:none; font-weight:675; font-size:1.06rem; letter-spacing:-.035em; white-space:nowrap; } +.brand-mark { width:24px; flex:none; height:28px; position:relative; transform:rotate(-6deg); display:inline-block; } .brand-mark i { position:absolute; width:18px; height:13px; border:2px solid #85c7a9; background:var(--nav); border-radius:3px; transform:skewY(-17deg); left:4px; top:11px; } .brand-mark i:nth-child(2) { top:7px; } .brand-mark i:nth-child(3) { top:3px; background:#b5e9c7; border-color:#b5e9c7; } .sidebar nav { margin-top:36px; display:grid; gap:5px; }