From 43e879460d814afbf9bc1bd03687ae53ef87f623 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:06:06 -0500 Subject: [PATCH 1/5] feat: propose inactive application parent and entitlement transactions --- .../PARENT-CONTRACT.md | 213 ++++++++ .../application-registration-2104/parents.sql | 73 +++ .../protocol-composition.py | 38 ++ .../qualification-bootstrap.sql | 14 + .../registration.sql | 132 +++++ .../sources.json | 63 +++ .../test_registration.py | 477 ++++++++++++++++++ 7 files changed, 1010 insertions(+) create mode 100644 proposals/application-registration-2104/PARENT-CONTRACT.md create mode 100644 proposals/application-registration-2104/parents.sql create mode 100644 proposals/application-registration-2104/protocol-composition.py create mode 100644 proposals/application-registration-2104/qualification-bootstrap.sql create mode 100644 proposals/application-registration-2104/registration.sql create mode 100644 proposals/application-registration-2104/sources.json create mode 100644 proposals/application-registration-2104/test_registration.py diff --git a/proposals/application-registration-2104/PARENT-CONTRACT.md b/proposals/application-registration-2104/PARENT-CONTRACT.md new file mode 100644 index 0000000..d731482 --- /dev/null +++ b/proposals/application-registration-2104/PARENT-CONTRACT.md @@ -0,0 +1,213 @@ +# Inactive application parent and entitlement candidate — App2104 + +17 November 2026. **Proposed source for disposable qualification only. No runtime +or customer policy is adopted.** This directory is outside `supabase/migrations`, +has no workflow, public API/MCP caller, grants, production role, enrollment API, +provider call, DNS resolver, connection string or bootstrap path. Do not deploy it, +point a fixture at another database, or use `qualification-bootstrap.sql` in runtime. + +The concrete contribution is an atomic parent-creation transaction and explicit +management entitlement check. The existing proof/configuration algorithms can operate +on its parent shapes in an isolated composition. Passing qualification does not make +this an application registry release, least-privilege runtime adapter or App2104 completion. +Only the initial selected environment is created; there is no add-environment operation. + +## Files and source bindings + +| File | Purpose | +| --- | --- | +| `parents.sql` | Proposed parents, enrolled personal principals, named creation/management entitlements and immutable registration history. No seeded permission or grants. | +| `registration.sql` | Unexposed invoker helpers, atomic create and authorized historical receipt read. | +| `qualification-bootstrap.sql` | Synthetic existing accounts and a trivial fresh-auth observation stub. Test setup only; not part of candidate runtime SQL. | +| `protocol-composition.py` | Exact-hash mechanical binding of the existing proof/configuration SQL to these parents and the new entitlement helper; disposable execution only. | +| `test_registration.py` | Owned Unix-socket PostgreSQL supervisor, new transaction/contended-lock tests and negative execution checks. | +| `sources.json` | API, Database and copied cleanup provenance; every composition substitution/count and adapter hash. | + +API authentication/validation references are pinned to accepted +`1fff6b55b8c1b98826c375f99b4f4f66a5ba201c`. Database source baseline is +`7708e337feca212563bdfa48934a72227bcf1b63`. The accepted proof/configuration sources +under `../application-proof-2104/` are not edited. `sources.json` binds their complete +bytes. Composition performs exactly 7 and 14 `proof_parent_fixture.` → +`application_registration_proposal.` substitutions, respectively, then appends the +hash-checked five-argument authority adapter. It preserves function volatility, +revisions, CAS, replay order and lock algorithms. Any unexpected source hash/count +fails before SQL. No `fixture-authority.sql`, fixture parent DDL or configuration-fixture +is loaded. Generated SQL is ephemeral, not a migration or a committed copied protocol. + +## Authentication is a precondition, not a SQL feature + +A future trusted server must freshly call the actual existing `validateAuthContext` +with `allowAccountCreation:false` and `includeVerificationEvidence:true`, with no +account or organization override. It must require original principal actor equals +effective account and selected workspace, self access, and no organization context. +Only that original identity is passed as `p_actor`. Original actor UUIDs are internal +server arguments, never customer registration fields. A positive authentication result +does not provide an application-management entitlement. + +The transaction locks/rechecks an existing `public.accounts` row and an explicitly +enrolled personal-principal row. It does **not** verify API keys/Privy tokens, observe +credential revocation after authentication, or classify personal accounts from UUID +equality alone. No credential/key hash/token ledger is added. The enrollment row is +an explicit proposed personal classification requiring separately authorized provisioning. +API-key/Privy verification and its lifetime boundary remain with the existing verifier. +There is no invented claim of atomic credential revocation with this database transaction. + +The qualification stub merely distinguishes labels representing accepted/rejected +fresh authentication. Its `current-key` versus revoked/wrong/changed labels are **not +tests of real key verification or revocation**. The real verifier bytes are pinned, +not exercised against live accounts. Stale/changed **idempotency keys and input** are +separately tested against actual SQL. There is no organization membership, admin, +service-role, client boolean or fixture-authority fallback. + +## Proposed authority and inputs + +`register_application(actor, workspace, environment, key, entitlement_revision, registration)` +requires current enabled `create_entitlements` for the exact actor/workspace/environment. +The proposed operation name is `create_application`, not an OAuth scope. Workspace +must equal actor and billing owner is fixed to workspace. Expected entitlement revision +is a concurrency observation, not authority. A new request must match it. Creation +has an optional expiry checked after authority-lock waits, after retry-key waits and +before parent insertion using `clock_timestamp()`. + +`registration` contains exactly `name` and sorted `origins`; every origin has exactly +`origin`, `hostname` and sorted distinct `return_urls`. A future server first uses the +existing shared registration validator, then sorts/projects its exact canonical values +and derives hostname with WHATWG URL parsing. SQL additionally rejects missing/extra +fields, duplicate/out-of-order origins, host mismatch, foreign returns, fragments, +whitespace and bounds violations. It does not implement WHATWG normalization, DNS +eligibility or ownership verification. Inputs are 1–32 exact origins, 1–32 total return +URLs, at most 2048 characters per URL, 120 per name and 256 KiB total JSON. An origin +may have no return URL if the entire registration still has one. Limits are engineering +qualification bounds, not commercial quotas. HTTP loopback is development-only. + +Create generates application and receipt UUIDs; the caller cannot select application +identity or billing owner. It atomically inserts application, one environment, exact +origins/return destinations (all three revisions initially 1), immutable receipt and +retry row. It grants **no** post-creation permissions and issues no credentials. + +Post-create operations require separately provisioned `management_entitlements` for +exact actor/workspace/application/environment/operation. Supported labels are +`read_registration`, `issue`, `verify`, `revoke`, `read` (proof receipt), and +`replace_existing_origin_return_urls`. These are proposed internal operation names. +They support explicit enabled/revision revocation, **not time-based leases**. An early +review removed post-create expiry because the unchanged proof/configuration algorithms +can wait after initial authorization; this candidate does not claim management expiry +fencing across those later waits. Adding that behavior requires a separately reviewed +protocol, not an inferred production policy. This limitation does not weaken creation's +explicitly tested expiry boundary. + +`read_registration(actor, workspace, application, environment, receipt)` checks the +exact named read entitlement before returning immutable history. A receipt ID is not +a capability. Reads do not require the original creator if a future policy permits +other principals; this proposed personal-only schema permits actor=workspace only. +No alternate policy is implemented. Missing/foreign resources yield the same controlled +authority-unavailable error. SQL errors have no adopted public transport mapping. + +## Locks, replay and participating writers + +One domain operation per transaction, READ COMMITTED only: + +1. Lock existing account `FOR SHARE`, then enrolled personal principal `FOR SHARE`. +2. Lock the exact named creation or management entitlement `FOR SHARE` and validate + enabled/policy state. For create, sample expiry after this lock. +3. For create, transaction advisory lock on `(actor,workspace,create_application,key)`; + recheck expiry after waiting, then authorized replay lookup. +4. New create checks expected entitlement revision and input, samples expiry again, + inserts generated application → selected environment → sorted exact origins, + then immutable receipt/retry record. No existing application is mutated. + +Authorization locks are held to transaction end. A revocation committed before lock +acquisition denies. Revocation arriving after an authorized operation waits for it; +it cannot undo an operation that serialized first. Subsequent calls, including exact +retries, fail. Any participating authority writer follows account → personal principal → +exact entitlement order, and uses exclusive row locks; multiple rows must be ordered +consistently. Tests use isolated direct updates to those rows as proposed revocation +writers, not a shipped grant/revoke administration API. + +The unchanged proof protocol then takes its own actor/workspace/operation/key advisory +lock, application/environment `FOR SHARE`, exact origin `FOR UPDATE`, and challenge +locks as needed. Configuration takes application `FOR SHARE`, environment `FOR UPDATE`, +then every origin in bytewise order `FOR UPDATE`. Proposed parents preserve the same +composite keys/immediate FKs, so configuration/proof parent serialization is retained. +No rename, transfer, origin-add/remove, restoration or suspension API is introduced. +Arbitrary direct DML, disabled constraints and privileged operators are not fenced. + +Creation retry scope is actor/workspace/create-operation/key, across environments. +The fingerprint contains exact environment, entitlement revision and canonical input. +Authorization precedes lookup. Identical retries return original IDs/timestamp/receipt +without creating anything or extending time; changed payload, environment or expected +revision under the same key conflicts. An original exact retry can return its old +entitlement revision after a later revision change if authority remains enabled/current; +a new key must match the current revision. Unknown outcome recovery uses the original +key and payload, never an automatic new key. Rollback restores every partial insert. +Receipt/retry UPDATE and DELETE are blocked; retention, purge, export and tombstone +lifetime remain unadopted. Fixture truncation is teardown only. + +## Outputs and privilege boundary + +Every registration receipt includes actor, workspace, fixed billing owner, generated +application/receipt IDs, selected environment, recorded timestamp, entitlement/policy +revision and full initial snapshot. It constrains all these flags false: +`origins_verified`, `bootstrap_enabled`, `access_activated`, `runtime_enabled`, +`production_persisted`. It labels `policy_status: proposed_unadopted` and +`evidence_kind: disposable_parent_assertion`. `production_persisted:false` distinguishes +local qualification persistence from a production write, not SQL's transaction durability. + +Proof/configuration receipts keep their original synthetic evidence and disabled-access +contracts; no synthetic resolver observation becomes live DNS proof. No Site resource, +provider configuration, billing operation, quotas, fan session or public bootstrap is +introduced. Creating applications cannot authorize spending or reset any allowance. + +All schemas/tables/functions explicitly revoke PUBLIC access, including internal +helpers. There are **no replacement grants, security-definer functions or production +roles**. The local cluster owner executes qualification; a synthetic non-login browser +role proves denial. This is not a least-privilege deployment proof. D3 remains open. + +## Qualification and runner safety + +```sh +PG_BIN=/path/to/postgresql15/bin python3 proposals/application-registration-2104/test_registration.py +PG_BIN=/path/to/postgresql17/bin python3 proposals/application-registration-2104/test_registration.py +``` + +The supervisor accepts a local binary directory, creates an owned random directory, +starts Unix-socket-only PostgreSQL, launches a dedicated worker process group, and +stops/removes only that verified lease. No hosted connection string is accepted. +The internal worker verifies absolute local socket path, UID/device/inode, parent PID, +registered binary directory and postmaster identity **before SQL**; connection-related +PG variables are stripped. The marker/lease is an accidental-target guard, not an OS +security boundary against a malicious local owner who can edit the runner itself. + +SQL, process startup, worker duration and cleanup have bounded waits. Scoped SIGTERM/ +SIGINT unwind cleanup; the worker group is quiesced even if its leader exited. The +exact reviewed worker-group and directory/PID cleanup functions are embedded with source +hashes in `sources.json`. That reuse alone does not inherit all prior supervisor tests. +This candidate separately exercises signal, worker timeout and exited-worker-with-child +faults via `REGISTRATION_QUALIFICATION_FAULT=signal|timeout|worker-exit`, using only its +own disposable cluster. Ambiguous ownership leaves files intact with a reported path. +Uncatchable supervisor SIGKILL/host loss is not claimed recoverable automatically. + +New tests cover missing/foreign/disabled entitlement and principal, exact binding, +revision conflict, changed-key input, exact/lost-response replay, revoked replay, +explicit and mid-parent rollback, read isolation, immutable history, disabled outputs, +PUBLIC/helper denial, input bounds, original protocol composition and stale CAS. +Two-connection cases require observed PostgreSQL lock waits before releasing the winner: +concurrent same-key create, revocation-first, create-first, expiry after authority wait, +and expiry after advisory wait. No unchanged full protocol suite is repeated. + +## Remaining adoption and publication boundaries + +D1–D4 remain unadopted: personal enrollment authority, organization/delegated policy, +execution identity/function-owner permissions, retention owner/period/deletion contract, +and pilot identities/timing. No value is inferred from this qualification. Actual +HTTP/MCP adapters, credential handling, production mapping, policy, grants and deployment +need their own review. App2345 native acceptance and the completed2094 bridge remain +separate; no hosted/provider/customer outcome is claimed here. + +Root reviews the exact diff and no-deploy path boundary before push. Any PR remains +DRAFT, unmerged and unapplied. Draft status alone does not disable external integrations. +The candidate changes only this proposal directory: no automatic migration files, +workflow triggers or runtime configs. Existing unconditional local-test workflows can +still run on a PR. A repository-integrated Supabase preview service may be configured +outside this checkout; its behavior is not proven by reading `.github/workflows`. +Do not publish until root dispositions that external-trigger boundary. diff --git a/proposals/application-registration-2104/parents.sql b/proposals/application-registration-2104/parents.sql new file mode 100644 index 0000000..97be523 --- /dev/null +++ b/proposals/application-registration-2104/parents.sql @@ -0,0 +1,73 @@ +-- INACTIVE PROPOSAL. Outside migrations; no live enrollment, grants or credential store. +-- Requires the existing public.accounts relation. Never load qualification-bootstrap in runtime. +CREATE SCHEMA application_registration_proposal; +REVOKE ALL ON SCHEMA application_registration_proposal FROM PUBLIC; +CREATE TABLE application_registration_proposal.personal_principals ( + account_id uuid PRIMARY KEY REFERENCES public.accounts(id), + enabled boolean NOT NULL DEFAULT true, + policy_version text NOT NULL DEFAULT 'proposed-personal-v1' CHECK(policy_version='proposed-personal-v1') +); +-- An enrollment row is an explicit proposed personal classification, not UUID equality/membership inference. +CREATE TABLE application_registration_proposal.create_entitlements ( + actor uuid NOT NULL REFERENCES application_registration_proposal.personal_principals(account_id), + workspace_id uuid NOT NULL CHECK(workspace_id=actor), + environment text NOT NULL CHECK(environment IN ('production','development')), + revision bigint NOT NULL DEFAULT 1 CHECK(revision BETWEEN 1 AND 9007199254740991), + enabled boolean NOT NULL DEFAULT true, expires_at timestamptz CHECK(isfinite(expires_at)), + policy_version text NOT NULL DEFAULT 'proposed-personal-v1' CHECK(policy_version='proposed-personal-v1'), + PRIMARY KEY(actor,workspace_id,environment) +); +CREATE TABLE application_registration_proposal.applications ( + workspace_id uuid NOT NULL REFERENCES application_registration_proposal.personal_principals(account_id), + id uuid NOT NULL DEFAULT gen_random_uuid(), + billing_owner_id uuid NOT NULL CHECK(billing_owner_id=workspace_id), + name text NOT NULL CHECK(length(name) BETWEEN 1 AND 120), + suspended boolean NOT NULL DEFAULT false, + PRIMARY KEY(workspace_id,id) +); +CREATE TABLE application_registration_proposal.environments ( + workspace_id uuid NOT NULL, application_id uuid NOT NULL, + environment text NOT NULL CHECK(environment IN ('production','development')), + suspended boolean NOT NULL DEFAULT false, + PRIMARY KEY(workspace_id,application_id,environment), + FOREIGN KEY(workspace_id,application_id) REFERENCES application_registration_proposal.applications +); +CREATE TABLE application_registration_proposal.origins ( + workspace_id uuid NOT NULL, application_id uuid NOT NULL, environment text NOT NULL, + origin text NOT NULL, hostname text NOT NULL, return_urls text[] NOT NULL, + config_revision bigint NOT NULL DEFAULT 1 CHECK(config_revision>0), + proof_revision bigint NOT NULL DEFAULT 1 CHECK(proof_revision>0), + cas_revision bigint NOT NULL DEFAULT 1 CHECK(cas_revision>0), revoked boolean NOT NULL DEFAULT false, + PRIMARY KEY(workspace_id,application_id,environment,origin), + FOREIGN KEY(workspace_id,application_id,environment) REFERENCES application_registration_proposal.environments +); +CREATE TABLE application_registration_proposal.management_entitlements ( + actor uuid NOT NULL REFERENCES application_registration_proposal.personal_principals(account_id), + workspace_id uuid NOT NULL CHECK(workspace_id=actor), application_id uuid NOT NULL, environment text NOT NULL, + operation text NOT NULL CHECK(operation IN ('read_registration','issue','verify','revoke','read','replace_existing_origin_return_urls')), + enabled boolean NOT NULL DEFAULT true, revision bigint NOT NULL DEFAULT 1 CHECK(revision>0), + policy_version text NOT NULL DEFAULT 'proposed-personal-v1' CHECK(policy_version='proposed-personal-v1'), + PRIMARY KEY(actor,workspace_id,application_id,environment,operation), + FOREIGN KEY(workspace_id,application_id,environment) REFERENCES application_registration_proposal.environments +); +CREATE TABLE application_registration_proposal.receipts ( + id uuid PRIMARY KEY, actor uuid NOT NULL, workspace_id uuid NOT NULL, + application_id uuid NOT NULL, environment text NOT NULL, recorded_at timestamptz NOT NULL, + result jsonb NOT NULL, + FOREIGN KEY(workspace_id,application_id,environment) REFERENCES application_registration_proposal.environments, + CHECK(result @> '{"origins_verified":false,"bootstrap_enabled":false,"access_activated":false,"runtime_enabled":false,"production_persisted":false,"policy_status":"proposed_unadopted","evidence_kind":"disposable_parent_assertion"}') +); +CREATE TABLE application_registration_proposal.requests ( + actor uuid NOT NULL, workspace_id uuid NOT NULL, key text NOT NULL, + input jsonb NOT NULL, receipt_id uuid NOT NULL REFERENCES application_registration_proposal.receipts, + PRIMARY KEY(actor,workspace_id,key) +); +CREATE FUNCTION application_registration_proposal.immutable_history() RETURNS trigger + LANGUAGE plpgsql SET search_path='' AS $$ +BEGIN RAISE EXCEPTION 'immutable registration history'; END $$; +CREATE TRIGGER immutable_receipt BEFORE UPDATE OR DELETE ON application_registration_proposal.receipts + FOR EACH ROW EXECUTE FUNCTION application_registration_proposal.immutable_history(); +CREATE TRIGGER immutable_request BEFORE UPDATE OR DELETE ON application_registration_proposal.requests + FOR EACH ROW EXECUTE FUNCTION application_registration_proposal.immutable_history(); +REVOKE ALL ON ALL TABLES IN SCHEMA application_registration_proposal FROM PUBLIC; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA application_registration_proposal FROM PUBLIC; diff --git a/proposals/application-registration-2104/protocol-composition.py b/proposals/application-registration-2104/protocol-composition.py new file mode 100644 index 0000000..8e8068c --- /dev/null +++ b/proposals/application-registration-2104/protocol-composition.py @@ -0,0 +1,38 @@ +"""Disposable-only mechanical parent/authority binding. No fixture authority imported.""" +import hashlib +import json +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def compose(): + manifest = json.loads((HERE / 'sources.json').read_text()) + chunks = [] + for source in manifest['composition']: + raw = (HERE.parent.parent / source['path']).read_bytes() + if hashlib.sha256(raw).hexdigest() != source['sha256']: + raise ValueError('Unexpected protocol source: '+source['path']) + text = raw.decode() + for binding in source['bindings']: + if text.count(binding['from']) != binding['count']: + raise ValueError('Unexpected binding count: '+source['path']) + text = text.replace(binding['from'], binding['to']) + chunks.append(text) + # Same five-argument management contract, now using the proposed exact entitlement table. + # This is the sole adapter body; its expected digest is included in the manifest below. + adapter = '''CREATE OR REPLACE FUNCTION application_proof_proposal.authorize_management( + p_actor uuid,p_workspace uuid,p_application uuid,p_environment text,p_operation text +) RETURNS void LANGUAGE plpgsql SET search_path='' AS $$ +BEGIN + PERFORM application_registration_proposal.authorize_management(p_actor,p_workspace,p_application,p_environment,p_operation); +END $$; +REVOKE ALL ON FUNCTION application_proof_proposal.authorize_management(uuid,uuid,uuid,text,text) FROM PUBLIC; +''' + if hashlib.sha256(adapter.encode()).hexdigest() != manifest['authorityAdapterSha256']: + raise ValueError('Unexpected management adapter') + return '\n'.join(chunks) + '\n' + adapter + + +if __name__ == '__main__': + print(compose()) diff --git a/proposals/application-registration-2104/qualification-bootstrap.sql b/proposals/application-registration-2104/qualification-bootstrap.sql new file mode 100644 index 0000000..10718a6 --- /dev/null +++ b/proposals/application-registration-2104/qualification-bootstrap.sql @@ -0,0 +1,14 @@ +-- SYNTHETIC TEST SETUP ONLY. Never import in a production migration/runtime. +-- Minimal existing-account stand-in, not an account creation path in the candidate. +CREATE TABLE public.accounts(id uuid PRIMARY KEY); +INSERT INTO public.accounts VALUES ('00000000-0000-0000-0000-000000000001'),('00000000-0000-0000-0000-000000000002'); +CREATE SCHEMA qualification_auth; +REVOKE ALL ON SCHEMA qualification_auth FROM PUBLIC; +-- No tokens, keys or verifier algorithm: a small test double for fresh trusted verification. +CREATE FUNCTION qualification_auth.original_actor(observation text) RETURNS uuid + LANGUAGE plpgsql SET search_path='' AS $$ +BEGIN + IF observation IS DISTINCT FROM 'current-key' THEN RAISE EXCEPTION 'verification unavailable'; END IF; + RETURN '00000000-0000-0000-0000-000000000001'::uuid; +END $$; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA qualification_auth FROM PUBLIC; diff --git a/proposals/application-registration-2104/registration.sql b/proposals/application-registration-2104/registration.sql new file mode 100644 index 0000000..c3c5859 --- /dev/null +++ b/proposals/application-registration-2104/registration.sql @@ -0,0 +1,132 @@ +-- SOURCE CANDIDATE ONLY. All functions are invokers, ungranted, not public RPCs/authenticators. +-- p_actor is the original existing-account identity from trusted server verification, never body input. +CREATE FUNCTION application_registration_proposal.authorize_principal(p_actor uuid,p_workspace uuid) + RETURNS void LANGUAGE plpgsql SET search_path='' AS $$ +DECLARE active boolean; +BEGIN + IF current_setting('transaction_isolation')<>'read committed' THEN RAISE EXCEPTION 'read committed required'; END IF; + IF p_actor IS NULL OR p_workspace IS DISTINCT FROM p_actor THEN + RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + PERFORM 1 FROM public.accounts WHERE id=p_actor FOR SHARE; + IF NOT FOUND THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + SELECT p.enabled INTO active FROM application_registration_proposal.personal_principals p + WHERE p.account_id=p_actor AND p.policy_version='proposed-personal-v1' FOR SHARE; + IF active IS DISTINCT FROM true THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; +END $$; +CREATE FUNCTION application_registration_proposal.authorize_create(p_actor uuid,p_workspace uuid,p_environment text) + RETURNS application_registration_proposal.create_entitlements LANGUAGE plpgsql SET search_path='' AS $$ +DECLARE authority application_registration_proposal.create_entitlements%ROWTYPE; +BEGIN + PERFORM application_registration_proposal.authorize_principal(p_actor,p_workspace); + SELECT e.* INTO authority FROM application_registration_proposal.create_entitlements e + WHERE e.actor=p_actor AND e.workspace_id=p_workspace AND e.environment=p_environment FOR SHARE; + IF authority.enabled IS DISTINCT FROM true OR authority.policy_version IS DISTINCT FROM 'proposed-personal-v1' + OR authority.expires_at<=clock_timestamp() THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + RETURN authority; +END $$; +CREATE FUNCTION application_registration_proposal.authorize_management( + p_actor uuid,p_workspace uuid,p_application uuid,p_environment text,p_operation text +) RETURNS void LANGUAGE plpgsql SET search_path='' AS $$ +DECLARE authority application_registration_proposal.management_entitlements%ROWTYPE; +BEGIN + PERFORM application_registration_proposal.authorize_principal(p_actor,p_workspace); + SELECT e.* INTO authority FROM application_registration_proposal.management_entitlements e + WHERE e.actor=p_actor AND e.workspace_id=p_workspace AND e.application_id=p_application + AND e.environment=p_environment AND e.operation=p_operation FOR SHARE; + IF authority.enabled IS DISTINCT FROM true OR authority.policy_version IS DISTINCT FROM 'proposed-personal-v1' THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; +END $$; + +CREATE FUNCTION application_registration_proposal.register_application( + p_actor uuid,p_workspace uuid,p_environment text,p_key text,p_entitlement_revision bigint,p_registration jsonb +) RETURNS jsonb LANGUAGE plpgsql SET search_path='' SET timezone='UTC' AS $$ +DECLARE authority application_registration_proposal.create_entitlements%ROWTYPE; + prior application_registration_proposal.requests%ROWTYPE; + fingerprint jsonb; result_value jsonb; application_id uuid; receipt_id uuid; at_time timestamptz; + item jsonb; urls text[]; total_urls integer:=0; snapshot jsonb; origin_list text[]; return_list text[]; +BEGIN + IF p_environment IS NULL OR p_environment NOT IN ('production','development') + OR p_key IS NULL OR length(p_key) NOT BETWEEN 1 AND 128 + OR p_entitlement_revision IS NULL OR p_entitlement_revision NOT BETWEEN 1 AND 9007199254740991 + OR p_registration IS NULL OR jsonb_typeof(p_registration)<>'object' OR octet_length(p_registration::text)>262144 + THEN RAISE EXCEPTION 'invalid input'; END IF; + authority:=application_registration_proposal.authorize_create(p_actor,p_workspace,p_environment); + PERFORM pg_advisory_xact_lock(hashtextextended(jsonb_build_array(p_actor,p_workspace,'create_application'::text,p_key)::text,0)); + -- Authorization rows remain locked; time can still change while waiting for a retry-key lock. + IF authority.expires_at<=clock_timestamp() THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + fingerprint:=jsonb_build_object('environment',p_environment,'entitlement_revision',p_entitlement_revision,'registration',p_registration); + SELECT q.* INTO prior FROM application_registration_proposal.requests q + WHERE q.actor=p_actor AND q.workspace_id=p_workspace AND q.key=p_key; + IF FOUND THEN + IF prior.input IS DISTINCT FROM fingerprint THEN RAISE EXCEPTION 'idempotency conflict'; END IF; + SELECT r.result INTO result_value FROM application_registration_proposal.receipts r WHERE r.id=prior.receipt_id; + RETURN result_value; + END IF; + IF authority.revision<>p_entitlement_revision THEN RAISE EXCEPTION 'entitlement revision conflict'; END IF; + IF NOT(p_registration ?& ARRAY['name','origins']) OR p_registration-ARRAY['name','origins']<>'{}'::jsonb + OR jsonb_typeof(p_registration->'name')<>'string' OR length(p_registration->>'name') NOT BETWEEN 1 AND 120 + OR btrim(p_registration->>'name')<>p_registration->>'name' + OR jsonb_typeof(p_registration->'origins')<>'array' THEN RAISE EXCEPTION 'invalid registration'; END IF; + IF jsonb_array_length(p_registration->'origins') NOT BETWEEN 1 AND 32 THEN RAISE EXCEPTION 'invalid origins'; END IF; + -- Trusted adapter uses WHATWG canonical validation first. These are additional structural checks, not DNS proof. + FOR item IN SELECT value FROM jsonb_array_elements(p_registration->'origins') LOOP + IF jsonb_typeof(item)<>'object' OR NOT(item ?& ARRAY['origin','hostname','return_urls']) + OR item-ARRAY['origin','hostname','return_urls']<>'{}'::jsonb + OR jsonb_typeof(item->'origin')<>'string' OR jsonb_typeof(item->'hostname')<>'string' + OR jsonb_typeof(item->'return_urls')<>'array' THEN RAISE EXCEPTION 'invalid origin'; END IF; + IF length(item->>'origin')>2048 OR length(item->>'hostname') NOT BETWEEN 1 AND 253 + OR (item->>'hostname') !~ '^([a-z0-9.-]+|\[[0-9a-f:]+\])$' + OR (item->>'origin') !~ '^(https|http)://[^/?#@[:space:]]+$' + OR regexp_replace(item->>'origin','^https?://','') !~ ('^'||replace(replace(replace(item->>'hostname','.','\.'),'[','\['),']','\]')||'(:[0-9]+)?$') + OR (left(item->>'origin',7)='http://' AND NOT(p_environment='development' AND item->>'hostname' IN ('localhost','127.0.0.1','[::1]'))) + OR (p_environment='production' AND item->>'hostname' IN ('localhost','127.0.0.1','[::1]')) + THEN RAISE EXCEPTION 'invalid canonical origin'; END IF; + IF jsonb_array_length(item->'return_urls')>32 OR EXISTS(SELECT 1 FROM jsonb_array_elements(item->'return_urls') u WHERE jsonb_typeof(u)<>'string') + THEN RAISE EXCEPTION 'invalid return URLs'; END IF; + SELECT coalesce(array_agg(DISTINCT u COLLATE "C" ORDER BY u COLLATE "C"),'{}') INTO urls + FROM jsonb_array_elements_text(item->'return_urls') t(u); + IF to_jsonb(urls) IS DISTINCT FROM item->'return_urls' + OR EXISTS(SELECT 1 FROM unnest(urls) u WHERE length(u)>2048 OR left(u,length(item->>'origin')+1)<>(item->>'origin')||'/' + OR position('#' IN u)>0 OR u ~ '[[:space:][:cntrl:]]') THEN RAISE EXCEPTION 'invalid return URLs'; END IF; + total_urls:=total_urls+cardinality(urls); + END LOOP; + SELECT array_agg(DISTINCT o->>'origin' COLLATE "C" ORDER BY o->>'origin' COLLATE "C") INTO origin_list + FROM jsonb_array_elements(p_registration->'origins') o; + IF cardinality(origin_list)<>jsonb_array_length(p_registration->'origins') + OR to_jsonb(origin_list) IS DISTINCT FROM (SELECT jsonb_agg(o->'origin') FROM jsonb_array_elements(p_registration->'origins') o) + OR total_urls NOT BETWEEN 1 AND 32 THEN RAISE EXCEPTION 'invalid origins or total return URLs'; END IF; + SELECT array_agg(u ORDER BY u COLLATE "C") INTO return_list FROM jsonb_array_elements(p_registration->'origins') o, + LATERAL jsonb_array_elements_text(o->'return_urls') t(u); + application_id:=gen_random_uuid(); receipt_id:=gen_random_uuid(); at_time:=clock_timestamp(); + IF authority.expires_at<=at_time THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + INSERT INTO application_registration_proposal.applications(workspace_id,id,billing_owner_id,name) + VALUES(p_workspace,application_id,p_workspace,p_registration->>'name'); + INSERT INTO application_registration_proposal.environments(workspace_id,application_id,environment) + VALUES(p_workspace,application_id,p_environment); + FOR item IN SELECT value FROM jsonb_array_elements(p_registration->'origins') LOOP + INSERT INTO application_registration_proposal.origins(workspace_id,application_id,environment,origin,hostname,return_urls) + VALUES(p_workspace,application_id,p_environment,item->>'origin',item->>'hostname',ARRAY(SELECT jsonb_array_elements_text(item->'return_urls'))); + END LOOP; + snapshot:=jsonb_build_object('workspace_id',p_workspace,'application_id',application_id,'name',p_registration->>'name', + 'environment',p_environment,'allowed_origins',origin_list,'return_urls',return_list,'origins', + (SELECT jsonb_agg(jsonb_build_object('origin',o,'config_revision',1,'proof_revision',1,'cas_revision',1,'revoked',false) ORDER BY o COLLATE "C") FROM unnest(origin_list) o)); + result_value:=jsonb_build_object('receipt_id',receipt_id,'application_id',application_id,'actor',p_actor, + 'workspace_id',p_workspace,'billing_owner_id',p_workspace,'environment',p_environment,'recorded_at',at_time, + 'entitlement_revision',authority.revision,'policy_version',authority.policy_version,'snapshot',snapshot, + 'origins_verified',false,'bootstrap_enabled',false,'access_activated',false,'runtime_enabled',false, + 'production_persisted',false,'policy_status','proposed_unadopted','evidence_kind','disposable_parent_assertion'); + INSERT INTO application_registration_proposal.receipts VALUES(receipt_id,p_actor,p_workspace,application_id,p_environment,at_time,result_value); + INSERT INTO application_registration_proposal.requests VALUES(p_actor,p_workspace,p_key,fingerprint,receipt_id); + RETURN result_value; +END $$; +CREATE FUNCTION application_registration_proposal.read_registration( + p_actor uuid,p_workspace uuid,p_application uuid,p_environment text,p_receipt uuid +) RETURNS jsonb LANGUAGE plpgsql SET search_path='' AS $$ +DECLARE result_value jsonb; +BEGIN + PERFORM application_registration_proposal.authorize_management(p_actor,p_workspace,p_application,p_environment,'read_registration'); + SELECT r.result INTO result_value FROM application_registration_proposal.receipts r + WHERE r.id=p_receipt AND r.workspace_id=p_workspace AND r.application_id=p_application AND r.environment=p_environment; + IF NOT FOUND THEN RAISE EXCEPTION 'authority unavailable' USING ERRCODE='42501'; END IF; + RETURN result_value; +END $$; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA application_registration_proposal FROM PUBLIC; diff --git a/proposals/application-registration-2104/sources.json b/proposals/application-registration-2104/sources.json new file mode 100644 index 0000000..b682af0 --- /dev/null +++ b/proposals/application-registration-2104/sources.json @@ -0,0 +1,63 @@ +{ + "apiCommit": "1fff6b55b8c1b98826c375f99b4f4f66a5ba201c", + "databaseCommit": "7708e337feca212563bdfa48934a72227bcf1b63", + "api": [ + { + "path": "lib/applications/applicationRegistrationSchema.ts", + "sha256": "5bfb55ded25eae323bea02b535d6fb010eec5b2a767b891a13b86e4c91427a30" + }, + { + "path": "lib/applications/validateApplicationRegistration.ts", + "sha256": "b842cd312e0123a65ec1dd872c54474f77872b337ef5285ecedff1dad96ac0c6" + }, + { + "path": "lib/auth/validateAuthContext.ts", + "sha256": "055ac2965db8487c8f67d74c549101d866968ed507d295498ed4485d62867c28" + }, + { + "path": "lib/auth/VerificationEvidence.ts", + "sha256": "51c089a2459f50d2ac2e23955de6a3cbdb1ec9033fd1ba6ae3b0b71f36588eb1" + }, + { + "path": "lib/auth/getAccountIdByApiKey.ts", + "sha256": "5512a0c0ad1f293d2d226e9cb162b68fdb11706a0407bf95dbdcea54f29ee503" + } + ], + "composition": [ + { + "path": "proposals/application-proof-2104/proposal.sql", + "sha256": "2cf96399422cfc1e68b0578b7aeb7b58a97c56303d85b91ee6cf862329f6c86c", + "bindings": [ + { + "from": "proof_parent_fixture.", + "to": "application_registration_proposal.", + "count": 7 + } + ] + }, + { + "path": "proposals/application-proof-2104/configuration.sql", + "sha256": "148819c1363929e990bf2cfd67bae02f7567c2e2e2a05732cb17ea2248bad3b1", + "bindings": [ + { + "from": "proof_parent_fixture.", + "to": "application_registration_proposal.", + "count": 14 + } + ] + } + ], + "cleanupSource": { + "repository": "recoupable/api", + "commit": "ddd614c998ffdbc837f8bfde58333350c36d648c", + "path": "scripts/sites-evidence-sql-bridge/stop_owned_cluster.py", + "sha256": "56c6852acbf7ed91f33c3634878ffb7418f184653c546d56c28a78c31506f8a5" + }, + "authorityAdapterSha256": "947922a043d8e44f09ad06c81c0f28241d5add5d035085672faa950cf356dac1", + "workerCleanupSource": { + "repository": "recoupable/api", + "commit": "ddd614c998ffdbc837f8bfde58333350c36d648c", + "path": "scripts/sites-evidence-sql-bridge/quiesce_worker.py", + "sha256": "03a15bdb69513d2391bd5df7602f2b893b67d82bdce8dab3ec339f5968dd2f05" + } +} diff --git a/proposals/application-registration-2104/test_registration.py b/proposals/application-registration-2104/test_registration.py new file mode 100644 index 0000000..8fc37a1 --- /dev/null +++ b/proposals/application-registration-2104/test_registration.py @@ -0,0 +1,477 @@ +"""New parent transactions only. Parent owns Unix cluster; no hosted DSN accepted.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import unittest +from concurrent.futures import ThreadPoolExecutor + +HERE = Path(__file__).resolve().parent +S = 'application_registration_proposal' +A = '00000000-0000-0000-0000-000000000001' +B = '00000000-0000-0000-0000-000000000002' + +def quote(value): + return "'" + str(value).replace("'", "''") + "'" + + +def payload(): + return {'name': 'Music', 'origins': [ + {'origin': 'https://music.example', 'hostname': 'music.example', + 'return_urls': ['https://music.example/return']}, + {'origin': 'https://preview.example', 'hostname': 'preview.example', 'return_urls': []}]} + + +class Registration(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.socket, cls.bin = verify_worker_lease() + clean_env = {k:v for k,v in os.environ.items() if not k.startswith('PG')} + cls.env = {**clean_env, 'PGHOST': cls.socket, 'PGPORT': '55473', 'PGDATABASE': 'postgres', + 'PGOPTIONS': '-c statement_timeout=10000 -c lock_timeout=8000'} + for filename in ['qualification-bootstrap.sql', 'parents.sql', 'registration.sql']: + cls.sql((HERE / filename).read_text()) + spec = importlib.util.spec_from_file_location('composition', HERE / 'protocol-composition.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + cls.sql(module.compose()) + cls.sql('CREATE ROLE qualification_browser NOLOGIN;') + + @classmethod + def args(cls): + return [str(cls.bin / 'psql'), '-XqAt', '-v', 'ON_ERROR_STOP=1'] + + @classmethod + def sql(cls, sql, name='registration-test'): + r = subprocess.run(cls.args(), input=sql, env={**cls.env, 'PGAPPNAME': name}, + capture_output=True, text=True, timeout=15) + if r.returncode: + raise AssertionError(r.stderr) + return r.stdout.strip() + + def setUp(self): + self.sql(f'TRUNCATE {S}.personal_principals CASCADE;') + self.sql(f"INSERT INTO {S}.personal_principals(account_id) VALUES ('{A}'),('{B}');") + self.sql(f"INSERT INTO {S}.create_entitlements(actor,workspace_id,environment) " + f"SELECT account_id,account_id,e FROM {S}.personal_principals CROSS JOIN " + "unnest(ARRAY['production','development']) e;") + + def statement(self, actor=A, workspace=A, env='production', key='create', rev=1, body=None): + args = [quote(actor), quote(workspace), quote(env), quote(key), str(rev), + quote(json.dumps(payload() if body is None else body)) + '::jsonb'] + return f"SELECT {S}.register_application(" + ','.join(args) + ');' + + def create(self, **kw): + return json.loads(self.sql(self.statement(**kw))) + + def deny(self, sql, message='authority unavailable'): + with self.assertRaisesRegex(AssertionError, message): + self.sql(sql) + + def grant_management(self, app, ops, actor=A, env='production'): + self.sql(f"INSERT INTO {S}.management_entitlements(actor,workspace_id,application_id,environment,operation) " + f"SELECT '{actor}','{actor}',{quote(app)},{quote(env)},op FROM unnest(ARRAY[" + + ','.join(quote(x) for x in ops) + ']) op;') + + def proof(self, app, operation='issue', key='proof', revisions=(1, 1, 1), data=None, **kw): + values = [kw.get('actor', A), kw.get('workspace', A), app, kw.get('env', 'production'), + 'https://music.example', operation, key] + return 'SELECT application_proof_proposal.transact(' + ','.join(quote(x) for x in values) + ',' + \ + ','.join(str(x) for x in revisions) + ',' + quote(json.dumps(data or {'digest': 'a' * 64})) + '::jsonb);' + + def read_receipt(self, r, **kw): + return f"SELECT {S}.read_registration(" + ','.join(quote(x) for x in [ + kw.get('actor', A), kw.get('workspace', A), kw.get('app', r['application_id']), + kw.get('env', 'production'), r['receipt_id']]) + ');' + + def test_create_disabled_isolated_and_no_implicit_management(self): + r = self.create() + for flag in ['origins_verified', 'bootstrap_enabled', 'access_activated', 'runtime_enabled', 'production_persisted']: + self.assertIs(r[flag], False) + self.assertEqual(r['policy_status'], 'proposed_unadopted') + self.assertEqual(r['billing_owner_id'], A) + self.assertEqual(r['snapshot']['allowed_origins'], [x['origin'] for x in payload()['origins']]) + self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.management_entitlements'), '0') + self.deny(self.proof(r['application_id'])) + self.deny(self.read_receipt(r)) + other = self.create(actor=B, workspace=B) + dev = self.create(env='development', key='dev') + self.assertEqual(len({r['application_id'], other['application_id'], dev['application_id']}), 3) + self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.environments'), '3') + + def test_denial_actor_workspace_environment_operation_personal_classification(self): + for kw in [{'actor': B}, {'workspace': B}, {'env': 'staging'}]: + self.deny(self.statement(**kw), 'authority unavailable|invalid input') + self.sql(f"DELETE FROM {S}.create_entitlements WHERE actor='{A}'") + self.deny(self.statement()) + self.sql(f"UPDATE {S}.personal_principals SET enabled=false WHERE account_id='{B}'") + self.deny(self.statement(actor=B, workspace=B)) + self.deny(self.statement(actor='00000000-0000-0000-0000-000000000099', workspace='00000000-0000-0000-0000-000000000099')) + + def test_revision_changed_key_lost_response_replay_and_revoked_replay(self): + self.deny(self.statement(rev=2), 'revision conflict') + r = self.create() + self.assertEqual(self.create(), r) + for kw in [{'rev': 2}, {'body': {**payload(), 'name': 'Changed'}}, {'env': 'development'}]: + self.deny(self.statement(**kw), 'idempotency conflict') + self.sql(f"UPDATE {S}.create_entitlements SET revision=2 WHERE actor='{A}'") + self.assertEqual(self.create(), r) # current authority, original exact input/history + self.deny(self.statement(key='new'), 'revision conflict') + self.sql(f"UPDATE {S}.create_entitlements SET enabled=false WHERE actor='{A}'") + self.deny(self.statement()) + self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.applications'), '1') + self.deny(f"UPDATE {S}.receipts SET result='{{}}'::jsonb", 'immutable') + self.deny(f'DELETE FROM {S}.requests', 'immutable') + + def test_receipt_read_binding_and_current_authority(self): + r = self.create() + other = self.create(key='other') + self.grant_management(r['application_id'], ['read_registration']) + self.assertEqual(json.loads(self.sql(self.read_receipt(r))), r) + for kw in [{'actor': B}, {'workspace': B}, {'env': 'development'}, {'app': other['application_id']}]: + self.deny(self.read_receipt(r, **kw)) + self.sql(f'UPDATE {S}.management_entitlements SET enabled=false') + self.deny(self.read_receipt(r)) + + def test_explicit_and_mid_parent_failure_rollback(self): + self.sql('BEGIN;' + self.statement() + 'ROLLBACK;') + self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.applications'), '0') + self.sql(f"""CREATE FUNCTION qualification_auth.fail_origin() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.origin='https://preview.example' THEN RAISE EXCEPTION 'forced second origin failure'; END IF; RETURN NEW; END $$; + CREATE TRIGGER fail_second BEFORE INSERT ON {S}.origins FOR EACH ROW EXECUTE FUNCTION qualification_auth.fail_origin();""") + try: + self.deny(self.statement(), 'forced second origin') + for table in ['applications', 'environments', 'origins', 'receipts', 'requests']: + self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.{table}'), '0') + finally: + self.sql(f'DROP TRIGGER fail_second ON {S}.origins; DROP FUNCTION qualification_auth.fail_origin();') + + def test_input_bounds_and_no_invented_authority_fields(self): + for body in [{}, {**payload(), 'actor': A}, {**payload(), 'name': ''}, + {**payload(), 'origins': []}, + {**payload(), 'origins': [payload()['origins'][0]] * 2}, + {**payload(), 'origins': [{**payload()['origins'][0], 'hostname': 'other.example'}]}, + {**payload(), 'origins': [{**payload()['origins'][0], 'return_urls': ['https://evil.example/']}]}]: + self.deny(self.statement(body=body), 'invalid') + self.deny('BEGIN ISOLATION LEVEL REPEATABLE READ;' + self.statement(), 'read committed') + + def test_no_public_table_or_helper_privileges(self): + for schema in [S, 'application_proof_proposal']: + self.assertEqual(self.sql(f"SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON p.pronamespace=n.oid WHERE n.nspname={quote(schema)} AND has_function_privilege('qualification_browser',p.oid,'EXECUTE')"), '0') + self.assertEqual(self.sql(f"SELECT count(*) FROM pg_class c JOIN pg_namespace n ON c.relnamespace=n.oid WHERE n.nspname={quote(schema)} AND c.relkind='r' AND has_table_privilege('qualification_browser',c.oid,'SELECT,INSERT,UPDATE,DELETE')"), '0') + self.deny('SET ROLE qualification_browser;' + self.statement(), 'permission denied') + self.deny(f"SET ROLE qualification_browser; SELECT {S}.authorize_create('{A}','{A}','production');", 'permission denied') + + def test_direct_remote_worker_target_rejected_before_sql(self): + r = subprocess.run([sys.executable, str(Path(__file__).resolve()), '--worker'], + env={**os.environ, 'REGISTRATION_QUALIFICATION_SOCKET': 'example.invalid', 'PGPASSWORD': 'synthetic-unusable'}, + capture_output=True, text=True, timeout=5) + self.assertNotEqual(r.returncode, 0) + self.assertIn('Owned absolute Unix socket directory required', r.stderr) + self.assertNotIn('synthetic-unusable', r.stderr) + + def test_synthetic_auth_boundary_not_a_database_credential_verifier(self): + self.assertEqual(self.sql("SELECT qualification_auth.original_actor('current-key')"), A) + for token in ['missing', 'revoked-key', 'wrong-actor-key', 'changed-key']: + self.deny(f"SELECT qualification_auth.original_actor({quote(token)})", 'verification unavailable') + # Only the qualification stub has credential observations; proposed tables store none. + self.assertEqual(self.sql(f"SELECT count(*) FROM information_schema.columns WHERE table_schema='{S}' AND column_name ~ '(token|credential|key_hash)'"), '0') + + def test_composition_issue_configure_cas_and_disabled_history(self): + r = self.create(); app = r['application_id'] + self.grant_management(app, ['issue', 'read', 'replace_existing_origin_return_urls']) + issued = json.loads(self.sql(self.proof(app))) + expected = json.loads(self.sql(f"SELECT application_proof_proposal.configuration_snapshot('{A}',{quote(app)},'production')")) + changes = [{'origin': 'https://music.example', 'expected': {'config_revision': 1, 'proof_revision': 1, 'cas_revision': 2}, + 'next': {'config_revision': 2, 'proof_revision': 1, 'cas_revision': 3}, 'return_urls': ['https://music.example/new']}] + stmt = f"SELECT application_proof_proposal.configure_return_urls('{A}','{A}',{quote(app)},'production','config',{quote(json.dumps(expected))}::jsonb,{quote(json.dumps(changes))}::jsonb);" + configured = json.loads(self.sql(stmt)); self.assertEqual(json.loads(self.sql(stmt)), configured) + self.assertFalse(configured['access_activated']); self.assertFalse(configured['bootstrap_enabled']) + self.assertEqual(self.sql('SELECT state FROM application_proof_proposal.challenges WHERE id='+quote(issued['challenge_id'])), 'superseded') + self.deny(stmt.replace("'config'", "'different'"), 'snapshot conflict') + for kw in [{'env': 'development'}, {'workspace': B}, {'actor': B}]: + self.deny(self.proof(app, **kw)) + self.deny(self.proof(app, key='stale'), 'revision conflict') + + def holder(self, sql): + p = subprocess.Popen(self.args(), env={**self.env, 'PGAPPNAME': 'registration-holder'}, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(lambda: p.poll() is None and p.kill()) + p.stdin.write('BEGIN;'+sql+"SELECT 'held';\n"); p.stdin.flush() + # Reading marker is bounded by PostgreSQL statement_timeout and select readiness. + import select + deadline = time.monotonic()+12 + output = '' + while time.monotonic() 1: + raise RuntimeError('Multiple postmasters bound to lease; preserve root') + pid = metadata.get('postmaster_pid') + if pidfile.exists(): + lines = pidfile.read_text().splitlines() + pid = int(lines[0]) + if pathlib.Path(lines[1]).resolve() != cluster: + raise RuntimeError('Postmaster data directory mismatch; preserve root') + if discovered and discovered != [pid]: + raise RuntimeError('Postmaster PID identity mismatch; preserve root') + if discovered: + result = subprocess.run([str(pg_bin / 'pg_ctl'), '-D', str(cluster), '-m', 'immediate', '-w', '-t', '5', 'stop'], env=env, capture_output=True, text=True, timeout=8) + if result.returncode: + raise RuntimeError('Parent could not stop owned PostgreSQL: ' + result.stderr) + elif discovered: + # A detached postmaster can precede its PID/socket files. Independently + # bind its command to the exact owned -D path before targeted immediate stop. + pid = discovered[0] + if _owned_postmasters(cluster) != [pid]: + raise RuntimeError('Startup process identity changed; preserve root') + os.kill(pid, signal.SIGQUIT) + deadline = time.monotonic() + 8 + while _owned_postmasters(cluster) and time.monotonic() < deadline: + time.sleep(0.05) + if _owned_postmasters(cluster) or (pid and _process_command(pid)): + raise RuntimeError('Recorded postmaster still present; preserve root') + socket_file = socket / '.s.PGSQL.55473' + if socket_file.exists(): + raise RuntimeError('Owned PostgreSQL socket still present; preserve root') + return {'cluster_created': True, 'registered_socket': str(socket), 'registered_cluster': str(cluster), + 'postmaster_pid': pid, 'discovered_postmasters': discovered, + 'postmaster_absent': True, 'socket_absent': True} + +# Reviewed group cleanup, copied byte-for-byte; provenance in sources.json. +"""Quiesce only the dedicated fixture worker process group.""" +import os +import signal +import subprocess +import time + + +def _group_exists(group): + try: + os.killpg(group, 0) + return True + except ProcessLookupError: + return False + + +def quiesce_worker(worker): + """Signal only the session/group created for this exact Popen child.""" + group = worker.pid # start_new_session=True establishes PID == PGID == SID. + if _group_exists(group): + os.killpg(group, signal.SIGTERM) + try: + worker.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + if _group_exists(group): + os.killpg(group, signal.SIGKILL) + worker.wait(timeout=5) + deadline = time.monotonic() + 5 + while _group_exists(group) and time.monotonic() < deadline: + time.sleep(0.05) + if _group_exists(group): + raise RuntimeError('Fixture process group not quiescent; preserve owned files') + return {'worker_pid': worker.pid, 'worker_group_absent': True, 'worker_returncode': worker.returncode} + +if __name__ == '__main__': + if sys.argv[1:] == ['--worker']: + socket, pg_bin = verify_worker_lease() + fault = os.environ.get('REGISTRATION_QUALIFICATION_FAULT') + if fault == 'timeout': time.sleep(30) + if fault == 'worker-exit': + subprocess.Popen([str(pg_bin/'psql'), '-XqAt', '-h', socket, '-p', '55473', '-d', 'postgres', '-c', 'SELECT pg_sleep(30)'], env={k:v for k,v in os.environ.items() if not k.startswith('PG')}) + time.sleep(.1) + raise SystemExit(86) + unittest.main(argv=[sys.argv[0]], verbosity=2) + elif len(sys.argv) == 1: + raise SystemExit(supervise()) + else: + raise SystemExit('No connection strings or external targets accepted') From 4662ff9f60ee77ee74bfd82fde1c9e5410f3c96d Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:25:14 -0500 Subject: [PATCH 2/5] fix: isolate application qualification process environments --- .../PARENT-CONTRACT.md | 13 ++- .../test_registration.py | 83 +++++++++++++++++-- 2 files changed, 87 insertions(+), 9 deletions(-) diff --git a/proposals/application-registration-2104/PARENT-CONTRACT.md b/proposals/application-registration-2104/PARENT-CONTRACT.md index d731482..0c4f39b 100644 --- a/proposals/application-registration-2104/PARENT-CONTRACT.md +++ b/proposals/application-registration-2104/PARENT-CONTRACT.md @@ -175,7 +175,18 @@ starts Unix-socket-only PostgreSQL, launches a dedicated worker process group, a stops/removes only that verified lease. No hosted connection string is accepted. The internal worker verifies absolute local socket path, UID/device/inode, parent PID, registered binary directory and postmaster identity **before SQL**; connection-related -PG variables are stripped. The marker/lease is an accidental-target guard, not an OS +variables are constructed from an allowlist, not copied from the ambient environment. +HOME/TMPDIR point to owned fixture directories; PATH contains only resolved PostgreSQL/ +Python directories and system binaries; LANG/LC_ALL/TZ are fixed. `initdb -E UTF8` +preserves Unicode/JSON semantics despite the C locale; qualification asserts server +encoding and a Unicode registration round trip. Only the explicit +socket/binary/validated fault controls accompany them. Worker SQL receives fixed +PGHOST/PORT/DATABASE/OPTIONS and an explicit application name. The supervisor clears +its inherited environment before launching any fixture or cleanup subprocess; workers +launch with isolated Python (-I) and scrub again before lease-check subprocesses. +Synthetic poison tests verify unrelated service, libpq service/password and loader/ +Python variables are absent from actual child environments. No real credential values +or home credential files are inspected. The marker/lease is an accidental-target guard, not an OS security boundary against a malicious local owner who can edit the runner itself. SQL, process startup, worker duration and cleanup have bounded waits. Scoped SIGTERM/ diff --git a/proposals/application-registration-2104/test_registration.py b/proposals/application-registration-2104/test_registration.py index 8fc37a1..fc0b522 100644 --- a/proposals/application-registration-2104/test_registration.py +++ b/proposals/application-registration-2104/test_registration.py @@ -33,7 +33,7 @@ class Registration(unittest.TestCase): @classmethod def setUpClass(cls): cls.socket, cls.bin = verify_worker_lease() - clean_env = {k:v for k,v in os.environ.items() if not k.startswith('PG')} + clean_env = fixture_environment(Path(cls.socket).parent, cls.bin) cls.env = {**clean_env, 'PGHOST': cls.socket, 'PGPORT': '55473', 'PGDATABASE': 'postgres', 'PGOPTIONS': '-c statement_timeout=10000 -c lock_timeout=8000'} for filename in ['qualification-bootstrap.sql', 'parents.sql', 'registration.sql']: @@ -169,8 +169,38 @@ def test_no_public_table_or_helper_privileges(self): self.deny('SET ROLE qualification_browser;' + self.statement(), 'permission denied') self.deny(f"SET ROLE qualification_browser; SELECT {S}.authorize_create('{A}','{A}','production');", 'permission denied') + def test_database_encoding_is_utf8(self): + self.assertEqual(self.sql('SHOW server_encoding'), 'UTF8') + self.assertEqual(self.create(body={**payload(), 'name': 'Música 音楽'})['snapshot']['name'], 'Música 音楽') + + def test_minimal_owned_environment_drops_synthetic_poison(self): + from unittest.mock import patch + socket = Path(self.socket) + poison = {key: 'synthetic-poison-do-not-forward' for key in [ + 'UNRELATED_SERVICE_SECRET', 'PGSERVICE', 'PGSERVICEFILE', 'PGPASSWORD', + 'PGPASSFILE', 'PGHOSTADDR', 'PYTHONPATH', 'PYTHONHOME', 'LD_PRELOAD', + 'DYLD_INSERT_LIBRARIES', 'NODE_OPTIONS', 'ENV', 'BASH_ENV']} + with patch.dict(os.environ, poison): + clean = fixture_environment(socket.parent, self.bin) + self.assertTrue(set(poison).isdisjoint(clean)) + self.assertTrue(set(poison).isdisjoint(os.environ)) + self.assertEqual(clean['HOME'], str(socket.parent/'home')) + self.assertEqual(clean['TMPDIR'], str(socket.parent/'tmp')) + self.assertEqual(os.environ['HOME'], clean['HOME']) + self.assertEqual(self.env['HOME'], clean['HOME']) + self.assertEqual(self.env['PGHOST'], self.socket) + self.assertEqual(set(self.env)-set(clean), {'PGHOST','PGPORT','PGDATABASE','PGOPTIONS'}) + probe = subprocess.run([str(Path(sys.executable).resolve()), '-I', '-c', + 'import json,os; print(json.dumps(dict(os.environ),sort_keys=True))'], + env=clean, capture_output=True, text=True, check=True, timeout=5) + actual = json.loads(probe.stdout) + # macOS CoreFoundation may synthesize this runtime encoding entry after exec. + self.assertLessEqual(set(actual)-set(clean), {'__CF_USER_TEXT_ENCODING'}) + self.assertTrue(set(poison).isdisjoint(actual)) + self.assertEqual({key: actual[key] for key in clean}, clean) + def test_direct_remote_worker_target_rejected_before_sql(self): - r = subprocess.run([sys.executable, str(Path(__file__).resolve()), '--worker'], + r = subprocess.run([str(Path(sys.executable).resolve()), '-I', str(Path(__file__).resolve()), '--worker'], env={**os.environ, 'REGISTRATION_QUALIFICATION_SOCKET': 'example.invalid', 'PGPASSWORD': 'synthetic-unusable'}, capture_output=True, text=True, timeout=5) self.assertNotEqual(r.returncode, 0) @@ -271,6 +301,39 @@ def test_expiry_after_observed_idempotency_lock_wait(self): self.assertEqual(self.sql(f'SELECT count(*) FROM {S}.applications'), '0') +def fixture_environment(root, pg_bin, fault=None): + """Allowlist only owned paths and fixed controls; never copy ambient values.""" + metadata = json.loads((root/'fixture-owner.json').read_text()) + socket = Path(metadata['socket']) + if not root.is_absolute() or root.resolve() != root or socket.parent != root: + raise RuntimeError('Owned absolute fixture root required') + for directory in [root/'home', root/'tmp']: + if directory.is_symlink() or not directory.is_dir() or directory.stat().st_uid != os.getuid(): + raise RuntimeError('Owned fixture home/tmp directory required') + if fault not in (None, 'signal', 'timeout', 'worker-exit'): + raise RuntimeError('Unknown qualification fault') + env = {'HOME': str(root/'home'), 'TMPDIR': str(root/'tmp'), + 'PATH': os.pathsep.join([str(pg_bin), str(Path(sys.executable).resolve().parent), '/usr/bin', '/bin']), + 'LANG': 'C', 'LC_ALL': 'C', 'TZ': 'UTC', + 'REGISTRATION_QUALIFICATION_BIN': str(pg_bin), + 'REGISTRATION_QUALIFICATION_SOCKET': str(socket)} + if fault is not None: env['REGISTRATION_QUALIFICATION_FAULT'] = fault + return env + + +def prepare_worker_environment(): + """Scrub before even lease-check subprocesses; then validate the registered owner.""" + socket = Path(os.environ['REGISTRATION_QUALIFICATION_SOCKET']) + if not socket.is_absolute() or socket.is_symlink() or socket.resolve() != socket: + raise RuntimeError('Owned absolute Unix socket directory required') + pg_bin = Path(os.environ['REGISTRATION_QUALIFICATION_BIN']) + fault = os.environ.get('REGISTRATION_QUALIFICATION_FAULT') + env = fixture_environment(socket.parent, pg_bin, fault) + os.environ.clear() + os.environ.update(env) + return verify_worker_lease() + + def verify_worker_lease(): """Reject direct/remote worker targets before any SQL or environment forwarding.""" import stat @@ -303,20 +366,24 @@ def interrupted(_signum, _frame): def supervise(): """Own one random cluster; stop only after exact directory/process identity checks.""" pg_bin = Path(os.environ.get('PG_BIN', '/opt/homebrew/opt/postgresql@15/bin')).resolve() + fault = os.environ.get('REGISTRATION_QUALIFICATION_FAULT') root = Path(tempfile.mkdtemp(prefix='registration-qual-', dir='/private/tmp' if Path('/private/tmp').exists() else '/tmp')).resolve() socket = Path(tempfile.mkdtemp(prefix='recoup-cases-', dir=root)).resolve() cluster = socket / 'pg'; info = socket.stat() (root/'fixture-owner.json').write_text(json.dumps({'socket': str(socket), 'cluster': str(cluster), 'uid': info.st_uid, 'device': info.st_dev, 'inode': info.st_ino, 'worker_pid': os.getpid(), 'pg_bin': str(pg_bin)})) - env = {k:v for k,v in os.environ.items() if not k.startswith('PG')} - env.update({'REGISTRATION_QUALIFICATION_BIN': str(pg_bin), 'REGISTRATION_QUALIFICATION_SOCKET': str(socket)}) + (root/'home').mkdir(mode=0o700) + (root/'tmp').mkdir(mode=0o700) + env = fixture_environment(root, pg_bin, fault) + os.environ.clear() + os.environ.update(env) worker = None old_handlers = {sig: signal.signal(sig, interrupted) for sig in (signal.SIGTERM, signal.SIGINT)} try: - subprocess.run([str(pg_bin/'initdb'), '-D', str(cluster), '-A', 'trust'], env=env, check=True, capture_output=True, timeout=30) + subprocess.run([str(pg_bin/'initdb'), '-D', str(cluster), '-A', 'trust', '-E', 'UTF8'], env=env, check=True, capture_output=True, timeout=30) subprocess.run([str(pg_bin/'pg_ctl'), '-D', str(cluster), '-l', str(root/'postgres.log'), '-w', '-t', '10', '-o', f"-k {socket} -p 55473 -c listen_addresses=''", 'start'], env=env, check=True, capture_output=True, timeout=15) - worker = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), '--worker'], env=env, start_new_session=True) + worker = subprocess.Popen([str(Path(sys.executable).resolve()), '-I', str(Path(__file__).resolve()), '--worker'], env=env, start_new_session=True) if env.get('REGISTRATION_QUALIFICATION_FAULT') == 'signal': os.kill(os.getpid(), signal.SIGTERM) return worker.wait(timeout=.3 if env.get('REGISTRATION_QUALIFICATION_FAULT') == 'timeout' else 120) @@ -463,11 +530,11 @@ def quiesce_worker(worker): if __name__ == '__main__': if sys.argv[1:] == ['--worker']: - socket, pg_bin = verify_worker_lease() + socket, pg_bin = prepare_worker_environment() fault = os.environ.get('REGISTRATION_QUALIFICATION_FAULT') if fault == 'timeout': time.sleep(30) if fault == 'worker-exit': - subprocess.Popen([str(pg_bin/'psql'), '-XqAt', '-h', socket, '-p', '55473', '-d', 'postgres', '-c', 'SELECT pg_sleep(30)'], env={k:v for k,v in os.environ.items() if not k.startswith('PG')}) + subprocess.Popen([str(pg_bin/'psql'), '-XqAt', '-h', socket, '-p', '55473', '-d', 'postgres', '-c', 'SELECT pg_sleep(30)'], env=fixture_environment(Path(socket).parent, pg_bin)) time.sleep(.1) raise SystemExit(86) unittest.main(argv=[sys.argv[0]], verbosity=2) From df7be4c65b98924373b38c7d257f4b1c1820d6b7 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:28:20 -0500 Subject: [PATCH 3/5] fix: verify owned worker group after denied signal probe --- .../PARENT-CONTRACT.md | 9 +++++-- .../sources.json | 3 ++- .../test_registration.py | 27 ++++++++++++++++++- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/proposals/application-registration-2104/PARENT-CONTRACT.md b/proposals/application-registration-2104/PARENT-CONTRACT.md index 0c4f39b..c5f2cc2 100644 --- a/proposals/application-registration-2104/PARENT-CONTRACT.md +++ b/proposals/application-registration-2104/PARENT-CONTRACT.md @@ -191,8 +191,13 @@ security boundary against a malicious local owner who can edit the runner itself SQL, process startup, worker duration and cleanup have bounded waits. Scoped SIGTERM/ SIGINT unwind cleanup; the worker group is quiesced even if its leader exited. The -exact reviewed worker-group and directory/PID cleanup functions are embedded with source -hashes in `sources.json`. That reuse alone does not inherit all prior supervisor tests. +reviewed directory/PID cleanup is embedded unchanged. The worker-group helper has one +explicitly recorded adaptation after an actual host PermissionError on killpg(group,0): +only that denial falls back to checked, complete numeric `/bin/ps -axo pgid=` enumeration +for the exact registered group. Command failure, malformed/empty output or timeout fails +closed. A present group still needs successful signaling; absence never substitutes for +independent postmaster/socket checks. Original provenance and the adaptation are recorded +in `sources.json`. That reuse alone does not inherit all prior supervisor tests. This candidate separately exercises signal, worker timeout and exited-worker-with-child faults via `REGISTRATION_QUALIFICATION_FAULT=signal|timeout|worker-exit`, using only its own disposable cluster. Ambiguous ownership leaves files intact with a reported path. diff --git a/proposals/application-registration-2104/sources.json b/proposals/application-registration-2104/sources.json index b682af0..154f1b5 100644 --- a/proposals/application-registration-2104/sources.json +++ b/proposals/application-registration-2104/sources.json @@ -58,6 +58,7 @@ "repository": "recoupable/api", "commit": "ddd614c998ffdbc837f8bfde58333350c36d648c", "path": "scripts/sites-evidence-sql-bridge/quiesce_worker.py", - "sha256": "03a15bdb69513d2391bd5df7602f2b893b67d82bdce8dab3ec339f5968dd2f05" + "sha256": "03a15bdb69513d2391bd5df7602f2b893b67d82bdce8dab3ec339f5968dd2f05", + "adaptation": "_group_exists: only on killpg(group,0) PermissionError, checked complete numeric /bin/ps -axo pgid= enumeration establishes exact group presence; failures/malformed output/timeouts preserve files. Other helper logic unchanged." } } diff --git a/proposals/application-registration-2104/test_registration.py b/proposals/application-registration-2104/test_registration.py index fc0b522..08d6f52 100644 --- a/proposals/application-registration-2104/test_registration.py +++ b/proposals/application-registration-2104/test_registration.py @@ -29,6 +29,21 @@ def payload(): {'origin': 'https://preview.example', 'hostname': 'preview.example', 'return_urls': []}]} +class GroupProbe(unittest.TestCase): + def test_permission_denied_probe_requires_checked_group_enumeration(self): + from unittest.mock import patch + with patch.object(os, 'killpg', side_effect=PermissionError('synthetic probe denial')): + for stdout, present in [('101\n202\n', False), ('101\n4242\n', True)]: + with patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, stdout, '')) as run: + self.assertEqual(_group_exists(4242), present) + run.assert_called_once_with(['/bin/ps', '-axo', 'pgid='], capture_output=True, text=True, timeout=5) + for status, stdout in [(1, ''), (0, ''), (0, 'not-a-group\n')]: + with patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], status, stdout, '')): + with self.assertRaises(RuntimeError): _group_exists(4242) + with patch.object(subprocess, 'run', side_effect=subprocess.TimeoutExpired('ps', 5)): + with self.assertRaises(subprocess.TimeoutExpired): _group_exists(4242) + + class Registration(unittest.TestCase): @classmethod def setUpClass(cls): @@ -493,7 +508,7 @@ def stop_owned_cluster(root, pg_bin, env, worker_pid): 'postmaster_pid': pid, 'discovered_postmasters': discovered, 'postmaster_absent': True, 'socket_absent': True} -# Reviewed group cleanup, copied byte-for-byte; provenance in sources.json. +# Reviewed group cleanup, with a narrow PermissionError enumeration adaptation; provenance in sources.json. """Quiesce only the dedicated fixture worker process group.""" import os import signal @@ -507,6 +522,16 @@ def _group_exists(group): return True except ProcessLookupError: return False + except PermissionError: + # An actual exited-worker probe was denied by the host. Require independent + # complete process metadata; never infer absence from a signal denial. + result = subprocess.run(['/bin/ps', '-axo', 'pgid='], capture_output=True, text=True, timeout=5) + if result.returncode: + raise RuntimeError('Cannot enumerate worker groups; preserve owned files') + groups = result.stdout.splitlines() + if not groups or any(not line.strip().isascii() or not line.strip().isdigit() for line in groups): + raise RuntimeError('Invalid worker group enumeration; preserve owned files') + return group in {int(line.strip()) for line in groups} def quiesce_worker(worker): From f507a77696f20429f977df9885d6c8c11a5f304b Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:10:13 -0500 Subject: [PATCH 4/5] Define structured proposal registration conflict outcome --- .../PARENT-CONTRACT.md | 26 +++++++++ .../registration.sql | 4 +- .../test_registration.py | 53 +++++++++++++++++++ 3 files changed, 81 insertions(+), 2 deletions(-) diff --git a/proposals/application-registration-2104/PARENT-CONTRACT.md b/proposals/application-registration-2104/PARENT-CONTRACT.md index c5f2cc2..a2971d5 100644 --- a/proposals/application-registration-2104/PARENT-CONTRACT.md +++ b/proposals/application-registration-2104/PARENT-CONTRACT.md @@ -143,6 +143,32 @@ key and payload, never an automatic new key. Rollback restores every partial ins Receipt/retry UPDATE and DELETE are blocked; retention, purge, export and tombstone lifetime remain unadopted. Fixture truncation is teardown only. +## Definite registration conflict errors + +`register_application` reserves SQLSTATE `P2101` (`application_registration_conflict`) +for exactly two definite failures: an existing retry key with a different fingerprint, +and a new request whose expected entitlement revision differs from current authority. +Both map to the same proposed domain `conflict` kind; human diagnostic text is not a +classification contract. No other input, structural, transaction or transport failure +may be inferred to be a conflict from its message or SQLSTATE class. `42501` remains +the authority-denied code. Other unclassified errors remain unknown to the adapter. +This is an inactive storage contract, not an adopted public HTTP/MCP error mapping. + +Current authority checks and expiry rechecks still precede retry lookup. Valid but +conflicting input cannot disclose history after authority is denied. The conflict +raises remain before inserts and abort the failed operation; they neither alter the +original receipt nor imply that an earlier request did not commit. Exact authorized +replay still returns original history after an enabled entitlement revision advances; +a new key must match the current revision. Unknown transport outcomes still require +retaining the original operation/key/input, with no automatic retry or new ledger. +The code annotations change no locks, transaction boundaries, receipt flags or policy. + +The SQLSTATE tests compare `RETURNED_SQLSTATE` inside a disposable test subtransaction, +not localized error text. They cover both conflict sites, all fingerprint dimensions, +unchanged contents of all five registration tables, original-receipt replay, authority +precedence, and generic validation errors that remain `P0001`. A generic exception +whose message says idempotency conflict still has `P0001`. + ## Outputs and privilege boundary Every registration receipt includes actor, workspace, fixed billing owner, generated diff --git a/proposals/application-registration-2104/registration.sql b/proposals/application-registration-2104/registration.sql index c3c5859..9bd6204 100644 --- a/proposals/application-registration-2104/registration.sql +++ b/proposals/application-registration-2104/registration.sql @@ -57,11 +57,11 @@ BEGIN SELECT q.* INTO prior FROM application_registration_proposal.requests q WHERE q.actor=p_actor AND q.workspace_id=p_workspace AND q.key=p_key; IF FOUND THEN - IF prior.input IS DISTINCT FROM fingerprint THEN RAISE EXCEPTION 'idempotency conflict'; END IF; + IF prior.input IS DISTINCT FROM fingerprint THEN RAISE EXCEPTION 'idempotency conflict' USING ERRCODE='P2101'; END IF; SELECT r.result INTO result_value FROM application_registration_proposal.receipts r WHERE r.id=prior.receipt_id; RETURN result_value; END IF; - IF authority.revision<>p_entitlement_revision THEN RAISE EXCEPTION 'entitlement revision conflict'; END IF; + IF authority.revision<>p_entitlement_revision THEN RAISE EXCEPTION 'entitlement revision conflict' USING ERRCODE='P2101'; END IF; IF NOT(p_registration ?& ARRAY['name','origins']) OR p_registration-ARRAY['name','origins']<>'{}'::jsonb OR jsonb_typeof(p_registration->'name')<>'string' OR length(p_registration->>'name') NOT BETWEEN 1 AND 120 OR btrim(p_registration->>'name')<>p_registration->>'name' diff --git a/proposals/application-registration-2104/test_registration.py b/proposals/application-registration-2104/test_registration.py index 08d6f52..5c2ba58 100644 --- a/proposals/application-registration-2104/test_registration.py +++ b/proposals/application-registration-2104/test_registration.py @@ -90,6 +90,59 @@ def deny(self, sql, message='authority unavailable'): with self.assertRaisesRegex(AssertionError, message): self.sql(sql) + def assert_sqlstate(self, statement, expected): + # Catch only inside a test subtransaction; compare structured diagnostics, + # never PostgreSQL's localized message text. Success must also fail. + command = statement.rstrip().removesuffix(';') + self.sql(f"""DO $assert_state$ DECLARE observed text; + BEGIN + BEGIN + EXECUTE {quote(command)}; + EXCEPTION WHEN OTHERS THEN + GET STACKED DIAGNOSTICS observed = RETURNED_SQLSTATE; + END; + IF observed IS DISTINCT FROM {quote(expected)} THEN + RAISE EXCEPTION 'Expected SQLSTATE %, observed %', {quote(expected)}, coalesce(observed, 'SUCCESS'); + END IF; + END $assert_state$;""") + + def registration_state(self): + return {table: self.sql(f"SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text), '[]'::jsonb) FROM {S}.{table} t") + for table in ['applications', 'environments', 'origins', 'receipts', 'requests']} + + def test_structured_conflicts_preserve_history_and_authority_precedence(self): + empty = self.registration_state() + with self.subTest(conflict='new-key-stale-revision'): + self.assert_sqlstate(self.statement(rev=2), 'P2101') + self.assertEqual(self.registration_state(), empty) + original = self.create() + saved = self.registration_state() + changed = [{'rev': 2}, {'body': {**payload(), 'name': 'Changed'}}, {'env': 'development'}] + for kw in changed: + with self.subTest(conflict=kw): + self.assert_sqlstate(self.statement(**kw), 'P2101') + self.assertEqual(self.registration_state(), saved) + self.sql(f"UPDATE {S}.create_entitlements SET revision=2 WHERE actor='{A}'") + self.assertEqual(self.create(), original) + with self.subTest(conflict='advanced-revision-new-key'): + self.assert_sqlstate(self.statement(key='new'), 'P2101') + self.assertEqual(self.registration_state(), saved) + for mutation in [f"UPDATE {S}.create_entitlements SET enabled=false WHERE actor='{A}'", + f"DELETE FROM {S}.create_entitlements WHERE actor='{A}'"]: + self.sql(mutation) + for kw in [{}] + changed + [{'key': 'new'}]: + self.assert_sqlstate(self.statement(**kw), '42501') + self.assertEqual(self.registration_state(), saved) + + def test_structured_nonconflict_errors_are_not_conflicts(self): + saved = self.registration_state() + for kw in [{'env': 'staging'}, {'body': {}}, {'body': {**payload(), 'name': ''}}]: + self.assert_sqlstate(self.statement(**kw), 'P0001') + self.assertEqual(self.registration_state(), saved) + self.assert_sqlstate("DO $$ BEGIN RAISE EXCEPTION 'idempotency conflict'; END $$", 'P0001') + self.assert_sqlstate(self.statement(actor=B), '42501') + self.assertEqual(self.registration_state(), saved) + def grant_management(self, app, ops, actor=A, env='production'): self.sql(f"INSERT INTO {S}.management_entitlements(actor,workspace_id,application_id,environment,operation) " f"SELECT '{actor}','{actor}',{quote(app)},{quote(env)},op FROM unnest(ARRAY[" + From acea75c0e118b6ca12bb9a22470a8bd7b383f925 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:12:34 -0500 Subject: [PATCH 5/5] Qualify inactive registration create and read privileges --- .../EXECUTION-CONTRACT.md | 84 ++++ .../execution.sql | 34 ++ .../qualification-roles.sql | 69 +++ .../sources.json | 63 +++ .../test_privileges.py | 447 ++++++++++++++++++ 5 files changed, 697 insertions(+) create mode 100644 proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md create mode 100644 proposals/application-registration-execution-2104/execution.sql create mode 100644 proposals/application-registration-execution-2104/qualification-roles.sql create mode 100644 proposals/application-registration-execution-2104/sources.json create mode 100644 proposals/application-registration-execution-2104/test_privileges.py diff --git a/proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md b/proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md new file mode 100644 index 0000000..32dc732 --- /dev/null +++ b/proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md @@ -0,0 +1,84 @@ +# Inactive create/read execution contract + +This is a **local disposable privilege qualification**, outside migrations. It adds two fixed entry functions over unchanged Database D `f507a77696f20429f977df9885d6c8c11a5f304b`; API provenance is merged `ec284cba127d73d0c3e7e74deceabac5c6a145f1`. It does not supply a production connection, role name, enrollment policy, migration, route/tool registration or storage factory. Database138 remains draft and unapplied. D1 personal enrollment, D2 pilot operation/policy and D4 retention/deletion remain unadopted. + +Only these five files belong to this proposal. `sources.json` pins the D supervisor, loaded SQL, parent contract and API provenance. The runner hashes all five D files before importing the supervisor or issuing SQL; source drift fails closed. API hashes record the reviewed handoff source, not a locally executed credential verifier. No proof/configuration composition is loaded. D's synthetic bootstrap defines `qualification_auth.original_actor`, but this runner never invokes it or uses its result as authority. + +## Identity and trust + +All `qualification_registration_*` names are **synthetic fixture labels**, not production recommendations: + +| Role | Capability | +| --- | --- | +| `data_owner` | NOLOGIN; owns D schemas/tables/internal functions, distinct from executor | +| `executor` | NOLOGIN; owns exactly the two entry functions; bounded column and helper privileges; no table ownership, schema CREATE, superuser or BYPASSRLS | +| `runtime` | NOLOGIN; entry-schema USAGE and two application entry EXECUTE grants only | +| `client` | Separate NOINHERIT LOGIN; member of runtime only, no ADMIN option; explicitly SET ROLE runtime | +| `browser` | Separate NOINHERIT LOGIN; unrelated, no memberships or application grants | + +All five lack SUPERUSER, CREATEDB, CREATEROLE, REPLICATION and BYPASSRLS. Positive calls connect with `psql -U qualification_registration_client` on the controller's owned Unix trust socket; they are not SET ROLE inside an original superuser login. RESET ROLE and SET SESSION AUTHORIZATION DEFAULT return to that unprivileged client. Attempts to become the executor, data owner or installer are denied. The disposable controller installs fixtures and inspects state; its administrative success is never counted as runtime access. + +NOLOGIN is not an isolation proof: function ownership and the ability to alter roles/grants remain administrative trust. No login is a member of the executor/data owner, and catalogs plus forbidden switching tests establish the fixture boundary. The fixture controller can alter anything; this proposal does not constrain that controller. + +Database PUBLIC CONNECT remains available inside the private socket fixture. PUBLIC CREATE and TEMP are explicitly revoked; runtime/client/browser/executor have neither. Trusted schemas deny runtime/executor CREATE after installation. A single shadow-object test temporarily grants TEMP to runtime, creates temporary objects, then revokes TEMP and proves denial again. That separate reversible profile is not a retained runtime privilege. “Two EXECUTE grants” refers to application entry points; ordinary PostgreSQL built-ins remain available. + +## Exact call graph and installation + +`application_registration_execution_proposal.create_registration(uuid,uuid,text,text,bigint,jsonb)` calls D's `register_application` once. `read_registration(uuid,uuid,uuid,text,uuid)` calls D's `read_registration` once. Both return jsonb, are SECURITY DEFINER owned by executor, and fix `search_path=pg_catalog,pg_temp` and `row_security=on`. Their bodies contain only the fully qualified invocation; no dynamic SQL, role switch, retry, exception remapping, claims parser or transaction control. + +D remains SECURITY INVOKER with its original empty search path. Create calls authorize_create → authorize_principal; read calls authorize_management → authorize_principal. The executor gets exactly those five D function EXECUTE grants and D/public schema USAGE. Runtime cannot call the D entries/helpers directly. `immutable_history` is not granted to executor/runtime; existing triggers continue to enforce history immutability. The tests inspect both trigger bindings and function owners/configuration, and exercise the original immutable-history failures. + +`execution.sql` creates entry functions, revokes PUBLIC EXECUTE and grants the two signatures in one transaction. Default EXECUTE is globally revoked for each actual creator: fixture installer, data owner and executor. New probe functions created as each role verify the defaults; schema-only revocation or ownership transfer is not treated as sufficient. A marker and fixture prerequisites reject accidental standalone loading; the marker is not authentication or permission to use a live database. + +## Measured privilege matrix + +All relations are synthetic. No production RLS or database ACL is changed. + +| Relation | Executor SELECT | Executor INSERT | Row-lock UPDATE column | +| --- | --- | --- | --- | +| public.accounts | id | none | id | +| personal_principals | account_id, enabled, policy_version | none | account_id | +| create_entitlements | all 7 D columns | none | actor | +| management_entitlements | all 8 D columns | none | actor | +| requests | all 5 D columns | all 5 D columns | none | +| receipts | id, result, workspace_id, application_id, environment | all 7 D columns | none | +| applications | none | workspace_id, id, billing_owner_id, name | none | +| environments | none | workspace_id, application_id, environment | none | +| origins | none | workspace_id, application_id, environment, origin, hostname, return_urls | none | + +No sequence, DELETE, TRUNCATE, REFERENCES or TRIGGER grant is added. Tests compare catalog column privileges to this exact matrix, verify runtime/client/browser have no table/column privileges, and remove every SELECT/INSERT column separately to require a real 42501 denial with all five result tables unchanged. They remove each of the four UPDATE-column grants separately too. No broader grant is substituted for a failure. + +FOR SHARE needs UPDATE privilege on at least one column. Each of the four authority/account relations therefore has executor SELECT USING true and UPDATE USING true **WITH CHECK false**. All nine account/proposal tables ENABLE and FORCE RLS. The five result tables have executor INSERT WITH CHECK true; requests/receipts also have SELECT policies. There are exactly fifteen policies, all executor-specific, with no permissive ALL/UPDATE policy that could OR away the false update check. Executor is neither table owner nor RLS bypass. Removing UPDATE USING access independently denies the lock-based operation; actual UPDATE of the granted column is rejected without row changes. + +These policies constrain operations, **not caller identity**. D's explicit actor/workspace/operation checks and row locks remain the proposed tenant authority boundary. Hidden rows can produce different outcomes: if receipt SELECT visibility is removed, unchanged D's replay lookup returns SQL NULL, while its read function raises 42501. Qualification records that distinction and rejects NULL as a receipt. The API's receipt validation must remain after storage. A completed SQL statement alone is never sufficient success evidence. + +## Original actor handoff and limits + +A UUID argument is not authentication. The intentionally positive limitation test shows the **same runtime login successfully asserting either of two enrolled actors**. This capability is suitable only behind the reviewed trusted server boundary; it is not a browser/PostgREST end-user RPC contract. + +Before real storage entry, the owning API must verify the original request with nonprovisioning existing-account/self/no-organization rules, pass the private server-derived actor/workspace to a fixed parameterized invocation and preserve receipt validation. Do not accept body account IDs, authInfo, caller JWT/GUC claims or role names as proof. The accepted API source rechecks admission/tool/domain observations and observes termination before entry; this SQL runner does not execute that authentication, call Privy, inspect credentials or close its races. + +Credential-only change with the same actor at the third domain observation is not detectable by its actor/workspace storage guard. API-key/Privy revocation is not atomic with SQL. After storage entry, HTTP abort/deadline or SDK closure does not cancel/roll back SQL. Preserve one invocation, unknown-outcome handling and explicit original-key reconciliation; never auto-retry. The response-loss test discards output only after a real committed transaction, then explicitly replays the original key and checks the stored IDs/timestamp/full history. + +D requires READ COMMITTED. Revocation writers must use account → enrollment → entitlement lock order. Create entitlement expiry is nullable; null means no expiry. D checks expiry after authority lookup, after its retry-key advisory wait and immediately before insertion. This is **not a commit-time deadline** or a check after every later wait. Management entitlements have no expiry column; this proposal adds no management TTL. Authority locks serialize those row changes, not external credential revocation. No organization/delegation, DNS proof, configuration, provider, spending or retention policy is added. + +## Qualification and lifecycle + +Run from this owning Database checkout, using a locally installed PostgreSQL bin directory: + +```sh +PG_BIN=/opt/homebrew/opt/postgresql@15/bin /Library/Frameworks/Python.framework/Versions/3.12/bin/python3 -I proposals/application-registration-execution-2104/test_privileges.py +PG_BIN=/opt/homebrew/opt/postgresql@17/bin /Library/Frameworks/Python.framework/Versions/3.12/bin/python3 -I proposals/application-registration-execution-2104/test_privileges.py +``` + +No DSN arguments, env files, hosted account lookup or live connection is accepted. D's hash-pinned supervisor creates a random Unix-only cluster, allows only its fixed environment, binds the directory/PID/worker lease, bounds SQL/process timeouts, quiesces the dedicated worker process group and verifies the owned postmaster/socket before removal. The only dispatch adaptation sets the imported module's `__file__` to this runner so its child re-enters this suite. It does not replace cleanup functions, copy a lifecycle framework or alter D source. Its original signal/timeout/worker-exit faults are forwarded for focused trampoline-cleanup qualification. + +The suite covers separate-login create/read and forbidden escalation; catalog ACL/default grants/owners/RLS; no implicit read grant; two actors/apps/environments; both P2101 conflicts and 42501-before-replay; replay after enabled revision advance; explicit rollback and injected second-origin failure; committed response loss; history immutability; controlled RLS NULL; temporary/public shadow boundaries; and observed two-connection locks for concurrent replay, both revocation orders and expiry after authority/advisory waits. Lock evidence is tied by pg_blocking_pids to the actual holder before the test releases it. Snapshot comparisons include complete rows of applications, environments, origins, receipts and requests. + +Source qualification and review receipts remain local under Mono `.local/audits/sites2104-execution-contract-local-2026-11-18/`. The focused RED removes the two entry EXECUTE grants and runs the positive case: it must fail at create permission. Full passing results and exact runtime/cleanup facts are recorded in that receipt, not inferred from this specification. No source publication is authorized until root's separate gate. + +## Later release prerequisites + +Reuse existing DB-OBSERVATION-01 only after root verifies target/runner relevance: actual creator/default ACL, function owner, runtime connection/SET ROLE support, production RLS integration, transaction/pooling/timeouts and cancellation/unknown outcomes remain unproved. Catalog/reservation observations are not automatically Sites capability proof. No new credential request or duplicate human alert is warranted by this disposable work. + +Plan seal: `852a8ff829bfc9b9a426ee32382435bede1cabd30ed8b3297e6c6eef7c0da4d7`; decision successor seal: `076754718f7aaa10278a322ef448fe0dff33fdc214b85634cb97554a30b14765`; independent OAuth plan review seal: `2c0bc1a0b08ce84218e2593edb9831e649b68bdb9b4931f0fccd1eb888905828`. Their local receipts are respectively `sites2104-create-read-privilege-plan-2026-11-18`, `sites2104-runtime-policy-decision-successor-2026-11-18`, and `oauth-sites2104-execution-plan-review-2026-11-18` under Mono `.local/audits/`. diff --git a/proposals/application-registration-execution-2104/execution.sql b/proposals/application-registration-execution-2104/execution.sql new file mode 100644 index 0000000..2e4e652 --- /dev/null +++ b/proposals/application-registration-execution-2104/execution.sql @@ -0,0 +1,34 @@ +-- INACTIVE DISPOSABLE QUALIFICATION ONLY. Not a migration or production role contract. +-- Requires exact D and qualification-roles.sql in an owned Unix-only test cluster. +BEGIN; +DO $$ BEGIN + IF current_setting('qualification.registration_fixture',true) IS DISTINCT FROM 'owned-disposable-only' + OR to_regrole('qualification_registration_executor') IS NULL + OR to_regclass('application_registration_proposal.requests') IS NULL THEN + RAISE EXCEPTION 'owned disposable registration fixture required'; + END IF; +END $$; +ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; +ALTER DEFAULT PRIVILEGES FOR ROLE qualification_registration_data_owner REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; +ALTER DEFAULT PRIVILEGES FOR ROLE qualification_registration_executor REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; +CREATE SCHEMA application_registration_execution_proposal AUTHORIZATION qualification_registration_data_owner; +REVOKE ALL ON SCHEMA application_registration_execution_proposal FROM PUBLIC; +GRANT USAGE,CREATE ON SCHEMA application_registration_execution_proposal TO qualification_registration_executor; +SET LOCAL ROLE qualification_registration_executor; +CREATE FUNCTION application_registration_execution_proposal.create_registration( + p_actor uuid,p_workspace uuid,p_environment text,p_key text,p_entitlement_revision bigint,p_registration jsonb +) RETURNS jsonb LANGUAGE sql SECURITY DEFINER + SET search_path=pg_catalog,pg_temp SET row_security=on + AS $$ SELECT application_registration_proposal.register_application($1,$2,$3,$4,$5,$6) $$; +CREATE FUNCTION application_registration_execution_proposal.read_registration( + p_actor uuid,p_workspace uuid,p_application uuid,p_environment text,p_receipt uuid +) RETURNS jsonb LANGUAGE sql SECURITY DEFINER + SET search_path=pg_catalog,pg_temp SET row_security=on + AS $$ SELECT application_registration_proposal.read_registration($1,$2,$3,$4,$5) $$; +RESET ROLE; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA application_registration_execution_proposal FROM PUBLIC; +REVOKE CREATE ON SCHEMA application_registration_execution_proposal FROM qualification_registration_executor; +GRANT USAGE ON SCHEMA application_registration_execution_proposal TO qualification_registration_runtime; +GRANT EXECUTE ON FUNCTION application_registration_execution_proposal.create_registration(uuid,uuid,text,text,bigint,jsonb), + application_registration_execution_proposal.read_registration(uuid,uuid,uuid,text,uuid) TO qualification_registration_runtime; +COMMIT; diff --git a/proposals/application-registration-execution-2104/qualification-roles.sql b/proposals/application-registration-execution-2104/qualification-roles.sql new file mode 100644 index 0000000..0876ac2 --- /dev/null +++ b/proposals/application-registration-execution-2104/qualification-roles.sql @@ -0,0 +1,69 @@ +-- SYNTHETIC OWNED-CLUSTER SETUP ONLY. Never run on a hosted/live database. +DO $$ BEGIN + IF current_setting('qualification.registration_fixture',true) IS DISTINCT FROM 'owned-disposable-only' THEN + RAISE EXCEPTION 'owned disposable registration fixture required'; + END IF; +END $$; +CREATE ROLE qualification_registration_data_owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT; +CREATE ROLE qualification_registration_executor NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT; +CREATE ROLE qualification_registration_runtime NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT; +CREATE ROLE qualification_registration_client LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT; +CREATE ROLE qualification_registration_browser LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT; +GRANT qualification_registration_runtime TO qualification_registration_client; +-- Ordinary PostgreSQL defaults include database TEMP and public schema USAGE. +-- This stricter synthetic profile denies TEMP; one reversible shadow-test grant is separate. +REVOKE CREATE,TEMPORARY ON DATABASE postgres FROM PUBLIC; +REVOKE ALL ON SCHEMA public,qualification_auth,application_registration_proposal FROM PUBLIC; +ALTER SCHEMA public OWNER TO qualification_registration_data_owner; +ALTER SCHEMA qualification_auth OWNER TO qualification_registration_data_owner; +ALTER SCHEMA application_registration_proposal OWNER TO qualification_registration_data_owner; +ALTER TABLE public.accounts OWNER TO qualification_registration_data_owner; +DO $$ DECLARE r record; +BEGIN + FOR r IN SELECT c.oid::regclass AS relation FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='application_registration_proposal' AND c.relkind='r' LOOP + EXECUTE format('ALTER TABLE %s OWNER TO qualification_registration_data_owner',r.relation); + END LOOP; + FOR r IN SELECT p.oid::regprocedure AS signature FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname IN ('application_registration_proposal','qualification_auth') LOOP + EXECUTE format('ALTER FUNCTION %s OWNER TO qualification_registration_data_owner',r.signature); + END LOOP; +END $$; +GRANT USAGE ON SCHEMA public,application_registration_proposal TO qualification_registration_executor; +GRANT EXECUTE ON FUNCTION application_registration_proposal.register_application(uuid,uuid,text,text,bigint,jsonb), + application_registration_proposal.read_registration(uuid,uuid,uuid,text,uuid), + application_registration_proposal.authorize_principal(uuid,uuid), + application_registration_proposal.authorize_create(uuid,uuid,text), + application_registration_proposal.authorize_management(uuid,uuid,uuid,text,text) TO qualification_registration_executor; +GRANT SELECT(id),UPDATE(id) ON public.accounts TO qualification_registration_executor; +GRANT SELECT(account_id,enabled,policy_version),UPDATE(account_id) ON application_registration_proposal.personal_principals TO qualification_registration_executor; +GRANT SELECT(actor,workspace_id,environment,revision,enabled,expires_at,policy_version),UPDATE(actor) ON application_registration_proposal.create_entitlements TO qualification_registration_executor; +GRANT SELECT(actor,workspace_id,application_id,environment,operation,enabled,revision,policy_version),UPDATE(actor) ON application_registration_proposal.management_entitlements TO qualification_registration_executor; +GRANT SELECT(actor,workspace_id,key,input,receipt_id),INSERT(actor,workspace_id,key,input,receipt_id) ON application_registration_proposal.requests TO qualification_registration_executor; +GRANT SELECT(id,result,workspace_id,application_id,environment),INSERT(id,actor,workspace_id,application_id,environment,recorded_at,result) ON application_registration_proposal.receipts TO qualification_registration_executor; +GRANT INSERT(workspace_id,id,billing_owner_id,name) ON application_registration_proposal.applications TO qualification_registration_executor; +GRANT INSERT(workspace_id,application_id,environment) ON application_registration_proposal.environments TO qualification_registration_executor; +GRANT INSERT(workspace_id,application_id,environment,origin,hostname,return_urls) ON application_registration_proposal.origins TO qualification_registration_executor; +DO $$ DECLARE t text; +BEGIN + FOREACH t IN ARRAY ARRAY['public.accounts','application_registration_proposal.personal_principals', + 'application_registration_proposal.create_entitlements','application_registration_proposal.management_entitlements', + 'application_registration_proposal.requests','application_registration_proposal.receipts', + 'application_registration_proposal.applications','application_registration_proposal.environments','application_registration_proposal.origins'] LOOP + EXECUTE 'ALTER TABLE '||t||' ENABLE ROW LEVEL SECURITY'; + EXECUTE 'ALTER TABLE '||t||' FORCE ROW LEVEL SECURITY'; + END LOOP; + FOREACH t IN ARRAY ARRAY['public.accounts','application_registration_proposal.personal_principals', + 'application_registration_proposal.create_entitlements','application_registration_proposal.management_entitlements', + 'application_registration_proposal.requests','application_registration_proposal.receipts'] LOOP + EXECUTE 'CREATE POLICY executor_select ON '||t||' FOR SELECT TO qualification_registration_executor USING (true)'; + END LOOP; + FOREACH t IN ARRAY ARRAY['public.accounts','application_registration_proposal.personal_principals', + 'application_registration_proposal.create_entitlements','application_registration_proposal.management_entitlements'] LOOP + EXECUTE 'CREATE POLICY executor_lock ON '||t||' FOR UPDATE TO qualification_registration_executor USING (true) WITH CHECK (false)'; + END LOOP; + FOREACH t IN ARRAY ARRAY['application_registration_proposal.applications','application_registration_proposal.environments', + 'application_registration_proposal.origins','application_registration_proposal.receipts','application_registration_proposal.requests'] LOOP + EXECUTE 'CREATE POLICY executor_insert ON '||t||' FOR INSERT TO qualification_registration_executor WITH CHECK (true)'; + END LOOP; +END $$; diff --git a/proposals/application-registration-execution-2104/sources.json b/proposals/application-registration-execution-2104/sources.json new file mode 100644 index 0000000..31433bd --- /dev/null +++ b/proposals/application-registration-execution-2104/sources.json @@ -0,0 +1,63 @@ +{ + "database_commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "api_commit": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "database_files": [ + { + "commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "path": "proposals/application-registration-2104/parents.sql", + "sha256": "2a1096eadf1ee947f2b1d6bb88f5750e26436ee8ea82ae1f306a279da8b41c2d" + }, + { + "commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "path": "proposals/application-registration-2104/registration.sql", + "sha256": "3377dd6f86bdf3052a2dd00b66380540764e07a763003f6a1c46192c336e6409" + }, + { + "commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "path": "proposals/application-registration-2104/test_registration.py", + "sha256": "4051b2581646cea5ac2d36a23d5d5e6271dd02cbf0997e0792623289914d230c" + }, + { + "commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "path": "proposals/application-registration-2104/qualification-bootstrap.sql", + "sha256": "6c318540735e46c8ace40cd686bf7cc1851fb3296b5a123d29e287f94be35c05" + }, + { + "commit": "f507a77696f20429f977df9885d6c8c11a5f304b", + "path": "proposals/application-registration-2104/PARENT-CONTRACT.md", + "sha256": "f08c2ed9438dc36bca06d2f0e687d283af5d68d0022d6320254b4b7267dea198" + } + ], + "api_provenance": [ + { + "commit": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "path": "lib/applications/proposedRegistration/proposedRegistrationContract.ts", + "sha256": "0162487073c4e70dfc88179a49d6577980dcbb8a945e0a3778498e00f307b6e8" + }, + { + "commit": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "path": "lib/applications/proposedRegistration/createProposedApplicationRegistration.ts", + "sha256": "0322dfd63e51314cfe7bcc5d5544127291574f3c1c8152fb536a3e1c6e4afef0" + }, + { + "commit": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "path": "lib/applications/proposedRegistration/readProposedApplicationRegistration.ts", + "sha256": "ca358e8de64b51550f9be50f55d9189a665ca1a38d722a7850f1d31be43ae134" + }, + { + "commit": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "path": "docs/internal/mcp-existing-application-actor.md", + "sha256": "587eb80f223839a757becb865cdb8aef26c8c7905e75aadd453e46fe0454bc84" + } + ], + "supervisor": "proposals/application-registration-2104/test_registration.py", + "loaded_sql": [ + "proposals/application-registration-2104/qualification-bootstrap.sql", + "proposals/application-registration-2104/parents.sql", + "proposals/application-registration-2104/registration.sql" + ], + "plan_seal": "852a8ff829bfc9b9a426ee32382435bede1cabd30ed8b3297e6c6eef7c0da4d7", + "decision_seal": "076754718f7aaa10278a322ef448fe0dff33fdc214b85634cb97554a30b14765", + "oauth_plan_review_seal": "2c0bc1a0b08ce84218e2593edb9831e649b68bdb9b4931f0fccd1eb888905828", + "activation": false +} diff --git a/proposals/application-registration-execution-2104/test_privileges.py b/proposals/application-registration-execution-2104/test_privileges.py new file mode 100644 index 0000000..dcb4780 --- /dev/null +++ b/proposals/application-registration-execution-2104/test_privileges.py @@ -0,0 +1,447 @@ +"""Owned disposable PG only; unchanged D supervisor and transaction bodies are imported. + +The explicit dispatch substitution changes only D.supervise's child script path. Its +lease, clean environment, process group, timeouts and cleanup functions stay intact. +""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import select +import subprocess +import sys +import time +import unittest +from concurrent.futures import ThreadPoolExecutor + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +S = 'application_registration_proposal' +E = 'application_registration_execution_proposal' +OWNER = 'qualification_registration_data_owner' +EXECUTOR = 'qualification_registration_executor' +RUNTIME = 'qualification_registration_runtime' +CLIENT = 'qualification_registration_client' +BROWSER = 'qualification_registration_browser' +A = '00000000-0000-0000-0000-000000000001' +B = '00000000-0000-0000-0000-000000000002' + + +def load_supervisor(): + manifest = json.loads((HERE/'sources.json').read_text()) + for item in manifest['database_files']: + if hashlib.sha256((ROOT/item['path']).read_bytes()).hexdigest() != item['sha256']: + raise RuntimeError('Pinned D source mismatch: '+item['path']) + spec = importlib.util.spec_from_file_location('pinned_registration', ROOT/manifest['supervisor']) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +D = load_supervisor() +quote = D.quote +payload = D.payload + + +class Privileges(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.socket, cls.bin = D.verify_worker_lease() + cls.env = {**D.fixture_environment(Path(cls.socket).parent, cls.bin), + 'PGHOST': cls.socket, 'PGPORT': '55473', 'PGDATABASE': 'postgres', + 'PGOPTIONS': '-c statement_timeout=10000 -c lock_timeout=8000'} + for name in ['qualification-bootstrap.sql', 'parents.sql', 'registration.sql']: + cls.admin((D.HERE/name).read_text()) + # Bootstrap defines a fake auth helper, but it is never invoked/composed. + # The installation marker is an accidental-use guard, not authentication. + cls.admin("SET qualification.registration_fixture='owned-disposable-only';"+ + (HERE/'qualification-roles.sql').read_text()+(HERE/'execution.sql').read_text()) + print('RUNTIME '+cls.admin("SELECT json_build_object('postgres',version(),'server_version_num',current_setting('server_version_num'),'controller',current_user)::text"), flush=True) + print('PYTHON '+sys.version, flush=True) + print('SOURCE_HASHES '+json.dumps(json.loads((HERE/'sources.json').read_text())['database_files']), flush=True) + + @classmethod + def args(cls, login=None): + return [str(cls.bin/'psql'), '-XqAt', '-v', 'ON_ERROR_STOP=1'] + (['-U',login] if login else []) + + @classmethod + def run_sql(cls, sql, login=None, role=None, name='privilege-test'): + command = (f'SET ROLE {role};' if role else '')+sql + result = subprocess.run(cls.args(login), input=command, + env={**cls.env, 'PGAPPNAME':name}, capture_output=True, text=True, timeout=15) + if result.returncode: + raise AssertionError(result.stderr) + return result.stdout.strip() + + @classmethod + def admin(cls, sql): + return cls.run_sql(sql) + + def runtime(self, sql): + return self.run_sql(sql, CLIENT, RUNTIME) + + def state(self): + return {t:self.admin(f"SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) FROM {S}.{t} t") + for t in ['applications','environments','origins','receipts','requests']} + + def setUp(self): + self.admin(f'TRUNCATE {S}.personal_principals CASCADE;'+ + f"INSERT INTO {S}.personal_principals(account_id) VALUES ('{A}'),('{B}');"+ + f"INSERT INTO {S}.create_entitlements(actor,workspace_id,environment) SELECT account_id,account_id,e FROM {S}.personal_principals CROSS JOIN unnest(ARRAY['production','development']) e;") + + def statement(self, **kw): + return D.Registration.statement(self, **kw).replace(S+'.register_application',E+'.create_registration') + + def read_statement(self, receipt, **kw): + return D.Registration.read_receipt(self, receipt, **kw).replace(S+'.read_registration',E+'.read_registration') + + def receipt(self, raw): + value=json.loads(raw) + self.assertIsInstance(value,dict) + for flag in ['origins_verified','bootstrap_enabled','access_activated','runtime_enabled','production_persisted']: + self.assertIs(value[flag],False) + self.assertEqual(value['policy_status'],'proposed_unadopted') + self.assertEqual(value['evidence_kind'],'disposable_parent_assertion') + for key in ['receipt_id','application_id','recorded_at','actor','workspace_id','snapshot']: + self.assertIn(key,value) + return value + + def create(self, **kw): + return self.receipt(self.runtime(self.statement(**kw))) + + def grant_read(self, receipt, actor=A, environment='production'): + self.admin(f"INSERT INTO {S}.management_entitlements(actor,workspace_id,application_id,environment,operation) VALUES ('{actor}','{actor}',{quote(receipt['application_id'])},{quote(environment)},'read_registration');") + + def assert_state(self, statement, expected, login=CLIENT, role=RUNTIME): + # The anonymous block executes in the actual unprivileged client session. + command=statement.strip().removesuffix(';') + self.run_sql(f"""DO $check$ DECLARE observed text; + BEGIN BEGIN EXECUTE {quote(command)}; + EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS observed=RETURNED_SQLSTATE; END; + IF observed IS DISTINCT FROM {quote(expected)} THEN RAISE EXCEPTION 'Expected %, observed %',{quote(expected)},coalesce(observed,'SUCCESS'); END IF; + END $check$;""",login,role) + + def test_01_runtime_create_read_and_isolation(self): + self.assertEqual(self.runtime('SELECT session_user,current_user'),CLIENT+'|'+RUNTIME) + receipt=self.create() + self.assertEqual(receipt['actor'],A) + self.assertEqual(self.admin(f'SELECT count(*) FROM {S}.management_entitlements'),'0') + self.assert_state(self.read_statement(receipt),'42501') + self.grant_read(receipt) + self.assertEqual(self.receipt(self.runtime(self.read_statement(receipt))),receipt) + other=self.create(actor=B,workspace=B) + dev=self.create(env='development',key='dev') + self.assertEqual(len({r['application_id'] for r in [receipt,other,dev]}),3) + saved=self.state() + for kw in [{'actor':B},{'workspace':B},{'env':'development'},{'app':other['application_id']}]: + self.assert_state(self.read_statement(receipt,**kw),'42501') + self.assertEqual(self.state(),saved) + + def test_02_malicious_runtime_actor_assertion_is_NOT_authentication(self): + # Intentional positive limitation: the same session can assert either enrolled actor. + first=self.create() + other=self.create(actor=B,workspace=B) + self.assertEqual((first['actor'],other['actor']),(A,B)) + print('TRUST_LIMIT same runtime login successfully asserted both enrolled actors; UUID is not authentication',flush=True) + saved=self.state() + self.assert_state(self.statement(actor=B,workspace=A),'42501') + self.admin(f"UPDATE {S}.personal_principals SET enabled=false WHERE account_id='{B}'") + self.assert_state(self.statement(actor=B,workspace=B),'42501') + self.assertEqual(self.state(),saved) + + def test_03_conflict_replay_authority_and_history(self): + empty=self.state() + self.assert_state(self.statement(rev=2),'P2101') + self.assertEqual(self.state(),empty) + original=self.create(); saved=self.state() + changed=[{'rev':2},{'env':'development'},{'body':{**payload(),'name':'Changed'}}] + for kw in changed: + self.assert_state(self.statement(**kw),'P2101'); self.assertEqual(self.state(),saved) + self.admin(f"UPDATE {S}.create_entitlements SET revision=2 WHERE actor='{A}'") + self.assertEqual(self.create(),original) + self.assert_state(self.statement(key='new'),'P2101') + for mutation in [f"UPDATE {S}.create_entitlements SET enabled=false WHERE actor='{A}'", + f"DELETE FROM {S}.create_entitlements WHERE actor='{A}'"]: + self.admin(mutation) + for kw in [{}]+changed+[{'key':'new'}]: + self.assert_state(self.statement(**kw),'42501'); self.assertEqual(self.state(),saved) + for table in ['receipts','requests']: + self.assert_state(f'DELETE FROM {S}.{table}','P0001',login=None,role=None) + self.assertEqual(self.state(),saved) + + def test_04_read_and_enrollment_revocation(self): + receipt=self.create(); self.grant_read(receipt); saved=self.state() + self.admin(f'UPDATE {S}.management_entitlements SET enabled=false') + self.assert_state(self.read_statement(receipt),'42501') + self.admin(f'UPDATE {S}.management_entitlements SET enabled=true; UPDATE {S}.personal_principals SET enabled=false') + self.assert_state(self.read_statement(receipt),'42501') + self.assert_state(self.statement(),'42501'); self.assertEqual(self.state(),saved) + + def test_05_rollback_mid_insert_and_real_commit_response_loss(self): + before=self.state() + self.runtime('BEGIN;'+self.statement()+'ROLLBACK;'); self.assertEqual(self.state(),before) + self.admin(f"CREATE FUNCTION {E}.fail_origin() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.origin='https://preview.example' THEN RAISE EXCEPTION 'forced second origin failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_second BEFORE INSERT ON {S}.origins FOR EACH ROW EXECUTE FUNCTION {E}.fail_origin();") + try: + self.assert_state(self.statement(),'P0001'); self.assertEqual(self.state(),before) + finally: + self.admin(f'DROP TRIGGER fail_second ON {S}.origins; DROP FUNCTION {E}.fail_origin();') + # psql completes a real COMMIT; discard its receipt to model transport loss. + self.runtime('BEGIN;'+self.statement()+'COMMIT;') + committed=self.state(); replay=self.create() + self.assertEqual(self.state(),committed) + stored=json.loads(self.admin(f'SELECT result FROM {S}.receipts')) + self.assertEqual(replay,stored) + + def test_06_roles_memberships_owners_and_database_defaults(self): + facts=json.loads(self.admin("SELECT json_agg(json_build_object('role',rolname,'super',rolsuper,'bypass',rolbypassrls,'inherit',rolinherit,'create_role',rolcreaterole,'create_db',rolcreatedb,'replicate',rolreplication,'login',rolcanlogin) ORDER BY rolname) FROM pg_roles WHERE rolname LIKE 'qualification_registration_%'")) + self.assertEqual(len(facts),5) + for fact in facts: + for flag in ['super','bypass','inherit','create_role','create_db','replicate']: + self.assertFalse(fact[flag]) + self.assertEqual(fact['login'],fact['role'] in [CLIENT,BROWSER]) + self.assertEqual(self.admin("SELECT r.rolname||':'||m.rolname||':'||a.admin_option FROM pg_auth_members a JOIN pg_roles r ON r.oid=a.roleid JOIN pg_roles m ON m.oid=a.member WHERE m.rolname LIKE 'qualification_registration_%'"),RUNTIME+':'+CLIENT+':false') + for role in [RUNTIME,CLIENT,BROWSER,EXECUTOR]: + self.assertEqual(self.admin(f"SELECT has_database_privilege('{role}','postgres','CREATE'),has_database_privilege('{role}','postgres','TEMP')"),'f|f') + self.assertEqual(self.runtime('RESET ROLE; SELECT session_user,current_user'),CLIENT+'|'+CLIENT) + self.assertEqual(self.runtime('SET SESSION AUTHORIZATION DEFAULT; SELECT session_user,current_user'),CLIENT+'|'+CLIENT) + for role in [OWNER,EXECUTOR]: + self.assert_state('SET ROLE '+role,'42501') + self.assert_state('SET SESSION AUTHORIZATION '+role,'42501') + self.assert_state('SET ROLE '+quote(self.admin('SELECT current_user')),'42501') + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE ((n.nspname='{S}' AND c.relkind='r') OR (n.nspname='public' AND c.relname='accounts')) AND c.relowner='{OWNER}'::regrole AND c.relrowsecurity AND c.relforcerowsecurity"),'9') + print('ROLE_FACTS '+json.dumps(facts,sort_keys=True),flush=True) + print('DATABASE_ACL '+self.admin("SELECT datacl::text FROM pg_database WHERE datname='postgres'"),flush=True) + + def test_07_no_direct_DML_DDL_or_escalation(self): + receipt=self.create(); saved=self.state() + statements=[f'SELECT * FROM {S}.receipts',f"INSERT INTO {S}.personal_principals(account_id) VALUES ('{A}')", + f'UPDATE {S}.receipts SET result=result',f'DELETE FROM {S}.requests',f'TRUNCATE {S}.applications CASCADE', + f'ALTER TABLE {S}.receipts ADD COLUMN evil text',f'DROP TABLE {S}.receipts CASCADE', + 'CREATE SCHEMA attacker','CREATE TEMP TABLE accounts(id uuid)', 'CREATE TABLE public.attacker(id int)', + f'CREATE TABLE {E}.attacker(id int)',f'GRANT {EXECUTOR} TO {CLIENT}', + 'CREATE ROLE attacker',f'ALTER ROLE {RUNTIME} SUPERUSER', + f"CREATE OR REPLACE FUNCTION {E}.read_registration(uuid,uuid,uuid,text,uuid) RETURNS jsonb LANGUAGE sql AS 'SELECT null::jsonb'", + f"SELECT {S}.authorize_principal('{A}','{A}')", + self.statement().replace(E+'.create_registration',S+'.register_application'), + self.read_statement(receipt).replace(E+'.read_registration',S+'.read_registration'), + "SELECT qualification_auth.original_actor('current-key')"] + for command in statements: + with self.subTest(command=command): + self.assert_state(command,'42501'); self.assertEqual(self.state(),saved) + # These schemas are absent; no proof/configuration composition was loaded. + self.assertEqual(self.admin("SELECT to_regnamespace('application_proof_proposal') IS NULL"),'t') + self.assert_state("SELECT application_proof_proposal.transact()",'3F000') + + def test_08_entry_ACLs_independent_of_schema_usage_and_default_execute(self): + for schema,expected in [(E,2),(S,0),('qualification_auth',0)]: + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='{schema}' AND has_function_privilege('{RUNTIME}',p.oid,'EXECUTE')"),str(expected)) + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='{E}' AND p.prosecdef AND p.proowner='{EXECUTOR}'::regrole AND p.proconfig @> ARRAY['search_path=pg_catalog, pg_temp','row_security=on']"),'2') + self.assert_state(self.statement(),'42501',BROWSER,None) + self.admin(f'GRANT USAGE ON SCHEMA {E},{S},qualification_auth TO {BROWSER}; GRANT USAGE ON SCHEMA {S} TO {RUNTIME}') + try: + self.assert_state(self.statement(),'42501',BROWSER,None) + self.assert_state(self.statement().replace(E+'.create_registration',S+'.register_application'),'42501') + self.assert_state(f"SELECT {S}.authorize_create('{A}','{A}','production')",'42501') + finally: + self.admin(f'REVOKE USAGE ON SCHEMA {E},{S},qualification_auth FROM {BROWSER}; REVOKE USAGE ON SCHEMA {S} FROM {RUNTIME}') + # Actual creator-specific defaults, including fixture installer, not owner-transfer guesses. + for creator in [self.admin('SELECT current_user'),OWNER,EXECUTOR]: + self.admin(f'GRANT CREATE ON SCHEMA {E} TO {quote_identifier(creator)}; SET ROLE {quote_identifier(creator)}; CREATE FUNCTION {E}.default_probe() RETURNS integer LANGUAGE sql AS $$ SELECT 1 $$; RESET ROLE;') + try: + self.assertEqual(self.admin(f"SELECT has_function_privilege('{RUNTIME}','{E}.default_probe()','EXECUTE'),has_function_privilege('{BROWSER}','{E}.default_probe()','EXECUTE')"),'f|f') + self.assert_state(f'SELECT {E}.default_probe()','42501') + finally: + self.admin(f'DROP FUNCTION {E}.default_probe(); REVOKE CREATE ON SCHEMA {E} FROM {quote_identifier(creator)}') + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace CROSS JOIN LATERAL aclexplode(coalesce(p.proacl,acldefault('f',p.proowner))) a WHERE n.nspname IN ('{E}','{S}','qualification_auth') AND a.grantee=0 AND a.privilege_type='EXECUTE'"),'0') + + def test_09_lock_column_privilege_and_using_are_each_required(self): + receipt=self.create(); self.grant_read(receipt); saved=self.state() + for table,column in [('public.accounts','id'),(S+'.personal_principals','account_id'),(S+'.create_entitlements','actor'),(S+'.management_entitlements','actor')]: + command=self.read_statement(receipt) if 'management' in table else self.statement() + self.admin(f'REVOKE UPDATE({column}) ON {table} FROM {EXECUTOR}') + try: self.assert_state(command,'42501'); self.assertEqual(self.state(),saved) + finally: self.admin(f'GRANT UPDATE({column}) ON {table} TO {EXECUTOR}') + self.admin(f'ALTER POLICY executor_lock ON {table} USING (false)') + try: self.assert_state(command,'42501'); self.assertEqual(self.state(),saved) + finally: self.admin(f'ALTER POLICY executor_lock ON {table} USING (true)') + before=self.admin(f"SELECT jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text) FROM {table} t") + # Explicit fixture-controller SET ROLE to probe executor; never a runtime proof. + self.assert_state(f'UPDATE {table} SET {column}={column}','42501',None,EXECUTOR) + self.assertEqual(self.admin(f"SELECT jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text) FROM {table} t"),before) + self.assertEqual(self.create(),receipt) + self.assertEqual(self.receipt(self.runtime(self.read_statement(receipt))),receipt) + + def test_10_rls_controls_do_not_count_null_as_receipt(self): + receipt=self.create(); self.grant_read(receipt); saved=self.state() + self.admin(f'ALTER POLICY executor_select ON {S}.receipts USING (false)') + try: + raw=self.runtime(self.statement()) + self.assertEqual(raw,'') # unchanged D replay can return SQL NULL when receipt hidden + with self.assertRaises((ValueError,AssertionError)): self.receipt(raw) + self.assert_state(self.read_statement(receipt),'42501') + self.assertEqual(self.state(),saved) + finally: self.admin(f'ALTER POLICY executor_select ON {S}.receipts USING (true)') + self.admin(f'ALTER POLICY executor_insert ON {S}.origins WITH CHECK (false)') + try: + self.assert_state(self.statement(key='blocked'),'42501'); self.assertEqual(self.state(),saved) + finally: self.admin(f'ALTER POLICY executor_insert ON {S}.origins WITH CHECK (true)') + self.assertEqual(self.receipt(self.runtime('SET row_security=off;'+self.statement())),receipt) + # Entry fixes row_security=on. Direct RLS is separately probed with temporary SELECT ACL. + self.admin(f'GRANT USAGE ON SCHEMA {S} TO {RUNTIME}; GRANT SELECT ON {S}.receipts TO {RUNTIME}') + try: + self.assertEqual(self.runtime(f'SELECT count(*) FROM {S}.receipts'),'0') + self.assert_state(f"SELECT set_config('row_security','off',false); SELECT * FROM {S}.receipts",'42501') + finally: self.admin(f'REVOKE SELECT ON {S}.receipts FROM {RUNTIME}; REVOKE USAGE ON SCHEMA {S} FROM {RUNTIME}') + + def test_11_shadow_objects_use_separate_reversible_TEMP_profile(self): + self.assert_state('CREATE TEMP TABLE accounts(id uuid)','42501') + self.admin(f'GRANT TEMPORARY ON DATABASE postgres TO {RUNTIME}') + try: + raw=self.runtime("CREATE TEMP TABLE accounts(id uuid); CREATE FUNCTION pg_temp.authorize_principal(uuid,uuid) RETURNS void LANGUAGE sql AS $$ SELECT $$; SET search_path=pg_temp,public;"+self.statement()) + self.receipt(raw) + self.assert_state("CREATE TEMP TABLE personal_principals(account_id uuid); SET search_path=pg_temp,public;"+self.statement(actor=B),'42501') + finally: self.admin(f'REVOKE TEMPORARY ON DATABASE postgres FROM {RUNTIME}') + self.assert_state('CREATE TEMP TABLE accounts(id uuid)','42501') + + def holder(self, statement, runtime=False): + process=subprocess.Popen(self.args(CLIENT if runtime else None),env={**self.env,'PGAPPNAME':'privilege-holder'},stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + self.addCleanup(lambda: process.poll() is None and process.kill()) + process.stdin.write((f'SET ROLE {RUNTIME};' if runtime else '')+'BEGIN;'+statement+"SELECT 'held';\n"); process.stdin.flush() + deadline=time.monotonic()+12; output='' + while time.monotonic()0 AND NOT attisdropped AND has_column_privilege('{EXECUTOR}',attrelid,attnum,'{privilege}')") + self.assertEqual(actual,','.join(sorted(matrix.get(privilege,[]))),table+' '+privilege) + for role in [RUNTIME,CLIENT,BROWSER]: + self.assertEqual(self.admin(f"SELECT has_any_column_privilege('{role}','{table}','{privilege}')"),'f') + self.assertEqual(self.admin(f"SELECT has_table_privilege('{EXECUTOR}','{table}','DELETE,TRUNCATE,REFERENCES,TRIGGER')"),'f') + empty_path = quote('search_path=""') + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_proc WHERE pronamespace='{S}'::regnamespace AND has_function_privilege('{EXECUTOR}',oid,'EXECUTE')"),'5') + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_proc WHERE pronamespace='{S}'::regnamespace AND (prosecdef OR proowner<>'{OWNER}'::regrole OR NOT proconfig @> ARRAY[{empty_path}])"),'0') + self.assertEqual(self.admin(f"SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgfoid='{S}.immutable_history()'::regprocedure"),'2') + self.assertEqual(self.admin(f"SELECT has_function_privilege('{EXECUTOR}','{S}.immutable_history()','EXECUTE')"),'f') + for role in [RUNTIME,CLIENT,BROWSER,EXECUTOR]: + for schema in ['public',S,E,'qualification_auth']: + self.assertEqual(self.admin(f"SELECT has_schema_privilege('{role}','{schema}','CREATE')"),'f') + policies=json.loads(self.admin(f"SELECT json_agg(json_build_object('table',schemaname||'.'||tablename,'command',cmd,'roles',roles,'using',qual,'check',with_check,'permissive',permissive) ORDER BY schemaname,tablename,policyname) FROM pg_policies WHERE schemaname='{S}' OR (schemaname='public' AND tablename='accounts')")) + self.assertEqual(len(policies),15) + for policy in policies: + self.assertEqual(policy['roles'],[EXECUTOR]) + self.assertIn(policy['command'],['SELECT','UPDATE','INSERT']) + if policy['command']=='UPDATE': + self.assertEqual((policy['using'],policy['check']),('true','false')) + print('EXACT_COLUMN_GRANTS '+json.dumps(self.permission_matrix(),sort_keys=True),flush=True) + print('RLS_POLICIES '+json.dumps(policies,sort_keys=True),flush=True) + print('FUNCTION_CATALOG '+self.admin(f"SELECT json_agg(json_build_object('signature',p.oid::regprocedure::text,'owner',p.proowner::regrole::text,'definer',p.prosecdef,'config',p.proconfig,'acl',p.proacl)) FROM pg_proc p WHERE pronamespace IN ('{E}'::regnamespace,'{S}'::regnamespace)"),flush=True) + + def test_18_each_select_insert_column_has_an_observed_dependency(self): + receipt=self.create(); self.grant_read(receipt); saved=self.state() + measured=[] + for table,matrix in self.permission_matrix().items(): + for privilege in ['SELECT','INSERT']: + for column in matrix.get(privilege,[]): + command=self.read_statement(receipt) if table in [S+'.management_entitlements',S+'.receipts'] and privilege=='SELECT' else self.statement(key='new') if privilege=='INSERT' else self.statement() + self.admin(f'REVOKE {privilege}({column}) ON {table} FROM {EXECUTOR}') + try: + self.assert_state(command,'42501'); self.assertEqual(self.state(),saved) + measured.append(table+':'+privilege+':'+column) + finally: self.admin(f'GRANT {privilege}({column}) ON {table} TO {EXECUTOR}') + self.assertEqual(self.create(),receipt) + print('MEASURED_COLUMN_DEPENDENCIES '+json.dumps(measured),flush=True) + + +def quote_identifier(value): + return '"'+value.replace('"','""')+'"' + + +def main(): + if sys.argv[1:]==['--worker']: + socket,pg_bin=D.prepare_worker_environment() + fault=os.environ.get('REGISTRATION_QUALIFICATION_FAULT') + if fault=='timeout': time.sleep(30) + if fault=='worker-exit': + subprocess.Popen([str(pg_bin/'psql'),'-XqAt','-h',socket,'-p','55473','-d','postgres','-c','SELECT pg_sleep(30)'],env=D.fixture_environment(Path(socket).parent,pg_bin)) + time.sleep(.1); return 86 + suite=unittest.defaultTestLoader.loadTestsFromTestCase(Privileges) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + if len(sys.argv)!=1: raise SystemExit('No connection strings or external targets accepted') + # Only redirect the existing supervisor's worker dispatch; no lifecycle copy. + D.__file__=str(Path(__file__).resolve()) + return D.supervise() + + +if __name__=='__main__': + raise SystemExit(main())