From 8a1274586ac30504d5905775e9bb2f1db0a0e9cf Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:45:57 -0500 Subject: [PATCH 1/6] Add unwired registration SQL helpers and restricted composition qualification --- .../ProposedRegistrationSqlClient.ts | 7 + .../__tests__/registrationSql.test.ts | 141 +++++++++ .../insertProposedApplicationRegistration.ts | 50 ++++ .../selectProposedApplicationRegistration.ts | 43 +++ .../sql-composition/README.md | 58 +++- .../sql-composition/qualification.test.ts | 269 ++++++++++++------ .../sql-composition/run.mjs | 65 ++++- .../sql-composition/source-bindings.json | 14 +- .../sql-composition/supervise.py | 7 +- 9 files changed, 546 insertions(+), 108 deletions(-) create mode 100644 lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient.ts create mode 100644 lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts create mode 100644 lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts create mode 100644 lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts diff --git a/lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient.ts b/lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient.ts new file mode 100644 index 000000000..5ee923cda --- /dev/null +++ b/lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient.ts @@ -0,0 +1,7 @@ +/** Trusted injected server client only; no connection or ambient configuration. + * Requires an idle autocommit session already holding the intended privileges. + * The helpers do not establish or verify session state. Proposal-only, unwired. + */ +export interface ProposedRegistrationSqlClient { + query(text: string, values: unknown[]): Promise<{ rows: Record[] }>; +} diff --git a/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts new file mode 100644 index 000000000..820402f20 --- /dev/null +++ b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts @@ -0,0 +1,141 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Client } from "pg"; +import type { ProposedRegistrationSqlClient } from "../ProposedRegistrationSqlClient"; +import { insertProposedApplicationRegistration as create } from "../insertProposedApplicationRegistration"; +import { selectProposedApplicationRegistration as read } from "../selectProposedApplicationRegistration"; +import { + ProposedStorageFailure, + type ProposedCreateCall, + type ProposedReadCall, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; + +// Compile-time compatibility only: no client construction, cast or connection. +const compatible = (client: Client): ProposedRegistrationSqlClient => client; +void compatible; +const actor = "11111111-1111-4111-8111-111111111111"; +const createCall: ProposedCreateCall = { + actor, + workspace: actor, + environment: "production", + key: "original-key", + entitlementRevision: 1, + registration: { + name: "Música", + origins: [ + { + origin: "https://music.example", + hostname: "music.example", + return_urls: ["https://music.example/cb"], + }, + ], + }, +}; +const readCall: ProposedReadCall = { + actor, + workspace: actor, + application: actor, + environment: "production", + receipt: actor, +}; +const cases = [ + { + operation: "create", + invoke: (client: ProposedRegistrationSqlClient) => create(client, createCall), + sql: "SELECT application_registration_execution_proposal.create_registration($1::uuid,$2::uuid,$3::text,$4::text,$5::bigint,$6::jsonb) AS receipt", + values: [ + actor, + actor, + "production", + "original-key", + 1, + JSON.stringify(createCall.registration), + ], + }, + { + operation: "read", + invoke: (client: ProposedRegistrationSqlClient) => read(client, readCall), + sql: "SELECT application_registration_execution_proposal.read_registration($1::uuid,$2::uuid,$3::uuid,$4::text,$5::uuid) AS receipt", + values: [actor, actor, actor, "production", actor], + }, +]; +afterEach(() => vi.restoreAllMocks()); +describe.each(cases)("$operation fixed proposal query", ({ operation, invoke, sql, values }) => { + it("returns the unchanged unknown receipt with one bound query", async () => { + const receipt = { actor, unvalidated: true }; + const query = vi.fn().mockResolvedValue({ rows: [{ receipt }] }); + expect(await invoke({ query })).toBe(receipt); + expect(query).toHaveBeenCalledExactlyOnceWith(sql, values); + }); + it.each(["42501", "P2101", "P0001", "P2102", "23505", "40001", undefined, 42501])( + "classifies only exact structured code %s (synthetic)", + async code => { + const raw = Object.assign(new Error("PRIVATE: idempotency conflict"), { code }); + const query = vi.fn().mockRejectedValue(raw); + const logs = [ + vi.spyOn(console, "error"), + vi.spyOn(console, "warn"), + vi.spyOn(console, "log"), + ]; + const error = await invoke({ query }).catch(e => e); + expect(error).toBeInstanceOf(ProposedStorageFailure); + if (!(error instanceof ProposedStorageFailure)) throw new Error("Expected typed failure"); + expect(error).not.toBe(raw); + expect(error.kind).toBe( + code === "42501" + ? "denied" + : code === "P2101" && operation === "create" + ? "conflict" + : "outcome_unknown", + ); + expect(error.cause).toBeUndefined(); + expect(error.message).not.toContain("PRIVATE"); + expect(query).toHaveBeenCalledTimes(1); + for (const log of logs) expect(log).not.toHaveBeenCalled(); + }, + ); + it.each([ + null, + "42501", + new ProposedStorageFailure("conflict"), + new ProposedStorageFailure("denied"), + Object.defineProperty({}, "code", { + get() { + throw new Error("PRIVATE getter"); + }, + }), + ])("does not trust client-thrown kinds or malformed errors", async raw => { + const query = vi.fn().mockRejectedValue(raw); + const error = await invoke({ query }).catch(e => e); + expect(error).toBeInstanceOf(ProposedStorageFailure); + if (!(error instanceof ProposedStorageFailure)) throw new Error("Expected typed failure"); + expect(error.kind).toBe("outcome_unknown"); + expect(error).not.toBe(raw); + expect(query).toHaveBeenCalledTimes(1); + }); + it.each([ + undefined, + null, + {}, + { rows: [] }, + { rows: [{}, {}] }, + { rows: [{}] }, + { rows: [{ receipt: null }] }, + { rows: [{ receipt: undefined }] }, + { rows: [null] }, + ])("rejects a malformed envelope", async result => { + const query = vi.fn().mockResolvedValue(result); + await expect(invoke({ query })).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(query).toHaveBeenCalledTimes(1); + }); +}); +it("serialization failure is unknown before any query", async () => { + const call = structuredClone(createCall); + Object.defineProperty(call.registration, "toJSON", { + value: () => { + throw new Error("PRIVATE"); + }, + }); + const query = vi.fn(); + await expect(create({ query }, call)).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(query).not.toHaveBeenCalled(); +}); diff --git a/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts new file mode 100644 index 000000000..c0423c752 --- /dev/null +++ b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts @@ -0,0 +1,50 @@ +import { + ProposedStorageFailure, + type ProposedCreateCall, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import type { ProposedRegistrationSqlClient } from "./ProposedRegistrationSqlClient"; + +/** Unwired proposal-only single call. The domain owns authentication and receipt validation. */ +export async function insertProposedApplicationRegistration( + client: ProposedRegistrationSqlClient, + call: ProposedCreateCall, +): Promise { + // Serialization/envelope failures are unknown, never SQL authorization outcomes. + let values: unknown[]; + try { + values = [ + call.actor, + call.workspace, + call.environment, + call.key, + call.entitlementRevision, + JSON.stringify(call.registration), + ]; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } + let result; + try { + result = await client.query( + "SELECT application_registration_execution_proposal.create_registration($1::uuid,$2::uuid,$3::text,$4::text,$5::bigint,$6::jsonb) AS receipt", + values, + ); + } catch (error) { + let code: unknown; + try { + if (typeof error === "object" && error !== null && "code" in error) code = error.code; + } catch { + /* A malformed error is not a SQLSTATE. */ + } + if (code === "42501") throw new ProposedStorageFailure("denied"); + if (code === "P2101") throw new ProposedStorageFailure("conflict"); + throw new ProposedStorageFailure("outcome_unknown"); + } + try { + if (!Array.isArray(result.rows) || result.rows.length !== 1 || result.rows[0]?.receipt == null) + throw new Error(); + return result.rows[0].receipt; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } +} diff --git a/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts new file mode 100644 index 000000000..ee1122c59 --- /dev/null +++ b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts @@ -0,0 +1,43 @@ +import { + ProposedStorageFailure, + type ProposedReadCall, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import type { ProposedRegistrationSqlClient } from "./ProposedRegistrationSqlClient"; + +/** Unwired proposal-only single call. The domain owns authentication and receipt validation. */ +export async function selectProposedApplicationRegistration( + client: ProposedRegistrationSqlClient, + call: ProposedReadCall, +): Promise { + // Serialization/envelope failures are unknown, never SQL authorization outcomes. + let values: unknown[]; + try { + values = [call.actor, call.workspace, call.application, call.environment, call.receipt]; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } + let result; + try { + result = await client.query( + "SELECT application_registration_execution_proposal.read_registration($1::uuid,$2::uuid,$3::uuid,$4::text,$5::uuid) AS receipt", + values, + ); + } catch (error) { + let code: unknown; + try { + if (typeof error === "object" && error !== null && "code" in error) code = error.code; + } catch { + /* A malformed error is not a SQLSTATE. */ + } + if (code === "42501") throw new ProposedStorageFailure("denied"); + + throw new ProposedStorageFailure("outcome_unknown"); + } + try { + if (!Array.isArray(result.rows) || result.rows.length !== 1 || result.rows[0]?.receipt == null) + throw new Error(); + return result.rows[0].receipt; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } +} diff --git a/scripts/application-registration-proposal/sql-composition/README.md b/scripts/application-registration-proposal/sql-composition/README.md index 6f5d2ef76..3445a5420 100644 --- a/scripts/application-registration-proposal/sql-composition/README.md +++ b/scripts/application-registration-proposal/sql-composition/README.md @@ -2,9 +2,9 @@ This harness joins the existing unwired API create/read domain to the exact inactive Database 138 proposal in an owned disposable PostgreSQL cluster. It is not a production storage adapter, credential verifier, route, MCP tool or policy adoption. -The actual REST authentication orchestration uses the existing controlled SDK/profile/Supabase leaves. Only explicit synthetic actors are enrolled by fixture setup. Domain calls execute one parameterized SQL function each, with setup/readback queries counted separately. No management permission is granted by create. Real SQL authorization errors `42501` map to denied. Only create-operation `P2101` maps to the existing conflict kind. Generic `P0001`, adjacent/unrecognized codes, transport failures and read-operation `P2101` remain `outcome_unknown`; no message text or SQLSTATE family is used for classification. +The actual REST authentication orchestration uses the existing controlled SDK/profile/Supabase leaves. Only explicit synthetic actors are enrolled by fixture setup. Domain calls use the actual injected SQL helpers to execute one parameterized wrapper each, with setup/readback queries counted separately. No management permission is granted by create. Real SQL authorization errors `42501` map to denied. Only create-operation `P2101` maps to the existing conflict kind. Generic `P0001`, adjacent/unrecognized codes, transport failures and read-operation `P2101` remain `outcome_unknown`; no message text or SQLSTATE family is used for classification. -The selected source pair is accepted local Database `f507a77696f20429f977df9885d6c8c11a5f304b` and accepted documented API successor `0769bc1957fce38bd6b847d342eae904044ae821` (the manifest's acceptedApiComposition). That successor inherits the reviewed joined qualification; `784bee20b3e0fe61e67ed156c7f3a39a08a441b2` remains the original pre-joined compatibility source recorded as originalApiCompatibility. The original apiMerge is retained as historical provenance. The policy descriptor and Database pins must match this pair; the historical df7 qualification is not reused as successor evidence. +Historical source pair (not successor qualification): accepted local Database `f507a77696f20429f977df9885d6c8c11a5f304b` and accepted documented API successor `0769bc1957fce38bd6b847d342eae904044ae821` (the manifest's acceptedApiComposition). That successor inherits the reviewed joined qualification; `784bee20b3e0fe61e67ed156c7f3a39a08a441b2` remains the original pre-joined compatibility source recorded as originalApiCompatibility. The original apiMerge is retained as historical provenance. The policy descriptor and Database pins must match this pair; the historical df7 qualification is not reused as successor evidence. The loss-of-response case drops the result only after actual SQL commit. Recovery explicitly reauthenticates and reuses the original key/input, then compares the SQL receipt and row count. Altered original intent now produces the definite conflict while preserving the original receipt and all five table contents. New-key stale revision, same-key fingerprint changes and authorized exact replay after revision advance are covered separately. No production retry ledger or automatic retry exists. Returned UUIDs/timestamps/flags are validated by the real domain parser; input-only read aliases remain supported. @@ -25,12 +25,60 @@ The successor local PostgreSQL 15.10/17.7 qualification uses Node 24.18.0. Earli Optional `--fault signal`, `--fault timeout`, or `--fault worker-exit` controls initialize a real guarded Node descendant, then deliberately interrupt the supervisor, time out its worker, or exit its worker while the child remains alive. Each retains an expected nonzero exit, but the launcher reports `COMPOSITION_FAULT_RESULT.passed=true` only after validating the expected exit, initialized Node lineage and both worker/cluster cleanup receipts. A nonzero exit alone is not a passing fault control. These are lifecycle controls, not functional SQL passes. -The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this eight-path qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same eight paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. +The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this nine-path adapter/qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same nine paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. Qualification targets PostgreSQL 15 and 17. This suite is distinct from the 130-case controlled adapter/MCP suite and ordinary Unit CI. It requires the explicitly pinned Database checkout and is not evidence of a hosted RPC, least-privilege deployment, live enrollment or public App 2104 availability. Personal policy, production authority provisioning, retention, deployed MCP nonprovisioning/original-actor handoff and client acceptance remain separate. Database 138 remains draft/unmerged/unapplied. -The eight qualification paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. +The nine candidate paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. The outer watchdog reports cleanup as unconfirmed if the supervisor cannot finish its bounded cleanup. It preserves the recorded lease for inspection; it does not claim that killing the supervisor or its group would remove separately sessioned workers and PostgreSQL. The focused fault controls do not exercise that outer watchdog. -Independent error controls use a session-local `pg_temp` function that emits structured SQLSTATE with the deliberately misleading message “idempotency conflict”. For those calls only, the test port executes that single synthetic SQL query instead of registration/read; these are classification controls, not failures observed from the real registration function. The transport negative throws before the SQL query and is likewise synthetic. Every attempt still enters one domain storage port; setup/readback queries are separately counted. Full row snapshots of applications, environments, origins, receipts and requests prove counts and historical values are unchanged, and subsequent original-key replay/read returns the original receipt. The separate committed-response-loss case executes the actual registration commit. +## Unwired SQL helper successor + +API baseline: `ec284cba127d73d0c3e7e74deceabac5c6a145f1`. Execution profile: +`acea75c0e118b6ca12bb9a22470a8bd7b383f925`, tree +`a8c45f920144db21ae1d00a807184aae51065b82`. D stays +`f507a77696f20429f977df9885d6c8c11a5f304b` in the domain policy. Earlier runs and +source pairs above are historical, not qualification for this successor. + +The required structural ProposedRegistrationSqlClient accepts an already-connected pg client. +Two helpers in lib/supabase/application_registration_proposal issue fixed six-parameter create +and five-parameter read statements against application_registration_execution_proposal wrappers. +There is no global client, connection, factory, route or runtime registration. The wrapper schema +remains disposable-only, not an adopted RPC or exposed PostgREST schema. + +The trusted caller must supply an idle autocommit session with intended privileges already set. +Helpers do not establish or query that state; an open caller transaction is unsupported because +it changes commit/receipt semantics. Endpoint/TLS/pooling/session reset/role selection/timeouts +and secret ownership belong to a separately reviewed deployment plan. + +Exact structured 42501 means denied; P2101 means conflict only for create. Other errors, +including read P2101, malformed envelopes and serialization failures, become fresh unknown +failures without raw causes/logs or retry. Exactly one non-null receipt is returned unchanged as +unknown to actual domain validation. The domain owns strict receipt, intent and actor bindings. +SQL actor parameters remain trusted server assertions, not credential authentication. + +The controller loads exact D, then the accepted roles/wrappers with the installation marker set +on that same connection. It is not authentication. D's transitive proof-composition pins remain +because unchanged D setup loads them. A separate pg client logs in as +qualification_registration_client and assumes qualification_registration_runtime during counted +setup. Only that client backs the actual helpers. Controller/setup queries are counted separately +from operations. The runtime receives no TEMP grant. Misleading-error classification controls +are labeled synthetic unit cases; no controller TEMP function stands in for runtime execution. + +Actual domain/helper/wrapper/D cases cover canonical receipts, denial/conflict/replay, revocation, +post-commit response loss and cross-actor isolation. Tampering controls alter a real returned +receipt before domain validation; they are not claims of SQL corruption. Real MCP SDK create/read +uses the same helpers; changed actor and termination before storage must yield zero operation +queries. Auth leaves are controlled synthetic fixtures, not live credential verification. + +The nine permitted candidate paths are the client interface, two helpers, unit test and existing +README, qualification.test.ts, run.mjs, supervise.py and source-bindings.json in this directory. +The launcher requires their raw bytes/types to match its recorded candidate commit/tree. Other +API source stays bound to ec284, with D and all five profile files pinned separately to exact +commits and raw blobs/modes. Native preload/socket guard/config and D lifecycle are unchanged. +Fresh PG15/17 joined runs and signal/timeout/worker-exit cleanup controls on each version are +required. Record actual Node versions; Node24 evidence is not a Node22 qualification. + +Sites owns Database139. Production policy, role adoption, enrollment, credentials, retention, +activation and deployment remain separate. A local source pass is not a release. diff --git a/scripts/application-registration-proposal/sql-composition/qualification.test.ts b/scripts/application-registration-proposal/sql-composition/qualification.test.ts index c743a7472..ade9a8d86 100644 --- a/scripts/application-registration-proposal/sql-composition/qualification.test.ts +++ b/scripts/application-registration-proposal/sql-composition/qualification.test.ts @@ -1,4 +1,4 @@ -import { beforeAll, beforeEach, afterAll, describe, expect, it } from "vitest"; +import { beforeAll, beforeEach, afterAll, afterEach, describe, expect, it, vi } from "vitest"; import { Client } from "pg"; import { userInfo } from "node:os"; import net from "node:net"; @@ -11,19 +11,22 @@ import { fixture } from "../setup"; import { installOwnedSocketGuard } from "./socket-guard.mjs"; import { createProposedApplicationRegistration as create } from "@/lib/applications/proposedRegistration/createProposedApplicationRegistration"; import { readProposedApplicationRegistration as read } from "@/lib/applications/proposedRegistration/readProposedApplicationRegistration"; -import { - ProposedStorageFailure, - type ProposedDependencies, - type ProposedCreateCall, - type ProposedReadCall, -} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import { type ProposedDependencies } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; + +import { insertProposedApplicationRegistration } from "@/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration"; +import { selectProposedApplicationRegistration } from "@/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration"; +import type { ProposedRegistrationSqlClient } from "@/lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient"; +import { Client as McpClient } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { handleProposedRegistrationMcpRequest as handle } from "@/lib/mcp/applications/handleProposedRegistrationMcpRequest"; +import supabase from "@/lib/supabase/serverClient"; // The shared auth setup denies all sockets; restore only the prevalidated owned Unix socket. installOwnedSocketGuard(); const actorA = "11111111-1111-4111-8111-111111111111"; const actorB = "33333333-3333-4333-8333-333333333333"; const socket = process.env.REGISTRATION_QUALIFICATION_SOCKET!; -const sql = new Client({ +const connection = { host: socket, port: 55473, user: userInfo().username, @@ -33,41 +36,52 @@ const sql = new Client({ query_timeout: 10000, statement_timeout: 10000, application_name: "registration-domain-composition", -}); +}; +const sql = new Client(connection); // Controller only: never passed to the helpers. +const runtime = new Client({ ...connection, user: "qualification_registration_client" }); +const nativeCompatibility: ProposedRegistrationSqlClient = runtime; +void nativeCompatibility; +let setupQueries = 0; +let runtimeIdentity: unknown; const calls: Array<{ operation: "create" | "read"; state: string; parameters: number }> = []; let fixtureQueries = 0; let dropCommittedResponse = false; -let injectedFailure: "P0001" | "P2102" | "P2101" | "transport" | undefined; +let alterReceipt: ((receipt: Record) => unknown) | undefined; let server: { version: string; encoding: string }; const fixtureQuery = async (text: string, values: unknown[] = []) => { fixtureQueries++; return sql.query(text, values); }; -const execute = async (operation: "create" | "read", text: string, values: unknown[]) => { - const observation = { operation, state: "started", parameters: values.length }; - calls.push(observation); - let result; - try { - if (injectedFailure === "transport") - throw new Error("Synthetic transport loss: idempotency conflict"); - result = injectedFailure - ? await sql.query("SELECT pg_temp.qualification_failure($1::text)", [injectedFailure]) - : await sql.query(text, values); - observation.state = "committed"; - } catch (error) { - const code = (error as { code?: string }).code; - observation.state = code ?? "unclassified"; - // P0001 includes multiple unrelated failures. Never classify it from exception text. - if (code === "42501") throw new ProposedStorageFailure("denied"); - if (operation === "create" && code === "P2101") throw new ProposedStorageFailure("conflict"); - throw error; - } - if (dropCommittedResponse && operation === "create") { - dropCommittedResponse = false; - observation.state = "committed_response_dropped"; - throw new Error("Synthetic response loss after actual SQL commit"); - } - return result.rows[0].receipt; +const observedClient: ProposedRegistrationSqlClient = { + async query(text, values) { + const operation = text.includes(".create_registration(") ? "create" : "read"; + expect(text).toBe( + operation === "create" + ? "SELECT application_registration_execution_proposal.create_registration($1::uuid,$2::uuid,$3::text,$4::text,$5::bigint,$6::jsonb) AS receipt" + : "SELECT application_registration_execution_proposal.read_registration($1::uuid,$2::uuid,$3::uuid,$4::text,$5::uuid) AS receipt", + ); + const observation: (typeof calls)[number] = { + operation, + state: "started", + parameters: values.length, + }; + calls.push(observation); + let result; + try { + result = await runtime.query(text, values); + observation.state = "committed"; + } catch (error) { + observation.state = (error as { code?: string }).code ?? "unclassified"; + throw error; + } + if (dropCommittedResponse && operation === "create") { + dropCommittedResponse = false; + observation.state = "committed_response_dropped"; + throw new Error("Synthetic response loss after actual SQL commit"); + } + if (alterReceipt) result.rows[0].receipt = alterReceipt(result.rows[0].receipt); + return result; + }, }; const dependencies: ProposedDependencies = { policy: { @@ -76,27 +90,11 @@ const dependencies: ProposedDependencies = { databaseHead: "f507a77696f20429f977df9885d6c8c11a5f304b", }, storage: { - create: (call: ProposedCreateCall) => - execute( - "create", - "SELECT application_registration_proposal.register_application($1::uuid,$2::uuid,$3::text,$4::text,$5::bigint,$6::jsonb) AS receipt", - [ - call.actor, - call.workspace, - call.environment, - call.key, - call.entitlementRevision, - JSON.stringify(call.registration), - ], - ), - read: (call: ProposedReadCall) => - execute( - "read", - "SELECT application_registration_proposal.read_registration($1::uuid,$2::uuid,$3::uuid,$4::text,$5::uuid) AS receipt", - [call.actor, call.workspace, call.application, call.environment, call.receipt], - ), + create: call => insertProposedApplicationRegistration(observedClient, call), + read: call => selectProposedApplicationRegistration(observedClient, call), }, }; + const input = { idempotency_key: "composition-create", expected_entitlement_revision: 1, @@ -145,8 +143,16 @@ const registrationState = async () => { beforeAll(async () => { await sql.connect(); - await fixtureQuery(`CREATE FUNCTION pg_temp.qualification_failure(code text) RETURNS jsonb - LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'idempotency conflict' USING ERRCODE=code; END $$`); + await runtime.connect(); + await runtime.query("SET ROLE qualification_registration_runtime"); + setupQueries++; + const identity = await runtime.query("SELECT session_user, current_user"); + setupQueries++; + runtimeIdentity = identity.rows[0]; + expect(runtimeIdentity).toEqual({ + session_user: "qualification_registration_client", + current_user: "qualification_registration_runtime", + }); const metadata = await fixtureQuery( "SELECT current_setting('server_version') AS version,current_setting('server_encoding') AS encoding", ); @@ -159,7 +165,8 @@ beforeAll(async () => { }); beforeEach(async () => { dropCommittedResponse = false; - injectedFailure = undefined; + alterReceipt = undefined; + vi.stubEnv("OAUTH_ENABLED", "false"); await fixtureQuery("TRUNCATE application_registration_proposal.personal_principals CASCADE"); await fixtureQuery( "INSERT INTO application_registration_proposal.personal_principals(account_id) VALUES($1::uuid),($2::uuid)", @@ -170,14 +177,27 @@ beforeEach(async () => { ); }); afterAll(async () => { + await runtime.end(); await sql.end(); console.log( "COMPOSITION_RECEIPT " + - JSON.stringify({ server, storageCalls: calls, fixtureQueries, activation: false }), + JSON.stringify({ + server, + runtimeIdentity, + storageCalls: calls, + fixtureQueries, + setupQueries, + activation: false, + }), ); }); -describe("actual domain to exact disposable SQL proposal", () => { +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +describe("actual domain and helpers to restricted disposable SQL wrappers", () => { it("creates disabled canonical rows and returns the unchanged SQL receipt", async () => { const receipt = await register(); const stored = await fixtureQuery( @@ -327,35 +347,6 @@ describe("actual domain to exact disposable SQL proposal", () => { expect(calls.at(-1)?.state).toBe("P2101"); expect(await registrationState()).toEqual(saved); }); - it.each(["P0001", "P2102", "transport"] as const)( - "keeps independent %s failure unknown despite misleading conflict text", - async failure => { - const original = await register(); - const saved = await registrationState(); - injectedFailure = failure; - await expect(register()).rejects.toMatchObject({ kind: "outcome_unknown" }); - expect(calls.at(-1)?.state).toBe(failure === "transport" ? "unclassified" : failure); - expect(await registrationState()).toEqual(saved); - injectedFailure = undefined; - expect(await register()).toEqual(original); - expect(await registrationState()).toEqual(saved); - }, - ); - it("does not classify a read P2101 as a create conflict", async () => { - const original = await register(); - await grantRead(original.application_id); - const saved = await registrationState(); - injectedFailure = "P2101"; - await expect( - oneStorage(() => read(request(), select(original), dependencies)), - ).rejects.toMatchObject({ kind: "outcome_unknown" }); - expect(calls.at(-1)?.state).toBe("P2101"); - expect(await registrationState()).toEqual(saved); - injectedFailure = undefined; - expect(await oneStorage(() => read(request(), select(original), dependencies))).toEqual( - original, - ); - }); it("rechecks SQL authority before replay and read, and fresh auth before storage", async () => { const receipt = await register(); await grantRead(receipt.application_id); @@ -385,6 +376,108 @@ describe("actual domain to exact disposable SQL proposal", () => { ); expect(calls).toHaveLength(before); }); + it("runtime cannot bypass wrappers or modify tables or create TEMP objects", async () => { + for (const statement of [ + "SELECT application_registration_proposal.read_registration(NULL,NULL,NULL,NULL,NULL)", + "UPDATE application_registration_proposal.applications SET name='forbidden'", + "CREATE TEMP TABLE forbidden_temp(id int)", + ]) { + setupQueries++; + await expect(runtime.query(statement)).rejects.toMatchObject({ code: "42501" }); + } + }); + it.each([ + "actor", + "workspace_id", + "billing_owner_id", + "access_activated", + "snapshot", + "extra", + "receipt_id", + ])("actual helpers preserve domain rejection of a tampered %s receipt", async field => { + const original = await register(); + await grantRead(original.application_id); + const saved = await registrationState(); + alterReceipt = receipt => ({ + ...receipt, + [field]: field === "access_activated" ? true : field === "snapshot" ? {} : actorB, + }); + if (field !== "receipt_id") + await expect(register()).rejects.toMatchObject({ kind: "outcome_unknown" }); + await expect( + oneStorage(() => read(request(), select(original), dependencies)), + ).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(await registrationState()).toEqual(saved); + alterReceipt = undefined; + expect(await register()).toEqual(original); + }); + it("real MCP SDK create/read reaches the restricted SQL wrappers", async () => { + const client = new McpClient({ name: "synthetic-sql-composition", version: "1" }); + const transport = new StreamableHTTPClientTransport(new URL("https://fixture.invalid/mcp"), { + requestInit: { headers: { Authorization: `Bearer ${fixture.key}` } }, + fetch: async (url, init) => + handle(new NextRequest(url instanceof Request ? url : String(url), init), dependencies), + }); + try { + await client.connect(transport); + const created = await oneStorage(() => + client.callTool({ name: "create_application_registration", arguments: input }), + ); + expect(created.isError).not.toBe(true); + const original = ( + await fixtureQuery("SELECT result FROM application_registration_proposal.receipts") + ).rows[0].result; + expect(created.content).toEqual([{ type: "text", text: JSON.stringify(original) }]); + await grantRead(original.application_id); + const selected = await oneStorage(() => + client.callTool({ name: "read_application_registration", arguments: select(original) }), + ); + expect(selected.isError).not.toBe(true); + expect(selected.content).toEqual(created.content); + } finally { + await client.close(); + } + }); + it.each(["changed-actor", "terminated"])( + "real SDK dispatch %s stops before SQL", + async failure => { + const client = new McpClient({ name: "synthetic-sql-negative", version: "1" }); + const abort = new AbortController(); + const transport = new StreamableHTTPClientTransport(new URL("https://fixture.invalid/mcp"), { + requestInit: { headers: { Authorization: `Bearer ${fixture.key}` } }, + fetch: async (url, init) => + handle( + new NextRequest(url instanceof Request ? url : String(url), { + ...init, + signal: abort.signal, + }), + dependencies, + ), + }); + try { + await client.connect(transport); + const original = supabase.from.bind(supabase); + let seen = 0; + vi.spyOn(supabase, "from").mockImplementation(table => { + if (++seen === 2) { + if (failure === "changed-actor") fixture.actor = actorB; + else abort.abort(); + } + return original(table); + }); + const before = calls.length; + const result = await client + .callTool({ name: "create_application_registration", arguments: input }) + .catch(error => error); + expect(seen).toBeGreaterThanOrEqual(2); + if (failure === "changed-actor") expect(result.isError).toBe(true); + else expect(result).toBeInstanceOf(Error); + expect(calls).toHaveLength(before); + } finally { + await client.close(); + } + }, + ); it("denies native DNS, TCP, UDP and unrelated Unix sockets before access", async () => { expect( globalThis[Symbol.for("recoup.disposable.registration.originalSocketConnect")], diff --git a/scripts/application-registration-proposal/sql-composition/run.mjs b/scripts/application-registration-proposal/sql-composition/run.mjs index 4fbc87f9d..030921cfc 100644 --- a/scripts/application-registration-proposal/sql-composition/run.mjs +++ b/scripts/application-registration-proposal/sql-composition/run.mjs @@ -41,6 +41,7 @@ const bindings = JSON.parse(await readFile(join(here, "source-bindings.json"), " for (const [base, entries] of [ [root, bindings.apiInputs], [database, bindings.databaseInputs], + [database, bindings.executionProfileInputs], ]) { for (const [path, expected] of Object.entries(entries)) { const digest = createHash("sha256") @@ -56,8 +57,8 @@ const gitEnv = { GIT_CONFIG_GLOBAL: "/dev/null", }; // Bind tracked API source bytes, including transitive authentication imports. -// Only this reviewed eight-path qualification slice may differ from the accepted revision. -const apiRevision = bindings.acceptedApiComposition ?? bindings.apiMerge; +// Only this reviewed nine-path adapter/qualification slice may differ from the accepted revision. +const apiRevision = bindings.acceptedApiBaseline; if (!/^[0-9a-f]{40}$/.test(apiRevision)) throw new Error("Exact API revision required"); const gitRead = args => execFileSync("/usr/bin/git", ["-C", root, ...args], { @@ -70,17 +71,30 @@ if (gitRead(["rev-parse", "--verify", `${apiRevision}^{commit}`]).trim() !== api throw new Error("Bound API revision unavailable"); gitRead(["merge-base", "--is-ancestor", apiRevision, "HEAD"]); const allowedChanges = new Set([ - "vitest.config.ts", ...[ - "README.md", - "run.mjs", - "qualification.test.ts", - "source-bindings.json", - "supervise.py", - "socket-guard.mjs", - "vitest.config.ts", - ].map(name => `scripts/application-registration-proposal/sql-composition/${name}`), + "ProposedRegistrationSqlClient.ts", + "insertProposedApplicationRegistration.ts", + "selectProposedApplicationRegistration.ts", + "__tests__/registrationSql.test.ts", + ].map(name => `lib/supabase/application_registration_proposal/${name}`), + ...["README.md", "run.mjs", "qualification.test.ts", "source-bindings.json", "supervise.py"].map( + name => `scripts/application-registration-proposal/sql-composition/${name}`, + ), ]); +// Candidate changes are review inputs, but executed bytes must equal a recorded commit. +const candidate = gitRead(["rev-parse", "HEAD"]).trim(); +const candidateTree = gitRead(["rev-parse", "HEAD^{tree}"]).trim(); +for (const path of allowedChanges) { + const listing = gitRead(["ls-tree", "HEAD", "--", path]).trim(); + const match = /^(100644|100755) blob ([0-9a-f]{40})\t/.exec(listing); + const stat = await lstat(join(root, path)); + if (!match || !stat.isFile() || Boolean(stat.mode & 0o111) !== (match[1] === "100755")) + throw new Error(`Uncommitted candidate source/type: ${path}`); + const bytes = await readFile(join(root, path)); + const actual = createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex"); + if (actual !== match[2]) throw new Error(`Uncommitted candidate bytes: ${path}`); +} +console.log("ADAPTER_CANDIDATE " + JSON.stringify({ candidate, candidateTree })); const committedChanges = gitRead([ "diff-tree", "--no-commit-id", @@ -162,8 +176,35 @@ const databaseHead = execFileSync("/usr/bin/git", ["-C", database, "rev-parse", encoding: "utf8", timeout: 5000, }).trim(); -if (databaseHead !== bindings.databaseHead) +if (databaseHead !== bindings.executionProfileHead) throw new Error("Exact Database proposal head required"); +// Exact profile tree, unchanged D ancestor, and raw profile/D file modes and blobs. +const dbGit = args => + execFileSync("/usr/bin/git", ["-C", database, ...args], { + env: gitEnv, + encoding: "utf8", + timeout: 5000, + }); +if (dbGit(["rev-parse", "HEAD^{tree}"]).trim() !== bindings.executionProfileTree) + throw new Error("Execution profile tree mismatch"); +dbGit(["merge-base", "--is-ancestor", bindings.databaseHead, "HEAD"]); +for (const [revision, inputs] of [ + [bindings.databaseHead, bindings.databaseInputs], + [bindings.executionProfileHead, bindings.executionProfileInputs], +]) { + for (const path of Object.keys(inputs)) { + const listing = dbGit(["ls-tree", revision, "--", path]).trim(); + const match = /^(100644|100755) blob ([0-9a-f]{40})\t/.exec(listing); + const stat = await lstat(join(database, path)); + if (!match || !stat.isFile() || Boolean(stat.mode & 0o111) !== (match[1] === "100755")) + throw new Error(`Unbound database source/type: ${path}`); + const bytes = await readFile(join(database, path)); + if ( + createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex") !== match[2] + ) + throw new Error(`Unbound database bytes: ${path}`); + } +} console.log("Composition source bindings verified; no hosted target accepted"); const owned = await mkdtemp("/tmp/registration-composition-launch-"); await mkdir(join(owned, "home")); diff --git a/scripts/application-registration-proposal/sql-composition/source-bindings.json b/scripts/application-registration-proposal/sql-composition/source-bindings.json index 17dd526e2..605eb7b6d 100644 --- a/scripts/application-registration-proposal/sql-composition/source-bindings.json +++ b/scripts/application-registration-proposal/sql-composition/source-bindings.json @@ -36,7 +36,17 @@ "proposals/application-proof-2104/configuration.sql": "148819c1363929e990bf2cfd67bae02f7567c2e2e2a05732cb17ea2248bad3b1", "proposals/application-registration-2104/sources.json": "a617bc3acc14f1cc8af2dfa951eebff0da2e406a4299c5842427f1980560e744" }, - "qualification": "Disposable test-only composition; no production factory or hosted target", + "qualification": "Unwired fixed SQL adapter through exact disposable execution profile; no production factory or hosted target", "acceptedApiComposition": "0769bc1957fce38bd6b847d342eae904044ae821", - "originalApiCompatibility": "784bee20b3e0fe61e67ed156c7f3a39a08a441b2" + "originalApiCompatibility": "784bee20b3e0fe61e67ed156c7f3a39a08a441b2", + "acceptedApiBaseline": "ec284cba127d73d0c3e7e74deceabac5c6a145f1", + "executionProfileHead": "acea75c0e118b6ca12bb9a22470a8bd7b383f925", + "executionProfileTree": "a8c45f920144db21ae1d00a807184aae51065b82", + "executionProfileInputs": { + "proposals/application-registration-execution-2104/qualification-roles.sql": "a5e8916c8fc13776d05d045cb6846d06c5b3670a353dc7f8153cedffb529e8c1", + "proposals/application-registration-execution-2104/sources.json": "0934493a7742d7c3c64e3dbc00646138bcb74442a27be22bc6a9782e52247e46", + "proposals/application-registration-execution-2104/test_privileges.py": "da2965852d0d5ba3726f92ea596f9fbccfa84ef08432c49602fab742e5e30e2e", + "proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md": "036bc58deb8576ab40fbbb8d79e75c764a853c29ebca8c5d45825a4cc008e4b7", + "proposals/application-registration-execution-2104/execution.sql": "8ffc568bf01513d14297fd92a48716a7921e023cfacf3f3d124f943e6490a1d7" + } } diff --git a/scripts/application-registration-proposal/sql-composition/supervise.py b/scripts/application-registration-proposal/sql-composition/supervise.py index 2362384ac..ce215bd4a 100644 --- a/scripts/application-registration-proposal/sql-composition/supervise.py +++ b/scripts/application-registration-proposal/sql-composition/supervise.py @@ -19,7 +19,7 @@ def database_module(database): """Validate the pinned fixture sources before importing their lifecycle owner.""" bindings = json.loads((HERE / 'source-bindings.json').read_text()) - for relative, expected in bindings['databaseInputs'].items(): + for relative, expected in {**bindings['databaseInputs'], **bindings['executionProfileInputs']}.items(): if hashlib.sha256((database / relative).read_bytes()).hexdigest() != expected: raise RuntimeError('Database source binding mismatch: ' + relative) source = database / 'proposals/application-registration-2104/test_registration.py' @@ -34,6 +34,11 @@ def run_worker(database, node, fault=None): module = database_module(Path(database)) socket, pg_bin = module.prepare_worker_environment() module.Registration.setUpClass() + profile = Path(database) / 'proposals/application-registration-execution-2104' + # One controller connection: the marker is installation context, not authentication. + module.Registration.sql("SET qualification.registration_fixture='owned-disposable-only';" + + (profile/'qualification-roles.sql').read_text() + + (profile/'execution.sql').read_text()) root = Path(socket).parent scope = {'socket': socket, 'driver_pid': os.getpid(), 'supervisor_pid': os.getppid(), 'postmaster_pid': int((Path(socket)/'pg/postmaster.pid').read_text().splitlines()[0])} From a7423e3a4bbf5f5e453cedda17613e9ac1c69c40 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:47:21 -0500 Subject: [PATCH 2/6] Correct SDK assertions and verify recovery preserves all committed rows --- .../sql-composition/qualification.test.ts | 63 ++++++++++++------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/scripts/application-registration-proposal/sql-composition/qualification.test.ts b/scripts/application-registration-proposal/sql-composition/qualification.test.ts index ade9a8d86..b782214d8 100644 --- a/scripts/application-registration-proposal/sql-composition/qualification.test.ts +++ b/scripts/application-registration-proposal/sql-composition/qualification.test.ts @@ -297,8 +297,9 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = const original = ( await fixtureQuery("SELECT result FROM application_registration_proposal.receipts") ).rows[0].result; - expect(await register()).toEqual(original); const saved = await registrationState(); + expect(await register()).toEqual(original); + expect(await registrationState()).toEqual(saved); expect( ( await fixtureQuery( @@ -427,7 +428,10 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = const original = ( await fixtureQuery("SELECT result FROM application_registration_proposal.receipts") ).rows[0].result; - expect(created.content).toEqual([{ type: "text", text: JSON.stringify(original) }]); + expect(created.content).toHaveLength(1); + const content = created.content as Array<{ type: string; text: string }>; + expect(content[0].type).toBe("text"); + expect(JSON.parse(content[0].text)).toEqual(original); await grantRead(original.application_id); const selected = await oneStorage(() => client.callTool({ name: "read_application_registration", arguments: select(original) }), @@ -443,35 +447,52 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = async failure => { const client = new McpClient({ name: "synthetic-sql-negative", version: "1" }); const abort = new AbortController(); + let seen = 0; + let toolStatus: number | undefined; const transport = new StreamableHTTPClientTransport(new URL("https://fixture.invalid/mcp"), { requestInit: { headers: { Authorization: `Bearer ${fixture.key}` } }, - fetch: async (url, init) => - handle( - new NextRequest(url instanceof Request ? url : String(url), { - ...init, - signal: abort.signal, - }), - dependencies, - ), + fetch: async (url, init) => { + const toolCall = + typeof init?.body === "string" && JSON.parse(init.body).method === "tools/call"; + const original = supabase.from.bind(supabase); + const spy = toolCall + ? vi.spyOn(supabase, "from").mockImplementation(table => { + if (++seen === 2) { + if (failure === "changed-actor") fixture.actor = actorB; + else abort.abort(); + } + return original(table); + }) + : undefined; + try { + const response = await handle( + new NextRequest(url instanceof Request ? url : String(url), { + ...init, + signal: abort.signal, + }), + dependencies, + ); + if (toolCall) toolStatus = response.status; + return response; + } finally { + spy?.mockRestore(); + } + }, }); try { await client.connect(transport); - const original = supabase.from.bind(supabase); - let seen = 0; - vi.spyOn(supabase, "from").mockImplementation(table => { - if (++seen === 2) { - if (failure === "changed-actor") fixture.actor = actorB; - else abort.abort(); - } - return original(table); - }); const before = calls.length; const result = await client .callTool({ name: "create_application_registration", arguments: input }) .catch(error => error); expect(seen).toBeGreaterThanOrEqual(2); - if (failure === "changed-actor") expect(result.isError).toBe(true); - else expect(result).toBeInstanceOf(Error); + if (failure === "changed-actor") { + expect(toolStatus).toBe(200); + expect(result.isError).toBe(true); + } else { + expect(toolStatus).toBe(408); + expect(result).toBeInstanceOf(Error); + } expect(calls).toHaveLength(before); } finally { await client.close(); From 593f37a9e8e303a594af86fb4ce03bc209c9fe6f Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:46:27 -0500 Subject: [PATCH 3/6] Reject missing registration serialization and share source blob verification --- .../__tests__/registrationSql.test.ts | 7 +++++ .../insertProposedApplicationRegistration.ts | 4 ++- .../selectProposedApplicationRegistration.ts | 2 +- .../sql-composition/run.mjs | 28 +++++++------------ 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts index 820402f20..62633820e 100644 --- a/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts +++ b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts @@ -139,3 +139,10 @@ it("serialization failure is unknown before any query", async () => { await expect(create({ query }, call)).rejects.toMatchObject({ kind: "outcome_unknown" }); expect(query).not.toHaveBeenCalled(); }); +it("missing serialization is unknown before any query", async () => { + const call = structuredClone(createCall); + Object.defineProperty(call.registration, "toJSON", { value: () => undefined }); + const query = vi.fn(); + await expect(create({ query }, call)).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(query).not.toHaveBeenCalled(); +}); diff --git a/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts index c0423c752..dcb31dae5 100644 --- a/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts +++ b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts @@ -12,13 +12,15 @@ export async function insertProposedApplicationRegistration( // Serialization/envelope failures are unknown, never SQL authorization outcomes. let values: unknown[]; try { + const registration = JSON.stringify(call.registration); + if (typeof registration !== "string") throw new Error(); values = [ call.actor, call.workspace, call.environment, call.key, call.entitlementRevision, - JSON.stringify(call.registration), + registration, ]; } catch { throw new ProposedStorageFailure("outcome_unknown"); diff --git a/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts index ee1122c59..b2c9a9c59 100644 --- a/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts +++ b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts @@ -9,7 +9,7 @@ export async function selectProposedApplicationRegistration( client: ProposedRegistrationSqlClient, call: ProposedReadCall, ): Promise { - // Serialization/envelope failures are unknown, never SQL authorization outcomes. + // Input-access/envelope failures are unknown, never SQL authorization outcomes. let values: unknown[]; try { values = [call.actor, call.workspace, call.application, call.environment, call.receipt]; diff --git a/scripts/application-registration-proposal/sql-composition/run.mjs b/scripts/application-registration-proposal/sql-composition/run.mjs index 030921cfc..b8a8e7793 100644 --- a/scripts/application-registration-proposal/sql-composition/run.mjs +++ b/scripts/application-registration-proposal/sql-composition/run.mjs @@ -84,16 +84,18 @@ const allowedChanges = new Set([ // Candidate changes are review inputs, but executed bytes must equal a recorded commit. const candidate = gitRead(["rev-parse", "HEAD"]).trim(); const candidateTree = gitRead(["rev-parse", "HEAD^{tree}"]).trim(); -for (const path of allowedChanges) { - const listing = gitRead(["ls-tree", "HEAD", "--", path]).trim(); +async function verifyBlob(readGit, revision, base, path, label) { + const listing = readGit(["ls-tree", revision, "--", path]).trim(); const match = /^(100644|100755) blob ([0-9a-f]{40})\t/.exec(listing); - const stat = await lstat(join(root, path)); + const stat = await lstat(join(base, path)); if (!match || !stat.isFile() || Boolean(stat.mode & 0o111) !== (match[1] === "100755")) - throw new Error(`Uncommitted candidate source/type: ${path}`); - const bytes = await readFile(join(root, path)); + throw new Error(`${label} source/type: ${path}`); + const bytes = await readFile(join(base, path)); const actual = createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex"); - if (actual !== match[2]) throw new Error(`Uncommitted candidate bytes: ${path}`); + if (actual !== match[2]) throw new Error(`${label} bytes: ${path}`); } +for (const path of allowedChanges) + await verifyBlob(gitRead, "HEAD", root, path, "Uncommitted candidate"); console.log("ADAPTER_CANDIDATE " + JSON.stringify({ candidate, candidateTree })); const committedChanges = gitRead([ "diff-tree", @@ -192,18 +194,8 @@ for (const [revision, inputs] of [ [bindings.databaseHead, bindings.databaseInputs], [bindings.executionProfileHead, bindings.executionProfileInputs], ]) { - for (const path of Object.keys(inputs)) { - const listing = dbGit(["ls-tree", revision, "--", path]).trim(); - const match = /^(100644|100755) blob ([0-9a-f]{40})\t/.exec(listing); - const stat = await lstat(join(database, path)); - if (!match || !stat.isFile() || Boolean(stat.mode & 0o111) !== (match[1] === "100755")) - throw new Error(`Unbound database source/type: ${path}`); - const bytes = await readFile(join(database, path)); - if ( - createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex") !== match[2] - ) - throw new Error(`Unbound database bytes: ${path}`); - } + for (const path of Object.keys(inputs)) + await verifyBlob(dbGit, revision, database, path, "Unbound database"); } console.log("Composition source bindings verified; no hosted target accepted"); const owned = await mkdtemp("/tmp/registration-composition-launch-"); From 86cc8900401ab6684b155b6efe5ac8c4e1de916e Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:00:24 -0500 Subject: [PATCH 4/6] Share registration SQL binding failure and receipt helpers --- .../__tests__/registrationSql.test.ts | 29 ++++++++++++ .../getProposedCreateSqlValues.ts | 21 +++++++++ .../getProposedReadSqlValues.ts | 12 +++++ .../getProposedSqlFailure.ts | 13 ++++++ .../getProposedSqlReceipt.ts | 14 ++++++ .../insertProposedApplicationRegistration.ts | 45 ++++--------------- .../selectProposedApplicationRegistration.ts | 36 ++++----------- .../sql-composition/README.md | 8 ++-- .../sql-composition/run.mjs | 10 ++++- .../sql-composition/source-bindings.json | 17 ++++++- 10 files changed, 135 insertions(+), 70 deletions(-) create mode 100644 lib/supabase/application_registration_proposal/getProposedCreateSqlValues.ts create mode 100644 lib/supabase/application_registration_proposal/getProposedReadSqlValues.ts create mode 100644 lib/supabase/application_registration_proposal/getProposedSqlFailure.ts create mode 100644 lib/supabase/application_registration_proposal/getProposedSqlReceipt.ts diff --git a/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts index 62633820e..d1209a57e 100644 --- a/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts +++ b/lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts @@ -112,6 +112,16 @@ describe.each(cases)("$operation fixed proposal query", ({ operation, invoke, sq expect(error).not.toBe(raw); expect(query).toHaveBeenCalledTimes(1); }); + it("envelope access failure stays unknown even with a denial code", async () => { + const result = Object.defineProperty({}, "rows", { + get() { + throw { code: "42501" }; + }, + }); + const query = vi.fn().mockResolvedValue(result); + await expect(invoke({ query })).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(query).toHaveBeenCalledTimes(1); + }); it.each([ undefined, null, @@ -146,3 +156,22 @@ it("missing serialization is unknown before any query", async () => { await expect(create({ query }, call)).rejects.toMatchObject({ kind: "outcome_unknown" }); expect(query).not.toHaveBeenCalled(); }); + +it.each(["create", "read"])( + "%s input access fails before querying and cannot claim SQL denial", + async operation => { + const query = vi.fn(); + const input = structuredClone(operation === "create" ? createCall : readCall); + Object.defineProperty(input, "actor", { + get() { + throw { code: "42501" }; + }, + }); + const result = + operation === "create" + ? create({ query }, input as ProposedCreateCall) + : read({ query }, input as ProposedReadCall); + await expect(result).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(query).not.toHaveBeenCalled(); + }, +); diff --git a/lib/supabase/application_registration_proposal/getProposedCreateSqlValues.ts b/lib/supabase/application_registration_proposal/getProposedCreateSqlValues.ts new file mode 100644 index 000000000..d4f4aacab --- /dev/null +++ b/lib/supabase/application_registration_proposal/getProposedCreateSqlValues.ts @@ -0,0 +1,21 @@ +import { + ProposedStorageFailure, + type ProposedCreateCall, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +/** Serialize the canonical create call before entering SQL. */ +export function getProposedCreateSqlValues(call: ProposedCreateCall): unknown[] { + try { + const registration = JSON.stringify(call.registration); + if (typeof registration !== "string") throw new Error(); + return [ + call.actor, + call.workspace, + call.environment, + call.key, + call.entitlementRevision, + registration, + ]; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } +} diff --git a/lib/supabase/application_registration_proposal/getProposedReadSqlValues.ts b/lib/supabase/application_registration_proposal/getProposedReadSqlValues.ts new file mode 100644 index 000000000..bade0d6f8 --- /dev/null +++ b/lib/supabase/application_registration_proposal/getProposedReadSqlValues.ts @@ -0,0 +1,12 @@ +import { + ProposedStorageFailure, + type ProposedReadCall, +} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +/** Bind a domain-owned selection; input-access failures are not SQL denials. */ +export function getProposedReadSqlValues(call: ProposedReadCall): unknown[] { + try { + return [call.actor, call.workspace, call.application, call.environment, call.receipt]; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } +} diff --git a/lib/supabase/application_registration_proposal/getProposedSqlFailure.ts b/lib/supabase/application_registration_proposal/getProposedSqlFailure.ts new file mode 100644 index 000000000..aecd716d5 --- /dev/null +++ b/lib/supabase/application_registration_proposal/getProposedSqlFailure.ts @@ -0,0 +1,13 @@ +import { ProposedStorageFailure } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +/** Classify query failures only, without retaining raw errors or trusting their kind. */ +export function getProposedSqlFailure(error: unknown, operation: "create" | "read") { + let code: unknown; + try { + if (typeof error === "object" && error !== null && "code" in error) code = error.code; + } catch { + // A malformed error is not a SQLSTATE. + } + if (code === "42501") return new ProposedStorageFailure("denied"); + if (operation === "create" && code === "P2101") return new ProposedStorageFailure("conflict"); + return new ProposedStorageFailure("outcome_unknown"); +} diff --git a/lib/supabase/application_registration_proposal/getProposedSqlReceipt.ts b/lib/supabase/application_registration_proposal/getProposedSqlReceipt.ts new file mode 100644 index 000000000..67b8690e1 --- /dev/null +++ b/lib/supabase/application_registration_proposal/getProposedSqlReceipt.ts @@ -0,0 +1,14 @@ +import { ProposedStorageFailure } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +/** Unwrap one receipt unchanged; strict receipt validation belongs to the domain. */ +export function getProposedSqlReceipt(result: unknown): unknown { + try { + if (typeof result !== "object" || result === null || !("rows" in result)) throw new Error(); + const rows = result.rows; + if (!Array.isArray(rows) || rows.length !== 1) throw new Error(); + const receipt = rows[0]?.receipt; + if (receipt == null) throw new Error(); + return receipt; + } catch { + throw new ProposedStorageFailure("outcome_unknown"); + } +} diff --git a/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts index dcb31dae5..e23f81e60 100644 --- a/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts +++ b/lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts @@ -1,30 +1,15 @@ -import { - ProposedStorageFailure, - type ProposedCreateCall, -} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import type { ProposedCreateCall } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; import type { ProposedRegistrationSqlClient } from "./ProposedRegistrationSqlClient"; +import { getProposedCreateSqlValues } from "./getProposedCreateSqlValues"; +import { getProposedSqlFailure } from "./getProposedSqlFailure"; +import { getProposedSqlReceipt } from "./getProposedSqlReceipt"; -/** Unwired proposal-only single call. The domain owns authentication and receipt validation. */ +/** Unwired single call; the domain owns authentication and strict receipt validation. */ export async function insertProposedApplicationRegistration( client: ProposedRegistrationSqlClient, call: ProposedCreateCall, ): Promise { - // Serialization/envelope failures are unknown, never SQL authorization outcomes. - let values: unknown[]; - try { - const registration = JSON.stringify(call.registration); - if (typeof registration !== "string") throw new Error(); - values = [ - call.actor, - call.workspace, - call.environment, - call.key, - call.entitlementRevision, - registration, - ]; - } catch { - throw new ProposedStorageFailure("outcome_unknown"); - } + const values = getProposedCreateSqlValues(call); let result; try { result = await client.query( @@ -32,21 +17,7 @@ export async function insertProposedApplicationRegistration( values, ); } catch (error) { - let code: unknown; - try { - if (typeof error === "object" && error !== null && "code" in error) code = error.code; - } catch { - /* A malformed error is not a SQLSTATE. */ - } - if (code === "42501") throw new ProposedStorageFailure("denied"); - if (code === "P2101") throw new ProposedStorageFailure("conflict"); - throw new ProposedStorageFailure("outcome_unknown"); - } - try { - if (!Array.isArray(result.rows) || result.rows.length !== 1 || result.rows[0]?.receipt == null) - throw new Error(); - return result.rows[0].receipt; - } catch { - throw new ProposedStorageFailure("outcome_unknown"); + throw getProposedSqlFailure(error, "create"); } + return getProposedSqlReceipt(result); } diff --git a/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts index b2c9a9c59..21ca2ff5e 100644 --- a/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts +++ b/lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts @@ -1,21 +1,15 @@ -import { - ProposedStorageFailure, - type ProposedReadCall, -} from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; +import type { ProposedReadCall } from "@/lib/applications/proposedRegistration/proposedRegistrationContract"; import type { ProposedRegistrationSqlClient } from "./ProposedRegistrationSqlClient"; +import { getProposedReadSqlValues } from "./getProposedReadSqlValues"; +import { getProposedSqlFailure } from "./getProposedSqlFailure"; +import { getProposedSqlReceipt } from "./getProposedSqlReceipt"; -/** Unwired proposal-only single call. The domain owns authentication and receipt validation. */ +/** Unwired single call; the domain owns authentication and strict receipt validation. */ export async function selectProposedApplicationRegistration( client: ProposedRegistrationSqlClient, call: ProposedReadCall, ): Promise { - // Input-access/envelope failures are unknown, never SQL authorization outcomes. - let values: unknown[]; - try { - values = [call.actor, call.workspace, call.application, call.environment, call.receipt]; - } catch { - throw new ProposedStorageFailure("outcome_unknown"); - } + const values = getProposedReadSqlValues(call); let result; try { result = await client.query( @@ -23,21 +17,7 @@ export async function selectProposedApplicationRegistration( values, ); } catch (error) { - let code: unknown; - try { - if (typeof error === "object" && error !== null && "code" in error) code = error.code; - } catch { - /* A malformed error is not a SQLSTATE. */ - } - if (code === "42501") throw new ProposedStorageFailure("denied"); - - throw new ProposedStorageFailure("outcome_unknown"); - } - try { - if (!Array.isArray(result.rows) || result.rows.length !== 1 || result.rows[0]?.receipt == null) - throw new Error(); - return result.rows[0].receipt; - } catch { - throw new ProposedStorageFailure("outcome_unknown"); + throw getProposedSqlFailure(error, "read"); } + return getProposedSqlReceipt(result); } diff --git a/scripts/application-registration-proposal/sql-composition/README.md b/scripts/application-registration-proposal/sql-composition/README.md index 3445a5420..bada244a4 100644 --- a/scripts/application-registration-proposal/sql-composition/README.md +++ b/scripts/application-registration-proposal/sql-composition/README.md @@ -25,11 +25,11 @@ The successor local PostgreSQL 15.10/17.7 qualification uses Node 24.18.0. Earli Optional `--fault signal`, `--fault timeout`, or `--fault worker-exit` controls initialize a real guarded Node descendant, then deliberately interrupt the supervisor, time out its worker, or exit its worker while the child remains alive. Each retains an expected nonzero exit, but the launcher reports `COMPOSITION_FAULT_RESULT.passed=true` only after validating the expected exit, initialized Node lineage and both worker/cluster cleanup receipts. A nonzero exit alone is not a passing fault control. These are lifecycle controls, not functional SQL passes. -The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this nine-path adapter/qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same nine paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. +The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this thirteen-path adapter/qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same thirteen paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. Qualification targets PostgreSQL 15 and 17. This suite is distinct from the 130-case controlled adapter/MCP suite and ordinary Unit CI. It requires the explicitly pinned Database checkout and is not evidence of a hosted RPC, least-privilege deployment, live enrollment or public App 2104 availability. Personal policy, production authority provisioning, retention, deployed MCP nonprovisioning/original-actor handoff and client acceptance remain separate. Database 138 remains draft/unmerged/unapplied. -The nine candidate paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. +The thirteen candidate paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. The outer watchdog reports cleanup as unconfirmed if the supervisor cannot finish its bounded cleanup. It preserves the recorded lease for inspection; it does not claim that killing the supervisor or its group would remove separately sessioned workers and PostgreSQL. The focused fault controls do not exercise that outer watchdog. @@ -72,7 +72,7 @@ receipt before domain validation; they are not claims of SQL corruption. Real MC uses the same helpers; changed actor and termination before storage must yield zero operation queries. Auth leaves are controlled synthetic fixtures, not live credential verification. -The nine permitted candidate paths are the client interface, two helpers, unit test and existing +The thirteen permitted candidate paths are the client interface, two operation helpers, four shared helpers, unit test and existing README, qualification.test.ts, run.mjs, supervise.py and source-bindings.json in this directory. The launcher requires their raw bytes/types to match its recorded candidate commit/tree. Other API source stays bound to ec284, with D and all five profile files pinned separately to exact @@ -82,3 +82,5 @@ required. Record actual Node versions; Node24 evidence is not a Node22 qualifica Sites owns Database139. Production policy, role adoption, enrollment, credentials, retention, activation and deployment remain separate. A local source pass is not a release. + +The four shared helpers own create/read value binding, defensive SQLSTATE mapping and receipt-envelope unwrapping, with one named export per file. Only query errors enter SQLSTATE mapping; serialization/input-access and envelope failures remain unknown. The manifest lists all thirteen exact paths, checked against the launcher allowlist, and their physical bytes/types must match the recorded candidate Git blobs. This scope expansion addresses the current CodeRabbit pre-merge duplication warning; its earlier skipped-review comment is not the final review result. diff --git a/scripts/application-registration-proposal/sql-composition/run.mjs b/scripts/application-registration-proposal/sql-composition/run.mjs index b8a8e7793..1e253f1a7 100644 --- a/scripts/application-registration-proposal/sql-composition/run.mjs +++ b/scripts/application-registration-proposal/sql-composition/run.mjs @@ -57,7 +57,7 @@ const gitEnv = { GIT_CONFIG_GLOBAL: "/dev/null", }; // Bind tracked API source bytes, including transitive authentication imports. -// Only this reviewed nine-path adapter/qualification slice may differ from the accepted revision. +// Only this reviewed thirteen-path adapter/qualification slice may differ from the accepted revision. const apiRevision = bindings.acceptedApiBaseline; if (!/^[0-9a-f]{40}$/.test(apiRevision)) throw new Error("Exact API revision required"); const gitRead = args => @@ -73,6 +73,10 @@ gitRead(["merge-base", "--is-ancestor", apiRevision, "HEAD"]); const allowedChanges = new Set([ ...[ "ProposedRegistrationSqlClient.ts", + "getProposedCreateSqlValues.ts", + "getProposedReadSqlValues.ts", + "getProposedSqlFailure.ts", + "getProposedSqlReceipt.ts", "insertProposedApplicationRegistration.ts", "selectProposedApplicationRegistration.ts", "__tests__/registrationSql.test.ts", @@ -81,6 +85,10 @@ const allowedChanges = new Set([ name => `scripts/application-registration-proposal/sql-composition/${name}`, ), ]); +if ( + JSON.stringify([...allowedChanges].sort()) !== JSON.stringify([...bindings.candidatePaths].sort()) +) + throw new Error("Exact candidate path manifest mismatch"); // Candidate changes are review inputs, but executed bytes must equal a recorded commit. const candidate = gitRead(["rev-parse", "HEAD"]).trim(); const candidateTree = gitRead(["rev-parse", "HEAD^{tree}"]).trim(); diff --git a/scripts/application-registration-proposal/sql-composition/source-bindings.json b/scripts/application-registration-proposal/sql-composition/source-bindings.json index 605eb7b6d..57498fc2a 100644 --- a/scripts/application-registration-proposal/sql-composition/source-bindings.json +++ b/scripts/application-registration-proposal/sql-composition/source-bindings.json @@ -48,5 +48,20 @@ "proposals/application-registration-execution-2104/test_privileges.py": "da2965852d0d5ba3726f92ea596f9fbccfa84ef08432c49602fab742e5e30e2e", "proposals/application-registration-execution-2104/EXECUTION-CONTRACT.md": "036bc58deb8576ab40fbbb8d79e75c764a853c29ebca8c5d45825a4cc008e4b7", "proposals/application-registration-execution-2104/execution.sql": "8ffc568bf01513d14297fd92a48716a7921e023cfacf3f3d124f943e6490a1d7" - } + }, + "candidatePaths": [ + "lib/supabase/application_registration_proposal/ProposedRegistrationSqlClient.ts", + "lib/supabase/application_registration_proposal/getProposedCreateSqlValues.ts", + "lib/supabase/application_registration_proposal/getProposedReadSqlValues.ts", + "lib/supabase/application_registration_proposal/getProposedSqlFailure.ts", + "lib/supabase/application_registration_proposal/getProposedSqlReceipt.ts", + "lib/supabase/application_registration_proposal/insertProposedApplicationRegistration.ts", + "lib/supabase/application_registration_proposal/selectProposedApplicationRegistration.ts", + "lib/supabase/application_registration_proposal/__tests__/registrationSql.test.ts", + "scripts/application-registration-proposal/sql-composition/README.md", + "scripts/application-registration-proposal/sql-composition/run.mjs", + "scripts/application-registration-proposal/sql-composition/qualification.test.ts", + "scripts/application-registration-proposal/sql-composition/source-bindings.json", + "scripts/application-registration-proposal/sql-composition/supervise.py" + ] } From adb8c1ef7888af9a332b9aa78ce1f5c11173eff1 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:15:29 -0500 Subject: [PATCH 5/6] Reject invalid Unicode in proposal registration inputs before storage --- .../__tests__/operations.test.ts | 51 ++++++++++++++++ .../isProposedRegistrationText.ts | 4 ++ .../proposedRegistrationContract.ts | 17 +++++- .../source-bindings.json | 4 +- .../sql-composition/README.md | 15 +++-- .../sql-composition/qualification.test.ts | 58 +++++++++++++++++++ .../sql-composition/run.mjs | 7 ++- .../sql-composition/source-bindings.json | 11 +++- 8 files changed, 155 insertions(+), 12 deletions(-) create mode 100644 lib/applications/proposedRegistration/isProposedRegistrationText.ts diff --git a/lib/applications/proposedRegistration/__tests__/operations.test.ts b/lib/applications/proposedRegistration/__tests__/operations.test.ts index 394cd9421..7b668cbf2 100644 --- a/lib/applications/proposedRegistration/__tests__/operations.test.ts +++ b/lib/applications/proposedRegistration/__tests__/operations.test.ts @@ -8,6 +8,7 @@ import { assertProposedRegistrationReceipt } from "../assertProposedRegistration import { projectProposedRegistration } from "../projectProposedRegistration"; import { ProposedStorageFailure, + proposedCreateInputSchema, type ProposedDependencies, type ProposedCreateCall, } from "../proposedRegistrationContract"; @@ -403,3 +404,53 @@ describe("strict receipt acceptance", () => { } }); }); + +const invalidText = [ + String.fromCharCode(0), + String.fromCharCode(0xd800), + String.fromCharCode(0xdc00), +]; +describe("proposal-local PostgreSQL text boundary", () => { + it.each( + invalidText.flatMap(character => [ + { field: "key", character }, + { field: "name", character }, + ]), + )("rejects actual invalid code units in $field before storage", async ({ field, character }) => { + expect([0, 0xd800, 0xdc00]).toContain(character.charCodeAt(0)); + const value = + field === "key" + ? { ...input, idempotency_key: `req-${character}` } + : { ...input, registration: { ...input.registration, name: `Name${character}` } }; + expect(proposedCreateInputSchema.safeParse(value).success).toBe(false); + const deps = dependencies(); + await expect(create(request(), value, deps)).rejects.toMatchObject({ name: "ZodError" }); + expect(deps.storage.create).not.toHaveBeenCalled(); + expect(deps.storage.read).not.toHaveBeenCalled(); + }); + it.each([String.fromCharCode(0xd83d, 0xde80), String.fromCharCode(0xfffd), "Música 音楽"])( + "preserves valid Unicode and existing name trimming", + async text => { + const key = ` key-${text} `; + const value = { + ...input, + idempotency_key: key, + registration: { ...input.registration, name: ` Name${text} ` }, + }; + const parsed = proposedCreateInputSchema.parse(value); + expect(parsed.idempotency_key).toBe(key); + expect(parsed.registration.name).toBe(`Name${text}`); + expect(Buffer.from(parsed.idempotency_key)).toEqual(Buffer.from(key)); + const deps = dependencies(); + const receipt = structuredClone(golden.createReceipt); + receipt.snapshot.name = `Name${text}`; + deps.storage.create.mockResolvedValue(receipt); + expect(await create(request(), value, deps)).toEqual(receipt); + expect(deps.storage.create).toHaveBeenCalledExactlyOnceWith({ + ...golden.input, + key, + registration: { ...golden.input.registration, name: `Name${text}` }, + }); + }, + ); +}); diff --git a/lib/applications/proposedRegistration/isProposedRegistrationText.ts b/lib/applications/proposedRegistration/isProposedRegistrationText.ts new file mode 100644 index 000000000..59e820ce5 --- /dev/null +++ b/lib/applications/proposedRegistration/isProposedRegistrationText.ts @@ -0,0 +1,4 @@ +/** PostgreSQL text requires NUL-free Unicode scalar values, without normalization. */ +export function isProposedRegistrationText(value: string): boolean { + return !/[\u0000\uD800-\uDFFF]/u.test(value); +} diff --git a/lib/applications/proposedRegistration/proposedRegistrationContract.ts b/lib/applications/proposedRegistration/proposedRegistrationContract.ts index 9633f4895..6b3141c3d 100644 --- a/lib/applications/proposedRegistration/proposedRegistrationContract.ts +++ b/lib/applications/proposedRegistration/proposedRegistrationContract.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { applicationRegistrationSchema } from "../applicationRegistrationSchema"; +import { isProposedRegistrationText } from "./isProposedRegistrationText"; export const proposedPolicySchema = z .object({ status: z.literal("proposed_unadopted"), @@ -11,9 +12,21 @@ const revision = z.number().int().min(1).max(Number.MAX_SAFE_INTEGER); const environment = z.enum(["production", "development"]); export const proposedCreateInputSchema = z .object({ - idempotency_key: z.string().min(1).max(128), + idempotency_key: z + .string() + .min(1) + .max(128) + .refine(isProposedRegistrationText, "Key must contain valid Unicode without NUL"), expected_entitlement_revision: revision, - registration: applicationRegistrationSchema.omit({ organization_id: true }).strict(), + registration: applicationRegistrationSchema + .omit({ organization_id: true }) + .extend({ + name: applicationRegistrationSchema.shape.name.refine( + isProposedRegistrationText, + "Name must contain valid Unicode without NUL", + ), + }) + .strict(), }) .strict(); export const proposedReadInputSchema = z diff --git a/scripts/application-registration-proposal/source-bindings.json b/scripts/application-registration-proposal/source-bindings.json index 3be7d8479..6b92a2fcb 100644 --- a/scripts/application-registration-proposal/source-bindings.json +++ b/scripts/application-registration-proposal/source-bindings.json @@ -11,7 +11,9 @@ "tsconfig.json": "b32629dbc2af272f06db2eb3c5e6bd249183a72cec77481e624b0a4086c10d93", "lib/keys/getApiKeyDetails.ts": "68813ca17af04703ded1efc25d8c6864aaa1f7b9c297ddeadb44c6c10220c644", "lib/mcp/__tests__/verifyApiKeyExpiry.test.ts": "1b4b18f8147217734b9b1d89418a57ae23c968e6046109d072469b7735fdd1bc", - "vercel.json": "4b3dfd36dbd274213a3ccf2d6bfbfa9be1ba6be26ea71946828f535e1bbfbf8a" + "vercel.json": "4b3dfd36dbd274213a3ccf2d6bfbfa9be1ba6be26ea71946828f535e1bbfbf8a", + "lib/applications/proposedRegistration/proposedRegistrationContract.ts": "9e54808c597030c4fcc16e4cb80e6ec2898fc88b148ec7517513f2bc29224587", + "lib/applications/proposedRegistration/isProposedRegistrationText.ts": "6cec3b1f7e7441d7babda35729df77a088b53e0a59406b0b7990c2bb1a84a2cc" }, "databaseInputs": { "proposals/application-registration-2104/protocol-composition.py": "377791d3ef4a26103bd046609d4b8dbf8f63a3d475aa2c72faeba68b553aada5", diff --git a/scripts/application-registration-proposal/sql-composition/README.md b/scripts/application-registration-proposal/sql-composition/README.md index bada244a4..e1a729103 100644 --- a/scripts/application-registration-proposal/sql-composition/README.md +++ b/scripts/application-registration-proposal/sql-composition/README.md @@ -25,11 +25,11 @@ The successor local PostgreSQL 15.10/17.7 qualification uses Node 24.18.0. Earli Optional `--fault signal`, `--fault timeout`, or `--fault worker-exit` controls initialize a real guarded Node descendant, then deliberately interrupt the supervisor, time out its worker, or exit its worker while the child remains alive. Each retains an expected nonzero exit, but the launcher reports `COMPOSITION_FAULT_RESULT.passed=true` only after validating the expected exit, initialized Node lineage and both worker/cluster cleanup receipts. A nonzero exit alone is not a passing fault control. These are lifecycle controls, not functional SQL passes. -The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this thirteen-path adapter/qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same thirteen paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. +The launcher verifies pinned files, tracked API source against the accepted revision (allowing only this seventeen-path adapter/qualification slice), and the exact Database head. It compares actual file bytes and types against Git blobs without trusting index flags, stat caches or clean filters. Environment files are never opened, including the tracked example; dotenv loading remains disabled. The accepted revision must be an ancestor of HEAD, and cumulative committed changes must stay within the same seventeen paths. Unexpected tracked differences, nonignored untracked files, and ignored executable sources under the API/auth and qualification directories fail before the worker starts. It then imports the reviewed database supervisor. That owner creates a UTF8 cluster without TCP listeners, scrubs the environment, owns the worker process group and verifies worker/postmaster/socket absence before removal. Node imports network denial before auth code; direct TCP/UDP creation and inbound TCP listening are denied; the PostgreSQL connector accepts only the registered owned Unix socket. The raw connector remains module-private; the global cross-import handle can only reinstall the lease-checked guard. Native guard initialization is required in the runner and each Vitest worker before the shared authentication setup. Native DNS lookup/resolve/reverse and Resolver constructors are denied in callback and promise APIs. Vitest receives only a fixed synthetic localhost answer; this never invokes OS or DNS resolution. A Node 23.6.1 loader defect can retain socket stat state during cached module-path resolution. The guard validates the owned directory after each socket stat, preserving both checks and avoiding that stale state. Dotenv is disabled. No hosted DSN, ambient credentials or arbitrary external socket is accepted. Qualification targets PostgreSQL 15 and 17. This suite is distinct from the 130-case controlled adapter/MCP suite and ordinary Unit CI. It requires the explicitly pinned Database checkout and is not evidence of a hosted RPC, least-privilege deployment, live enrollment or public App 2104 availability. Personal policy, production authority provisioning, retention, deployed MCP nonprovisioning/original-actor handoff and client acceptance remain separate. Database 138 remains draft/unmerged/unapplied. -The thirteen candidate paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. +The seventeen candidate paths are the test code under review, not self-authenticating inputs. Record their exact commit and file hashes with each evidence packet; changing a guard, launcher or assertion invalidates earlier qualification evidence. Other tracked API inputs, including the freshly captured D golden receipt, are checked against the accepted Git tree. This SQL suite reads real SQL receipts and does not use that golden as its result oracle. The guard is an in-process test boundary, not an OS sandbox for hostile code. The outer watchdog reports cleanup as unconfirmed if the supervisor cannot finish its bounded cleanup. It preserves the recorded lease for inspection; it does not claim that killing the supervisor or its group would remove separately sessioned workers and PostgreSQL. The focused fault controls do not exercise that outer watchdog. @@ -72,8 +72,11 @@ receipt before domain validation; they are not claims of SQL corruption. Real MC uses the same helpers; changed actor and termination before storage must yield zero operation queries. Auth leaves are controlled synthetic fixtures, not live credential verification. -The thirteen permitted candidate paths are the client interface, two operation helpers, four shared helpers, unit test and existing -README, qualification.test.ts, run.mjs, supervise.py and source-bindings.json in this directory. +The candidate paths are listed exactly in source-bindings.json: eight files under +lib/supabase/application_registration_proposal/ (interface, six helpers and unit test), +three proposal-domain files (contract, text predicate and operations test), the parent +scripts/application-registration-proposal/source-bindings.json, and five files in this +directory (README.md, qualification.test.ts, run.mjs, supervise.py and source-bindings.json). The launcher requires their raw bytes/types to match its recorded candidate commit/tree. Other API source stays bound to ec284, with D and all five profile files pinned separately to exact commits and raw blobs/modes. Native preload/socket guard/config and D lifecycle are unchanged. @@ -83,4 +86,6 @@ required. Record actual Node versions; Node24 evidence is not a Node22 qualifica Sites owns Database139. Production policy, role adoption, enrollment, credentials, retention, activation and deployment remain separate. A local source pass is not a release. -The four shared helpers own create/read value binding, defensive SQLSTATE mapping and receipt-envelope unwrapping, with one named export per file. Only query errors enter SQLSTATE mapping; serialization/input-access and envelope failures remain unknown. The manifest lists all thirteen exact paths, checked against the launcher allowlist, and their physical bytes/types must match the recorded candidate Git blobs. This scope expansion addresses the current CodeRabbit pre-merge duplication warning; its earlier skipped-review comment is not the final review result. +The four shared helpers own create/read value binding, defensive SQLSTATE mapping and receipt-envelope unwrapping, with one named export per file. Only query errors enter SQLSTATE mapping; serialization/input-access and envelope failures remain unknown. The manifest lists all seventeen exact paths, checked against the launcher allowlist, and their physical bytes/types must match the recorded candidate Git blobs. This scope expansion addresses the current CodeRabbit pre-merge duplication warning; its earlier skipped-review comment is not the final review result. + +The proposed create schema rejects NUL and unpaired UTF16 surrogates in the key and name before storage. It preserves valid keys exactly, including whitespace, supplementary Unicode and literal U+FFFD; names retain the shared schema's existing trimming and length constraints. This refinement is proposal-local: the shared public applicationRegistrationSchema and its preflight consumers remain unchanged. The original domain and real MCP tool both use this refined contract. Actual-codepoint schema/domain/MCP regressions prove zero storage calls for invalid values; joined SQL verifies unchanged valid-key replay and distinct valid keys. diff --git a/scripts/application-registration-proposal/sql-composition/qualification.test.ts b/scripts/application-registration-proposal/sql-composition/qualification.test.ts index b782214d8..7d020f890 100644 --- a/scripts/application-registration-proposal/sql-composition/qualification.test.ts +++ b/scripts/application-registration-proposal/sql-composition/qualification.test.ts @@ -412,6 +412,48 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = alterReceipt = undefined; expect(await register()).toEqual(original); }); + it.each( + [0, 0xd800, 0xdc00].flatMap(code => [ + { field: "key", code }, + { field: "name", code }, + ]), + )("rejects invalid $field code unit $code before any SQL query", async ({ field, code }) => { + const character = String.fromCharCode(code); + expect(character.charCodeAt(0)).toBe(code); + const value = + field === "key" + ? { ...input, idempotency_key: `req-${character}` } + : { ...input, registration: { ...input.registration, name: `Name${character}` } }; + const before = calls.length; + await expect(create(request(), value, dependencies)).rejects.toMatchObject({ + name: "ZodError", + }); + expect(calls).toHaveLength(before); + }); + it("preserves valid Unicode keys and distinguishes replay from another valid key", async () => { + const pair = String.fromCharCode(0xd83d, 0xde80); + const replacement = String.fromCharCode(0xfffd); + expect(pair.codePointAt(0)).toBe(0x1f680); + expect(replacement.codePointAt(0)).toBe(0xfffd); + const firstInput = { + ...input, + idempotency_key: ` key-${pair} `, + registration: { ...input.registration, name: ` Name${pair}${replacement} ` }, + }; + const first = await register(firstInput); + expect(first.snapshot.name).toBe(`Name${pair}${replacement}`); + const saved = await registrationState(); + expect(await register(firstInput)).toEqual(first); + expect(await registrationState()).toEqual(saved); + const second = await register({ ...firstInput, idempotency_key: ` key-${replacement} ` }); + expect(second.application_id).not.toBe(first.application_id); + const keys = await fixtureQuery( + 'SELECT key FROM application_registration_proposal.requests ORDER BY key COLLATE "C"', + ); + expect(keys.rows.map(row => row.key).sort()).toEqual( + [firstInput.idempotency_key, ` key-${replacement} `].sort(), + ); + }); it("real MCP SDK create/read reaches the restricted SQL wrappers", async () => { const client = new McpClient({ name: "synthetic-sql-composition", version: "1" }); const transport = new StreamableHTTPClientTransport(new URL("https://fixture.invalid/mcp"), { @@ -421,6 +463,22 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = }); try { await client.connect(transport); + for (const code of [0, 0xd800, 0xdc00]) { + const character = String.fromCharCode(code); + expect(character.charCodeAt(0)).toBe(code); + for (const value of [ + { ...input, idempotency_key: `req-${character}` }, + { ...input, registration: { ...input.registration, name: `Name${character}` } }, + ]) { + const before = calls.length; + const rejected = await client.callTool({ + name: "create_application_registration", + arguments: value, + }); + expect(rejected.isError).toBe(true); + expect(calls).toHaveLength(before); + } + } const created = await oneStorage(() => client.callTool({ name: "create_application_registration", arguments: input }), ); diff --git a/scripts/application-registration-proposal/sql-composition/run.mjs b/scripts/application-registration-proposal/sql-composition/run.mjs index 1e253f1a7..c18cd9ec1 100644 --- a/scripts/application-registration-proposal/sql-composition/run.mjs +++ b/scripts/application-registration-proposal/sql-composition/run.mjs @@ -57,7 +57,7 @@ const gitEnv = { GIT_CONFIG_GLOBAL: "/dev/null", }; // Bind tracked API source bytes, including transitive authentication imports. -// Only this reviewed thirteen-path adapter/qualification slice may differ from the accepted revision. +// Only this reviewed seventeen-path adapter/qualification slice may differ from the accepted revision. const apiRevision = bindings.acceptedApiBaseline; if (!/^[0-9a-f]{40}$/.test(apiRevision)) throw new Error("Exact API revision required"); const gitRead = args => @@ -71,6 +71,11 @@ if (gitRead(["rev-parse", "--verify", `${apiRevision}^{commit}`]).trim() !== api throw new Error("Bound API revision unavailable"); gitRead(["merge-base", "--is-ancestor", apiRevision, "HEAD"]); const allowedChanges = new Set([ + "lib/applications/proposedRegistration/isProposedRegistrationText.ts", + "lib/applications/proposedRegistration/proposedRegistrationContract.ts", + "lib/applications/proposedRegistration/__tests__/operations.test.ts", + "scripts/application-registration-proposal/source-bindings.json", + ...[ "ProposedRegistrationSqlClient.ts", "getProposedCreateSqlValues.ts", diff --git a/scripts/application-registration-proposal/sql-composition/source-bindings.json b/scripts/application-registration-proposal/sql-composition/source-bindings.json index 57498fc2a..9dd69f624 100644 --- a/scripts/application-registration-proposal/sql-composition/source-bindings.json +++ b/scripts/application-registration-proposal/sql-composition/source-bindings.json @@ -13,13 +13,14 @@ "vercel.json": "4b3dfd36dbd274213a3ccf2d6bfbfa9be1ba6be26ea71946828f535e1bbfbf8a", "lib/applications/proposedRegistration/readProposedApplicationRegistration.ts": "ca358e8de64b51550f9be50f55d9189a665ca1a38d722a7850f1d31be43ae134", "lib/applications/proposedRegistration/validateProposedRegistrationActor.ts": "c56077ada47829f3ba20a618eaf0ae3ccfd67d9cf38db72e13939e57f89b8902", - "lib/applications/proposedRegistration/proposedRegistrationContract.ts": "0162487073c4e70dfc88179a49d6577980dcbb8a945e0a3778498e00f307b6e8", + "lib/applications/proposedRegistration/proposedRegistrationContract.ts": "9e54808c597030c4fcc16e4cb80e6ec2898fc88b148ec7517513f2bc29224587", "lib/applications/proposedRegistration/projectProposedRegistration.ts": "a3075ece761fa2a419dc48bf5c6cbfd8a6b2f0dc41e4d361f2695229022203af", "lib/applications/proposedRegistration/assertProposedRegistrationReceipt.ts": "cd8c2aae288df9f245386e630fc179435db5986da9def01fa4b154a1860698c7", "lib/applications/proposedRegistration/createProposedApplicationRegistration.ts": "0322dfd63e51314cfe7bcc5d5544127291574f3c1c8152fb536a3e1c6e4afef0", "lib/applications/proposedRegistration/authenticateProposedRegistration.ts": "00a1eeb4b9ae5726f5930fc42fbe7599ab7e47f6349ca8f2de8a550f9f392f78", "scripts/application-registration-proposal/setup.ts": "40d634fc986cde87f440f0596969985b9a68bf1d2c38ea87f00c4ecd893eb063", - "scripts/application-registration-proposal/denyNetwork.mjs": "5ed3c818af2732fe8abddda8e46e4b0e3a8a0edf6ff40c6d7edd54ea64dd159a" + "scripts/application-registration-proposal/denyNetwork.mjs": "5ed3c818af2732fe8abddda8e46e4b0e3a8a0edf6ff40c6d7edd54ea64dd159a", + "lib/applications/proposedRegistration/isProposedRegistrationText.ts": "6cec3b1f7e7441d7babda35729df77a088b53e0a59406b0b7990c2bb1a84a2cc" }, "databaseInputs": { "proposals/application-registration-2104/protocol-composition.py": "377791d3ef4a26103bd046609d4b8dbf8f63a3d475aa2c72faeba68b553aada5", @@ -62,6 +63,10 @@ "scripts/application-registration-proposal/sql-composition/run.mjs", "scripts/application-registration-proposal/sql-composition/qualification.test.ts", "scripts/application-registration-proposal/sql-composition/source-bindings.json", - "scripts/application-registration-proposal/sql-composition/supervise.py" + "scripts/application-registration-proposal/sql-composition/supervise.py", + "lib/applications/proposedRegistration/isProposedRegistrationText.ts", + "lib/applications/proposedRegistration/proposedRegistrationContract.ts", + "lib/applications/proposedRegistration/__tests__/operations.test.ts", + "scripts/application-registration-proposal/source-bindings.json" ] } From caaa1b5835a92ce6ae985ca446aa359147117899 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:30:57 -0500 Subject: [PATCH 6/6] test: complete proposal Unicode boundary qualification --- .../__tests__/operations.test.ts | 80 +++++++++++-------- .../sql-composition/qualification.test.ts | 46 ++++++++--- 2 files changed, 81 insertions(+), 45 deletions(-) diff --git a/lib/applications/proposedRegistration/__tests__/operations.test.ts b/lib/applications/proposedRegistration/__tests__/operations.test.ts index 7b668cbf2..c9489a880 100644 --- a/lib/applications/proposedRegistration/__tests__/operations.test.ts +++ b/lib/applications/proposedRegistration/__tests__/operations.test.ts @@ -405,19 +405,18 @@ describe("strict receipt acceptance", () => { }); }); -const invalidText = [ - String.fromCharCode(0), - String.fromCharCode(0xd800), - String.fromCharCode(0xdc00), -]; +const invalidText = [[0], [0xd800], [0xdc00], [0xd800, 0x61], [0xdc00, 0xd800]]; describe("proposal-local PostgreSQL text boundary", () => { it.each( - invalidText.flatMap(character => [ - { field: "key", character }, - { field: "name", character }, + invalidText.flatMap(units => [ + { field: "key", units }, + { field: "name", units }, ]), - )("rejects actual invalid code units in $field before storage", async ({ field, character }) => { - expect([0, 0xd800, 0xdc00]).toContain(character.charCodeAt(0)); + )("rejects actual invalid code units in $field before storage", async ({ field, units }) => { + const character = String.fromCharCode(...units); + expect( + Array.from({ length: character.length }, (_, index) => character.charCodeAt(index)), + ).toEqual(units); const value = field === "key" ? { ...input, idempotency_key: `req-${character}` } @@ -428,29 +427,40 @@ describe("proposal-local PostgreSQL text boundary", () => { expect(deps.storage.create).not.toHaveBeenCalled(); expect(deps.storage.read).not.toHaveBeenCalled(); }); - it.each([String.fromCharCode(0xd83d, 0xde80), String.fromCharCode(0xfffd), "Música 音楽"])( - "preserves valid Unicode and existing name trimming", - async text => { - const key = ` key-${text} `; - const value = { - ...input, - idempotency_key: key, - registration: { ...input.registration, name: ` Name${text} ` }, - }; - const parsed = proposedCreateInputSchema.parse(value); - expect(parsed.idempotency_key).toBe(key); - expect(parsed.registration.name).toBe(`Name${text}`); - expect(Buffer.from(parsed.idempotency_key)).toEqual(Buffer.from(key)); - const deps = dependencies(); - const receipt = structuredClone(golden.createReceipt); - receipt.snapshot.name = `Name${text}`; - deps.storage.create.mockResolvedValue(receipt); - expect(await create(request(), value, deps)).toEqual(receipt); - expect(deps.storage.create).toHaveBeenCalledExactlyOnceWith({ - ...golden.input, - key, - registration: { ...golden.input.registration, name: `Name${text}` }, - }); - }, - ); + it.each([ + String.fromCharCode(0xd83d, 0xde80), + String.fromCharCode(0xfffd), + "Música 音楽", + String.fromCharCode(0x5c, 0x75, 0x30, 0x30, 0x30, 0x30), + String.fromCharCode(0x5c, 0x75, 0x44, 0x38, 0x30, 0x30), + ])("preserves valid Unicode and existing name trimming", async text => { + if (text.charCodeAt(0) === 0x5c) { + const units = Array.from({ length: text.length }, (_, index) => text.charCodeAt(index)); + expect([ + [0x5c, 0x75, 0x30, 0x30, 0x30, 0x30], + [0x5c, 0x75, 0x44, 0x38, 0x30, 0x30], + ]).toContainEqual(units); + expect(text).toHaveLength(6); + } + const key = ` key-${text} `; + const value = { + ...input, + idempotency_key: key, + registration: { ...input.registration, name: ` Name${text} ` }, + }; + const parsed = proposedCreateInputSchema.parse(value); + expect(parsed.idempotency_key).toBe(key); + expect(parsed.registration.name).toBe(`Name${text}`); + expect(Buffer.from(parsed.idempotency_key)).toEqual(Buffer.from(key)); + const deps = dependencies(); + const receipt = structuredClone(golden.createReceipt); + receipt.snapshot.name = `Name${text}`; + deps.storage.create.mockResolvedValue(receipt); + expect(await create(request(), value, deps)).toEqual(receipt); + expect(deps.storage.create).toHaveBeenCalledExactlyOnceWith({ + ...golden.input, + key, + registration: { ...golden.input.registration, name: `Name${text}` }, + }); + }); }); diff --git a/scripts/application-registration-proposal/sql-composition/qualification.test.ts b/scripts/application-registration-proposal/sql-composition/qualification.test.ts index 7d020f890..bd09a8593 100644 --- a/scripts/application-registration-proposal/sql-composition/qualification.test.ts +++ b/scripts/application-registration-proposal/sql-composition/qualification.test.ts @@ -413,13 +413,15 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = expect(await register()).toEqual(original); }); it.each( - [0, 0xd800, 0xdc00].flatMap(code => [ - { field: "key", code }, - { field: "name", code }, + [[0], [0xd800], [0xdc00], [0xd800, 0x61], [0xdc00, 0xd800]].flatMap(units => [ + { field: "key", units }, + { field: "name", units }, ]), - )("rejects invalid $field code unit $code before any SQL query", async ({ field, code }) => { - const character = String.fromCharCode(code); - expect(character.charCodeAt(0)).toBe(code); + )("rejects invalid $field code units $units before any SQL query", async ({ field, units }) => { + const character = String.fromCharCode(...units); + expect( + Array.from({ length: character.length }, (_, index) => character.charCodeAt(index)), + ).toEqual(units); const value = field === "key" ? { ...input, idempotency_key: `req-${character}` } @@ -463,9 +465,11 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = }); try { await client.connect(transport); - for (const code of [0, 0xd800, 0xdc00]) { - const character = String.fromCharCode(code); - expect(character.charCodeAt(0)).toBe(code); + for (const units of [[0], [0xd800], [0xdc00], [0xd800, 0x61], [0xdc00, 0xd800]]) { + const character = String.fromCharCode(...units); + expect( + Array.from({ length: character.length }, (_, index) => character.charCodeAt(index)), + ).toEqual(units); for (const value of [ { ...input, idempotency_key: `req-${character}` }, { ...input, registration: { ...input.registration, name: `Name${character}` } }, @@ -479,8 +483,18 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = expect(calls).toHaveLength(before); } } + const literalUnits = [0x5c, 0x75, 0x30, 0x30, 0x30, 0x30, 0x5c, 0x75, 0x44, 0x38, 0x30, 0x30]; + const literal = String.fromCharCode(...literalUnits); + expect( + Array.from({ length: literal.length }, (_, index) => literal.charCodeAt(index)), + ).toEqual(literalUnits); + const sdkInput = { + ...input, + idempotency_key: ` key-${literal} `, + registration: { ...input.registration, name: ` Name${literal} ` }, + }; const created = await oneStorage(() => - client.callTool({ name: "create_application_registration", arguments: input }), + client.callTool({ name: "create_application_registration", arguments: sdkInput }), ); expect(created.isError).not.toBe(true); const original = ( @@ -490,6 +504,18 @@ describe("actual domain and helpers to restricted disposable SQL wrappers", () = const content = created.content as Array<{ type: string; text: string }>; expect(content[0].type).toBe("text"); expect(JSON.parse(content[0].text)).toEqual(original); + expect(original.snapshot.name).toBe(`Name${literal}`); + const storedKey = ( + await fixtureQuery("SELECT key FROM application_registration_proposal.requests") + ).rows[0].key; + expect(storedKey).toBe(sdkInput.idempotency_key); + expect(Buffer.from(storedKey)).toEqual(Buffer.from(sdkInput.idempotency_key)); + const saved = await registrationState(); + const replay = await oneStorage(() => + client.callTool({ name: "create_application_registration", arguments: sdkInput }), + ); + expect(replay.content).toEqual(created.content); + expect(await registrationState()).toEqual(saved); await grantRead(original.application_id); const selected = await oneStorage(() => client.callTool({ name: "read_application_registration", arguments: select(original) }),