diff --git a/.github/workflows/application-proof-proposal.yml b/.github/workflows/application-proof-proposal.yml index 64dcacd..a3f588f 100644 --- a/.github/workflows/application-proof-proposal.yml +++ b/.github/workflows/application-proof-proposal.yml @@ -33,3 +33,4 @@ jobs: run: | export PATH="/usr/lib/postgresql/${{ matrix.postgres }}/bin:$PATH" python3 proposals/application-proof-2104/test_transactions.py + python3 proposals/application-proof-2104/test_configuration.py diff --git a/proposals/application-proof-2104/CONFIGURATION.md b/proposals/application-proof-2104/CONFIGURATION.md new file mode 100644 index 0000000..0c29b40 --- /dev/null +++ b/proposals/application-proof-2104/CONFIGURATION.md @@ -0,0 +1,153 @@ +# Existing-origin return-URL configuration writer + +October 27, 2026. **Executable offline proposal, outside migrations.** This extends +[the proof receipt protocol](PROTOCOL.md) with the narrow contract adopted from +[API #1191](https://github.com/recoupable/api/pull/1191), head +`e50082e3ea9ba4fa37a75e49340d94b3b97552dc`. It persists only disposable fixture rows. +No production adapter, role policy, grant, registration route, DNS request, migration +application, provider operation or bootstrap/access activation is introduced. + +## Scope and files + +- `configuration-fixture.sql` adds synthetic application name and per-origin return + URLs to the existing parent fixture. It is not a production registry schema. +- `configuration.sql` adds the default-denied invoker, immutable configuration + receipts/retry records and an internal snapshot reconstruction helper. +- `test_configuration.py` reuses the established disposable PostgreSQL harness and + exercises the actual SQL, including two-connection contention. CI runs it alongside + the unchanged proof transaction suite on PostgreSQL 15 and 17. + +The authority adapter remains the existing always-denying `authorize_management`. +Only the test runner adds `replace_existing_origin_return_urls` to synthetic fixture +operation lists. That label is not a production role or delegated OAuth scope. +There is no membership fallback or caller boolean. Invoker functions use the caller's +privileges; all new schema objects have PUBLIC access revoked and no replacement +grant. Tests use the disposable cluster owner plus a denied browser role; they do +not demonstrate an adopted least-privilege service role. The internal snapshot helper +has no authorization or locks of its own and must not be exposed as a read endpoint. + +## Exact input, baseline and projection + +`configure_return_urls(actor, workspace, application, environment, key, expected, +changes)` consumes the saved-parent baseline and sorted changes from the API +rehearsal. Authenticated actor and selected resource scope are server inputs, not +registration-body fields. The future real adapter must first use the shared +registration validator; it is absent here. + +`expected` has exactly the API rehearsal shape: workspace/application/environment, +name, sorted exact allowed origins, sorted exact return URLs, and one sorted origin +row containing configuration/proof/CAS revisions plus revoked status. SQL reconstructs +that entire object from locked parents. Any difference, including extra/missing +fields, changed name, an unmodified origin's revisions or destinations, or an origin +addition/removal, rejects with `snapshot conflict`. API uses sorted sets; the SQL +expects that canonical ordering and does not silently normalize a different baseline. + +Each change contains exactly `origin`, `expected`, `next` and sorted distinct +`return_urls`. SQL derives both revision triples from the locked origin: +configuration +1, CAS +1, proof unchanged. The supplied triples must match exactly; +callers cannot reset or invent revisions. Only changed, existing, non-revoked origins +are supported. No-op batches and unchanged entries are rejected; the API rehearsal +already avoids invoking an empty batch. Per-origin destinations may be empty if +the complete resulting configuration retains at least one destination. + +Bounds match the existing 1–32-origin / 1–32-total-return-URL shape, 2048 characters +per URL and JavaScript-safe revision projection. The prototype additionally caps +serialized expected state at 256 KiB and changes at 128 KiB. These are conservative +qualification limits, not commercial quotas. Return URLs must have the exact origin +prefix followed by `/`, with no fragment, whitespace or control characters. This +SQL guard is **not** a WHATWG URL parser and does not replace API canonical validation. +The fixture's origins/hostnames are trusted prevalidated assertions; this writer +does not qualify DNS eligibility or domain ownership. + +The transaction replaces return URLs only for affected origins, advances their +configuration/CAS revisions, and supersedes their pending challenges atomically. +Unchanged origins and their pending challenges are preserved. Prior verified proof +receipts and proof revision remain unchanged. New/removed origins, rename, transfer, +reactivation and membership changes are outside this writer; fixture topology edits +exist only to test conflicts. No synthetic parent or authority is promoted to production. + +## Lock protocol and origin-set phantoms + +READ COMMITTED is required. Lock order is: + +1. Current management-authority dependencies through the existing adapter. +2. Scoped idempotency advisory lock `(actor, workspace, operation, key)`. +3. Application `FOR SHARE`. +4. Environment **`FOR UPDATE`**, before any origin lock. +5. Every existing origin in bytewise (`COLLATE "C"`) order, `FOR UPDATE`. +6. Reconstruct and compare full baseline; validate the entire change projection; + update affected origins/challenges and append immutable receipt/retry result. + +The existing proof transaction takes application/environment `FOR SHARE` before +its origin lock, so it serializes against the stronger environment lock without +inverting the parent-before-child order. Application/environment suspension changes +also serialize, and the returned status is checked after lock acquisition. + +An inserted origin references the environment through the fixture's immediate +composite foreign key. Its FK key-share lock conflicts with the environment update +lock. Thus an insertion that commits first is visible in the reconstructed baseline; +an insertion arriving while the writer holds the parent lock waits until afterward. +The tests demonstrate both orderings with real database lock waits. Existing-origin +deletions conflict with the origin row locks; a prior committed deletion causes a +baseline mismatch. This is conditional on these immediate foreign keys and the +reviewed writer protocol. A superuser disabling constraints, arbitrary multi-step +writers using inverse lock order, or a different production schema are not covered. +Use one domain operation per transaction until larger transaction composition is reviewed. + +A change to an otherwise untouched origin still conflicts with the full baseline. +Tests include a concurrent proof issuance on that origin and competing configuration +batches that target different origins but start from one full snapshot. This prevents +blindly applying an older full-set intent to newer parent state. + +## Receipt, retry and failure behavior + +Configuration receipts contain actor/resource scope, server timestamp, complete +before/after snapshots and derived changes. Both `bootstrap_enabled` and +`access_activated` are constrained false; `production_persisted` is false and +`evidence_kind` is `synthetic_configuration`. The receipt records local fixture +persistence, not a public grant, current authorization or customer deployment. +It is a Database receipt, not the API rehearsal's fake acknowledgment envelope; +no production adapter connects those interfaces in this change. + +Retry scope is actor/workspace/this operation/key. The JSONB fingerprint includes +application, environment, exact expected baseline and exact ordered changes. +JSON object key order is immaterial; array order remains significant. After current +authorization and parent locks, an identical retry returns the original immutable +receipt before baseline/suspension/revocation checks. This is authorized history +with disabled activation, not renewed access. A changed payload on the same key +conflicts; retries never change timestamps or repeat configuration updates. Losing +a committed response is recovered with that same key and payload, not a blind new +mutation. Retention and real permission policy remain unadopted. + +Fresh mutations reject current suspension or any revoked origin. Exact retries +also require current management authority: revoked authority cannot recover history +through this operation. Rollback removes origin changes, challenge invalidations, +receipt and retry rows together. A test forces an error on the second origin update +and verifies the first origin and pending challenge are restored. Update/delete +triggers prevent mutation of saved configuration receipts and retry records. +Database errors remain internal prototype exceptions, not adopted HTTP error codes. + +## Qualification + +Run each with PostgreSQL binaries from a single installation on PATH: + +```sh +python3 proposals/application-proof-2104/test_transactions.py +python3 proposals/application-proof-2104/test_configuration.py +``` + +The new tests cover default authority/browser denial, exact projection including an +empty per-origin destination list, immutable proof history, complete snapshot +conflicts, unsupported/injected changes, current suspension/revocation, rollback, +lost-response recovery, exact/concurrent retry, and selective challenge invalidation. +Two connections test configuration versus configuration, proof issue/revoke/verify, +authority/suspension, untouched-origin issuance, and origin-set insertion/removal. +Barriers require PostgreSQL to report an actual lock wait before releasing the winner. +No timing-only assertion substitutes for observed contention. + +Before any runtime exposure: root reviews this source-only protocol; adopt real +management/delegated authority, production parent mapping and all participating +writer lock orders, least-privilege invoker access, canonical-validation adapter, +retention and consumer revocation. Keep activation disabled. No production migration +or role grants are part of this PR. #2110 hosted/provider/mobile/shared-callback gates +and the separate #2345 browser hold remain unchanged. diff --git a/proposals/application-proof-2104/configuration-fixture.sql b/proposals/application-proof-2104/configuration-fixture.sql new file mode 100644 index 0000000..550ded3 --- /dev/null +++ b/proposals/application-proof-2104/configuration-fixture.sql @@ -0,0 +1,3 @@ +-- Disposable parent extension only. Not a registry migration or role policy. +ALTER TABLE proof_parent_fixture.applications ADD COLUMN name text NOT NULL DEFAULT 'Music'; +ALTER TABLE proof_parent_fixture.origins ADD COLUMN return_urls text[] NOT NULL DEFAULT '{}'; diff --git a/proposals/application-proof-2104/configuration.sql b/proposals/application-proof-2104/configuration.sql new file mode 100644 index 0000000..498e499 --- /dev/null +++ b/proposals/application-proof-2104/configuration.sql @@ -0,0 +1,143 @@ +-- OFFLINE ONLY. Load after fixture.sql, proposal.sql and configuration-fixture.sql. +-- No live adapter or grants. Existing authorize_management defaults to denial. +CREATE TABLE application_proof_proposal.configuration_receipts ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + workspace_id uuid NOT NULL, application_id uuid NOT NULL, environment text NOT NULL, + actor uuid NOT NULL, recorded_at timestamptz NOT NULL, result jsonb NOT NULL, + FOREIGN KEY(workspace_id,application_id,environment) REFERENCES proof_parent_fixture.environments, + CHECK(result ? 'access_activated' AND result->'access_activated'='false'::jsonb), + CHECK(result ? 'bootstrap_enabled' AND result->'bootstrap_enabled'='false'::jsonb) +); +CREATE TABLE application_proof_proposal.configuration_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_proof_proposal.configuration_receipts, + PRIMARY KEY(actor,workspace_id,key) +); +CREATE TRIGGER immutable_configuration_receipt BEFORE UPDATE OR DELETE ON application_proof_proposal.configuration_receipts + FOR EACH ROW EXECUTE FUNCTION application_proof_proposal.immutable_receipt(); +CREATE TRIGGER immutable_configuration_retry BEFORE UPDATE OR DELETE ON application_proof_proposal.configuration_requests + FOR EACH ROW EXECUTE FUNCTION application_proof_proposal.immutable_receipt(); + +-- Internal reconstruction helper: no authority or locks of its own, no PUBLIC access. +CREATE FUNCTION application_proof_proposal.configuration_snapshot(p_workspace uuid,p_application uuid,p_environment text) + RETURNS jsonb LANGUAGE sql VOLATILE SET search_path='' AS $$ + SELECT jsonb_build_object('workspace_id',a.workspace_id,'application_id',a.id,'name',a.name, + 'environment',e.environment, + 'allowed_origins',coalesce((SELECT jsonb_agg(o.origin ORDER BY o.origin COLLATE "C") + FROM proof_parent_fixture.origins o WHERE o.workspace_id=a.workspace_id AND o.application_id=a.id + AND o.environment=e.environment),'[]'::jsonb), + 'return_urls',coalesce((SELECT jsonb_agg(u.url ORDER BY u.url COLLATE "C") + FROM proof_parent_fixture.origins o CROSS JOIN LATERAL unnest(o.return_urls) u(url) + WHERE o.workspace_id=a.workspace_id AND o.application_id=a.id AND o.environment=e.environment),'[]'::jsonb), + 'origins',coalesce((SELECT jsonb_agg(jsonb_build_object('origin',o.origin,'config_revision',o.config_revision, + 'proof_revision',o.proof_revision,'cas_revision',o.cas_revision,'revoked',o.revoked) ORDER BY o.origin COLLATE "C") + FROM proof_parent_fixture.origins o WHERE o.workspace_id=a.workspace_id AND o.application_id=a.id + AND o.environment=e.environment),'[]'::jsonb)) + FROM proof_parent_fixture.applications a JOIN proof_parent_fixture.environments e + ON e.workspace_id=a.workspace_id AND e.application_id=a.id + WHERE a.workspace_id=p_workspace AND a.id=p_application AND e.environment=p_environment; +$$; + +CREATE FUNCTION application_proof_proposal.configure_return_urls( + p_actor uuid,p_workspace uuid,p_application uuid,p_environment text,p_key text, + p_expected jsonb,p_changes jsonb +) RETURNS jsonb LANGUAGE plpgsql SET search_path='' SET timezone='UTC' AS $$ +DECLARE + operation_name constant text := 'replace_existing_origin_return_urls'; + app_suspended boolean; env_suspended boolean; current_snapshot jsonb; request_input jsonb; + prior application_proof_proposal.configuration_requests%ROWTYPE; + parent proof_parent_fixture.origins%ROWTYPE; + change jsonb; derived_changes jsonb := '[]'::jsonb; expected_revision jsonb; next_revision jsonb; + new_urls text[]; old_urls text[]; total_urls integer; receipt_id uuid; result_value jsonb; +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 NULL OR p_application IS NULL OR p_environment IS NULL + OR p_key IS NULL OR length(p_key) NOT BETWEEN 1 AND 128 + OR p_expected IS NULL OR jsonb_typeof(p_expected)<>'object' OR octet_length(p_expected::text)>262144 + OR p_changes IS NULL OR jsonb_typeof(p_changes)<>'array' OR octet_length(p_changes::text)>131072 + THEN RAISE EXCEPTION 'invalid input'; END IF; + IF jsonb_array_length(p_changes) NOT BETWEEN 1 AND 32 THEN RAISE EXCEPTION 'invalid changes'; END IF; + PERFORM application_proof_proposal.authorize_management(p_actor,p_workspace,p_application,p_environment,operation_name); + PERFORM pg_advisory_xact_lock(hashtextextended(jsonb_build_array(p_actor,p_workspace,operation_name,p_key)::text,0)); + SELECT a.suspended INTO app_suspended FROM proof_parent_fixture.applications a + WHERE a.workspace_id=p_workspace AND a.id=p_application FOR SHARE; + IF NOT FOUND THEN RAISE EXCEPTION 'resource unavailable' USING ERRCODE='42501'; END IF; + -- Stronger than proof transact's FOR SHARE; also conflicts with insertion's FK KEY SHARE. + SELECT e.suspended INTO env_suspended FROM proof_parent_fixture.environments e + WHERE e.workspace_id=p_workspace AND e.application_id=p_application AND e.environment=p_environment FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'resource unavailable' USING ERRCODE='42501'; END IF; + PERFORM 1 FROM proof_parent_fixture.origins o WHERE o.workspace_id=p_workspace + AND o.application_id=p_application AND o.environment=p_environment ORDER BY o.origin COLLATE "C" FOR UPDATE; + request_input:=jsonb_build_object('application_id',p_application,'environment',p_environment, + 'expected',p_expected,'changes',p_changes); + SELECT q.* INTO prior FROM application_proof_proposal.configuration_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 request_input THEN RAISE EXCEPTION 'idempotency conflict'; END IF; + SELECT r.result INTO result_value FROM application_proof_proposal.configuration_receipts r WHERE r.id=prior.receipt_id; + RETURN result_value; -- Authorized history, not a current configuration or access grant. + END IF; + current_snapshot:=application_proof_proposal.configuration_snapshot(p_workspace,p_application,p_environment); + IF current_snapshot IS DISTINCT FROM p_expected THEN RAISE EXCEPTION 'snapshot conflict'; END IF; + IF app_suspended OR env_suspended THEN RAISE EXCEPTION 'resource suspended'; END IF; + IF EXISTS(SELECT 1 FROM proof_parent_fixture.origins o WHERE o.workspace_id=p_workspace + AND o.application_id=p_application AND o.environment=p_environment AND o.revoked) + THEN RAISE EXCEPTION 'origin revoked'; END IF; + IF jsonb_array_length(current_snapshot->'origins') NOT BETWEEN 1 AND 32 + OR EXISTS(SELECT 1 FROM proof_parent_fixture.origins o WHERE o.workspace_id=p_workspace + AND o.application_id=p_application AND o.environment=p_environment + AND greatest(o.config_revision,o.proof_revision,o.cas_revision)>9007199254740990) + THEN RAISE EXCEPTION 'unsupported parent state'; END IF; + total_urls:=jsonb_array_length(current_snapshot->'return_urls'); + IF EXISTS(SELECT 1 FROM jsonb_array_elements(p_changes) c + WHERE jsonb_typeof(c)<>'object' OR NOT(c ?& ARRAY['origin','expected','next','return_urls']) + OR c-ARRAY['origin','expected','next','return_urls']<>'{}'::jsonb) + THEN RAISE EXCEPTION 'invalid changes'; END IF; + IF (SELECT count(DISTINCT c->>'origin') FROM jsonb_array_elements(p_changes) c)<>jsonb_array_length(p_changes) + THEN RAISE EXCEPTION 'invalid changes'; END IF; + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) ORDER BY value->>'origin' COLLATE "C" LOOP + IF jsonb_typeof(change->'origin')<>'string' OR jsonb_typeof(change->'return_urls')<>'array' + THEN RAISE EXCEPTION 'invalid changes'; END IF; + SELECT o.* INTO parent FROM proof_parent_fixture.origins o WHERE o.workspace_id=p_workspace + AND o.application_id=p_application AND o.environment=p_environment AND o.origin=change->>'origin'; + IF NOT FOUND THEN RAISE EXCEPTION 'origin unavailable'; END IF; + IF jsonb_array_length(change->'return_urls')>32 + OR EXISTS(SELECT 1 FROM jsonb_array_elements(change->'return_urls') u WHERE jsonb_typeof(u)<>'string') + THEN RAISE EXCEPTION 'invalid return URLs'; END IF; + SELECT coalesce(array_agg(DISTINCT url COLLATE "C" ORDER BY url COLLATE "C"),'{}') INTO new_urls + FROM jsonb_array_elements_text(change->'return_urls') u(url); + IF to_jsonb(new_urls) IS DISTINCT FROM change->'return_urls' + OR EXISTS(SELECT 1 FROM unnest(new_urls) u(url) WHERE length(url)>2048 + OR left(url,length(parent.origin)+1)<>parent.origin||'/' OR position('#' IN url)>0 OR url ~ '[[:space:][:cntrl:]]') + THEN RAISE EXCEPTION 'invalid return URLs'; END IF; + SELECT coalesce(array_agg(url ORDER BY url COLLATE "C"),'{}') INTO old_urls FROM unnest(parent.return_urls) u(url); + IF new_urls=old_urls THEN RAISE EXCEPTION 'unchanged origin in changes'; END IF; + expected_revision:=jsonb_build_object('config_revision',parent.config_revision,'proof_revision',parent.proof_revision,'cas_revision',parent.cas_revision); + next_revision:=jsonb_build_object('config_revision',parent.config_revision+1,'proof_revision',parent.proof_revision,'cas_revision',parent.cas_revision+1); + derived_changes:=derived_changes||jsonb_build_array(jsonb_build_object('origin',parent.origin,'expected',expected_revision, + 'next',next_revision,'return_urls',new_urls)); + total_urls:=total_urls-cardinality(old_urls)+cardinality(new_urls); + END LOOP; + IF derived_changes IS DISTINCT FROM p_changes THEN RAISE EXCEPTION 'revision projection conflict'; END IF; + IF total_urls NOT BETWEEN 1 AND 32 THEN RAISE EXCEPTION 'invalid total return URLs'; END IF; + FOR change IN SELECT value FROM jsonb_array_elements(derived_changes) LOOP + UPDATE proof_parent_fixture.origins SET return_urls=ARRAY(SELECT jsonb_array_elements_text(change->'return_urls')), + config_revision=config_revision+1,cas_revision=cas_revision+1 + WHERE workspace_id=p_workspace AND application_id=p_application AND environment=p_environment AND origin=change->>'origin'; + UPDATE application_proof_proposal.challenges SET state='superseded' + WHERE workspace_id=p_workspace AND application_id=p_application AND environment=p_environment + AND origin=change->>'origin' AND state='pending'; + END LOOP; + receipt_id:=gen_random_uuid(); + result_value:=jsonb_build_object('receipt_id',receipt_id,'actor',p_actor,'workspace_id',p_workspace, + 'application_id',p_application,'environment',p_environment,'operation',operation_name,'recorded_at',clock_timestamp(), + 'before',current_snapshot,'changes',derived_changes, + 'after',application_proof_proposal.configuration_snapshot(p_workspace,p_application,p_environment), + 'access_activated',false,'bootstrap_enabled',false,'production_persisted',false,'evidence_kind','synthetic_configuration'); + INSERT INTO application_proof_proposal.configuration_receipts(id,workspace_id,application_id,environment,actor,recorded_at,result) + VALUES(receipt_id,p_workspace,p_application,p_environment,p_actor,(result_value->>'recorded_at')::timestamptz,result_value); + INSERT INTO application_proof_proposal.configuration_requests VALUES(p_actor,p_workspace,p_key,request_input,receipt_id); + RETURN result_value; +END $$; +REVOKE ALL ON ALL TABLES IN SCHEMA application_proof_proposal FROM PUBLIC; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA application_proof_proposal FROM PUBLIC; diff --git a/proposals/application-proof-2104/test_configuration.py b/proposals/application-proof-2104/test_configuration.py new file mode 100644 index 0000000..d2cf148 --- /dev/null +++ b/proposals/application-proof-2104/test_configuration.py @@ -0,0 +1,254 @@ +"""Existing-origin writer against the existing proof fixture; no runtime adapter.""" +import copy +import json +import pathlib +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +import test_transactions as proof + +HERE = pathlib.Path(__file__).resolve().parent +ORIGIN = 'https://music.example' +SECOND = 'https://other.example' +OPERATION = 'replace_existing_origin_return_urls' +uid, literal = proof.uid, proof.literal + + +class Configuration(unittest.TestCase): + # Reuse only the established disposable harness/helpers, not inherited test cases. + args = classmethod(proof.ProofTransactions.args.__func__) + sql = classmethod(proof.ProofTransactions.sql.__func__) + stop = classmethod(proof.ProofTransactions.stop.__func__) + statement = proof.ProofTransactions.statement + call = proof.ProofTransactions.call + issue = proof.ProofTransactions.issue + observation = proof.ProofTransactions.observation + holder = proof.ProofTransactions.holder + race = proof.ProofTransactions.race + + @classmethod + def setUpClass(cls): + proof.ProofTransactions.setUpClass.__func__(cls) + cls.sql((HERE / 'configuration-fixture.sql').read_text()) + cls.sql((HERE / 'configuration.sql').read_text()) + + def setUp(self): + self.sql('ALTER TABLE proof_parent_fixture.origins DROP CONSTRAINT IF EXISTS fixture_fail_second;') + proof.ProofTransactions.setUp(self) + self.sql("UPDATE proof_parent_fixture.authority SET operations=array_append(operations,"+literal(OPERATION)+")") + self.sql("UPDATE proof_parent_fixture.origins SET return_urls=ARRAY[origin||'/done']") + self.sql(f"""INSERT INTO proof_parent_fixture.origins(workspace_id,application_id,environment,origin,hostname,return_urls) + VALUES('{uid(1)}','{uid(2)}','production','{SECOND}','other.example',ARRAY['{SECOND}/done']);""") + + def snapshot(self): + return json.loads(self.sql(f"SELECT application_proof_proposal.configuration_snapshot('{uid(1)}','{uid(2)}','production')")) + + def plan(self, snapshot=None, urls=None): + snapshot = snapshot or self.snapshot() + urls = urls or {ORIGIN: [ORIGIN+'/new']} + changes = [] + for row in snapshot['origins']: + if row['origin'] not in urls: + continue + expected = {k: row[k] for k in ('config_revision','proof_revision','cas_revision')} + next_values = {**expected, 'config_revision':expected['config_revision']+1, + 'cas_revision':expected['cas_revision']+1} + changes.append({'origin':row['origin'],'expected':expected,'next':next_values, + 'return_urls':urls[row['origin']]}) + return snapshot,changes + + def config_statement(self, snapshot=None, changes=None, key='config', actor=3, workspace=1, application=2, environment='production'): + if snapshot is None: + snapshot,changes=self.plan() + return ("SELECT application_proof_proposal.configure_return_urls("+ + ','.join(literal(x) for x in [uid(actor),uid(workspace),uid(application),environment,key])+ + ','+literal(json.dumps(snapshot))+'::jsonb,'+literal(json.dumps(changes))+'::jsonb);') + + def configure(self, *args, **kwargs): + return json.loads(self.sql(self.config_statement(*args, **kwargs))) + + def wait_for_lock(self): + deadline=time.monotonic()+5 + while time.monotonic()