Files
rust-discovery/migrations/0036_delete_device_pairing.sql
T

104 lines
6.9 KiB
PL/PgSQL

-- 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 $$;