-- Explicit customer administrator grants are provisioned by the database owner. -- The application role cannot add administrators or read the membership index. CREATE TABLE customer_admins ( principal text PRIMARY KEY CHECK (principal LIKE 'local:%'), home uuid NOT NULL, FOREIGN KEY(home,principal) REFERENCES memberships(tenant_id,principal) ); CREATE TABLE customer_member_index ( principal text NOT NULL, customer uuid NOT NULL, kind text NOT NULL, permissions text[] NOT NULL, PRIMARY KEY(principal,customer) ); REVOKE ALL ON customer_admins, customer_member_index FROM PUBLIC,rmm_app; CREATE FUNCTION index_customer_membership() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ BEGIN IF TG_OP <> 'INSERT' THEN DELETE FROM customer_member_index WHERE principal=OLD.principal AND customer=OLD.tenant_id; END IF; IF TG_OP <> 'DELETE' AND NEW.revoked_at IS NULL THEN INSERT INTO customer_member_index VALUES(NEW.principal,NEW.tenant_id,NEW.kind,NEW.permissions); END IF; RETURN NULL; END $$; REVOKE ALL ON FUNCTION index_customer_membership() FROM PUBLIC; CREATE TRIGGER maintain_customer_members AFTER INSERT OR UPDATE OR DELETE ON memberships FOR EACH ROW EXECUTE FUNCTION index_customer_membership(); DO $$ DECLARE t uuid; BEGIN FOR t IN SELECT tenant_id FROM tenants LOOP PERFORM set_config('app.tenant_id',t::text,true); INSERT INTO customer_member_index SELECT principal,tenant_id,kind,permissions FROM memberships WHERE tenant_id=t AND revoked_at IS NULL; END LOOP; END $$; CREATE FUNCTION is_customer_admin(actor text) RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ SELECT EXISTS(SELECT 1 FROM customer_admins a JOIN customer_member_index m ON m.principal=a.principal AND m.customer=a.home WHERE a.principal=actor AND m.kind='human' AND 'tokens:manage'=ANY(m.permissions)); $$; CREATE FUNCTION local_customer_tenants(actor text,home_id uuid) RETURNS uuid[] LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ SELECT ARRAY(SELECT customer FROM customer_member_index m WHERE m.principal=actor AND m.kind='human' AND (m.customer=home_id OR EXISTS(SELECT 1 FROM customer_admins a WHERE a.principal=actor AND a.home=home_id AND is_customer_admin(actor))) ORDER BY customer); $$; CREATE FUNCTION provision_customer_admin(home_id uuid,actor text) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),''); p text[]; t uuid; BEGIN -- Serialize changes to the customer directory with global grant creation. PERFORM pg_advisory_xact_lock(724035,28); SELECT permissions INTO STRICT p FROM customer_member_index WHERE principal=actor AND customer=home_id AND kind='human' AND 'tokens:manage'=ANY(permissions); INSERT INTO customer_admins(principal,home) VALUES(actor,home_id) ON CONFLICT(principal) DO NOTHING; IF NOT EXISTS(SELECT 1 FROM customer_admins WHERE principal=actor AND home=home_id) THEN RAISE EXCEPTION 'ADMIN_HOME_CONFLICT'; END IF; FOR t IN SELECT tenant_id FROM tenants LOOP PERFORM set_config('app.tenant_id',t::text,true); INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(t,actor,'human',p) ON CONFLICT(tenant_id,principal) DO NOTHING; END LOOP; PERFORM set_config('app.tenant_id',previous_tenant,true); END $$; REVOKE ALL ON FUNCTION provision_customer_admin(uuid,text) FROM PUBLIC,rmm_app; REVOKE ALL ON FUNCTION is_customer_admin(text), local_customer_tenants(text,uuid) FROM PUBLIC; GRANT EXECUTE ON FUNCTION is_customer_admin(text), local_customer_tenants(text,uuid) TO rmm_app; ALTER TABLE mcp_tokens ADD COLUMN all_customers boolean NOT NULL DEFAULT false; ALTER TABLE mcp_tokens ADD COLUMN customer_ids uuid[]; ALTER TABLE mcp_tokens ADD COLUMN issuer_admin_home uuid REFERENCES tenants; -- NULL is the preexisting single-customer audience. Global grants use []. ALTER TABLE mcp_tokens ADD CHECK (NOT all_customers OR (customer_ids IS NOT NULL AND cardinality(customer_ids)=0)); CREATE UNIQUE INDEX mcp_route_principal ON mcp_token_routes (('mcp:'||token_id::text)); CREATE TABLE global_mcp_credentials ( home uuid NOT NULL, token uuid PRIMARY KEY, FOREIGN KEY(home,token) REFERENCES mcp_tokens(tenant_id,token_id) ); REVOKE ALL ON global_mcp_credentials FROM PUBLIC,rmm_app; CREATE FUNCTION issue_customer_token(actor text,id uuid,label text,digest text,requested text[],expiry timestamptz, global_access boolean,selected uuid[]) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE home_id uuid:=current_setting('app.tenant_id')::uuid; customers uuid[]; t uuid; member text:='mcp:'||id::text; BEGIN PERFORM pg_advisory_xact_lock(724035,28); IF global_access THEN IF NOT is_customer_admin(actor) OR cardinality(selected) IS DISTINCT FROM 0 THEN RAISE EXCEPTION 'GLOBAL_ADMIN_REQUIRED' USING ERRCODE='42501'; END IF; SELECT array_agg(tenant_id) INTO customers FROM tenants; ELSE IF cardinality(selected) IS NULL OR cardinality(selected) NOT BETWEEN 1 AND 512 OR array_position(selected,NULL) IS NOT NULL OR cardinality(selected)<>(SELECT count(DISTINCT value) FROM unnest(selected) value) THEN RAISE EXCEPTION 'INVALID_CUSTOMER_SELECTION' USING ERRCODE='22023'; END IF; customers:=selected; END IF; FOREACH t IN ARRAY customers LOOP IF NOT EXISTS(SELECT 1 FROM customer_member_index WHERE principal=actor AND customer=t AND kind='human' AND 'tokens:manage'=ANY(permissions) AND requested <@ permissions) THEN RAISE EXCEPTION 'CUSTOMER_SCOPE_DENIED' USING ERRCODE='42501'; END IF; END LOOP; PERFORM issue_mcp_token(actor,id,label,digest,requested,expiry); UPDATE mcp_tokens SET all_customers=global_access,customer_ids=selected, issuer_admin_home=(SELECT home FROM customer_admins WHERE principal=actor) WHERE tenant_id=home_id AND token_id=id; INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES(home_id,gen_random_uuid(),actor,'mcp_token_audience', jsonb_build_object('token_id',id,'all_customers',global_access,'customer_ids',selected)); IF global_access THEN INSERT INTO global_mcp_credentials VALUES(home_id,id); END IF; FOREACH t IN ARRAY customers LOOP IF t<>home_id THEN PERFORM set_config('app.tenant_id',t::text,true); INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(t,member,'automation',requested); END IF; END LOOP; PERFORM set_config('app.tenant_id',home_id::text,true); END $$; REVOKE ALL ON FUNCTION issue_customer_token(text,uuid,text,text,text[],timestamptz,boolean,uuid[]) FROM PUBLIC; GRANT EXECUTE ON FUNCTION issue_customer_token(text,uuid,text,text,text[],timestamptz,boolean,uuid[]) TO rmm_app; -- Authorization projection evaluated inside the credential's home RLS context. -- No direct grant on this view. Both the target's membership and the issuer's -- current delegation ceiling are checked, even for previously submitted jobs. CREATE VIEW customer_token_rights AS SELECT t.tenant_id,t.token_id,t.principal,t.created_by,m.customer, ARRAY(SELECT s FROM unnest(t.scopes) s WHERE s=ANY(h.permissions) AND s=ANY(m.permissions) AND s=ANY(issuer.permissions) AND s=ANY(target_issuer.permissions)) AS scopes FROM mcp_tokens t JOIN customer_member_index h ON h.principal=t.principal AND h.customer=t.tenant_id AND h.kind='automation' JOIN customer_member_index m ON m.principal=t.principal AND m.kind='automation' JOIN customer_member_index issuer ON issuer.principal=t.created_by AND issuer.customer=t.tenant_id AND issuer.kind='human' AND 'tokens:manage'=ANY(issuer.permissions) JOIN customer_member_index target_issuer ON target_issuer.principal=t.created_by AND target_issuer.customer=m.customer AND target_issuer.kind='human' AND 'tokens:manage'=ANY(target_issuer.permissions) WHERE t.revoked_at IS NULL AND t.expires_at>now() AND (t.all_customers OR m.customer=ANY(coalesce(t.customer_ids,ARRAY[t.tenant_id]))) AND ((NOT t.all_customers AND (t.issuer_admin_home IS NULL OR (m.customer=t.issuer_admin_home AND t.tenant_id=t.issuer_admin_home))) OR is_customer_admin(t.created_by)) AND (left(t.created_by,5)<>'oidc:' OR EXISTS(SELECT 1 FROM oidc_principals o WHERE o.principal=t.created_by AND NOT o.disabled AND m.customer=ANY(o.tenant_ids) AND t.tenant_id=ANY(o.tenant_ids))); REVOKE ALL ON customer_token_rights FROM PUBLIC,rmm_app; -- Every authorization, including pending job admission, consults the original -- credential expiry/revocation, original membership and target membership. CREATE FUNCTION mcp_effective_scopes(member text,target_customer uuid) RETURNS text[] LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),''); home_id uuid; result text[]; BEGIN SELECT tenant_id INTO home_id FROM mcp_token_routes WHERE 'mcp:'||token_id::text=member; IF home_id IS NULL THEN RETURN '{}'; END IF; PERFORM set_config('app.tenant_id',home_id::text,true); SELECT scopes INTO result FROM customer_token_rights WHERE tenant_id=home_id AND principal=member AND customer=target_customer; PERFORM set_config('app.tenant_id',previous_tenant,true); RETURN coalesce(result,'{}'); END $$; REVOKE ALL ON FUNCTION mcp_effective_scopes(text,uuid) FROM PUBLIC,rmm_app; CREATE FUNCTION mcp_current_scopes(member text) RETURNS text[] LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ SELECT mcp_effective_scopes(member,nullif(current_setting('app.tenant_id',true),'')::uuid); $$; CREATE OR REPLACE FUNCTION mcp_principal_permission(member text,permission text) RETURNS boolean LANGUAGE sql STABLE SET search_path=pg_catalog,public AS $$ SELECT permission=ANY(mcp_current_scopes(member)); $$; CREATE FUNCTION mcp_credential_customers(digest text) RETURNS uuid[] LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),''); home_id uuid; id uuid; result uuid[]; BEGIN SELECT tenant_id,token_id INTO home_id,id FROM mcp_token_routes WHERE token_hash=digest; IF home_id IS NULL THEN RETURN '{}'; END IF; PERFORM set_config('app.tenant_id',home_id::text,true); SELECT ARRAY(SELECT customer FROM customer_token_rights WHERE tenant_id=home_id AND token_id=id AND cardinality(scopes)>0 ORDER BY (customer=home_id) DESC,customer) INTO result; PERFORM set_config('app.tenant_id',previous_tenant,true); RETURN result; END $$; REVOKE ALL ON FUNCTION mcp_credential_customers(text),mcp_current_scopes(text) FROM PUBLIC; GRANT EXECUTE ON FUNCTION mcp_credential_customers(text),mcp_current_scopes(text) TO rmm_app; -- Only return issuer metadata for a credential currently active in this tenant. CREATE FUNCTION mcp_current_issuer(member text) RETURNS text LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE target_id uuid:=nullif(current_setting('app.tenant_id',true),'')::uuid;home_id uuid;actor text; BEGIN IF target_id IS NULL THEN RETURN NULL; END IF; SELECT tenant_id INTO home_id FROM mcp_token_routes WHERE 'mcp:'||token_id::text=member; IF home_id IS NULL THEN RETURN NULL; END IF; PERFORM set_config('app.tenant_id',home_id::text,true); SELECT created_by INTO actor FROM customer_token_rights WHERE tenant_id=home_id AND principal=member AND customer=target_id AND cardinality(scopes)>0; PERFORM set_config('app.tenant_id',target_id::text,true); RETURN actor; END $$; REVOKE ALL ON FUNCTION mcp_current_issuer(text) FROM PUBLIC; GRANT EXECUTE ON FUNCTION mcp_current_issuer(text) TO rmm_app; -- Provision every newly inserted tenant, including administrative imports. CREATE FUNCTION seed_customer_access() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),''); id uuid:=NEW.tenant_id; credential record; m record; BEGIN PERFORM pg_advisory_xact_lock(724035,28); PERFORM set_config('app.tenant_id',id::text,true); INSERT INTO tenant_limits(tenant_id) VALUES(id); FOR m IN SELECT a.principal,i.permissions FROM customer_admins a JOIN customer_member_index i ON i.principal=a.principal AND i.customer=a.home WHERE i.kind='human' AND 'tokens:manage'=ANY(i.permissions) LOOP INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(id,m.principal,'human',m.permissions); END LOOP; FOR credential IN SELECT home,token FROM global_mcp_credentials LOOP PERFORM set_config('app.tenant_id',credential.home::text,true); SELECT t.principal, t.scopes INTO m FROM mcp_tokens t WHERE t.token_id=credential.token AND t.tenant_id=credential.home AND t.revoked_at IS NULL AND t.expires_at>now() AND t.all_customers; IF FOUND THEN PERFORM set_config('app.tenant_id',id::text,true); INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(id,m.principal,'automation',m.scopes); END IF; END LOOP; PERFORM set_config('app.tenant_id',previous_tenant,true); RETURN NEW; END $$; REVOKE ALL ON FUNCTION seed_customer_access() FROM PUBLIC,rmm_app; CREATE TRIGGER customer_access_created AFTER INSERT ON tenants FOR EACH ROW EXECUTE FUNCTION seed_customer_access(); CREATE FUNCTION manage_customer(actor text,id uuid,label text,new_customer boolean) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),''); BEGIN PERFORM pg_advisory_xact_lock(724035,28); IF NOT is_customer_admin(actor) THEN RAISE EXCEPTION 'ADMIN_REQUIRED' USING ERRCODE='42501'; END IF; IF label IS NULL OR label<>btrim(label) OR length(label) NOT BETWEEN 1 AND 120 OR label ~ '[[:cntrl:]]' THEN RAISE EXCEPTION 'INVALID_NAME' USING ERRCODE='22023'; END IF; IF EXISTS(SELECT 1 FROM tenants WHERE lower(name)=lower(label) AND tenant_id<>id) THEN RAISE EXCEPTION 'CUSTOMER_NAME_EXISTS' USING ERRCODE='23505'; END IF; PERFORM set_config('app.tenant_id',id::text,true); IF new_customer THEN INSERT INTO tenants(tenant_id,name) VALUES(id,label); ELSE IF NOT EXISTS(SELECT 1 FROM customer_member_index WHERE customer=id AND principal=actor AND kind='human') THEN RAISE EXCEPTION 'CUSTOMER_DENIED' USING ERRCODE='42501'; END IF; UPDATE tenants SET name=label WHERE tenant_id=id; END IF; PERFORM set_config('app.tenant_id',id::text,true); INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES(id,gen_random_uuid(),actor, CASE WHEN new_customer THEN 'customer_created' ELSE 'customer_renamed' END,jsonb_build_object('name',label)); PERFORM set_config('app.tenant_id',previous_tenant,true); END $$; REVOKE ALL ON FUNCTION manage_customer(text,uuid,text,boolean) FROM PUBLIC; GRANT EXECUTE ON FUNCTION manage_customer(text,uuid,text,boolean) TO rmm_app; -- Both heartbeat and periodic maintenance apply the same existing expiry rules. CREATE FUNCTION maintain_current_customer(target_agent uuid) RETURNS void LANGUAGE sql SET search_path=pg_catalog,public AS $maintain$ UPDATE approval_requests r SET approval_state='expired' FROM operation_plans p WHERE p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND r.approval_state='pending_approval' AND p.expires_at<=now(); UPDATE jobs j SET state='expired',pending_reason=NULL FROM operations o,approval_requests r,operation_plans p WHERE j.tenant_id=o.tenant_id AND j.operation_id=o.operation_id AND r.tenant_id=o.tenant_id AND r.operation_id=o.operation_id AND p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND (target_agent IS NULL OR j.agent_id=target_agent) AND j.state IN ('queued','accepted') AND NOT j.start_reserved AND p.expires_at<=now(); UPDATE jobs j SET state='unknown',pending_reason='reconciliation_required',result=COALESCE(j.result,'{}'::jsonb)||jsonb_build_object('error_code','START_OR_RESULT_UNCONFIRMED','source_id','server_grant_ledger') FROM execution_permits e WHERE e.tenant_id=j.tenant_id AND e.job_id=j.job_id AND (target_agent IS NULL OR j.agent_id=target_agent) AND j.start_reserved AND ((j.state='accepted' AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz>'start_before')::timestamptz+make_interval(secs=>(convert_from(e.payload,'UTF8')::jsonb->>'max_runtime_seconds')::integer)'approved' THEN 'authorization_revoked' WHEN (convert_from(j.payload,'UTF8')::jsonb->>'not_before')::timestamptz>now() THEN 'maintenance_window' WHEN i.last_contact_at IS NULL OR i.last_contact_at>'start_before')::timestamptz+make_interval(secs=>COALESCE((convert_from(j.payload,'UTF8')::jsonb->'action'->>'reconnect_timeout_seconds')::integer,3600))