diff --git a/crates/server/src/controls.rs b/crates/server/src/controls.rs index fa5ca11..286c4c1 100644 --- a/crates/server/src/controls.rs +++ b/crates/server/src/controls.rs @@ -1,9 +1,9 @@ use crate::jobs::Error; use axum::{ Json, Router, - extract::{Path, State}, + extract::{Path, Query, State}, http::{HeaderMap, StatusCode}, - routing::post, + routing::{delete, post}, }; use serde::Deserialize; use serde_json::{Value, json}; @@ -25,6 +25,7 @@ pub fn routes(r: Router) -> Router { "/api/v1/tenants/{tenant}/devices/{asset}/revocation", post(revoke_device), ) + .route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device)) .route( "/api/v1/tenants/{tenant}/devices/{asset}/archive", post(archive_device), @@ -127,23 +128,53 @@ async fn archive_device( tx.commit().await?; Ok(Json(json!({"asset_id":asset, "archived":input.archived}))) } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Pairing { + agent_id: Uuid, +} + +async fn remove_device( + State(s): State, + h: HeaderMap, + Path((tenant, asset)): Path<(Uuid, Uuid)>, + Query(pairing): Query, +) -> Result { + let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", "device_deleted").await?; + let status: String = sqlx::query_scalar("SELECT remove_revoked_device($1,$2,$3,$4)") + .bind(tenant).bind(asset).bind(pairing.agent_id).bind(&p.name) + .fetch_one(&mut *tx).await?; + match status.as_str() { + "deleted" => audit(&mut tx, &p, "device_deleted", + json!({"asset_id":asset, "agent_id":pairing.agent_id})).await?, + "absent" => (), + "active" => return Err(Error(StatusCode::CONFLICT, "DEVICE_REVOCATION_REQUIRED")), + "busy" => return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK")), + "forbidden" => return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")), + _ => return Err(Error(StatusCode::INTERNAL_SERVER_ERROR, "DEVICE_DELETION_FAILED")), + } + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + pub async fn revoke_device( State(s): State, h: HeaderMap, Path((t, asset)): Path<(Uuid, Uuid)>, + Query(selection): Query, Json(i): Json, ) -> Result, Error> { let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?; - let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1").bind(asset).execute(&mut *tx).await?.rows_affected(); + let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2)").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?.rows_affected(); if n == 0 { return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND")); } - sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).execute(&mut *tx).await?; + sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2) AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?; audit( &mut tx, &p, "device_revoked", - json!({"asset_id":asset,"reason":i.reason}), + json!({"asset_id":asset,"agent_id":selection.agent_id,"reason":i.reason}), ) .await?; tx.commit().await?; diff --git a/crates/server/src/local_auth.rs b/crates/server/src/local_auth.rs index 10f465a..1be5bb9 100644 --- a/crates/server/src/local_auth.rs +++ b/crates/server/src/local_auth.rs @@ -443,7 +443,8 @@ mod tests { 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 password = "test pairing removal"; + let mut config = sample(&issuer, a, &hex::encode(derive_password(password.as_bytes(), &[7; 32]).unwrap())); 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()); @@ -458,14 +459,16 @@ mod tests { .unwrap(), ), }; - let router = crate::jobs::routes( + let router = crate::controls::routes(crate::jobs::routes( Router::new() .route("/api/v1/tenants", get(crate::api::tenants)) .route( "/api/v1/tenants/{tenant}/devices/{asset}", get(crate::devices::detail), ), - ) + )) + .route("/auth/local/login", axum::routing::post(crate::auth::local_login)) + .route("/auth/session", get(crate::auth::session)) .layer(middleware::from_fn(crate::auth::context)) .with_state(state.clone()); let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) @@ -489,6 +492,7 @@ mod tests { "rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"}); for request in [ client.get(format!("{base}/{b}/devices/{asset}")), + client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")), client .post(format!("{base}/{b}/operation-plans")) .json(&forbidden_plan), @@ -511,6 +515,40 @@ mod tests { .await .unwrap(); assert_eq!(created, 0); + let pair = format!("{base}/{a}/devices/{asset}?agent_id={id}"); + let same_customer = client.delete(&pair).bearer_auth(&token).send().await.unwrap(); + assert_eq!(same_customer.status(), StatusCode::FORBIDDEN); + + let api = base.strip_suffix("/api/v1/tenants").unwrap(); + let origin = &state.auth.origin; + let credentials = input(password, &configured(&config).users[0].secret); + let logged_in = client.post(format!("{api}/auth/local/login")).header("origin", origin) + .json(&json!({"username":credentials.username,"password":credentials.password,"totp_code":credentials.totp_code})) + .send().await.unwrap().error_for_status().unwrap(); + let cookie = logged_in.headers()["set-cookie"].to_str().unwrap().split(';').next().unwrap(); + let session = client.get(format!("{api}/auth/session")).header("cookie", cookie) + .send().await.unwrap().json::().await.unwrap(); + let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie); + let csrf = session["csrf_token"].as_str().unwrap(); + assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN); + sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2") + .bind(a).bind(&issuer).execute(&admin).await.unwrap(); + sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)") + .bind(a).bind(asset).execute(&admin).await.unwrap(); + sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)") + .bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap(); + assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN); + assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT); + let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}")) + .header("origin", origin).header("cookie",cookie).header("x-csrf-token",csrf) + .json(&json!({"reason":"isolated retirement"})).send().await.unwrap(); + assert_eq!(revoked.status(), StatusCode::OK); + for _ in 0..2 { + assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::NO_CONTENT); + } + let records: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_deleted' AND data#>>'{decision,agent_id}'=$2") + .bind(a).bind(id.to_string()).fetch_one(&admin).await.unwrap(); + assert_eq!(records, 1); server.abort(); config["users"][0]["disabled"] = json!(true); let mut disabled = crate::auth::Auth::from_env("development").await.unwrap(); diff --git a/docs/public-access.md b/docs/public-access.md index 43cb072..70e9761 100644 --- a/docs/public-access.md +++ b/docs/public-access.md @@ -65,3 +65,8 @@ Weitere Serverupdates verwenden `tools/build.py server-arm64 --ssh --ref REVISIO 76 WebUI-Tests, drei Browser-Bedientests der Tokenverwaltung sowie fünf Backendtests gegen isoliertes PostgreSQL bestanden. Alle 27 Migrationen wurden mit einem eingeschränkten Migrationsbenutzer geprüft. Die öffentliche HTTPS-Abnahme bestätigte 25 Fälle einschließlich Passwort/TOTP, Replay, CSRF, Tenantgrenze, beschränktem Lesetoken und Widerruf in derselben MCP-Sitzung. Alle während der Abnahme erstellten Testtokens sind widerrufen; die Abschlusskontrolle fand null aktive Tokens. [Öffentlicher Nachweis](evidence/public-access-20261117.json) Die verwendeten Schutzmaßnahmen orientieren sich an den OWASP-Hinweisen zu Anmeldung, Passwortspeicherung und Sitzungen. [Authentifizierung](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html) · [Passwortspeicherung](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) · [Sitzungen](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html) + + +### Alte Gerätekopplung endgültig löschen + +Unter **Geräte → Historie** die betreffende Installation öffnen. Unter **Gerät verwalten** zuerst die Identität widerrufen und anschließend **Kopplung löschen** wählen. Die Bestätigung nennt Hostname, Kunde und Kopplungs-ID. Offene Genehmigungen oder laufende beziehungsweise ungeklärte Aufträge sperren das Löschen. Nach der Bestätigung entfallen die Geräteidentität, ihr Inventar und ihre eigenen Auftragsergebnisse. Eine weitere Installation desselben Geräts und deren Historie bleiben erhalten. Gemeinsame signierte Mehrgerätepläne und der Auditnachweis bleiben nachvollziehbar. diff --git a/migrations/0036_delete_device_pairing.sql b/migrations/0036_delete_device_pairing.sql new file mode 100644 index 0000000..46ff275 --- /dev/null +++ b/migrations/0036_delete_device_pairing.sql @@ -0,0 +1,103 @@ +-- The application role has no DELETE grant on the inventory, jobs or signed +-- history. Only this tenant-scoped operation retires a revoked installation. +CREATE FUNCTION remove_revoked_device(customer uuid, asset uuid, agent uuid, actor text) +RETURNS text LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, public, pg_temp AS $$ +DECLARE + revoked timestamptz; + plan_ids uuid[]; + op_ids uuid[]; + job_ids uuid[]; + previous_guard text; +BEGIN + IF customer::text IS DISTINCT FROM current_setting('app.tenant_id',true) THEN RETURN 'forbidden'; END IF; + PERFORM FROM memberships WHERE tenant_id=customer AND principal=actor + AND kind IN ('human','test_human') AND revoked_at IS NULL AND 'devices:revoke'=ANY(permissions) FOR SHARE; + IF NOT FOUND THEN RETURN 'forbidden'; END IF; + + -- Serialize removals of different agents in a shared plan and lock the + -- parent against a concurrent enrollment while deciding whether it is empty. + PERFORM pg_advisory_xact_lock(hashtextextended('remove-device:'||customer::text,0)); + PERFORM FROM assets WHERE tenant_id=customer AND asset_id=asset FOR UPDATE; + SELECT revoked_at INTO revoked FROM agent_installations + WHERE tenant_id=customer AND asset_id=asset AND agent_id=agent FOR UPDATE; + IF NOT FOUND THEN RETURN 'absent'; END IF; + IF revoked IS NULL THEN RETURN 'active'; END IF; + + IF EXISTS (SELECT FROM jobs WHERE tenant_id=customer AND agent_id=agent + 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.tenant_id=customer AND r.approval_state='pending_approval' AND p.expires_at>now() + AND convert_from(p.payload,'UTF8')::jsonb->'jobs' @> + jsonb_build_array(jsonb_build_object('payload',jsonb_build_object('agent_id',agent)))) + THEN RETURN 'busy'; END IF; + + SELECT array_agg(job_id) INTO job_ids FROM jobs WHERE tenant_id=customer AND agent_id=agent; + -- Shared plans and authorizations stay byte-exact while any other target exists. + SELECT array_agg(p.plan_id) INTO plan_ids FROM operation_plans p + CROSS JOIN LATERAL (SELECT convert_from(p.payload,'UTF8')::jsonb->'jobs' AS items) j + WHERE p.tenant_id=customer AND j.items @> jsonb_build_array(jsonb_build_object('payload',jsonb_build_object('agent_id',agent))) + AND NOT EXISTS (SELECT FROM jsonb_array_elements(j.items) elem + JOIN agent_installations i ON i.tenant_id=customer AND i.agent_id::text=elem#>>'{payload,agent_id}' + WHERE i.agent_id<>agent); + SELECT array_agg(operation_id) INTO op_ids FROM approval_requests WHERE tenant_id=customer AND plan_id=ANY(plan_ids); + + previous_guard := current_setting('rmm.removing_device',true); + PERFORM set_config('rmm.removing_device','on',true); + DELETE FROM windows_echo_completions c USING windows_echo_probe_scopes s + WHERE c.tenant_id=customer AND s.tenant_id=c.tenant_id AND s.agent_id=agent; + DELETE FROM windows_echo_probe_scopes WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM windows_checkpoint_review_receipts r USING windows_checkpoint_reviews w + WHERE r.tenant_id=customer AND (r.tenant_id,r.request_id)=(w.tenant_id,w.request_id) AND w.agent_id=agent; + DELETE FROM windows_checkpoint_reviews WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM windows_sync_alignment_receipts r USING windows_sync_alignment_reviews w + WHERE r.tenant_id=customer AND (r.tenant_id,r.request_id)=(w.tenant_id,w.request_id) AND w.agent_id=agent; + DELETE FROM windows_sync_alignment_reviews WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM windows_system_nonstart_receipts r USING windows_system_nonstart_reviews w + WHERE r.tenant_id=customer AND (r.tenant_id,r.request_id)=(w.tenant_id,w.request_id) AND w.agent_id=agent; + DELETE FROM windows_system_nonstart_reviews WHERE tenant_id=customer AND agent_id=agent; + + DELETE FROM job_unknown_closures WHERE tenant_id=customer AND job_id=ANY(job_ids); + DELETE FROM outbox WHERE tenant_id=customer AND job_id=ANY(job_ids); + DELETE FROM execution_permits WHERE tenant_id=customer AND job_id=ANY(job_ids); + DELETE FROM jobs WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM operations WHERE tenant_id=customer AND operation_id=ANY(op_ids); + DELETE FROM authorizations WHERE tenant_id=customer AND operation_id=ANY(op_ids); + DELETE FROM operation_submissions WHERE tenant_id=customer AND operation_id=ANY(op_ids); + DELETE FROM approval_requests WHERE tenant_id=customer AND operation_id=ANY(op_ids); + DELETE FROM live_query_requests WHERE tenant_id=customer AND plan_id=ANY(plan_ids); + DELETE FROM operation_plans WHERE tenant_id=customer AND plan_id=ANY(plan_ids); + + DELETE FROM job_receipts WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM observations WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM sync_checkpoints WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM agent_sync_state WHERE tenant_id=customer AND agent_id=agent; + DELETE FROM agent_installations WHERE tenant_id=customer AND asset_id=asset AND agent_id=agent; + DELETE FROM assets WHERE tenant_id=customer AND asset_id=asset + AND NOT EXISTS (SELECT FROM agent_installations WHERE tenant_id=customer AND asset_id=asset); + PERFORM set_config('rmm.removing_device',coalesce(previous_guard,''),true); + RETURN 'deleted'; +END $$; +REVOKE ALL ON FUNCTION remove_revoked_device(uuid,uuid,uuid,text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION remove_revoked_device(uuid,uuid,uuid,text) TO rmm_app; + +-- Preserve update protection and reject standalone deletes, including deletes +-- by rmm_app with a spoofed custom setting. The definer is the migration owner. +CREATE FUNCTION immutable_device_history() RETURNS trigger LANGUAGE plpgsql +SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF TG_OP='DELETE' AND current_setting('rmm.removing_device',true)='on' + AND current_user=pg_get_userbyid((SELECT proowner FROM pg_proc + WHERE oid='public.remove_revoked_device(uuid,uuid,uuid,text)'::regprocedure)) + THEN RETURN OLD; END IF; + RAISE EXCEPTION 'immutable device history'; +END $$; +DO $$ DECLARE tbl text; trig text; BEGIN + FOREACH tbl IN ARRAY ARRAY['operation_plans','windows_echo_probe_scopes','windows_echo_completions', + 'windows_checkpoint_reviews','windows_checkpoint_review_receipts','windows_sync_alignment_reviews', + 'windows_sync_alignment_receipts','windows_system_nonstart_reviews','windows_system_nonstart_receipts','job_unknown_closures'] LOOP + trig := CASE WHEN tbl='operation_plans' THEN 'immutable_plan' ELSE 'immutable_content' END; + EXECUTE format('DROP TRIGGER %I ON %I',trig,tbl); + EXECUTE format('CREATE TRIGGER %I BEFORE UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION immutable_device_history()',trig,tbl); + END LOOP; +END $$; diff --git a/tests/browser/customer-management.spec.ts b/tests/browser/customer-management.spec.ts index 06a8f6b..feae178 100644 --- a/tests/browser/customer-management.spec.ts +++ b/tests/browser/customer-management.spec.ts @@ -116,3 +116,87 @@ test('creates and renames a customer, opens its inventory, and hides editing for { method: 'PATCH', path: `/api/v1/tenants/${customerId}`, body: { name: 'Nord GmbH' } } ]); }); + +test('removes the confirmed historical installation and keeps its successor', async ({ page }) => { + const customer = { tenant_id: '22222222-2222-4222-8222-222222222222', name: 'Nord GmbH' }; + const asset = '33333333-3333-4333-8333-333333333333'; + const old = '44444444-4444-4444-8444-444444444444'; + const active = '55555555-5555-4555-8555-555555555555'; + const path = '/api/v1/tenants/' + customer.tenant_id + '/devices/' + asset; + const device = { tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: asset, + hostname: 'NORD-PC', os: 'Windows', recent_jobs: [], volumes: [] }; + const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false, + completeness: 'complete', as_of: new Date().toISOString() }); + let attempts = 0, revoked = false, deleted = false, canManage = true; + 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: 'operator', tenant_id: customer.tenant_id, csrf_token: 'fixture-csrf', testsimulation: false, + permissions: canManage ? ['inventory:read', 'devices:revoke'] : ['inventory:read'] + } })); + await page.route(origin + '/api/v1/**', async r => { + const req = r.request(), url = new URL(req.url()); + const historical = { ...device, agent_id: old, lifecycle: revoked ? 'revoked' : 'replaced', status: 'offline' }; + const successor = { ...device, agent_id: active, lifecycle: 'current', status: 'online' }; + if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) }); + if (url.pathname === '/api/v1/devices' || url.pathname === path.slice(0, path.lastIndexOf('/'))) { + return r.fulfill({ json: listing(url.searchParams.get('view') === 'history' ? (deleted ? [] : [historical]) : [successor]) }); + } + if (url.pathname === path && req.method() === 'GET') { + if (url.searchParams.get('agent_id') === old && !deleted) return r.fulfill({ json: historical }); + if (url.searchParams.get('agent_id') === active) return r.fulfill({ json: successor }); + } + if (url.pathname === path + '/revocation' && req.method() === 'POST') { + expect(url.searchParams.get('agent_id')).toBe(old); + expect(req.headers()['x-csrf-token']).toBe('fixture-csrf'); + expect(req.postDataJSON()).toEqual({ reason: 'Neuinstallation bestätigt' }); + revoked = true; + return r.fulfill({ json: { asset_id: asset, revoked: true } }); + } + if (url.pathname === path && req.method() === 'DELETE') { + expect(url.searchParams.get('agent_id')).toBe(old); + expect(req.headers()['x-rmm-tenant']).toBe(customer.tenant_id); + expect(req.headers()['x-csrf-token']).toBe('fixture-csrf'); + expect(req.postData()).toBeNull(); + if (++attempts === 1) return r.fulfill({ status: 409, json: { code: 'DEVICE_HAS_OPEN_WORK' } }); + deleted = true; + return r.fulfill({ status: 204 }); + } + return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } }); + }); + await page.goto(origin + '/#geraete'); + await page.getByRole('button', { name: 'Historie' }).click(); + await page.getByRole('button', { name: 'NORD-PC' }).click(); + await page.getByText('Gerät verwalten', { exact: true }).click(); + await expect(page.getByRole('button', { name: 'Kopplung löschen' })).toHaveCount(0); + await page.getByText('Geräteidentität widerrufen', { exact: true }).click(); + await page.getByLabel('Grund für Geräteidentität widerrufen').fill('Neuinstallation bestätigt'); + const nonce = await page.getByText('Aktuelle Bestätigungskennung:').locator('code').innerText(); + await page.getByLabel('Bestätigungskennung eingeben').fill(nonce); + await page.getByRole('checkbox', { name: 'Ich bestätige' }).check(); + await page.getByRole('button', { name: 'Geräteidentität widerrufen · ausdrücklich ausführen' }).click(); + await page.getByRole('button', { name: 'Kopplung löschen' }).click(); + await expect(page.locator('.warning')).toContainText('NORD-PC'); + await expect(page.locator('.warning')).toContainText(customer.name); + await expect(page.getByText('Kopplungs-ID')).toContainText(old); + await page.getByRole('button', { name: 'Abbrechen' }).click(); + expect(attempts).toBe(0); + await page.getByRole('button', { name: 'Kopplung löschen' }).click(); + await page.getByRole('button', { name: 'Endgültig löschen' }).click(); + await expect(page.getByRole('alert')).toContainText('offene Aufträge'); + await page.getByRole('button', { name: 'Endgültig löschen' }).click(); + await expect(page.getByRole('status')).toContainText('Kopplung von „NORD-PC“ bei „Nord GmbH“ gelöscht.'); + await expect(page.getByRole('button', { name: 'NORD-PC' })).toHaveCount(0); + await page.getByRole('button', { name: 'Bestand' }).click(); + await page.getByRole('button', { name: 'NORD-PC' }).click(); + await expect(page).toHaveURL(new RegExp(active + '$')); + await page.getByText('Gerät verwalten', { exact: true }).click(); + await expect(page.getByRole('button', { name: 'Kopplung löschen' })).toHaveCount(0); + await expect(page.getByText('Geräteidentität widerrufen', { exact: true })).toBeVisible(); + canManage = false; + await page.reload(); + await expect(page.getByRole('heading', { name: 'NORD-PC' })).toBeVisible(); + await expect(page.getByText('Gerät verwalten', { exact: true })).toHaveCount(0); + expect(attempts).toBe(2); +}); diff --git a/tests/device_pair_removal.sql b/tests/device_pair_removal.sql new file mode 100644 index 0000000..911cb9c --- /dev/null +++ b/tests/device_pair_removal.sql @@ -0,0 +1,67 @@ +-- Run as postgres in the isolated, fully migrated database. +BEGIN; +DO $$ +DECLARE + customer uuid := '11111111-1111-4111-8111-111111111111'; + other_customer uuid := '22222222-2222-4222-8222-222222222222'; + asset uuid := gen_random_uuid(); + agent uuid := gen_random_uuid(); + sibling uuid := gen_random_uuid(); + shared uuid := gen_random_uuid(); + single uuid := gen_random_uuid(); + op uuid := gen_random_uuid(); + auth uuid := gen_random_uuid(); + job uuid := gen_random_uuid(); + attempt uuid := gen_random_uuid(); + fixed_job jsonb := jsonb_build_object('payload',jsonb_build_object('agent_id',agent,'asset_id',asset)); + sibling_job jsonb := jsonb_build_object('payload',jsonb_build_object('agent_id',sibling,'asset_id',asset)); + operator_name text := 'simulated-testprincipal-a'; +BEGIN + PERFORM set_config('app.tenant_id',customer::text,true); + INSERT INTO assets(tenant_id,asset_id) VALUES(customer,asset),(other_customer,asset); + INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES + (customer,agent,asset,'delete-test-a'),(customer,sibling,asset,'delete-test-b'), + (other_customer,agent,asset,'delete-test-c'); + INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) + VALUES(customer,agent,gen_random_uuid(),gen_random_uuid(),1,now(),'windows.base','valid','partial',gen_random_uuid(),'{}','test'); + INSERT INTO operation_plans VALUES(customer,shared,'test', + convert_to(jsonb_build_object('jobs',jsonb_build_array(fixed_job,sibling_job))::text,'UTF8'),'sha',now()+interval '1 day',now()), + (customer,single,'test',convert_to(jsonb_build_object('jobs',jsonb_build_array(fixed_job))::text,'UTF8'),'sha',now()+interval '1 day',now()); + INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash) + VALUES(customer,op,single,'test','key','hash'); + SET LOCAL ROLE rmm_app; + IF has_table_privilege(current_user,'operation_plans','DELETE') OR + remove_revoked_device(customer,asset,agent,'viewer:'||customer::text)<>'forbidden' OR + remove_revoked_device(other_customer,asset,agent,operator_name)<>'forbidden' OR + remove_revoked_device(customer,asset,agent,operator_name)<>'active' THEN + RAISE EXCEPTION 'tenant, role or revocation check failed'; END IF; + UPDATE agent_installations SET revoked_at=now() WHERE agent_id=agent; + IF remove_revoked_device(customer,asset,agent,operator_name)<>'busy' THEN RAISE EXCEPTION 'pending approval removed'; END IF; + RESET ROLE; + UPDATE approval_requests SET approval_state='approved' WHERE tenant_id=customer AND operation_id=op; + INSERT INTO authorizations VALUES(customer,auth,op,single,'sha',operator_name,repeat('1',64),'dev_test_browser_simulation',true,1,now(),NULL); + INSERT INTO operations VALUES(customer,op,auth); + INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource) + VALUES(customer,job,attempt,op,agent,asset,'{}','sha','unknown','resource'); + INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES(customer,job,attempt); + SET LOCAL ROLE rmm_app; + IF remove_revoked_device(customer,asset,agent,operator_name)<>'busy' THEN RAISE EXCEPTION 'open effect removed'; END IF; + RESET ROLE; + UPDATE jobs SET state='failed' WHERE tenant_id=customer AND job_id=job; + SET LOCAL ROLE rmm_app; + IF remove_revoked_device(customer,asset,agent,operator_name)<>'deleted' THEN RAISE EXCEPTION 'not deleted'; END IF; + IF EXISTS(SELECT FROM observations WHERE agent_id=agent) OR EXISTS(SELECT FROM operation_plans WHERE plan_id=single) + OR EXISTS(SELECT FROM jobs WHERE job_id=job) OR EXISTS(SELECT FROM approval_requests WHERE operation_id=op) + OR EXISTS(SELECT FROM agent_installations WHERE agent_id=agent) + OR NOT EXISTS(SELECT FROM operation_plans WHERE plan_id=shared) + OR NOT EXISTS(SELECT FROM agent_installations WHERE agent_id=sibling) + OR NOT EXISTS(SELECT FROM assets WHERE asset_id=asset) THEN RAISE EXCEPTION 'pair cleanup incorrect'; END IF; + IF remove_revoked_device(customer,asset,agent,operator_name)<>'absent' THEN RAISE EXCEPTION 'retry failed'; END IF; + UPDATE agent_installations SET revoked_at=now() WHERE agent_id=sibling; + IF remove_revoked_device(customer,asset,sibling,operator_name)<>'deleted' THEN RAISE EXCEPTION 'last pair not removed'; END IF; + IF EXISTS(SELECT FROM operation_plans WHERE plan_id=shared) OR EXISTS(SELECT FROM assets WHERE asset_id=asset) THEN + RAISE EXCEPTION 'orphaned plan or asset'; END IF; + PERFORM set_config('app.tenant_id',other_customer::text,true); + IF NOT EXISTS(SELECT FROM agent_installations WHERE agent_id=agent AND revoked_at IS NULL) THEN RAISE EXCEPTION 'other customer changed'; END IF; +END $$; +ROLLBACK; diff --git a/tests/local_access_database.py b/tests/local_access_database.py index 52a9952..1d82e23 100644 --- a/tests/local_access_database.py +++ b/tests/local_access_database.py @@ -40,6 +40,7 @@ def main(): for path in sorted((ROOT / "migrations").glob("*.sql")): sql("rmm_migrator", path.read_text()) sql("postgres", (ROOT / "tests/customer_access.sql").read_text()) + sql("postgres", (ROOT / "tests/device_pair_removal.sql").read_text()) print("PASS selected, global and future customer grants, role boundaries, revocation and tenant context") test_command = [ "docker", "run", "--rm", "--network", "container:" + name, diff --git a/web/src/api.ts b/web/src/api.ts index f62533e..8f1eeba 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -45,11 +45,12 @@ export function page(value: unknown): Page { return { items: r.items.map(v => record(v)), next_cursor: r.next_cursor, completeness: stringField(r, 'completeness'), truncated: r.truncated !== false, as_of: stringField(r, 'as_of') }; } export class ApiError extends Error { constructor(public status: number, public code: string, message: string, public correlation: string) { super(`${code}: ${message}${correlation ? ` (Korrelation ${correlation})` : ''}`); } } -export async function request(path: string, options: { body?: unknown; csrf?: string; signal?: AbortSignal; method?: 'PATCH'; tenantId?: string } = {}): Promise { +export async function request(path: string, options: { body?: unknown; csrf?: string; signal?: AbortSignal; method?: 'PATCH' | 'DELETE'; tenantId?: string } = {}): Promise { if (!path.startsWith('/') || path.startsWith('//')) throw new Error('Nur gleiche Origin erlaubt'); - const changing = options.body !== undefined; + const hasBody = options.body !== undefined; + const changing = hasBody || options.method !== undefined; const response = await fetch(path, { method: options.method ?? (changing ? 'POST' : 'GET'), credentials: 'same-origin', cache: 'no-store', signal: options.signal, - headers: { ...(changing ? { 'Content-Type': 'application/json' } : {}), ...(changing && options.csrf ? { 'X-CSRF-Token': options.csrf } : {}), ...(options.tenantId ? { 'X-RMM-Tenant': options.tenantId } : {}) }, body: changing ? JSON.stringify(options.body) : undefined }); + headers: { ...(hasBody ? { 'Content-Type': 'application/json' } : {}), ...(changing && options.csrf ? { 'X-CSRF-Token': options.csrf } : {}), ...(options.tenantId ? { 'X-RMM-Tenant': options.tenantId } : {}) }, body: hasBody ? JSON.stringify(options.body) : undefined }); const raw: unknown = response.status === 204 ? {} : await response.json().catch(() => { throw new ApiError(response.status, 'HTTP_ERROR', 'keine JSON-Antwort', ''); }); if (!response.ok) { const r = record(raw); throw new ApiError(response.status, stringField(r, 'code'), stringField(r, 'message'), typeof r.correlation_id === 'string' ? r.correlation_id : ''); } return raw; diff --git a/web/src/devices.tsx b/web/src/devices.tsx index 92ac473..2030433 100644 --- a/web/src/devices.tsx +++ b/web/src/devices.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react'; import { + ApiError, objectId, page, pretty, @@ -129,7 +130,7 @@ function DeviceDetail({ auth: Session; back: () => void; openOperation: (id: string, jobId: string) => void; - changed: () => void; + changed: (notice?: string) => void; }) { const path = devicePath(customer, asset); const detail = useResource( @@ -143,6 +144,8 @@ function DeviceDetail({ ); const [busy, setBusy] = useState(false), [error, setError] = useState(null); + const [confirmDelete, setConfirmDelete] = useState(false); + const [managing, setManaging] = useState(false); const d = detail.data; const scoped = membership.data; const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : []; @@ -162,7 +165,7 @@ function DeviceDetail({ - + {!d && !detail.error &&

Inventar wird geladen …

} {d && ( <> @@ -238,9 +241,11 @@ function DeviceDetail({
{pretty(d)}
- {scoped && allowed(scoped, 'devices:revoke') && ( -
+ {scoped && allowed(scoped, 'devices:revoke') && + d.tenant_id === customer && d.asset_id === asset && d.agent_id === agent && ( +
setManaging(e.currentTarget.open)}> Gerät verwalten + {['archived', 'current'].includes(String(d.lifecycle)) && ( + + + ) : ( + + ))}
)} @@ -313,6 +354,7 @@ export function Devices({ [query, setQuery] = useState(''), [status, setStatus] = useState(''), [history, setHistory] = useState(false); + const [deletionNotice, setDeletionNotice] = useState(''); const [trail, setTrail] = useState<{ filter: string; routes: string[] }>({ filter, routes: [] }); const routes = trail.filter === filter ? trail.routes : []; function setRoutes(next: string[] | ((old: string[]) => string[])) { @@ -361,12 +403,13 @@ export function Devices({ if (target) return ( onOperation(target.customer, id, jobId)} - changed={() => { + changed={(notice) => { + setDeletionNotice(notice ?? ''); back(); setRoutes([]); onSelection({ customer: '', ids: [] }); @@ -386,6 +429,7 @@ export function Devices({ )} + {deletionNotice &&

{deletionNotice}

}