diff --git a/.github/workflows/application-proof-bridge.yml b/.github/workflows/application-proof-bridge.yml new file mode 100644 index 000000000..a73225e46 --- /dev/null +++ b/.github/workflows/application-proof-bridge.yml @@ -0,0 +1,51 @@ +name: Application proof API SQL bridge (offline only) +on: + pull_request: + branches: [main] + paths: + - "scripts/application-proof/**" + - "lib/applications/**" + - "pnpm-lock.yaml" + - "package.json" + - "vitest.config.ts" + - ".github/workflows/application-proof-bridge.yml" +permissions: + contents: read +jobs: + disposable-postgres: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + postgres: [15, 17] + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: recoupable/database + ref: 372de990156739dda1b605d18a40333cd6f1bdba + path: .worktrees/database-proof-source + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: "22" + - uses: pnpm/action-setup@v4 + with: + version: 9 + - run: pnpm install --frozen-lockfile + - name: Install PostgreSQL + timeout-minutes: 12 + run: | + sudo apt-get update + sudo apt-get install -y postgresql-common + sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y + sudo apt-get update + sudo apt-get install -y postgresql-${{ matrix.postgres }} + - name: Qualify pinned API and actual SQL receipt bridge + timeout-minutes: 3 + run: | + export PATH="/usr/lib/postgresql/${{ matrix.postgres }}/bin:$PATH" + python3 scripts/application-proof/sql-bridge/run.py --database-repo "$GITHUB_WORKSPACE/.worktrees/database-proof-source" diff --git a/scripts/application-proof/sql-bridge/README.md b/scripts/application-proof/sql-bridge/README.md new file mode 100644 index 000000000..c32b9f733 --- /dev/null +++ b/scripts/application-proof/sql-bridge/README.md @@ -0,0 +1,114 @@ +# Offline actual API → SQL configuration bridge + +October 27, 2026. This closes a source integration gap between the existing +[API rehearsal #1191](https://github.com/recoupable/api/pull/1191) and +[Database writer #131](https://github.com/recoupable/database/pull/131). It is not a +runtime adapter, endpoint, management policy, migration or activation path. + +## Actual code and source pins + +`sources.json` pins four API modules at merge commit +`959d30bf19f28ae6a8c75031f424831923403374` and five Database fixture/protocol files at +`372de990156739dda1b605d18a40333cd6f1bdba`, each by SHA-256. The runner verifies API +working-file bytes, then the dedicated Vitest loader hashes and freezes those bytes +again and executes that same cache. Its shutdown check requires all four pinned +modules to have passed through the loader. The runner obtains Database bytes with local +`git show :`. It does not fetch during qualification, copy the +SQL into this repository, or recreate its schema or transaction logic. The actual +preflight schema/validator and `rehearseConfigurationInvocation` execute in Vitest; +only organization membership and explicitly injected fixture decisions are mocked. +SQL runs the pinned real `configure_return_urls` function in a disposable cluster. + +The dedicated workflow checks out the public Database repository at that exact +commit. This read-only source checkout is separate from test execution. No hosted +DSN, provider credentials, DNS query, grants or publication are used by the harness. +Changing a pinned dependency requires deliberate pin review and requalification; +a source mismatch aborts before cluster creation. The original functions are unchanged. + +## Bridge behavior + +`invokeConfigurationSqlFixture` receives the original plan and caller-retained +idempotency key. It passes actor/resource binding, complete expected snapshot and +sorted changes to the actual SQL function. It neither generates a new key nor +retries, catches a conflict as success, or fabricates a replacement receipt. +SQL owns authorization, serialization, idempotency and immutable receipt storage. +The bridge uses escaped SQL literals through an explicitly injected fixture +transport; it is not a production query adapter. The test transport calls `psql` +without a shell and requires the runner's absolute Unix-socket path and fixture +marker. No arbitrary network hostname or connection-string parameter exists. + +The returned SQL JSON is strictly checked for receipt identity/timestamp, actor, +workspace/application/environment/operation, exact original baseline and changes, +and all disabled production/access flags. The expected after-state is assembled +from the actual rehearsal's `change.next` values and destination lists—no new +revision arithmetic or alternate origin parser is introduced. The entire returned +after snapshot must match, including unchanged origins and proof revisions. +Malformed, altered or activation-bearing receipts are rejected. + +After successful validation the bridge returns **both**: + +- The actual immutable SQL receipt, including its recorded before/after snapshots, + receipt ID and server timestamp. +- The existing rehearsal's exact `fixture-only-result` acknowledgment, preserving + `persisted: false`, `bootstrap_enabled: false`, `access_activated: false` and its + original plan. Here `persisted: false` belongs to the historical rehearsal + envelope; it does not deny that the disposable database committed fixture rows. + The SQL receipt separately says `production_persisted: false` and + `evidence_kind: synthetic_configuration`. + +An acknowledgment is never created before receipt validation. It confers no +management authority, proof of domain control, production persistence or access. + +## Unknown outcomes and conflicts + +Capture the complete plan and original key before dispatch. If transport fails +with unknown outcome, preserve those values and replay them directly through the +same bridge, subject to SQL's fresh authority check. Do not rerun the rehearsal +against newer parent state to manufacture a new request: it might produce a no-op +or different baseline and would lose the original receipt association. Do not +invent a new key. Changed payload on the original key conflicts in SQL. + +The test actually commits in PostgreSQL, discards the transport response, and then +recovers the original receipt with the original key/plan. Receipt count, key and +full original JSON are checked; no timestamp extension or duplicate mutation is +accepted. Conflicts and SQL authority revocation propagate through the actual API +rehearsal without automatic retry. Fault injection drops a real committed response; +it does not replace the database with a simulated result. + +## Authority and remaining boundary + +With no API fixture authority, the rehearsal rejects before reading a parent or +invoking SQL. With its explicit test marker but SQL's original default-denied +adapter, the actual SQL operation still rejects and stores nothing. Only loading +the pinned `fixture-authority.sql` in the disposable cluster allows the successful +cases. That override is not real membership, a management role or a delegated grant. +The test marker is never sent as SQL authority. The real production authority +boundary therefore remains **blocked by unadopted management/delegated policy**; +this harness demonstrates wiring under declared fixtures, not permission to expose it. + +Other unresolved runtime gates remain the production parent mapping and writer +protocol, service privileges, canonical request adapter, retention, resolver/origin +eligibility, consumer revocation and activation. No route imports this module. +Provider/independent-host/mobile acceptance and the separate browser hold are unchanged. + +## Run and evidence + +Install the API's existing dependencies, put PostgreSQL binaries from one version +on PATH, and provide a local Database repository containing the pinned commit: + +```sh +python3 scripts/application-proof/sql-bridge/run.py --database-repo /absolute/path/to/database +``` + +The runner creates a temporary cluster listening only on its Unix socket, loads +verified SQL bytes, records source identities/PostgreSQL version, runs the integration +suite, and stops/removes the cluster even on test failure. It does not use a hosted +connection or modify the supplied Database checkout. Its marker is an accidental- +misconfiguration guard, not a security credential. + +The dedicated CI workflow runs PostgreSQL 15 and 17. Normal unit runs skip these +integration cases when no runner-created socket exists; a skipped suite is not a +passing integration result. The runner supplies the socket and runs all ten cases: +API/default SQL denial, full successful mapping, quoted URL round-trip, absent +transport, real snapshot conflict, real authority revocation, committed-response +loss/recovery, receipt tampering rejection, and actual preflight rejection. diff --git a/scripts/application-proof/sql-bridge/bridge.integration.test.ts b/scripts/application-proof/sql-bridge/bridge.integration.test.ts new file mode 100644 index 000000000..496c0bc95 --- /dev/null +++ b/scripts/application-proof/sql-bridge/bridge.integration.test.ts @@ -0,0 +1,257 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { rehearseConfigurationInvocation } from "../rehearseConfigurationInvocation"; +import { invokeConfigurationSqlFixture } from "./invokeConfigurationSqlFixture"; +import { fixtureSql } from "./fixtureSql"; +vi.mock("@/lib/organizations/validateOrganizationAccess", () => ({ + validateOrganizationAccess: vi.fn(async () => true), +})); +const actor = "00000000-0000-4000-8000-000000000001"; +const app = "00000000-0000-4000-8000-000000000002"; +const origin = "https://music.example"; +const other = "https://other.example"; +const key = "original-configuration-key"; +type Plan = Awaited>["plan"]; +const input = () => ({ + name: "Music", + environment: "production", + allowed_origins: [origin, other], + return_urls: [other + "/new"], +}); +const snapshot = () => + JSON.parse( + fixtureSql( + `SELECT application_proof_proposal.configuration_snapshot('${actor}','${app}','production');`, + ), + ); +const transport = vi.fn(async (sql: string) => fixtureSql(sql)); +const authorize = async (scope: unknown) => ({ kind: "fixture-only-authority", scope }); +const enableSqlAuthority = () => + fixtureSql( + readFileSync(join(process.env.RECOUP_PROOF_BRIDGE_SOCKET!, "fixture-authority.sql"), "utf8"), + ); +const count = () => + Number(fixtureSql("SELECT count(*) FROM application_proof_proposal.configuration_receipts;")); + +describe.skipIf(!process.env.RECOUP_PROOF_BRIDGE_SOCKET)( + "pinned actual API to PostgreSQL configuration bridge", + () => { + beforeEach(() => { + transport.mockClear(); + fixtureSql( + readFileSync( + join(process.env.RECOUP_PROOF_BRIDGE_SOCKET!, "default-authority.sql"), + "utf8", + ), + ); + fixtureSql(`TRUNCATE proof_parent_fixture.workspaces,proof_parent_fixture.authority CASCADE; + INSERT INTO proof_parent_fixture.workspaces VALUES('${actor}'); + INSERT INTO proof_parent_fixture.applications(workspace_id,id) VALUES('${actor}','${app}'); + INSERT INTO proof_parent_fixture.environments(workspace_id,application_id,environment) VALUES('${actor}','${app}','production'); + INSERT INTO proof_parent_fixture.origins(workspace_id,application_id,environment,origin,hostname,return_urls) + VALUES('${actor}','${app}','production','${origin}','music.example',ARRAY['${origin}/done']), + ('${actor}','${app}','production','${other}','other.example',ARRAY['${other}/done']); + INSERT INTO proof_parent_fixture.authority VALUES('${actor}','${actor}','${app}','production',ARRAY['replace_existing_origin_return_urls'],true);`); + }); + it("denies missing API authority before SQL transport", async () => { + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => + (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment, + }), + ).rejects.toThrow("Management authority unavailable"); + expect(transport).not.toHaveBeenCalled(); + expect(count()).toBe(0); + }); + it("does not convert the API fixture marker into SQL management authority", async () => { + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => + (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment, + }), + ).rejects.toThrow("management authority unavailable"); + expect(transport).toHaveBeenCalledOnce(); + expect(count()).toBe(0); + }); + it("maps actual SQL receipt and full after state to the existing disabled acknowledgment", async () => { + enableSqlAuthority(); + let receipt: unknown; + const result = await rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => { + const bridge = await invokeConfigurationSqlFixture(plan, key, transport); + receipt = bridge.receipt; + return bridge.acknowledgment; + }, + }); + expect(result.plan.changes.map(change => change.return_urls)).toEqual([[], [other + "/new"]]); + expect(receipt).toMatchObject({ + actor, + application_id: app, + workspace_id: actor, + bootstrap_enabled: false, + access_activated: false, + production_persisted: false, + changes: result.plan.changes, + before: result.plan.expected_snapshot, + after: snapshot(), + }); + expect(snapshot().origins).toEqual( + [origin, other].map(value => ({ + origin: value, + config_revision: 2, + proof_revision: 1, + cas_revision: 2, + revoked: false, + })), + ); + expect(count()).toBe(1); + }); + it("round-trips apostrophes through actual canonical validation and SQL literals", async () => { + enableSqlAuthority(); + const destination = other + "/o'clock?from=artist"; + const result = await rehearseConfigurationInvocation( + actor, + app, + { ...input(), return_urls: [destination] }, + { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => + (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment, + }, + ); + expect(snapshot().return_urls).toEqual([destination]); + expect(result.plan.changes[1].return_urls).toEqual([destination]); + expect(count()).toBe(1); + }); + it("rejects an absent SQL transport without inventing a result", async () => { + enableSqlAuthority(); + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => + (await invokeConfigurationSqlFixture(plan, key)).acknowledgment, + }), + ).rejects.toThrow("Fixture SQL transport unavailable"); + expect(count()).toBe(0); + }); + it("propagates a full-snapshot conflict from actual SQL without a blind retry", async () => { + enableSqlAuthority(); + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => { + fixtureSql( + `UPDATE proof_parent_fixture.origins SET cas_revision=cas_revision+1 WHERE origin='${other}';`, + ); + return (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment; + }, + }), + ).rejects.toThrow("snapshot conflict"); + expect(transport).toHaveBeenCalledOnce(); + expect(count()).toBe(0); + }); + it("propagates SQL authority revocation after the API fixture decision", async () => { + enableSqlAuthority(); + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => { + fixtureSql("UPDATE proof_parent_fixture.authority SET enabled=false;"); + return (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment; + }, + }), + ).rejects.toThrow("management authority unavailable"); + expect(count()).toBe(0); + }); + it("recovers a lost committed response with the original plan/key and original receipt", async () => { + enableSqlAuthority(); + let captured: Plan | undefined; + const dropResponse = vi.fn(async (sql: string) => { + fixtureSql(sql); + throw new Error("outcome unknown: response lost"); + }); + await expect( + rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => { + captured = structuredClone(plan); + return (await invokeConfigurationSqlFixture(plan, key, dropResponse)).acknowledgment; + }, + }), + ).rejects.toThrow("outcome unknown"); + expect(dropResponse).toHaveBeenCalledOnce(); + expect(count()).toBe(1); + const original = JSON.parse( + fixtureSql("SELECT result FROM application_proof_proposal.configuration_receipts;"), + ); + const recovered = await invokeConfigurationSqlFixture(captured!, key, transport); + expect(recovered.receipt).toEqual(original); + expect(count()).toBe(1); + expect(fixtureSql("SELECT key FROM application_proof_proposal.configuration_requests;")).toBe( + key, + ); + const altered = structuredClone(captured!); + altered.changes[1].return_urls = [other + "/different"]; + await expect(invokeConfigurationSqlFixture(altered, key, transport)).rejects.toThrow( + "idempotency conflict", + ); + expect(count()).toBe(1); + }); + it("rejects altered real receipts rather than fabricating successful acknowledgments", async () => { + enableSqlAuthority(); + let plan: Plan | undefined; + await rehearseConfigurationInvocation(actor, app, input(), { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async value => { + plan = structuredClone(value); + return (await invokeConfigurationSqlFixture(value, key, transport)).acknowledgment; + }, + }); + for (const patch of [ + { access_activated: true }, + { production_persisted: true }, + { actor: app }, + { before: {} }, + { after: {} }, + { changes: [] }, + ]) { + await expect( + invokeConfigurationSqlFixture(plan!, key, async sql => + JSON.stringify({ ...JSON.parse(fixtureSql(sql)), ...patch }), + ), + ).rejects.toThrow(); + } + expect(count()).toBe(1); + }); + it("rejects malformed real preflight input before invoking SQL", async () => { + enableSqlAuthority(); + await expect( + rehearseConfigurationInvocation( + actor, + app, + { ...input(), return_urls: ["https://foreign.example/done"] }, + { + authorizeFixture: authorize, + readFixtureSnapshot: async () => snapshot(), + invokeFixture: async plan => + (await invokeConfigurationSqlFixture(plan, key, transport)).acknowledgment, + }, + ), + ).rejects.toThrow(); + expect(transport).not.toHaveBeenCalled(); + expect(count()).toBe(0); + }); + }, +); diff --git a/scripts/application-proof/sql-bridge/fixtureSql.ts b/scripts/application-proof/sql-bridge/fixtureSql.ts new file mode 100644 index 000000000..2d9d0ebea --- /dev/null +++ b/scripts/application-proof/sql-bridge/fixtureSql.ts @@ -0,0 +1,18 @@ +import { execFileSync } from "node:child_process"; +import { isAbsolute, join } from "node:path"; +import { readFileSync } from "node:fs"; +import pins from "./sources.json"; + +/** Test transport only: runner-created local socket, never a DSN or hostname. */ +export function fixtureSql(sql: string) { + const socket = process.env.RECOUP_PROOF_BRIDGE_SOCKET; + if (!socket || !isAbsolute(socket)) throw new Error("Offline fixture socket required"); + const marker = JSON.parse(readFileSync(join(socket, "offline-fixture.json"), "utf8")); + if (marker.offline_only !== true || marker.database_commit !== pins.database_commit) + throw new Error("Offline fixture marker mismatch"); + return execFileSync( + "psql", + ["-h", socket, "-p", "55483", "-d", "postgres", "-XqAt", "-v", "ON_ERROR_STOP=1"], + { input: sql, encoding: "utf8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"] }, + ).trim(); +} diff --git a/scripts/application-proof/sql-bridge/invokeConfigurationSqlFixture.ts b/scripts/application-proof/sql-bridge/invokeConfigurationSqlFixture.ts new file mode 100644 index 000000000..2ae41d332 --- /dev/null +++ b/scripts/application-proof/sql-bridge/invokeConfigurationSqlFixture.ts @@ -0,0 +1,83 @@ +import { isDeepStrictEqual } from "node:util"; +import { z } from "zod"; +import type { rehearseConfigurationInvocation } from "../rehearseConfigurationInvocation"; + +type Plan = Awaited>["plan"]; +const receiptSchema = z + .object({ + receipt_id: z.string().uuid(), + actor: z.string().uuid(), + workspace_id: z.string().uuid(), + application_id: z.string().uuid(), + environment: z.enum(["development", "production"]), + operation: z.literal("replace_existing_origin_return_urls"), + recorded_at: z.iso.datetime({ offset: true }), + before: z.unknown(), + changes: z.unknown(), + after: z.unknown(), + access_activated: z.literal(false), + bootstrap_enabled: z.literal(false), + production_persisted: z.literal(false), + evidence_kind: z.literal("synthetic_configuration"), + }) + .strict(); + +/** Offline SQL receipt bridge. Caller retains the original plan/key on uncertain outcome. */ +export async function invokeConfigurationSqlFixture( + originalPlan: Plan, + originalKey: string, + executeFixtureSql?: (sql: string) => Promise, +) { + z.string().min(1).max(128).parse(originalKey); + if (!executeFixtureSql) throw new Error("Fixture SQL transport unavailable"); + const plan = structuredClone(originalPlan); + const quote = (value: string) => "'" + value.replaceAll("'", "''") + "'"; + const scope = plan.scope; + const parameters = [ + scope.actor_id, + scope.workspace_id, + scope.application_id, + scope.environment, + originalKey, + ].map(quote); + parameters.push( + quote(JSON.stringify(plan.expected_snapshot)) + "::jsonb", + quote(JSON.stringify(plan.changes)) + "::jsonb", + ); + // SQL owns idempotency and the receipt. No retry, generated key, or local receipt substitute. + const raw = await executeFixtureSql( + `SELECT application_proof_proposal.configure_return_urls(${parameters.join(",")});`, + ); + const receipt = receiptSchema.parse(JSON.parse(raw)); + if ( + receipt.actor !== scope.actor_id || + receipt.workspace_id !== scope.workspace_id || + receipt.application_id !== scope.application_id || + receipt.environment !== scope.environment || + receipt.operation !== scope.operation || + !isDeepStrictEqual(receipt.before, plan.expected_snapshot) || + !isDeepStrictEqual(receipt.changes, plan.changes) + ) + throw new Error("SQL receipt binding mismatch"); + const after = structuredClone(plan.expected_snapshot); + const changed = new Map(plan.changes.map(change => [change.origin, change])); + after.origins = after.origins.map(entry => { + const change = changed.get(entry.origin); + return change ? { origin: entry.origin, revoked: entry.revoked, ...change.next } : entry; + }); + after.return_urls = [ + ...after.return_urls.filter(url => !changed.has(new URL(url).origin)), + ...plan.changes.flatMap(change => change.return_urls), + ].sort(); + if (!isDeepStrictEqual(receipt.after, after)) throw new Error("SQL receipt after-state mismatch"); + return { + receipt, + acknowledgment: { + kind: "fixture-only-result" as const, + persisted: false as const, + bootstrap_enabled: false as const, + access_activated: false as const, + plan, + }, + }; +} diff --git a/scripts/application-proof/sql-bridge/run.py b/scripts/application-proof/sql-bridge/run.py new file mode 100644 index 000000000..0cd294bf1 --- /dev/null +++ b/scripts/application-proof/sql-bridge/run.py @@ -0,0 +1,64 @@ +"""Pinned API -> SQL qualification using only a fresh Unix-socket PostgreSQL fixture.""" +import argparse +import hashlib +import json +import pathlib +import subprocess +import tempfile +import os + +HERE = pathlib.Path(__file__).resolve().parent +API = HERE.parents[2] + + +def run(args, **kwargs): + result = subprocess.run(args, text=True, capture_output=True, **kwargs) + if result.returncode: + raise RuntimeError(result.stdout + result.stderr) + return result.stdout + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--database-repo', required=True, type=pathlib.Path) + args = parser.parse_args() + pins = json.loads((HERE / 'sources.json').read_text()) + for name, expected in pins['api_files'].items(): + if hashlib.sha256((API / name).read_bytes()).hexdigest() != expected: + raise RuntimeError('API source pin mismatch: ' + name) + sources = {} + for name, expected in pins['database_files'].items(): + source = subprocess.check_output(['git', '-C', str(args.database_repo), 'show', pins['database_commit'] + ':' + name]) + if hashlib.sha256(source).hexdigest() != expected: + raise RuntimeError('Database source pin mismatch: ' + name) + sources[pathlib.Path(name).name] = source.decode() + with tempfile.TemporaryDirectory(prefix='recoup-proof-bridge-') as directory: + root = pathlib.Path(directory) + cluster = root / 'pg' + run(['initdb', '-D', str(cluster), '-A', 'trust']) + started = False + try: + run(['pg_ctl', '-D', str(cluster), '-l', str(root / 'postgres.log'), '-o', + f"-k {directory} -p 55483 -c listen_addresses=''", '-w', 'start']) + started = True + sql_args = ['psql', '-h', directory, '-p', '55483', '-d', 'postgres', '-XqAt', '-v', 'ON_ERROR_STOP=1'] + for name in ['fixture.sql', 'proposal.sql', 'configuration-fixture.sql', 'configuration.sql']: + run(sql_args, input=sources[name]) + proposal = sources['proposal.sql'] + (root / 'default-authority.sql').write_text(proposal[proposal.index('-- DEFAULT AUTHORITY'):proposal.index('-- TRANSACTION')]) + (root / 'fixture-authority.sql').write_text(sources['fixture-authority.sql']) + (root / 'offline-fixture.json').write_text(json.dumps({'offline_only': True, 'database_commit': pins['database_commit']})) + env = {**os.environ, 'RECOUP_PROOF_BRIDGE_SOCKET': directory} + print(json.dumps({'api_commit':pins['api_commit'],'database_commit':pins['database_commit'], + 'source_pins':'matched','postgres':run(['psql','--version']).strip()}), flush=True) + result = subprocess.run(['pnpm','exec','vitest','run','--config',str(HERE / 'vitest.bridge.config.ts')], + cwd=API, env=env, timeout=120) + if result.returncode: + raise RuntimeError('Bridge qualification failed') + finally: + if started: + run(['pg_ctl','-D',str(cluster),'-m','immediate','-w','stop']) + + +if __name__ == '__main__': + main() diff --git a/scripts/application-proof/sql-bridge/sources.json b/scripts/application-proof/sql-bridge/sources.json new file mode 100644 index 000000000..e5a81d9c4 --- /dev/null +++ b/scripts/application-proof/sql-bridge/sources.json @@ -0,0 +1,17 @@ +{ + "api_commit": "959d30bf19f28ae6a8c75031f424831923403374", + "api_files": { + "scripts/application-proof/rehearseConfigurationInvocation.ts": "0b6a23a988905d955627a9a15454ddaa5c044942e543f9dc5b916ce793aa6b5c", + "lib/applications/applicationRegistrationSchema.ts": "5bfb55ded25eae323bea02b535d6fb010eec5b2a767b891a13b86e4c91427a30", + "lib/applications/validateApplicationRegistration.ts": "b842cd312e0123a65ec1dd872c54474f77872b337ef5285ecedff1dad96ac0c6", + "lib/applications/ApplicationRegistrationError.ts": "56e8764fb3d17ac023c6c51f7ecbda3c5da82aa11076152abf32e5c407b5e7d3" + }, + "database_commit": "372de990156739dda1b605d18a40333cd6f1bdba", + "database_files": { + "proposals/application-proof-2104/fixture.sql": "b4435b1c5546d471c33b758f1ac8a7fd8ca199071b08cc541f4cb199e6412668", + "proposals/application-proof-2104/proposal.sql": "2cf96399422cfc1e68b0578b7aeb7b58a97c56303d85b91ee6cf862329f6c86c", + "proposals/application-proof-2104/configuration-fixture.sql": "b15593f26c58a856ea4dedf98a7d42f1bbe7cf229f6b15aa8a80bd9d0d598c80", + "proposals/application-proof-2104/configuration.sql": "148819c1363929e990bf2cfd67bae02f7567c2e2e2a05732cb17ea2248bad3b1", + "proposals/application-proof-2104/fixture-authority.sql": "0a2715a5a4f93c349df06d25a6334d513350f225a36af71ae8694fe1914c4c99" + } +} diff --git a/scripts/application-proof/sql-bridge/vitest.bridge.config.ts b/scripts/application-proof/sql-bridge/vitest.bridge.config.ts new file mode 100644 index 000000000..7052d6d98 --- /dev/null +++ b/scripts/application-proof/sql-bridge/vitest.bridge.config.ts @@ -0,0 +1,45 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { defineConfig, mergeConfig } from "vitest/config"; +import base from "../../../vitest.config"; +import pins from "./sources.json"; + +const root = fileURLToPath(new URL("../../../", import.meta.url)); +const cache = new Map( + Object.entries(pins.api_files).map(([path, expected]) => { + const filename = resolve(root, path); + const bytes = readFileSync(filename); + if (createHash("sha256").update(bytes).digest("hex") !== expected) + throw new Error(`API source pin mismatch: ${path}`); + return [filename, bytes.toString("utf8")]; + }), +); +const loaded = new Set(); +export default mergeConfig( + base, + defineConfig({ + plugins: [ + { + name: "frozen-application-proof-sources", + enforce: "pre", + load(id) { + const filename = id.split("?")[0]; + const source = cache.get(filename); + if (source !== undefined) { + loaded.add(filename); + return source; + } + }, + closeBundle() { + if (loaded.size !== cache.size) + throw new Error("Not every pinned API source was executed through the frozen loader"); + }, + }, + ], + test: { + include: [resolve(root, "scripts/application-proof/sql-bridge/bridge.integration.test.ts")], + }, + }), +);