diff --git a/proposals/sites-publish-evidence-2094/PROTOCOL.md b/proposals/sites-publish-evidence-2094/PROTOCOL.md new file mode 100644 index 0000000..1a6b700 --- /dev/null +++ b/proposals/sites-publish-evidence-2094/PROTOCOL.md @@ -0,0 +1,64 @@ +# Inactive Sites evidence proposal (#2094) + +**Draft technical proposal only.** All executable SQL stays here, outside `supabase/migrations`. No API/UI caller, database integration change, hosted apply/dry run, production grant, or gate activation is included. API #959's early-publish behavior remains unchanged. Root owns release and explicit override interaction decisions. + +Baseline: Database `7708e337feca212563bdfa48934a72227bcf1b63`; API #1260 merge `9fb18d854e927777886c5cd7ed1b2a165a9c669c`. Refreshed App main `630d3acae99d50186fa079814f0a2f94efdf7de5` still has an advisory `components/Sites/PublishSiteButton.tsx`; `SiteEditor.publishPreview` sends action/revision/return URL/optional generation token, not override intent. The earlier plan's App `9f3c3a` pin is historical, not the refreshed observation. + +## Proposed boundary + +One RLS-enabled private table, `sites_evidence_proposal.records`, retains immutable candidate/report or explicit-override records. One nullable `public.sites.published_evidence_id` identifies the record supporting the live snapshot. Existing publications start null. Two write transactions and one scoped read operate on the table: + +| Function | Inputs and result | +| --- | --- | +| `record_evidence` | Trusted authenticated actor, owner, site, current revision, operation key, complete candidate, candidate canonical text/digest, review or override decision, optional report canonical text. Returns the server-created ID/time and API1260 assessment record shape. | +| `read_evidence` | Actor, owner, site, record ID. Rechecks current membership and existing site; returns that scoped immutable record, including historical revisions. A UUID is not authorization. | +| `publish_candidate` | Actor, owner, site, expected draft revision, record ID, expected candidate digest, previously observed nullable publication pointer and explicitly nullable expected artist ID. Publishes only the stored candidate and updates pointer/time atomically. Keeps draft, draft revision and artist ID unchanged. | + +Actor identity is a trusted API forwarding obligation. SQL does not authenticate arbitrary UUID arguments. Each entry reuses the existing `authorize_context_case_actor` membership-lock primitive, matching current Sites personal/workspace membership semantics. Its use supplies a transaction-level membership check, not new commercial, creative or external-action authority. The future API must still perform all existing context, paid-workspace, artist/fan configuration and current-generation checks. Artist resolution/transitions are **not implemented here**; this proposal preserves the existing artist ID and compares it with the selected expected artist under the site row lock. Null matches null; null versus nonnull conflicts. No artist mutation or new attribution policy is introduced. A later adapter cannot treat this transaction as a replacement for those checks. + +The schema/function owner must be isolated from runtime roles. All function EXECUTE and table/column access are revoked from PUBLIC, anon, authenticated and service_role. No runtime role is created. `fixture-grants.sql` grants only schema USAGE and the three entry functions to the synthetic local service role; it is not a release grant. Entry functions are SECURITY DEFINER with empty search_path and qualified application/catalog relations. Internal validators and trigger functions remain non-callable to runtime roles. The disposable cluster owner is a PostgreSQL superuser: tests assert runtime ACL/ownership behavior, not resistance to an administrator who can alter objects or triggers. + +## Immutable records and retry semantics + +The database creates record UUID/time; neither can be supplied in decision JSON. An operation key is unique per site/workspace. A retry returns the original record only when actor, revision, full candidate, canonical bytes/digest and complete decision/report bytes match. Changed data conflicts. Different site/workspace keys are distinct namespaces after access checks. Site-row locking serializes competing captures. Every retry first checks current membership and revision: after draft advancement, old-key capture fails; scoped historical read can still return its original record. Do not automatically mint a new retry key after an unknown commit acknowledgment. + +Review and override decision envelopes reject unrelated fields, including claimed actor/time or human approval. Failed or malformed *object* reports can be retained with their actual digest but cannot publish as passed evidence. Nonobject reports and inconsistent digest envelopes are rejected at capture. An override requires the exact stored `publish-without-passed-review` intent and nonblank reason; publication requires the same authenticated actor. There is no implicit review-to-override fallback and no generic record TTL. + +`UPDATE` and direct `DELETE` of records are guarded, and runtime roles have no INSERT/UPDATE/DELETE/TRUNCATE/column privileges. Proposed retention is the lifetime of the site: an authorized explicit site deletion cascades only its records. This is a local technical proposal, not approved retention policy. Records cannot be moved to another site. A guarded owner transition is rejected whenever any evidence is retained for that site, including while unpublished; it cannot orphan an old workspace record or retain a foreign-workspace publication pointer. The owner guard is an additional non-callable SECURITY DEFINER trigger so runtime roles need no private-record SELECT grant. Existing service-role DELETE on sites remains a trusted destructive boundary, not proof of a human request. Service-role `TRUNCATE sites CASCADE` fails because it lacks TRUNCATE on the evidence table; cluster-owner fixture TRUNCATE remains privileged maintenance outside the runtime contract. Site deletion with a populated evidence pointer is exercised to qualify the FK cycle. + +## Digest and report boundary + +API `hashSiteEvidence` uses sorted JavaScript object keys plus JSON.stringify; PostgreSQL JSONB text is not equivalent. The adapter must provide those canonical UTF-8 strings. SQL checks that each string parses to the supplied candidate projection/report and that SHA-256 of the exact bytes matches its digest. Candidate projection excludes only `production.reviews` and `production.status`. The full immutable snapshot still includes both, and changing either conflicts on a retry key. SQL does not independently prove that supplied text is the unique JavaScript canonical form; producing it with the pinned helper semantics remains an adapter obligation. + +`api-digest-vectors.json` was generated using the actual pinned API helpers, including a Unicode-key/floating-number case. PostgreSQL tests persist those exact canonical strings and compare their real helper-produced digests. Report hashes and executed source/journey/runner digests are stored unchanged. No record-time code rewrites a review's evidence to match a new candidate. + +SQL rejects review publication unless necessary persisted conditions pass: pass verdict; no blocked state or blocking/direction issue; explicit generated-experience/not-recorded/not-tested metadata; well-formed digest fields and journey; exactly one successful mobile and desktop result, no errors/overflow; and complete passing opening review when supplied. Validators fail closed for malformed/null JSON, including direct SQL calls. These are **necessary structural checks**, not execution of the TypeScript renderer, proof that a model/browser ran, or full API policy replacement. The future trusted adapter must call `assessSitePublishEvidence` on the actual resolved candidate and same immutable record before publication to compare actual document, executed journey and current runner. Offline companion evidence exercised those actual API helpers with matching, source-drift and runner-drift fixtures; no browser/provider ran. + +Capture the fully assembled draft at the revision returned by final save. Generation claim and final draft save each advance revision; a fixture models both. Do not relabel an old report by adding one to its revision. Compute the new candidate binding while preserving original executed report digests, compare artifacts and reject drift. A working preview can differ within one revision and must retain signed account/site/current-generation validation in the future adapter. The database does not read Workflow history or authenticate a generation token. + +## Publication, legacy writers and concurrency + +The transaction locks membership, then the site, verifies revision/pointer/expected-artist/site/owner/record/digest and eligibility, and copies `records.candidate` into `sites.published`. It never accepts replacement JSON or reads a mutable latest draft. The pointer and publication timestamp commit together; any exception rolls back all writes. Draft revision is unchanged. Two publishers with the same observed pointer have one winner. A prior draft revision change rejects publication; a draft write waiting behind publication preserves the live snapshot/pointer afterward. + +The existing Sites table grants ALL to service_role, so an RPC alone is insufficient. Proposed row triggers reject direct runtime assignment of a nonnull evidence pointer and clear the pointer on legacy updates mentioning published/published_at/pointer, even a same-byte replacement. Artist-ID changes clear the pointer; draft-only updates, including an unchanged artist ID, preserve it. Unpublish clears published/published_at through the existing writer and the trigger clears its pointer. INSERT cannot forge a pointer. The schema owner is the trusted definer identity; a caller-controlled GUC is never authority. + +A null pointer cannot order two legacy publications or detect an evidence-pointer ABA caused by unpublish/republication. This proposal does not claim that guarantee or add another version column. Same-revision evidence-based publication CAS is tested against a stable observed pointer; broader intent sequencing would require a separate accepted concurrency contract. Existing advisory operations are not disabled. Future activation must reconcile legacy writers/old deployments rather than silently treating null pointers as approval. + +## Local qualification and remaining release work + +Run with one PostgreSQL installation on PATH, or `PG_BIN`: + +```sh +PG_BIN=/path/to/postgresql-15/bin python3 proposals/sites-publish-evidence-2094/test_contract.py +PG_BIN=/path/to/postgresql-17/bin python3 proposals/sites-publish-evidence-2094/test_contract.py +``` + +The suite reuses `tests/test_release_cases.py`'s disposable Unix-socket-only cluster and actual prerequisite Context SQL, then applies the actual Sites baseline and this proposal. Synthetic legacy tables supply only required historical prerequisites; this is not a full migration replay. It uses no hosted DSN, real credentials, Storage, provider calls or production data. It also runs the inherited release-case prerequisite test. Broad Supabase-shaped default grants are deliberately installed before the proposal, then table/column/internal-function ACLs are checked. + +The proposal requires separate release assessment of owner/grants, dependencies, legacy writer compatibility, retention and actor forwarding before any migration is authored or applied. API capture/read/publication adapters, exact-candidate preview selection and explicit override interaction remain later and unwired. The current Publish click must not become a fabricated override. No mandatory artist approval, source collector, paid repair loop, screenshot store or native qualification is added. This does not complete all of #2094 or #2345. + +### Expected-artist fence revision + +`publish_candidate` now requires its eighth argument, `p_expected_artist_id uuid`, with no default or seven-argument overload. It compares `sites.artist_id IS DISTINCT FROM p_expected_artist_id` under the same existing `FOR UPDATE` lock before any publication writes, returning SQLSTATE40001 on mismatch. An artist writer that commits between the final API read and this transaction therefore causes a conflict even when revision and a null publication pointer are unchanged. The failed attempt changes neither published snapshot, pointer, published_at nor updated_at. A concurrent held artist-writer lock is exercised: the publisher waits, then observes the committed artist and rejects. Stable nonnull and null artist matches pass without changing artist attribution. + +Capture/read signatures, assessment-record shape, canonical golden vectors, record immutability, retention and default-denied ACLs are unchanged; API#1263 remains compatible. Only the inactive publication RPC signature and fixture-only grant are extended. General paid/Context/fan-configuration/Workflow checks still require API rechecks and are not made atomic by this artist-ID fence. diff --git a/proposals/sites-publish-evidence-2094/api-digest-vectors.json b/proposals/sites-publish-evidence-2094/api-digest-vectors.json new file mode 100644 index 0000000..b909075 --- /dev/null +++ b/proposals/sites-publish-evidence-2094/api-digest-vectors.json @@ -0,0 +1,201 @@ +{ + "apiCommit": "9fb18d854e927777886c5cd7ed1b2a165a9c669c", + "sourceHashes": { + "getSitePublishIdentity.ts": "fafcaffc8b51333b7a320328c7d53eba26de8ed406f49284e88da8025bff1798", + "hashSiteEvidence.ts": "6482f20729a762e027d94f4d5c695349171ae51a0a1899a73d388af5cde09f95", + "prepareSiteRenderArtifacts.ts": "da8a025de2db179436b9b5c87a91dcc178aeca26dcffddc907359a8e11e52964", + "assessSitePublishEvidence.ts": "610956438219d0ac680b13672e1e90ae4c393de914c74597b2ffe51e755849e1" + }, + "vectors": [ + { + "name": "ordinary", + "candidate": { + "name": "Synthetic preview", + "releaseUrl": "", + "assets": [], + "design": { + "experience": { + "html": "", + "css": "", + "javascript": "void 0" + } + }, + "production": { + "version": 1, + "context": {}, + "direction": {}, + "reviews": [], + "status": "reviewed" + } + }, + "candidateCanonical": "{\"assets\":[],\"design\":{\"experience\":{\"css\":\"\",\"html\":\"\",\"javascript\":\"void 0\"}},\"name\":\"Synthetic preview\",\"production\":{\"context\":{},\"direction\":{},\"version\":1},\"releaseUrl\":\"\"}", + "candidateSha256": "0cc032b80c00a8c7df33a00b4d0e7abebe0a6d426782b057bac7054f0d96f3b5", + "review": { + "verdict": "pass", + "issues": [], + "summary": "Synthetic; no browser ran", + "verification": { + "scope": "generated-experience", + "humanApproval": "not-recorded", + "nativeShareDelivery": "not-tested", + "spotifyAuthentication": "not-tested", + "evidence": { + "sourceSha256": "f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b", + "journeySha256": "011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da", + "runnerSha256": "b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294" + }, + "journey": { + "releaseConnection": "A concrete release connection", + "evidence": [ + "Synthetic" + ], + "motivation": "A concrete motivation for participation", + "payoff": "A concrete payoff from participation", + "capabilities": [ + "browser-interaction" + ], + "steps": [ + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "participate" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "result" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "delivery" + } + ] + }, + "viewports": [ + { + "name": "mobile", + "journeyPassed": true, + "errors": [], + "overflow": false + }, + { + "name": "desktop", + "journeyPassed": true, + "errors": [], + "overflow": false + } + ] + } + }, + "reviewCanonical": "{\"issues\":[],\"summary\":\"Synthetic; no browser ran\",\"verdict\":\"pass\",\"verification\":{\"evidence\":{\"journeySha256\":\"011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da\",\"runnerSha256\":\"b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294\",\"sourceSha256\":\"f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b\"},\"humanApproval\":\"not-recorded\",\"journey\":{\"capabilities\":[\"browser-interaction\"],\"evidence\":[\"Synthetic\"],\"motivation\":\"A concrete motivation for participation\",\"payoff\":\"A concrete payoff from participation\",\"releaseConnection\":\"A concrete release connection\",\"steps\":[{\"action\":\"click\",\"checkpoint\":\"participate\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"result\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"delivery\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"}]},\"nativeShareDelivery\":\"not-tested\",\"scope\":\"generated-experience\",\"spotifyAuthentication\":\"not-tested\",\"viewports\":[{\"errors\":[],\"journeyPassed\":true,\"name\":\"mobile\",\"overflow\":false},{\"errors\":[],\"journeyPassed\":true,\"name\":\"desktop\",\"overflow\":false}]}}", + "reviewSha256": "0fa29ee1a6ce36eab359f50ecec75f8ee86727d1aedfad61781241cf9376448b" + }, + { + "name": "unicode-and-numbers", + "candidate": { + "name": "Synthetic preview", + "releaseUrl": "", + "assets": [], + "design": { + "experience": { + "html": "", + "css": "", + "javascript": "void 0" + } + }, + "production": { + "version": 1, + "context": { + "𐀀": 1, + "": 2, + "numbers": [ + 0, + 1e+21, + 1e-7, + 1.5 + ], + "text": "🎵 café" + }, + "direction": {}, + "reviews": [], + "status": "reviewed" + } + }, + "candidateCanonical": "{\"assets\":[],\"design\":{\"experience\":{\"css\":\"\",\"html\":\"\",\"javascript\":\"void 0\"}},\"name\":\"Synthetic preview\",\"production\":{\"context\":{\"numbers\":[0,1e+21,1e-7,1.5],\"text\":\"🎵 café\",\"𐀀\":1,\"\":2},\"direction\":{},\"version\":1},\"releaseUrl\":\"\"}", + "candidateSha256": "543df88ccfb1714a8a28836065d2749e34492bc0caaf921a5a04a8528ab16740", + "review": { + "verdict": "pass", + "issues": [], + "summary": "Synthetic; no browser ran", + "verification": { + "scope": "generated-experience", + "humanApproval": "not-recorded", + "nativeShareDelivery": "not-tested", + "spotifyAuthentication": "not-tested", + "evidence": { + "sourceSha256": "f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b", + "journeySha256": "011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da", + "runnerSha256": "b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294" + }, + "journey": { + "releaseConnection": "A concrete release connection", + "evidence": [ + "Synthetic" + ], + "motivation": "A concrete motivation for participation", + "payoff": "A concrete payoff from participation", + "capabilities": [ + "browser-interaction" + ], + "steps": [ + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "participate" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "result" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "delivery" + } + ] + }, + "viewports": [ + { + "name": "mobile", + "journeyPassed": true, + "errors": [], + "overflow": false + }, + { + "name": "desktop", + "journeyPassed": true, + "errors": [], + "overflow": false + } + ] + } + }, + "reviewCanonical": "{\"issues\":[],\"summary\":\"Synthetic; no browser ran\",\"verdict\":\"pass\",\"verification\":{\"evidence\":{\"journeySha256\":\"011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da\",\"runnerSha256\":\"b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294\",\"sourceSha256\":\"f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b\"},\"humanApproval\":\"not-recorded\",\"journey\":{\"capabilities\":[\"browser-interaction\"],\"evidence\":[\"Synthetic\"],\"motivation\":\"A concrete motivation for participation\",\"payoff\":\"A concrete payoff from participation\",\"releaseConnection\":\"A concrete release connection\",\"steps\":[{\"action\":\"click\",\"checkpoint\":\"participate\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"result\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"delivery\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"}]},\"nativeShareDelivery\":\"not-tested\",\"scope\":\"generated-experience\",\"spotifyAuthentication\":\"not-tested\",\"viewports\":[{\"errors\":[],\"journeyPassed\":true,\"name\":\"mobile\",\"overflow\":false},{\"errors\":[],\"journeyPassed\":true,\"name\":\"desktop\",\"overflow\":false}]}}", + "reviewSha256": "0fa29ee1a6ce36eab359f50ecec75f8ee86727d1aedfad61781241cf9376448b" + } + ] +} diff --git a/proposals/sites-publish-evidence-2094/fixture-grants.sql b/proposals/sites-publish-evidence-2094/fixture-grants.sql new file mode 100644 index 0000000..af46a2b --- /dev/null +++ b/proposals/sites-publish-evidence-2094/fixture-grants.sql @@ -0,0 +1,5 @@ +-- Synthetic local fixture admission ONLY. Not production grants or a migration. +grant usage on schema sites_evidence_proposal to service_role; +grant execute on function sites_evidence_proposal.record_evidence(uuid,uuid,uuid,integer,text,jsonb,text,text,jsonb,text) to service_role; +grant execute on function sites_evidence_proposal.read_evidence(uuid,uuid,uuid,uuid) to service_role; +grant execute on function sites_evidence_proposal.publish_candidate(uuid,uuid,uuid,integer,uuid,text,uuid,uuid) to service_role; diff --git a/proposals/sites-publish-evidence-2094/proposal.sql b/proposals/sites-publish-evidence-2094/proposal.sql new file mode 100644 index 0000000..ca4f462 --- /dev/null +++ b/proposals/sites-publish-evidence-2094/proposal.sql @@ -0,0 +1,283 @@ +-- INACTIVE PROPOSAL. Apply only to a disposable fixture, never through migration discovery. +-- No callable roles are granted here. fixture-grants.sql is synthetic test admission only. +begin; +do $$ begin + if current_user in ('service_role','anon','authenticated') or pg_has_role('service_role',current_user,'MEMBER') then + raise exception 'Proposal owner must be isolated from runtime roles'; + end if; +end $$; +create schema sites_evidence_proposal; +revoke all on schema sites_evidence_proposal from public, anon, authenticated, service_role; + +create table sites_evidence_proposal.records ( + id uuid primary key default gen_random_uuid(), + site_id uuid not null references public.sites(id) on delete cascade, + owner_id uuid not null references public.accounts(id), + revision integer not null check(revision >= 0), + operation_key text not null check(operation_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + recorded_by_account_id uuid not null references public.accounts(id), + recorded_at timestamptz not null default clock_timestamp(), + candidate jsonb not null, + candidate_canonical text not null, + candidate_sha256 text not null check(candidate_sha256 ~ '^[a-f0-9]{64}$'), + decision jsonb not null, + review_canonical text, + unique(site_id,owner_id,operation_key) +); +alter table sites_evidence_proposal.records enable row level security; +revoke all on sites_evidence_proposal.records from public,anon,authenticated,service_role; +alter table public.sites add column published_evidence_id uuid + references sites_evidence_proposal.records(id) on delete set null; + +-- Only deletion of the parent site purges retained evidence. Ordinary UPDATE/DELETE is denied. +create function sites_evidence_proposal.guard_record() returns trigger +language plpgsql set search_path='' as $$ +begin + if tg_op='DELETE' and not exists(select 1 from public.sites where id=old.site_id) then return old; end if; + raise exception 'Sites evidence is immutable' using errcode='42501'; +end $$; +create trigger immutable_site_evidence before update or delete on sites_evidence_proposal.records + for each row execute function sites_evidence_proposal.guard_record(); + +-- JSONB is not JSON.stringify. The trusted adapter supplies canonical UTF-8 text using +-- API hashSiteEvidence's sorting/serialization; SQL verifies its JSON meaning and byte digest. +-- This is a content binding, NOT independent renderer/reviewer or authentication execution. +create function sites_evidence_proposal.candidate_projection(p_candidate jsonb) returns jsonb +language sql immutable set search_path='' as $$ + select case when p_candidate ? 'production' then + jsonb_set(p_candidate,'{production}',(p_candidate->'production')-'reviews'-'status') + else p_candidate end +$$; + +create function sites_evidence_proposal.journey_shape(p_journey jsonb) returns boolean +language plpgsql immutable set search_path='' as $$ +declare item jsonb; key text; +begin + if jsonb_typeof(p_journey) is distinct from 'object' then return false; end if; + foreach key in array array['releaseConnection','motivation','payoff'] loop + if jsonb_typeof(p_journey->key) is distinct from 'string' or length(p_journey->>key)<20 then return false; end if; + end loop; + if jsonb_typeof(p_journey->'evidence') is distinct from 'array' + or jsonb_array_length(p_journey->'evidence') not between 1 and 8 then return false; end if; + for item in select value from jsonb_array_elements(p_journey->'evidence') loop + if jsonb_typeof(item) is distinct from 'string' or length(item#>>'{}')<5 then return false; end if; + end loop; + if jsonb_typeof(p_journey->'capabilities') is distinct from 'array' + or jsonb_array_length(p_journey->'capabilities')<1 then return false; end if; + for item in select value from jsonb_array_elements(p_journey->'capabilities') loop + if jsonb_typeof(item) is distinct from 'string' or item#>>'{}' not in + ('browser-interaction','production-artwork','image-download','file-share') then return false; end if; + end loop; + if jsonb_typeof(p_journey->'steps') is distinct from 'array' + or jsonb_array_length(p_journey->'steps') not between 3 and 16 then return false; end if; + for item in select value from jsonb_array_elements(p_journey->'steps') loop + if jsonb_typeof(item) is distinct from 'object' + or jsonb_typeof(item->'action') is distinct from 'string' or item->>'action' not in ('click','fill','press','download','share') + or jsonb_typeof(item->'target') is distinct from 'string' or length(item->>'target') not between 1 and 100 + or jsonb_typeof(item->'value') is distinct from 'string' or length(item->>'value')>200 + or jsonb_typeof(item->'expected') is distinct from 'string' or length(item->>'expected')>300 + or jsonb_typeof(item->'checkpoint') is distinct from 'string' or item->>'checkpoint' not in ('participate','result','delivery') then return false; end if; + foreach key in array array['holdMs','waitMs'] loop + if item ? key and (jsonb_typeof(item->key) is distinct from 'number' + or (item->>key)::numeric<>trunc((item->>key)::numeric) + or (item->>key)::numeric<0 or (item->>key)::numeric>case when key='holdMs' then 2000 else 20000 end) then return false; end if; + end loop; + end loop; + return true; +exception when others then return false; +end $$; + +-- Necessary persisted conditions matching API1260. Full API assessment must additionally +-- compare the actual candidate's document, executed journey and current runner digests. +create function sites_evidence_proposal.review_passes(p_review jsonb) returns boolean +language plpgsql immutable set search_path='' as $$ +declare v jsonb; item jsonb; key text; opening jsonb; +begin + if jsonb_typeof(p_review) is distinct from 'object' or p_review->>'verdict' is distinct from 'pass' + or p_review ? 'blocked' or jsonb_typeof(p_review->'summary') is distinct from 'string' + or jsonb_typeof(p_review->'issues') is distinct from 'array' or jsonb_array_length(p_review->'issues')>12 then return false; end if; + for item in select value from jsonb_array_elements(p_review->'issues') loop + if jsonb_typeof(item) is distinct from 'object' + or jsonb_typeof(item->'severity') is distinct from 'string' or item->>'severity' not in ('visual','minor') + or jsonb_typeof(item->'module') is distinct from 'string' or item->>'module' not in ('assets','implementation') + or jsonb_typeof(item->'detail') is distinct from 'string' or jsonb_typeof(item->'fix') is distinct from 'string' then return false; end if; + end loop; + v:=p_review->'verification'; + if jsonb_typeof(v) is distinct from 'object' or v->>'scope' is distinct from 'generated-experience' + or v->>'humanApproval' is distinct from 'not-recorded' or v->>'nativeShareDelivery' is distinct from 'not-tested' + or v->>'spotifyAuthentication' is distinct from 'not-tested' + or jsonb_typeof(v->'evidence') is distinct from 'object' then return false; end if; + foreach key in array array['sourceSha256','journeySha256','runnerSha256'] loop + if jsonb_typeof(v->'evidence'->key) is distinct from 'string' + or (v->'evidence'->>key) !~ '^[a-f0-9]{64}$' then return false; end if; + end loop; + if not sites_evidence_proposal.journey_shape(v->'journey') then return false; end if; + if jsonb_typeof(v->'viewports') is distinct from 'array' or jsonb_array_length(v->'viewports')<>2 then return false; end if; + if (select count(distinct value->>'name') from jsonb_array_elements(v->'viewports'))<>2 then return false; end if; + for item in select value from jsonb_array_elements(v->'viewports') loop + if jsonb_typeof(item) is distinct from 'object' or jsonb_typeof(item->'name') is distinct from 'string' + or item->>'name' not in ('mobile','desktop') or item->'journeyPassed' is distinct from 'true'::jsonb + or item->'errors' is distinct from '[]'::jsonb or item->'overflow' is distinct from 'false'::jsonb then return false; end if; + end loop; + if v ? 'opening' then + opening:=v->'opening'; + if jsonb_typeof(opening) is distinct from 'object' or opening->>'verdict' is distinct from 'pass' + or opening->'issues' is distinct from '[]'::jsonb or jsonb_typeof(opening->'summary') is distinct from 'string' + or jsonb_typeof(opening->'observations') is distinct from 'array' or jsonb_array_length(opening->'observations')<>2 then return false; end if; + for item in select value from jsonb_array_elements(opening->'observations') loop + if jsonb_typeof(item) is distinct from 'object' or jsonb_typeof(item->'viewport') is distinct from 'string' + or item->>'viewport' not in ('mobile','desktop') then return false; end if; + foreach key in array array['invitation','firstAction','expectedResponse'] loop + if jsonb_typeof(item->key) is distinct from 'string' then return false; end if; + end loop; + end loop; + end if; + return true; +exception when others then return false; +end $$; + +-- Match ECMAScript trim whitespace for the API's explicit nonblank reason contract. +create function sites_evidence_proposal.explicit_override(p_decision jsonb) returns boolean +language plpgsql immutable set search_path='' as $$ +begin + return coalesce(jsonb_typeof(p_decision)='object' + and p_decision - array['kind','intent','reason']='{}'::jsonb + and p_decision->>'kind'='override' + and p_decision->>'intent'='publish-without-passed-review' + and jsonb_typeof(p_decision->'reason')='string' + and length(btrim(p_decision->>'reason', U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF')) between 1 and 2000,false); +exception when others then return false; +end $$; + +create function sites_evidence_proposal.record_json(r sites_evidence_proposal.records) returns jsonb +language sql stable set search_path='' as $$ + select jsonb_build_object('id',r.id,'siteId',r.site_id,'ownerId',r.owner_id,'revision',r.revision, + 'candidateSha256',r.candidate_sha256,'recordedByAccountId',r.recorded_by_account_id, + 'recordedAt',to_char(r.recorded_at at time zone 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"')) || r.decision +$$; + +create function sites_evidence_proposal.record_evidence( + p_actor uuid,p_owner uuid,p_site uuid,p_revision integer,p_key text, + p_candidate jsonb,p_candidate_canonical text,p_candidate_sha text,p_decision jsonb,p_review_canonical text +) returns jsonb language plpgsql security definer set search_path='' as $$ +declare s public.sites; r sites_evidence_proposal.records; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into s from public.sites where id=p_site and owner_id=p_owner for update; + if s.id is null then raise exception 'Site unavailable' using errcode='42501'; end if; + if p_revision is null or s.revision<>p_revision then raise exception 'Revision conflict' using errcode='40001'; end if; + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid operation key'; end if; + if jsonb_typeof(p_candidate) is distinct from 'object' or octet_length(p_candidate::text)>1048576 + or jsonb_typeof(p_candidate#>'{design,experience}') is distinct from 'object' + or jsonb_typeof(p_candidate#>'{design,experience,html}') is distinct from 'string' or length(p_candidate#>>'{design,experience,html}')=0 + or jsonb_typeof(p_candidate#>'{design,experience,css}') is distinct from 'string' + or jsonb_typeof(p_candidate#>'{design,experience,javascript}') is distinct from 'string' + or (p_candidate ? 'production' and jsonb_typeof(p_candidate->'production') is distinct from 'object') then raise exception 'Invalid candidate'; end if; + if p_candidate_canonical is null or octet_length(p_candidate_canonical)>1048576 + or p_candidate_canonical::jsonb is distinct from sites_evidence_proposal.candidate_projection(p_candidate) + or p_candidate_sha is null or p_candidate_sha !~ '^[a-f0-9]{64}$' + or encode(sha256(convert_to(p_candidate_canonical,'UTF8')),'hex')<>p_candidate_sha then raise exception 'Candidate digest mismatch'; end if; + if jsonb_typeof(p_decision) is distinct from 'object' or octet_length(p_decision::text)>1048576 then raise exception 'Invalid decision'; end if; + if p_decision->>'kind'='review' then + if p_decision - array['kind','review','reviewSha256'] <> '{}'::jsonb + or jsonb_typeof(p_decision->'review') is distinct from 'object' + or p_review_canonical is null or octet_length(p_review_canonical)>1048576 + or p_review_canonical::jsonb is distinct from p_decision->'review' + or jsonb_typeof(p_decision->'reviewSha256') is distinct from 'string' + or (p_decision->>'reviewSha256') !~ '^[a-f0-9]{64}$' + or encode(sha256(convert_to(p_review_canonical,'UTF8')),'hex')<>p_decision->>'reviewSha256' then raise exception 'Report digest mismatch'; end if; + elsif p_decision->>'kind'='override' then + if p_review_canonical is not null or not sites_evidence_proposal.explicit_override(p_decision) + then raise exception 'Explicit override required'; end if; + else raise exception 'Invalid decision kind'; end if; + select * into r from sites_evidence_proposal.records where site_id=p_site and owner_id=p_owner and operation_key=p_key; + if r.id is not null then + if r.revision<>p_revision or r.recorded_by_account_id<>p_actor or r.candidate<>p_candidate + or r.candidate_canonical<>p_candidate_canonical or r.candidate_sha256<>p_candidate_sha + or r.decision<>p_decision or r.review_canonical is distinct from p_review_canonical then raise exception 'Idempotency conflict' using errcode='23505'; end if; + return sites_evidence_proposal.record_json(r); + end if; + insert into sites_evidence_proposal.records(site_id,owner_id,revision,operation_key,recorded_by_account_id, + candidate,candidate_canonical,candidate_sha256,decision,review_canonical) + values(p_site,p_owner,p_revision,p_key,p_actor,p_candidate,p_candidate_canonical,p_candidate_sha,p_decision,p_review_canonical) returning * into r; + return sites_evidence_proposal.record_json(r); +end $$; + +create function sites_evidence_proposal.read_evidence(p_actor uuid,p_owner uuid,p_site uuid,p_record uuid) +returns jsonb language plpgsql security definer set search_path='' as $$ +declare r sites_evidence_proposal.records; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform 1 from public.sites where id=p_site and owner_id=p_owner for share; + if not found then raise exception 'Site unavailable' using errcode='42501'; end if; + select * into r from sites_evidence_proposal.records where id=p_record and site_id=p_site and owner_id=p_owner; + if r.id is null then raise exception 'Evidence unavailable' using errcode='42501'; end if; + return sites_evidence_proposal.record_json(r); +end $$; + +-- Retained records remain bound to their original workspace, even while unpublished. +-- The trigger needs owner privilege only to inspect private record existence. +create function sites_evidence_proposal.guard_owner() returns trigger +language plpgsql security definer set search_path='' as $$ +begin + if new.owner_id is distinct from old.owner_id and exists( + select 1 from sites_evidence_proposal.records where site_id=old.id + ) then raise exception 'Evidence owner cannot change' using errcode='42501'; end if; + return new; +end $$; +create trigger preserve_site_evidence_owner before update of owner_id on public.sites + for each row execute function sites_evidence_proposal.guard_owner(); + +-- Legacy advisory writers can still publish/unpublish, but cannot claim evidence. +-- The schema owner is the trusted function owner, not the service caller or a settable GUC. +create function sites_evidence_proposal.guard_publication() returns trigger +language plpgsql set search_path='' as $$ +declare trusted_owner name; r sites_evidence_proposal.records; +begin + select pg_get_userbyid(nspowner) into trusted_owner from pg_catalog.pg_namespace where nspname='sites_evidence_proposal'; + if new.published_evidence_id is distinct from old.published_evidence_id and new.published_evidence_id is not null + and current_user<>trusted_owner then raise exception 'Evidence pointer is server-owned' using errcode='42501'; end if; + if new.published is null then new.published_evidence_id:=null; + elsif current_user<>trusted_owner and + (tg_argv[0]='publication' or new.artist_id is distinct from old.artist_id) + then new.published_evidence_id:=null; + end if; + if new.published_evidence_id is not null and + (new.published_evidence_id is distinct from old.published_evidence_id or new.published is distinct from old.published or new.published_at is distinct from old.published_at) then + select * into r from sites_evidence_proposal.records where id=new.published_evidence_id and site_id=new.id and owner_id=new.owner_id; + if r.id is null or r.candidate is distinct from new.published or r.revision<>new.revision then raise exception 'Evidence pointer mismatch'; end if; + end if; + return new; +end $$; +create trigger maintain_site_publication_evidence before insert or update of published,published_at,published_evidence_id on public.sites + for each row execute function sites_evidence_proposal.guard_publication('publication'); +create trigger maintain_site_artist_evidence before update of artist_id on public.sites + for each row execute function sites_evidence_proposal.guard_publication('artist'); + +create function sites_evidence_proposal.publish_candidate( + p_actor uuid,p_owner uuid,p_site uuid,p_revision integer,p_record uuid,p_candidate_sha text,p_expected_pointer uuid,p_expected_artist_id uuid +) returns jsonb language plpgsql security definer set search_path='' as $$ +declare s public.sites; r sites_evidence_proposal.records; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into s from public.sites where id=p_site and owner_id=p_owner for update; + if s.id is null then raise exception 'Site unavailable' using errcode='42501'; end if; + if p_revision is null or s.revision<>p_revision or s.published_evidence_id is distinct from p_expected_pointer or s.artist_id is distinct from p_expected_artist_id then raise exception 'Publication conflict' using errcode='40001'; end if; + select * into r from sites_evidence_proposal.records where id=p_record and site_id=p_site and owner_id=p_owner; + if r.id is null or r.revision<>p_revision or p_candidate_sha is distinct from r.candidate_sha256 then raise exception 'Evidence conflict' using errcode='40001'; end if; + if not coalesce(case r.decision->>'kind' + when 'review' then sites_evidence_proposal.review_passes(r.decision->'review') + when 'override' then sites_evidence_proposal.explicit_override(r.decision) and r.recorded_by_account_id=p_actor + else false end,false) then raise exception 'Evidence not eligible' using errcode='42501'; end if; + update public.sites set published=r.candidate,published_evidence_id=r.id,published_at=clock_timestamp(),updated_at=clock_timestamp() + where id=p_site returning * into s; + return jsonb_build_object('site',to_jsonb(s),'evidence',sites_evidence_proposal.record_json(r),'humanApproval','not-recorded'); +end $$; + +-- Functions are default-denied, including to service_role, until a separately reviewed admission. +do $$ declare f regprocedure; begin + for f in select p.oid::regprocedure from pg_catalog.pg_proc p join pg_catalog.pg_namespace n on n.oid=p.pronamespace where n.nspname='sites_evidence_proposal' loop + execute format('revoke all on function %s from public,anon,authenticated,service_role',f); + end loop; +end $$; +commit; diff --git a/proposals/sites-publish-evidence-2094/test_contract.py b/proposals/sites-publish-evidence-2094/test_contract.py new file mode 100644 index 0000000..a7f1f03 --- /dev/null +++ b/proposals/sites-publish-evidence-2094/test_contract.py @@ -0,0 +1,517 @@ +"""Synthetic Sites proposal on the existing disposable Unix-socket PostgreSQL harness.""" +import concurrent.futures +import copy +import hashlib +import json +import os +import pathlib +import subprocess +import sys +import time +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[2] +HERE = pathlib.Path(__file__).resolve().parent +if os.environ.get('PG_BIN'): + os.environ['PATH'] = os.environ['PG_BIN'] + os.pathsep + os.environ['PATH'] +sys.path.insert(0, str(ROOT / 'tests')) +import test_release_cases as harness + + +def uid(n): + return f'00000000-0000-0000-0000-{n:012d}' + + +def literal(value): + return 'NULL' if value is None else "'" + str(value).replace("'", "''") + "'" + + +def canonical(value): + # Fixtures use ASCII keys and safe integer values; checked against pinned API vectors. + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + + +def digest(text): + return hashlib.sha256(text.encode()).hexdigest() + + +def candidate(): + return {'name': 'Synthetic preview', 'releaseUrl': '', 'assets': [], 'design': { + 'experience': {'html': '', 'css': '', 'javascript': 'void 0'}}, + 'production': {'version': 1, 'context': {}, 'direction': {}, 'reviews': [], 'status': 'reviewed'}} + + +def projection(value): + value = copy.deepcopy(value) + if 'production' in value: + value['production'].pop('reviews', None) + value['production'].pop('status', None) + return value + + +def report(): + return {'verdict': 'pass', 'issues': [], 'summary': 'Synthetic; no browser ran', 'verification': { + 'scope': 'generated-experience', 'humanApproval': 'not-recorded', + 'nativeShareDelivery': 'not-tested', 'spotifyAuthentication': 'not-tested', + 'evidence': {'sourceSha256': 'a' * 64, 'journeySha256': 'b' * 64, 'runnerSha256': 'c' * 64}, + 'journey': {'releaseConnection': 'A concrete release connection', 'evidence': ['Synthetic'], + 'motivation': 'A concrete motivation for participation', 'payoff': 'A concrete payoff from participation', + 'capabilities': ['browser-interaction'], 'steps': [ + {'action': 'click', 'target': 'Start', 'value': '', 'expected': '', 'checkpoint': checkpoint} + for checkpoint in ['participate', 'result', 'delivery']]}, + 'viewports': [{'name': name, 'journeyPassed': True, 'errors': [], 'overflow': False} + for name in ['mobile', 'desktop']]}} + + +class SitesEvidence(harness.ReleaseCases): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.sql('ALTER TABLE storage.buckets ADD COLUMN allowed_mime_types text[];') + cls.sql((ROOT / 'supabase/migrations/20260918010000_sites.sql').read_text()) + cls.sql('ALTER DEFAULT PRIVILEGES GRANT ALL ON TABLES TO anon,authenticated,service_role; ALTER DEFAULT PRIVILEGES GRANT EXECUTE ON FUNCTIONS TO service_role;') + cls.sql((HERE / 'proposal.sql').read_text()) + cls.sql((HERE / 'fixture-grants.sql').read_text()) + + def setUp(self): + self.sql('TRUNCATE public.sites CASCADE; DELETE FROM public.account_organization_ids;') + self.sql(f"""INSERT INTO accounts(id) VALUES ('{uid(1)}'),('{uid(2)}'),('{uid(3)}'),('{uid(4)}') ON CONFLICT DO NOTHING; + INSERT INTO account_organization_ids(account_id,organization_id) VALUES ('{uid(2)}','{uid(1)}'),('{uid(3)}','{uid(1)}'); + INSERT INTO sites(id,owner_id,created_by,name,revision,draft) VALUES ('{uid(10)}','{uid(1)}','{uid(2)}','Fixture',2,{literal(json.dumps(candidate()))});""") + + def execute(self, statement, role='service_role'): + return '\n'.join(line for line in self.sql(f'SET ROLE {role}; ' + statement).stdout.strip().splitlines() if line != 'SET') + + def record_sql(self, key='capture', actor=2, owner=1, revision=2, value=None, review=None, override=False, candidate_hash=None, report_hash=None, override_reason='Explicit synthetic choice'): + value = candidate() if value is None else value + ctext = canonical(projection(value)) + r = report() if review is None else review + rtext = None if override else canonical(r) + decision = {'kind': 'override', 'intent': 'publish-without-passed-review', 'reason': override_reason} if override else { + 'kind': 'review', 'review': r, 'reviewSha256': report_hash or digest(rtext)} + args = [uid(actor), uid(owner), uid(10), revision, key, json.dumps(value), ctext, + candidate_hash or digest(ctext), json.dumps(decision), rtext] + return 'SELECT sites_evidence_proposal.record_evidence(' + ','.join(literal(v) for v in args) + ');' + + def record(self, **kwargs): + return json.loads(self.execute(self.record_sql(**kwargs))) + + def publish_sql(self, record, actor=2, owner=1, revision=2, expected_pointer=None, expected_digest=None, expected_artist=None): + args = [uid(actor), uid(owner), uid(10), revision, record['id'], + expected_digest or record['candidateSha256'], expected_pointer, expected_artist] + return 'SELECT sites_evidence_proposal.publish_candidate(' + ','.join(literal(v) for v in args) + ');' + + def state(self): + return self.sql(f"SELECT row_to_json(s) FROM sites s WHERE id='{uid(10)}'").stdout.strip() + + def test_original_identity_time_and_payload_retry(self): + first = self.record() + self.assertEqual(first, self.record()) + self.assertEqual(first['recordedByAccountId'], uid(2)) + self.assertEqual(first['review'], report()) + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '1') + for changes in [{'actor': 3}, {'review': {**report(), 'summary': 'changed'}}, {'value': {**candidate(), 'name': 'changed'}}]: + with self.assertRaisesRegex(AssertionError, 'conflict'): + self.record(**changes) + + def test_parallel_capture_returns_one_original_record(self): + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + rows = list(pool.map(lambda _: self.record(), range(8))) + self.assertTrue(all(row == rows[0] for row in rows)) + + def test_roles_owner_and_scoped_read(self): + row = self.record() + statement = f"SELECT sites_evidence_proposal.read_evidence('{uid(2)}','{uid(1)}','{uid(10)}','{row['id']}');" + self.assertEqual(json.loads(self.execute(statement)), row) + for role in ['anon', 'authenticated']: + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute(statement, role) + for kwargs in [{'actor': 4}, {'owner': 4}]: + with self.assertRaisesRegex(AssertionError, 'denied|unavailable'): + self.record(**kwargs) + with self.assertRaisesRegex(AssertionError, 'denied|unavailable'): + self.execute(statement.replace(uid(1), uid(4))) + for operation in ['SELECT * FROM', 'DELETE FROM', 'TRUNCATE']: + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute(operation + ' sites_evidence_proposal.records;') + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute("UPDATE sites_evidence_proposal.records SET recorded_at=now();") + + def test_revocation_blocks_capture_retry_read_and_publish(self): + row = self.record() + self.sql(f"DELETE FROM account_organization_ids WHERE account_id='{uid(2)}';") + for statement in [self.record_sql(), self.publish_sql(row), f"SELECT sites_evidence_proposal.read_evidence('{uid(2)}','{uid(1)}','{uid(10)}','{row['id']}');"]: + with self.assertRaisesRegex(AssertionError, 'denied'): + self.execute(statement) + + def test_execute_privilege_revocation(self): + signature = 'sites_evidence_proposal.publish_candidate(uuid,uuid,uuid,integer,uuid,text,uuid,uuid)' + row = self.record() + self.sql('REVOKE EXECUTE ON FUNCTION ' + signature + ' FROM service_role;') + try: + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute(self.publish_sql(row)) + finally: + self.sql('GRANT EXECUTE ON FUNCTION ' + signature + ' TO service_role;') + + def test_publication_uses_stored_candidate_without_advancing_revision(self): + row = self.record() + # Same-revision draft movement cannot substitute a new snapshot for the selected record. + self.sql(f"UPDATE sites SET draft='{{\"different\":true}}' WHERE id='{uid(10)}';") + self.execute(self.publish_sql(row)) + state = json.loads(self.state()) + self.assertEqual(state['published'], candidate()) + self.assertEqual(state['published_evidence_id'], row['id']) + self.assertEqual(state['revision'], 2) + self.assertEqual(self.record(), row) + + def test_conflicts_leave_publication_unchanged(self): + row = self.record() + before = self.state() + for kwargs in [{'revision': 1}, {'expected_digest': 'd' * 64}, {'expected_pointer': uid(88)}, {'owner': 4}]: + with self.assertRaises(AssertionError): + self.execute(self.publish_sql(row, **kwargs)) + self.assertEqual(self.state(), before) + self.sql('UPDATE sites SET revision=3;') + before = self.state() + with self.assertRaisesRegex(AssertionError, 'conflict'): + self.execute(self.publish_sql(row)) + self.assertEqual(self.state(), before) + + def test_concurrent_publications_have_one_pointer_winner(self): + a = self.record(key='a') + b = self.record(key='b', value={**candidate(), 'name': 'Another'}) + def attempt(row): + try: + self.execute(self.publish_sql(row)) + return row + except AssertionError as error: + self.assertIn('conflict', str(error)) + return None + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(attempt, [a, b])) + winner = [r for r in results if r] + self.assertEqual(len(winner), 1) + self.assertEqual(json.loads(self.state())['published_evidence_id'], winner[0]['id']) + + def test_failed_or_malformed_reports_cannot_publish_even_direct_sql(self): + mutations = [lambda r: r.update(verdict='revise'), lambda r: r.update(blocked='credits'), + lambda r: r.update(issues=[{'severity': 'blocking', 'module': 'implementation', 'detail': 'bad', 'fix': 'fix'}]), + lambda r: r.update(issues=[{'severity': 'minor', 'module': 'direction', 'detail': 'bad', 'fix': 'fix'}]), + lambda r: r['verification'].pop('humanApproval'), + lambda r: r['verification']['viewports'].pop(), + lambda r: r['verification']['viewports'][1].update(name='mobile'), + lambda r: r['verification']['viewports'][0].update(journeyPassed=False), + lambda r: r['verification']['viewports'][0].update(errors=['failure']), + lambda r: r['verification']['viewports'][0].update(overflow=True), + lambda r: r['verification'].update(opening={'verdict': 'pass', 'issues': []}), + lambda r: r['verification'].update(journey={}), + lambda r: r['verification'].update(evidence={}), + lambda r: r['verification'].update(viewports='malformed'), + lambda r: r.update(issues=None)] + for index, mutate in enumerate(mutations): + with self.subTest(index=index): + r = report(); mutate(r) + row = self.record(key=f'bad-{index}', review=r) + before = self.state() + with self.assertRaisesRegex(AssertionError, 'not eligible'): + self.execute(self.publish_sql(row)) + self.assertEqual(self.state(), before) + + def test_override_requires_explicit_intent_and_same_actor(self): + row = self.record(override=True) + with self.assertRaisesRegex(AssertionError, 'not eligible'): + self.execute(self.publish_sql(row, actor=3)) + self.execute(self.publish_sql(row)) + self.assertEqual(json.loads(self.state())['published_evidence_id'], row['id']) + for statement in [self.record_sql(key='bad', override=True).replace('publish-without-passed-review', 'publish'), + self.record_sql(key='bad', override=True).replace('Explicit synthetic choice', ' ')]: + with self.assertRaises(AssertionError): + self.execute(statement) + + def test_digest_mismatch_and_original_report_are_not_rewritten(self): + for kwargs in [{'candidate_hash': '0' * 64}, {'report_hash': '0' * 64}]: + with self.assertRaisesRegex(AssertionError, 'digest'): + self.record(**kwargs) + original = report() + row = self.record(review=original) + self.assertEqual(row['review']['verification']['evidence'], original['verification']['evidence']) + + def test_legacy_clear_unpublish_and_pointer_forgery(self): + row = self.record() + self.execute(self.publish_sql(row)) + self.execute("UPDATE sites SET published='{\"legacy\":true}', published_at=clock_timestamp();") + state = json.loads(self.state()) + self.assertIsNone(state['published_evidence_id']) + self.assertEqual(state['revision'], 2) + with self.assertRaisesRegex(AssertionError, 'pointer'): + self.execute(f"UPDATE sites SET published_evidence_id='{row['id']}';") + self.execute(self.publish_sql(row)) + self.execute('UPDATE sites SET published=NULL,published_at=NULL;') + self.assertIsNone(json.loads(self.state())['published_evidence_id']) + self.assertEqual(json.loads(self.state())['revision'], 2) + + def test_delete_retention_and_immutable_guards(self): + row = self.record() + self.execute(self.publish_sql(row)) + for statement in ['UPDATE sites_evidence_proposal.records SET recorded_at=now();', 'DELETE FROM sites_evidence_proposal.records;']: + with self.assertRaisesRegex(AssertionError, 'immutable'): + self.sql(statement) + self.execute(f"DELETE FROM sites WHERE id='{uid(10)}';") + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '0') + with self.assertRaisesRegex(AssertionError, 'unavailable'): + self.execute(f"SELECT sites_evidence_proposal.read_evidence('{uid(2)}','{uid(1)}','{uid(10)}','{row['id']}');") + + def test_broad_defaults_do_not_leak_table_column_or_helper_access(self): + self.assertEqual(self.sql("""SELECT bool_and(NOT has_table_privilege(role,'sites_evidence_proposal.records',privilege)) + FROM unnest(ARRAY['anon','authenticated','service_role']) role, + unnest(ARRAY['SELECT','INSERT','UPDATE','DELETE','TRUNCATE','REFERENCES','TRIGGER']) privilege;""").stdout.strip(), 't') + self.assertEqual(self.sql("""SELECT bool_and(NOT has_column_privilege(role,'sites_evidence_proposal.records',column_name,privilege)) + FROM information_schema.columns, unnest(ARRAY['anon','authenticated','service_role']) role, + unnest(ARRAY['SELECT','INSERT','UPDATE','REFERENCES']) privilege + WHERE table_schema='sites_evidence_proposal' AND table_name='records';""").stdout.strip(), 't') + self.assertEqual(self.sql("""SELECT bool_and(NOT has_function_privilege(role,p.oid,'EXECUTE')) FROM pg_proc p + JOIN pg_namespace n ON n.oid=p.pronamespace, unnest(ARRAY['anon','authenticated']) role + WHERE n.nspname='sites_evidence_proposal';""").stdout.strip(), 't') + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute("SELECT sites_evidence_proposal.review_passes('{}');") + self.assertEqual(self.sql("""SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='sites_evidence_proposal' AND p.prosecdef + AND p.proowner=n.nspowner AND p.proconfig=ARRAY['search_path=\"\"'];""").stdout.strip(), '4') + + def test_shadow_objects_do_not_redirect_definers(self): + self.sql('CREATE SCHEMA sites_shadow; GRANT ALL ON SCHEMA sites_shadow TO service_role;') + try: + self.execute("CREATE TABLE sites_shadow.sites(id text); CREATE TABLE sites_shadow.records(id text); SET search_path=sites_shadow,public; " + self.record_sql()) + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '1') + self.assertEqual(self.sql('SELECT count(*) FROM sites_shadow.records').stdout.strip(), '0') + row = self.record() + self.execute("CREATE TEMP TABLE pg_namespace(nspname text,nspowner oid); INSERT INTO pg_namespace SELECT 'sites_evidence_proposal',oid FROM pg_roles WHERE rolname='service_role'; " + self.publish_sql(row)) + self.assertEqual(json.loads(self.state())['published_evidence_id'], row['id']) + finally: + self.sql('DROP SCHEMA sites_shadow CASCADE;') + + def test_actor_null_missing_site_and_advanced_revision_retry(self): + row = self.record() + for statement in [self.record_sql().replace(literal(uid(2)), 'NULL', 1), self.record_sql().replace(uid(10), uid(99))]: + with self.assertRaisesRegex(AssertionError, 'denied|unavailable'): + self.execute(statement) + self.sql('UPDATE sites SET revision=3;') + with self.assertRaisesRegex(AssertionError, 'conflict'): + self.record() + self.assertEqual(json.loads(self.execute(f"SELECT sites_evidence_proposal.read_evidence('{uid(2)}','{uid(1)}','{uid(10)}','{row['id']}');")), row) + + def test_parallel_different_payload_same_key_has_one_winner(self): + def attempt(name): + try: + return self.record(value={**candidate(), 'name': name}) + except AssertionError as error: + self.assertIn('conflict', str(error)) + return None + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(attempt, ['A', 'B'])) + self.assertEqual(sum(row is not None for row in results), 1) + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '1') + + def test_legacy_same_bytes_artist_timestamp_and_insert_pointer_guards(self): + row = self.record() + for statement in ['UPDATE sites SET published=published;', 'UPDATE sites SET published_at=clock_timestamp();', + f"UPDATE sites SET artist_id='{uid(4)}';"]: + self.execute(self.publish_sql(row)) + self.execute(statement) + self.assertIsNone(json.loads(self.state())['published_evidence_id']) + self.execute(self.publish_sql(row, expected_artist=uid(4))) + self.execute('UPDATE sites SET draft=draft,revision=revision+1,artist_id=artist_id;') + self.assertEqual(json.loads(self.state())['published_evidence_id'], row['id']) + with self.assertRaisesRegex(AssertionError, 'pointer'): + self.execute(f"INSERT INTO sites(id,owner_id,created_by,name,published,published_evidence_id) VALUES ('{uid(11)}','{uid(1)}','{uid(2)}','Forgery','{{}}','{row['id']}');") + before = self.state() + with self.assertRaisesRegex(AssertionError, 'permission denied'): + self.execute('TRUNCATE sites CASCADE;') + self.assertEqual(self.state(), before) + + def test_failed_write_is_atomic_and_other_sites_survive_retention(self): + self.sql("""CREATE FUNCTION sites_evidence_proposal.synthetic_fail() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'synthetic storage failure'; END $$; + CREATE TRIGGER synthetic_insert_failure BEFORE INSERT ON sites_evidence_proposal.records + FOR EACH ROW EXECUTE FUNCTION sites_evidence_proposal.synthetic_fail();""") + before = self.state() + try: + with self.assertRaisesRegex(AssertionError, 'synthetic storage failure'): + self.record() + finally: + self.sql('DROP TRIGGER synthetic_insert_failure ON sites_evidence_proposal.records;') + self.assertEqual(self.state(), before) + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '0') + row = self.record() + self.sql('CREATE TRIGGER synthetic_publish_failure BEFORE UPDATE ON sites FOR EACH ROW EXECUTE FUNCTION sites_evidence_proposal.synthetic_fail();') + try: + with self.assertRaisesRegex(AssertionError, 'synthetic storage failure'): + self.execute(self.publish_sql(row)) + finally: + self.sql('DROP TRIGGER synthetic_publish_failure ON sites; DROP FUNCTION sites_evidence_proposal.synthetic_fail();') + self.assertEqual(self.state(), before) + self.sql(f"INSERT INTO sites(id,owner_id,created_by,name,revision) VALUES ('{uid(11)}','{uid(1)}','{uid(2)}','Other',2);") + other = json.loads(self.execute(self.record_sql().replace(uid(10), uid(11)))) + self.execute(self.publish_sql(row)) + self.execute(f"DELETE FROM sites WHERE id='{uid(10)}';") + self.assertEqual(self.sql('SELECT count(*) FROM sites_evidence_proposal.records').stdout.strip(), '1') + self.assertEqual(json.loads(self.execute(f"SELECT sites_evidence_proposal.read_evidence('{uid(2)}','{uid(1)}','{uid(11)}','{other['id']}');")), other) + + def test_membership_revocation_waits_for_authorized_transaction(self): + def capture(): + return self.sql("SET application_name='sites-capture-lock'; BEGIN; SET ROLE service_role; " + self.record_sql() + " SELECT pg_sleep(1.2); COMMIT;") + def revoke(): + return self.sql(f"SET application_name='sites-revoke-lock'; DELETE FROM account_organization_ids WHERE account_id='{uid(2)}';") + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(capture) + deadline = time.monotonic() + 5 + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-capture-lock' AND wait_event='PgSleep';").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Capture did not reach held-lock checkpoint') + time.sleep(0.02) + second = pool.submit(revoke) + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-revoke-lock' AND cardinality(pg_blocking_pids(pid))>0;").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Revocation was not observed waiting on membership lock') + time.sleep(0.02) + first.result(timeout=8); second.result(timeout=8) + with self.assertRaisesRegex(AssertionError, 'denied'): + self.record() + + def test_actual_api_digest_vectors_survive_jsonb_storage(self): + vectors = json.loads((HERE / 'api-digest-vectors.json').read_text()) + for vector in vectors['vectors']: + decision = {'kind': 'review', 'review': vector['review'], 'reviewSha256': vector['reviewSha256']} + args = [uid(2), uid(1), uid(10), 2, vector['name'], json.dumps(vector['candidate']), + vector['candidateCanonical'], vector['candidateSha256'], json.dumps(decision), vector['reviewCanonical']] + row = json.loads(self.execute('SELECT sites_evidence_proposal.record_evidence(' + ','.join(literal(v) for v in args) + ');')) + self.assertEqual(row['candidateSha256'], vector['candidateSha256']) + self.assertEqual(row['reviewSha256'], vector['reviewSha256']) + self.assertEqual(row['review']['verification']['evidence'], vector['review']['verification']['evidence']) + state = json.loads(self.state()) + self.execute(self.publish_sql(row, expected_pointer=state['published_evidence_id'])) + self.assertEqual(json.loads(self.state())['published'], vector['candidate']) + + def test_capture_binds_returned_final_save_revision_not_claim_revision(self): + self.sql('UPDATE sites SET revision=1;') + self.execute('UPDATE sites SET revision=revision+1;') # Existing generation claim: now 2. + final = candidate() + final['production']['context'] = {'source': 'Synthetic assembled context'} + self.execute(f"UPDATE sites SET draft={literal(json.dumps(final))},revision=revision+1;") + saved = json.loads(self.state()) + self.assertEqual(saved['revision'], 3) + with self.assertRaisesRegex(AssertionError, 'conflict'): + self.record(revision=2, value=final) + row = self.record(revision=saved['revision'], value=saved['draft']) + self.assertEqual(row['revision'], 3) + self.execute(self.publish_sql(row, revision=3)) + self.assertEqual(json.loads(self.state())['published'], final) + + def test_draft_write_waiting_after_publish_preserves_live_pointer(self): + row = self.record() + def publish(): + return self.sql("SET application_name='sites-publish-lock'; BEGIN; SET ROLE service_role; " + self.publish_sql(row) + " SELECT pg_sleep(1.2); COMMIT;") + def edit(): + return self.sql("SET application_name='sites-draft-lock'; SET ROLE service_role; UPDATE sites SET revision=revision+1,draft='{\"newDraft\":true}',artist_id=artist_id;") + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(publish) + deadline = time.monotonic() + 5 + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-publish-lock' AND wait_event='PgSleep';").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Publisher did not hold site lock') + time.sleep(0.02) + second = pool.submit(edit) + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-draft-lock' AND cardinality(pg_blocking_pids(pid))>0;").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Draft update was not observed waiting') + time.sleep(0.02) + first.result(timeout=8); second.result(timeout=8) + saved = json.loads(self.state()) + self.assertEqual(saved['revision'], 3) + self.assertEqual(saved['published'], candidate()) + self.assertEqual(saved['published_evidence_id'], row['id']) + + def test_owner_transition_cannot_orphan_retained_evidence(self): + row = self.record() + for published in [False, True]: + if published: + self.execute(self.publish_sql(row)) + before = self.state() + with self.assertRaisesRegex(AssertionError, 'Evidence owner'): + self.execute(f"UPDATE sites SET owner_id='{uid(4)}';") + self.assertEqual(self.state(), before) + + def test_artist_selection_conflict_after_final_api_read(self): + row = self.record() + for selected, current in [(uid(3), uid(4)), (uid(3), None), (None, uid(4))]: + with self.subTest(selected=selected, current=current): + self.execute("UPDATE sites SET published=NULL,published_at=NULL;") + self.execute(f"UPDATE sites SET artist_id={literal(selected)},published='{{\"legacy\":true}}',published_at='2026-01-01T00:00:00Z';") + # The selected artist was observed by the final API read. A legacy writer + # then changes it without advancing revision or the null evidence pointer. + self.execute(f"UPDATE sites SET artist_id={literal(current)};") + before = self.state() + with self.assertRaisesRegex(AssertionError, 'Publication conflict'): + self.execute(self.publish_sql(row, expected_artist=selected)) + self.assertEqual(self.state(), before) + + def test_artist_selection_stable_and_null_match(self): + row = self.record() + for artist in [uid(3), None]: + self.execute(f"UPDATE sites SET artist_id={literal(artist)};") + before = json.loads(self.state()) + self.execute(self.publish_sql(row, expected_pointer=before['published_evidence_id'], expected_artist=artist)) + after = json.loads(self.state()) + self.assertEqual(after['artist_id'], artist) + self.assertEqual(after['published'], candidate()) + self.assertEqual(after['published_evidence_id'], row['id']) + self.assertEqual(after['revision'], 2) + + def test_artist_writer_lock_serializes_publication_fence(self): + row = self.record() + self.execute(f"UPDATE sites SET artist_id='{uid(3)}',published='{{\"legacy\":true}}',published_at='2026-01-01T00:00:00Z';") + def change_artist(): + return self.sql(f"SET application_name='sites-artist-change'; BEGIN; SET ROLE service_role; UPDATE sites SET artist_id='{uid(4)}'; SELECT pg_sleep(1.2); COMMIT;") + def publish(): + return self.sql("SET application_name='sites-artist-publish'; SET ROLE service_role; " + self.publish_sql(row, expected_artist=uid(3))) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(change_artist) + deadline = time.monotonic() + 5 + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-artist-change' AND wait_event='PgSleep';").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Artist writer did not hold site lock') + time.sleep(0.02) + before = json.loads(self.state()) + second = pool.submit(publish) + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='sites-artist-publish' AND cardinality(pg_blocking_pids(pid))>0;").stdout.strip() != '1': + if time.monotonic() > deadline: + self.fail('Publisher did not wait behind artist writer') + time.sleep(0.02) + first.result(timeout=8) + with self.assertRaisesRegex(AssertionError, 'Publication conflict'): + second.result(timeout=8) + expected = {**before, 'artist_id': uid(4)} + self.assertEqual(json.loads(self.state()), expected) + + def test_nonspace_whitespace_is_not_explicit_override_reason(self): + for reason in ['\t', '\n', '\u00a0', '\ufeff']: + with self.subTest(reason=repr(reason)): + with self.assertRaisesRegex(AssertionError, 'Explicit override required'): + self.record(key=f'blank-{ord(reason)}', override=True, override_reason=reason) + + def test_corrupt_record_kind_is_not_eligible_for_direct_publication(self): + row = self.record() + # Privileged fixture-only corrupt seed stresses the publisher independently of its writer. + self.sql(f"""INSERT INTO sites_evidence_proposal.records(id,site_id,owner_id,revision,operation_key, + recorded_by_account_id,candidate,candidate_canonical,candidate_sha256,decision,review_canonical) + SELECT '{uid(90)}',site_id,owner_id,revision,'corrupt',recorded_by_account_id,candidate, + candidate_canonical,candidate_sha256,'{{"kind":"unknown"}}',NULL FROM sites_evidence_proposal.records;""") + before = self.state() + with self.assertRaisesRegex(AssertionError, 'not eligible'): + self.execute(self.publish_sql({**row, 'id': uid(90)})) + self.assertEqual(self.state(), before) + + +if __name__ == '__main__': + unittest.main(verbosity=2)