diff --git a/scripts/application-registration-proposal/sql-composition/README.md b/scripts/application-registration-proposal/sql-composition/README.md new file mode 100644 index 000000000..0bf05234a --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/README.md @@ -0,0 +1,32 @@ +# Disposable registration composition qualification + +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; generic `P0001` failures remain `outcome_unknown` and are never classified from message text. + +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. 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. + +Resolve the intended Node executable to an absolute path first, then run from the API repository with a minimal parent environment and explicit local source and tool paths: + +```sh +node_path=/absolute/path/to/node +env -i PATH=/usr/bin:/bin LANG=C LC_ALL=C TZ=UTC "$node_path" \ + scripts/application-registration-proposal/sql-composition/run.mjs \ + --database-root /absolute/path/to/exact-database-proposal \ + --pg-bin /absolute/path/to/postgresql/bin \ + --python /absolute/path/to/python3 +``` + +The minimal parent environment prevents ambient `NODE_OPTIONS` from executing code before the launcher can scrub its child. Do not supply a real `HOME` or an env file. Dependency installation happens separately and is outside this process-containment claim. + +The final local PostgreSQL 15.10/17.7 qualification and fault controls used Node 24.18.0. The separate loader-defect reproduction used Node 23.6.1. Node 22 has not been qualified by this local suite. + +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. + +Qualification targets PostgreSQL 15 and 17. This suite is distinct from the 45-case adapter 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, actual 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 legacy 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. diff --git a/scripts/application-registration-proposal/sql-composition/qualification.test.ts b/scripts/application-registration-proposal/sql-composition/qualification.test.ts new file mode 100644 index 000000000..e09d74dbd --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/qualification.test.ts @@ -0,0 +1,342 @@ +import { beforeAll, beforeEach, afterAll, describe, expect, it } from "vitest"; +import { Client } from "pg"; +import { userInfo } from "node:os"; +import net from "node:net"; +import http2 from "node:http2"; +import dgram from "node:dgram"; +import dns from "node:dns"; +import dnsPromises from "node:dns/promises"; +import { NextRequest, NextResponse } from "next/server"; +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"; + +// 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({ + host: socket, + port: 55473, + user: userInfo().username, + database: "postgres", + ssl: false, + connectionTimeoutMillis: 5000, + query_timeout: 10000, + statement_timeout: 10000, + application_name: "registration-domain-composition", +}); +const calls: Array<{ operation: "create" | "read"; state: string; parameters: number }> = []; +let fixtureQueries = 0; +let dropCommittedResponse = false; +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 { + result = 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"); + 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 dependencies: ProposedDependencies = { + policy: { + status: "proposed_unadopted", + version: "proposed-personal-v1", + databaseHead: "df7be4c65b98924373b38c7d257f4b1c1820d6b7", + }, + 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], + ), + }, +}; +const input = { + idempotency_key: "composition-create", + expected_entitlement_revision: 1, + registration: { + name: "Música 音楽", + environment: "production" as const, + allowed_origins: ["https://preview.example", "https://music.example"], + return_urls: ["https://music.example/Z", "https://music.example/%C3%A9"], + }, +}; +const request = () => + new NextRequest("https://fixture.invalid", { headers: { "x-api-key": fixture.key } }); +const oneStorage = async (operation: () => Promise): Promise => { + const before = calls.length; + try { + return await operation(); + } finally { + expect(calls.length - before).toBe(1); + } +}; +const register = (value: unknown = input) => + oneStorage(() => create(request(), value, dependencies)); +const select = (receipt: { application_id: string; receipt_id: string }) => ({ + application_id: receipt.application_id, + receipt_id: receipt.receipt_id, + environment: "production" as const, +}); +const grantRead = async (application: string) => + fixtureQuery( + "INSERT INTO application_registration_proposal.management_entitlements(actor,workspace_id,application_id,environment,operation) VALUES($1::uuid,$1::uuid,$2::uuid,'production','read_registration')", + [actorA, application], + ); + +beforeAll(async () => { + await sql.connect(); + const metadata = await fixtureQuery( + "SELECT current_setting('server_version') AS version,current_setting('server_encoding') AS encoding", + ); + server = metadata.rows[0]; + expect(server.encoding).toBe("UTF8"); + await fixtureQuery( + "INSERT INTO public.accounts(id) VALUES($1::uuid),($2::uuid) ON CONFLICT DO NOTHING", + [actorA, actorB], + ); +}); +beforeEach(async () => { + dropCommittedResponse = 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)", + [actorA, actorB], + ); + await fixtureQuery( + "INSERT INTO application_registration_proposal.create_entitlements(actor,workspace_id,environment) SELECT account_id,account_id,e FROM application_registration_proposal.personal_principals CROSS JOIN unnest(ARRAY['production','development']) e", + ); +}); +afterAll(async () => { + await sql.end(); + console.log( + "COMPOSITION_RECEIPT " + + JSON.stringify({ server, storageCalls: calls, fixtureQueries, activation: false }), + ); +}); + +describe("actual domain to exact disposable SQL proposal", () => { + it("creates disabled canonical rows and returns the unchanged SQL receipt", async () => { + const receipt = await register(); + const stored = await fixtureQuery( + "SELECT result FROM application_registration_proposal.receipts WHERE id=$1::uuid", + [receipt.receipt_id], + ); + expect(receipt).toEqual(stored.rows[0].result); + expect(receipt.actor).toBe(actorA); + expect(receipt.workspace_id).toBe(actorA); + expect(receipt.billing_owner_id).toBe(actorA); + expect(receipt.recorded_at).toMatch(/T.*(?:Z|\+00:00)$/); + expect(receipt.snapshot.return_urls).toEqual([ + "https://music.example/%C3%A9", + "https://music.example/Z", + ]); + const rows = await fixtureQuery( + 'SELECT a.workspace_id,a.billing_owner_id,a.name,e.environment,o.origin,o.return_urls FROM application_registration_proposal.applications a JOIN application_registration_proposal.environments e ON e.workspace_id=a.workspace_id AND e.application_id=a.id JOIN application_registration_proposal.origins o ON o.workspace_id=e.workspace_id AND o.application_id=e.application_id AND o.environment=e.environment ORDER BY o.origin COLLATE "C"', + ); + expect(rows.rows).toHaveLength(2); + for (const row of rows.rows) + expect(row).toMatchObject({ + workspace_id: actorA, + billing_owner_id: actorA, + name: "Música 音楽", + environment: "production", + }); + expect(rows.rows.map(row => row.origin)).toEqual(receipt.snapshot.allowed_origins); + expect( + ( + await fixtureQuery( + "SELECT count(*)::int AS n FROM application_registration_proposal.management_entitlements", + ) + ).rows[0].n, + ).toBe(0); + }); + it("requires explicit named read authority and accepts only input UUID aliases", async () => { + const receipt = await register(); + await expect( + oneStorage(() => read(request(), select(receipt), dependencies)), + ).rejects.toMatchObject({ kind: "denied" }); + await grantRead(receipt.application_id); + const selected = { + ...select(receipt), + application_id: receipt.application_id.toUpperCase(), + receipt_id: receipt.receipt_id.toUpperCase(), + }; + expect(await oneStorage(() => read(request(), selected, dependencies))).toEqual(receipt); + }); + it("denies other actors, environments and receipt selections against actual SQL", async () => { + const receipt = await register(); + await grantRead(receipt.application_id); + fixture.actor = actorB; + await expect( + oneStorage(() => read(request(), select(receipt), dependencies)), + ).rejects.toMatchObject({ kind: "denied" }); + fixture.actor = actorA; + for (const selected of [ + { ...select(receipt), environment: "development" }, + { ...select(receipt), receipt_id: actorB }, + ]) + await expect(oneStorage(() => read(request(), selected, dependencies))).rejects.toMatchObject( + { kind: "denied" }, + ); + expect( + ( + await fixtureQuery( + "SELECT count(*)::int AS n FROM application_registration_proposal.applications", + ) + ).rows[0].n, + ).toBe(1); + }); + it("keeps unrelated applications and development/production rows isolated", async () => { + const first = await register(); + fixture.actor = actorB; + const second = await register(); + fixture.actor = actorA; + const development = await register({ + ...input, + idempotency_key: "development-create", + registration: { ...input.registration, environment: "development" }, + }); + expect( + new Set([first.application_id, second.application_id, development.application_id]).size, + ).toBe(3); + expect(second.workspace_id).toBe(actorB); + expect(development.environment).toBe("development"); + const rows = await fixtureQuery( + "SELECT workspace_id,environment,count(*)::int AS n FROM application_registration_proposal.environments GROUP BY workspace_id,environment", + ); + expect(rows.rows).toHaveLength(3); + for (const row of rows.rows) expect(row.n).toBe(1); + }); + it("recovers an actual committed response only with explicit original-key replay", async () => { + dropCommittedResponse = true; + await expect(register()).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(calls.at(-1)?.state).toBe("committed_response_dropped"); + const original = ( + await fixtureQuery("SELECT result FROM application_registration_proposal.receipts") + ).rows[0].result; + expect(await register()).toEqual(original); + expect( + ( + await fixtureQuery( + "SELECT count(*)::int AS n FROM application_registration_proposal.applications", + ) + ).rows[0].n, + ).toBe(1); + await expect( + register({ + ...input, + registration: { ...input.registration, name: "Changed original intent" }, + }), + ).rejects.toMatchObject({ kind: "outcome_unknown" }); + expect(calls.at(-1)?.state).toBe("P0001"); + expect( + (await fixtureQuery("SELECT result FROM application_registration_proposal.receipts")).rows[0] + .result, + ).toEqual(original); + }); + it("does not infer a conflict class from another generic P0001 failure", async () => { + await expect(register({ ...input, expected_entitlement_revision: 2 })).rejects.toMatchObject({ + kind: "outcome_unknown", + }); + expect(calls.at(-1)?.state).toBe("P0001"); + expect( + ( + await fixtureQuery( + "SELECT count(*)::int AS n FROM application_registration_proposal.applications", + ) + ).rows[0].n, + ).toBe(0); + }); + it("rechecks SQL authority before replay and read, and fresh auth before storage", async () => { + const receipt = await register(); + await grantRead(receipt.application_id); + await fixtureQuery( + "UPDATE application_registration_proposal.create_entitlements SET enabled=false WHERE actor=$1::uuid", + [actorA], + ); + await expect(register()).rejects.toMatchObject({ kind: "denied" }); + await fixtureQuery( + "UPDATE application_registration_proposal.management_entitlements SET enabled=false WHERE actor=$1::uuid", + [actorA], + ); + await expect( + oneStorage(() => read(request(), select(receipt), dependencies)), + ).rejects.toMatchObject({ kind: "denied" }); + fixture.keyPresent = false; + const before = calls.length; + await expect(create(request(), input, dependencies)).rejects.toBeInstanceOf(NextResponse); + await expect(read(request(), select(receipt), dependencies)).rejects.toBeInstanceOf( + NextResponse, + ); + expect(calls).toHaveLength(before); + }); + it("denies native DNS, TCP, UDP and unrelated Unix sockets before access", async () => { + expect( + globalThis[Symbol.for("recoup.disposable.registration.originalSocketConnect")], + ).toBeUndefined(); + const installer = globalThis[Symbol.for("recoup.disposable.registration.ownedSocketInstaller")]; + expect(Object.keys(installer).sort()).toEqual(["install", "pid"]); + expect(Object.isFrozen(installer)).toBe(true); + expect(() => new WebSocket("wss://fixture.invalid")).toThrow("Network forbidden"); + expect(() => http2.connect("https://fixture.invalid")).toThrow("Network forbidden"); + expect(() => new net.Server().listen(0, "127.0.0.1")).toThrow("Network forbidden"); + expect(() => dns.lookup("fixture.invalid", () => {})).toThrow("Network forbidden"); + expect(() => dns.resolve4("fixture.invalid", () => {})).toThrow("Network forbidden"); + expect(() => Reflect.construct(dns.Resolver, [])).toThrow("Network forbidden"); + expect(() => dnsPromises.resolve4("fixture.invalid")).toThrow("Network forbidden"); + await expect(dnsPromises.lookup("fixture.invalid")).rejects.toThrow("Network forbidden"); + await expect(dnsPromises.lookup("localhost")).resolves.toEqual({ + address: "127.0.0.1", + family: 4, + }); + expect(() => dgram.createSocket("udp4")).toThrow("Network forbidden"); + expect(() => Reflect.construct(dgram.Socket, ["udp4"])).toThrow("Network forbidden"); + expect(() => new net.Socket().connect(443, "example.invalid")).toThrow( + "Owned Unix socket only", + ); + expect(() => new net.Socket().connect("/tmp/unrelated-postgres-socket")).toThrow( + "Owned Unix socket only", + ); + }); +}); diff --git a/scripts/application-registration-proposal/sql-composition/run.mjs b/scripts/application-registration-proposal/sql-composition/run.mjs new file mode 100644 index 000000000..4fbc87f9d --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/run.mjs @@ -0,0 +1,305 @@ +import { access, mkdtemp, mkdir, readFile, readlink, lstat, realpath, rm } from "node:fs/promises"; +import { constants } from "node:fs"; +import { createHash } from "node:crypto"; +import { spawn, execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +const root = fileURLToPath(new URL("../../../", import.meta.url)); +const here = fileURLToPath(new URL("./", import.meta.url)); +const args = process.argv.slice(2); +const options = {}; +const faultIndex = args.indexOf("--fault"); +const fault = faultIndex === -1 ? undefined : args[faultIndex + 1]; +if (faultIndex !== -1) { + if ( + faultIndex !== 6 || + args.length !== 8 || + !["signal", "timeout", "worker-exit"].includes(fault) + ) + throw new Error("Invalid explicit fault control"); + args.splice(6, 2); +} +if (args.length !== 6) + throw new Error( + "Require --database-root PATH --pg-bin PATH --python PATH; no DSN or ambient connection settings", + ); +for (let i = 0; i < args.length; i += 2) { + if (!["--database-root", "--pg-bin", "--python"].includes(args[i]) || options[args[i]]) + throw new Error("Unknown or duplicate qualification option"); + options[args[i]] = await realpath(args[i + 1]); +} +const database = options["--database-root"]; +const pg = options["--pg-bin"]; +const python = options["--python"]; +for (const executable of [ + python, + ...["postgres", "pg_ctl", "psql", "initdb"].map(name => join(pg, name)), +]) + await access(executable, constants.X_OK); +const bindings = JSON.parse(await readFile(join(here, "source-bindings.json"), "utf8")); +for (const [base, entries] of [ + [root, bindings.apiInputs], + [database, bindings.databaseInputs], +]) { + for (const [path, expected] of Object.entries(entries)) { + const digest = createHash("sha256") + .update(await readFile(join(base, path))) + .digest("hex"); + if (digest !== expected) throw new Error(`Composition source binding mismatch: ${path}`); + } +} +const gitEnv = { + PATH: "/usr/bin:/bin", + HOME: "/nonexistent/registration-qualification", + GIT_CONFIG_NOSYSTEM: "1", + 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; +if (!/^[0-9a-f]{40}$/.test(apiRevision)) throw new Error("Exact API revision required"); +const gitRead = args => + execFileSync("/usr/bin/git", ["-C", root, ...args], { + env: gitEnv, + encoding: "utf8", + timeout: 5000, + maxBuffer: 16 * 1024 * 1024, + }); +if (gitRead(["rev-parse", "--verify", `${apiRevision}^{commit}`]).trim() !== apiRevision) + 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}`), +]); +const committedChanges = gitRead([ + "diff-tree", + "--no-commit-id", + "--name-only", + "-r", + "-z", + apiRevision, + "HEAD", +]) + .split("\0") + .filter(Boolean); +for (const path of committedChanges) { + if (!allowedChanges.has(path)) throw new Error(`Unbound committed API change: ${path}`); +} +const entries = gitRead(["ls-tree", "-r", "-z", apiRevision]).split("\0").filter(Boolean); +const baselinePaths = new Set(); +let trackedInputsVerified = 0; +const unreadEnvPaths = []; +for (const entry of entries) { + const separator = entry.indexOf("\t"); + const [mode, type, oid] = entry.slice(0, separator).split(" "); + const path = entry.slice(separator + 1); + baselinePaths.add(path); + if (allowedChanges.has(path)) continue; + // Dotenv is disabled; never open environment-file contents, including the tracked example. + if (/(?:^|\/)\.env(?:$|\.)/.test(path)) { + unreadEnvPaths.push(path); + continue; + } + if (type !== "blob" || !["100644", "100755", "120000"].includes(mode)) + throw new Error(`Unsupported bound API entry: ${path}`); + const full = join(root, path); + const stat = await lstat(full); + const matchesType = + mode === "120000" + ? stat.isSymbolicLink() + : stat.isFile() && Boolean(stat.mode & 0o111) === (mode === "100755"); + if (!matchesType) throw new Error(`Unbound API source type: ${path}`); + const bytes = + mode === "120000" ? await readlink(full, { encoding: "buffer" }) : await readFile(full); + // Hash raw working-tree bytes as Git blobs: no index flags, stat cache or clean filters. + const actual = createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex"); + if (actual !== oid) throw new Error(`Unbound API source change: ${path}`); + trackedInputsVerified++; +} +const indexedPaths = gitRead(["ls-files", "--cached", "-z"]).split("\0").filter(Boolean); +const untrackedPaths = gitRead(["ls-files", "--others", "--exclude-standard", "-z"]) + .split("\0") + .filter(Boolean); +const ignoredSources = gitRead([ + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "-z", + "--", + "lib", + "app", + "types", + "scripts/application-registration-proposal", +]) + .split("\0") + .filter(path => /\.(?:[cm]?[jt]sx?|json|py|sql)$/.test(path)); +for (const path of [...indexedPaths, ...untrackedPaths, ...ignoredSources]) { + if (!baselinePaths.has(path) && !allowedChanges.has(path)) + throw new Error(`Unbound API source change: ${path}`); +} +console.log( + "API_SOURCE_SCOPE " + + JSON.stringify({ + revision: apiRevision, + trackedInputsVerified, + unreadEnvPaths, + allowedQualificationPaths: [...allowedChanges], + }), +); +const databaseHead = execFileSync("/usr/bin/git", ["-C", database, "rev-parse", "HEAD"], { + env: gitEnv, + encoding: "utf8", + timeout: 5000, +}).trim(); +if (databaseHead !== bindings.databaseHead) + throw new Error("Exact Database proposal head required"); +console.log("Composition source bindings verified; no hosted target accepted"); +const owned = await mkdtemp("/tmp/registration-composition-launch-"); +await mkdir(join(owned, "home")); +const env = { + HOME: join(owned, "home"), + TMPDIR: owned, + PATH: `${dirname(python)}:${dirname(process.execPath)}:/usr/bin:/bin`, + LANG: "C", + LC_ALL: "C", + TZ: "UTC", + PG_BIN: pg, +}; +let requestedSignal; +const onInt = () => { + requestedSignal = "SIGINT"; +}; +const onTerm = () => { + requestedSignal = "SIGTERM"; +}; +process.on("SIGINT", onInt); +process.on("SIGTERM", onTerm); +let child; +let complete = false; +let code; +let error; +let interruptedAt; +const faultReceipts = {}; +let faultBuffer = ""; +let invalidFaultOutput = false; +const started = Date.now(); +try { + child = spawn( + python, + [ + "-I", + join(here, "supervise.py"), + "--database-root", + database, + "--node", + process.execPath, + ...(fault ? ["--fault", fault] : []), + ], + { cwd: root, env, stdio: fault ? ["ignore", "pipe", "inherit"] : "inherit", detached: true }, + ); + if (fault) { + child.stdout.setEncoding("utf8"); + child.stdout.on("data", chunk => { + process.stdout.write(chunk); + faultBuffer += chunk; + if (faultBuffer.length > 65536) { + invalidFaultOutput = true; + faultBuffer = ""; + return; + } + let end; + while ((end = faultBuffer.indexOf("\n")) !== -1) { + const line = faultBuffer.slice(0, end); + faultBuffer = faultBuffer.slice(end + 1); + for (const key of [ + "COMPOSITION_FAULT_READY", + "OWNED_WORKER_CLEANUP", + "OWNED_CLUSTER_CLEANUP", + ]) { + if (!line.startsWith(key + " ")) continue; + try { + if (faultReceipts[key]) invalidFaultOutput = true; + faultReceipts[key] = JSON.parse(line.slice(key.length + 1)); + } catch { + invalidFaultOutput = true; + } + } + } + }); + } + child.once("error", value => { + error = value; + complete = true; + }); + // close waits for piped fault evidence to drain as well as process exit. + child.once("close", value => { + code = value; + complete = true; + }); + while (!complete) { + if ((requestedSignal || Date.now() - started > 210000) && !interruptedAt) { + interruptedAt = Date.now(); + // The reviewed Python owner performs lease-bound worker/cluster cleanup. + child.kill("SIGTERM"); + } + if (interruptedAt && Date.now() - interruptedAt > 45000) { + child.kill("SIGKILL"); + throw new Error( + "Supervisor cleanup unconfirmed; preserve owned evidence and inspect its recorded lease", + ); + } + await delay(50); + } + if (error) throw error; + process.exitCode = interruptedAt ? 1 : (code ?? 1); + if (fault) { + const ready = faultReceipts.COMPOSITION_FAULT_READY; + const worker = faultReceipts.OWNED_WORKER_CLEANUP; + const cluster = faultReceipts.OWNED_CLUSTER_CLEANUP; + const passed = Boolean( + !invalidFaultOutput && + !faultBuffer.trim() && + !interruptedAt && + code === (fault === "worker-exit" ? 23 : 1) && + ready?.fault === fault && + ready.supervisor_pid === child.pid && + Number.isInteger(ready.node_pid) && + Number.isInteger(ready.driver_pid) && + worker?.worker_pid === ready.driver_pid && + worker.worker_group_absent === true && + cluster?.cluster_created === true && + cluster.postmaster_absent === true && + cluster.socket_absent === true, + ); + console.log("COMPOSITION_FAULT_RESULT " + JSON.stringify({ fault, passed, exit: code })); + if (!passed) { + process.exitCode = 1; + throw new Error(`Fault readiness/cleanup validation failed; preserved ${owned}`); + } + } + if (code === 0 && !interruptedAt) { + await rm(owned, { recursive: true, force: true }); + console.log("Composition supervisor completed and launch home removed"); + } else + console.error( + `${fault ? "Expected fault verified" : "Failed/interrupted qualification"}; preserved launch home ${owned}`, + ); +} finally { + process.removeListener("SIGINT", onInt); + process.removeListener("SIGTERM", onTerm); + if (!complete) { + process.exitCode = 1; + console.error(`Unconfirmed supervisor exit; preserved ${owned}`); + } +} diff --git a/scripts/application-registration-proposal/sql-composition/socket-guard.mjs b/scripts/application-registration-proposal/sql-composition/socket-guard.mjs new file mode 100644 index 000000000..6122308cf --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/socket-guard.mjs @@ -0,0 +1,147 @@ +import net from "node:net"; +import dgram from "node:dgram"; +import dns from "node:dns"; +import dnsPromises from "node:dns/promises"; +import { fileURLToPath } from "node:url"; +import tls from "node:tls"; +import http from "node:http"; +import https from "node:https"; +import http2 from "node:http2"; +import { lstatSync, readFileSync, realpathSync } from "node:fs"; +import { dirname, isAbsolute, join } from "node:path"; +import { syncBuiltinESMExports } from "node:module"; +const saved = Symbol.for("recoup.disposable.registration.ownedSocketInstaller"); +let nativeConnect; // Module-private; never publish the raw connector on globalThis. +// Capture once, in Node's --import preload before Vitest or authentication imports. +if (!globalThis[saved]) { + const explicitPreload = process.execArgv.some( + (value, index, args) => + value === "--import" && args[index + 1] === fileURLToPath(import.meta.url), + ); + if (!explicitPreload || process.env.REGISTRATION_CONNECTOR_INITIALIZED === String(process.pid)) + throw new Error("Native owned connector preload required"); + nativeConnect = net.Socket.prototype.connect; + globalThis[saved] = Object.freeze({ pid: process.pid, install: installNativeOwnedSocketGuard }); + process.env.REGISTRATION_CONNECTOR_INITIALIZED = String(process.pid); +} +if ( + globalThis[saved].pid !== process.pid || + process.env.REGISTRATION_CONNECTOR_INITIALIZED !== String(process.pid) +) + throw new Error("Owned connector initialization mismatch"); +const denyNetwork = function () { + throw new Error("Network forbidden in disposable SQL composition"); +}; +globalThis.fetch = globalThis.WebSocket = denyNetwork; +dgram.createSocket = dgram.Socket = denyNetwork; +for (const target of [dns, dnsPromises]) { + for (const key of Object.keys(target)) { + if ( + key === "Resolver" || + key.startsWith("resolve") || + key === "reverse" || + key === "lookupService" + ) + target[key] = denyNetwork; + } +} +// Vite inspects localhost while loading configuration. Answer it without OS/DNS calls. +const syntheticLocalhost = (hostname, options = {}) => { + if (hostname !== "localhost") return denyNetwork(); + const family = (typeof options === "number" ? options : options.family) === 6 ? 6 : 4; + const result = { address: family === 6 ? "::1" : "127.0.0.1", family }; + return typeof options === "object" && options.all ? [result] : result; +}; +dns.lookup = (hostname, options, callback) => { + if (typeof options === "function") { + callback = options; + options = {}; + } + const result = syntheticLocalhost(hostname, options); + if (typeof callback !== "function") throw new Error("Synthetic localhost callback required"); + queueMicrotask(() => + Array.isArray(result) ? callback(null, result) : callback(null, result.address, result.family), + ); +}; +dnsPromises.lookup = async (hostname, options) => syntheticLocalhost(hostname, options); +net.connect = net.createConnection = net.Socket.prototype.connect = denyNetwork; +net.Server.prototype.listen = denyNetwork; +tls.connect = http.request = http.get = https.request = https.get = http2.connect = denyNetwork; + +/** Allow only the supervisor's current owned Unix socket; never a host/port or alias. */ +export function installOwnedSocketGuard() { + return globalThis[saved].install(); +} + +function installNativeOwnedSocketGuard() { + const socket = process.env.REGISTRATION_QUALIFICATION_SOCKET; + if (!socket || !isAbsolute(socket) || realpathSync(socket) !== socket) + throw new Error("Owned Unix socket scope required"); + const root = dirname(socket); + const owner = JSON.parse(readFileSync(join(root, "fixture-owner.json"), "utf8")); + const scope = JSON.parse(readFileSync(join(root, "composition-scope.json"), "utf8")); + const expected = join(socket, ".s.PGSQL.55473"); + const identity = lstatSync(expected); + // Validate the directory last: Node 23.6.1 realpath shares stat scratch state with lstat. + // Leaving a socket stat last can corrupt cached module-path resolution. + const directory = lstatSync(socket); + const pid = readFileSync(join(socket, "pg", "postmaster.pid"), "utf8").split("\n"); + if ( + owner.socket !== socket || + owner.cluster !== join(socket, "pg") || + scope.socket !== socket || + owner.worker_pid !== scope.supervisor_pid || + owner.uid !== process.getuid() || + directory.uid !== owner.uid || + directory.dev !== owner.device || + directory.ino !== owner.inode || + !directory.isDirectory() || + directory.isSymbolicLink() || + !identity.isSocket() || + identity.uid !== owner.uid || + Number(pid[0]) !== scope.postmaster_pid || + pid[1] !== owner.cluster + ) + throw new Error("Owned Unix socket lease mismatch"); + if (process.ppid === scope.driver_pid) + process.env.REGISTRATION_COMPOSITION_NODE = String(process.pid); + else if (process.ppid !== Number(process.env.REGISTRATION_COMPOSITION_NODE)) + throw new Error("Owned qualification parent required"); + console.log( + "OWNED_NODE_LINEAGE " + + JSON.stringify({ + version: process.version, + exec: process.execPath, + execArgv: process.execArgv, + pid: process.pid, + ppid: process.ppid, + driver_pid: scope.driver_pid, + supervisor_pid: scope.supervisor_pid, + node_pid: Number(process.env.REGISTRATION_COMPOSITION_NODE), + module: import.meta.url, + original_connect: typeof nativeConnect, + }), + ); + const original = nativeConnect; + net.Socket.prototype.connect = function (...args) { + const current = lstatSync(expected); + const currentDirectory = lstatSync(socket); + if ( + !currentDirectory.isDirectory() || + currentDirectory.dev !== directory.dev || + currentDirectory.ino !== directory.ino || + currentDirectory.uid !== directory.uid || + args[0] !== expected || + args.length > 2 || + (args[1] !== undefined && typeof args[1] !== "function") || + !current.isSocket() || + current.dev !== identity.dev || + current.ino !== identity.ino || + current.uid !== identity.uid + ) + throw new Error("Owned Unix socket only; TCP and unrelated paths forbidden"); + return Reflect.apply(original, this, args); + }; + syncBuiltinESMExports(); +} +installOwnedSocketGuard(); diff --git a/scripts/application-registration-proposal/sql-composition/source-bindings.json b/scripts/application-registration-proposal/sql-composition/source-bindings.json new file mode 100644 index 000000000..02e56c4d4 --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/source-bindings.json @@ -0,0 +1,41 @@ +{ + "apiMerge": "38ee9828635881526ac9f8b304626739ef1813f8", + "databaseHead": "df7be4c65b98924373b38c7d257f4b1c1820d6b7", + "apiInputs": { + "lib/auth/validateAuthContext.ts": "055ac2965db8487c8f67d74c549101d866968ed507d295498ed4485d62867c28", + "lib/applications/applicationRegistrationSchema.ts": "5bfb55ded25eae323bea02b535d6fb010eec5b2a767b891a13b86e4c91427a30", + "lib/applications/validateApplicationRegistration.ts": "b842cd312e0123a65ec1dd872c54474f77872b337ef5285ecedff1dad96ac0c6", + "package.json": "6129bd1116b3f3b3644c4560484daf2feafb57272e29f68cb5156b22ef1bbd50", + "pnpm-lock.yaml": "59d2629cd37287ad1bfd5e35589d0ed4c15c09d3c1965fff78aaba4a871487ee", + "tsconfig.json": "b32629dbc2af272f06db2eb3c5e6bd249183a72cec77481e624b0a4086c10d93", + "lib/keys/getApiKeyDetails.ts": "68813ca17af04703ded1efc25d8c6864aaa1f7b9c297ddeadb44c6c10220c644", + "lib/mcp/__tests__/verifyApiKeyExpiry.test.ts": "1b4b18f8147217734b9b1d89418a57ae23c968e6046109d072469b7735fdd1bc", + "vercel.json": "3321280d5e9e9c4fbba06651418ffb0f5716418acdddc8f889f618ac8eca0fa3", + "lib/applications/proposedRegistration/readProposedApplicationRegistration.ts": "ca358e8de64b51550f9be50f55d9189a665ca1a38d722a7850f1d31be43ae134", + "lib/applications/proposedRegistration/validateProposedRegistrationActor.ts": "c56077ada47829f3ba20a618eaf0ae3ccfd67d9cf38db72e13939e57f89b8902", + "lib/applications/proposedRegistration/proposedRegistrationContract.ts": "e4c355f112b2a21ada49ab2146318837f13d2cd66e59e3f8a08569d055162fed", + "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" + }, + "databaseInputs": { + "proposals/application-registration-2104/protocol-composition.py": "377791d3ef4a26103bd046609d4b8dbf8f63a3d475aa2c72faeba68b553aada5", + "proposals/application-registration-2104/registration.sql": "472440d1540a79eb34255efcbc7a6286bb394e1f3779e7ed6a6b7ace33cd9074", + "proposals/application-registration-2104/parents.sql": "2a1096eadf1ee947f2b1d6bb88f5750e26436ee8ea82ae1f306a279da8b41c2d", + "proposals/application-registration-2104/qualification-bootstrap.sql": "6c318540735e46c8ace40cd686bf7cc1851fb3296b5a123d29e287f94be35c05", + "proposals/application-registration-2104/test_registration.py": "ca498687ee4983767f2cf592dfd424a954fe17d0acaa04e18ae9960ed62f3a16", + "proposals/application-proof-2104/proposal.sql": "2cf96399422cfc1e68b0578b7aeb7b58a97c56303d85b91ee6cf862329f6c86c", + "proposals/application-proof-2104/fixture.sql": "b4435b1c5546d471c33b758f1ac8a7fd8ca199071b08cc541f4cb199e6412668", + "proposals/application-proof-2104/test_configuration.py": "43b686a33660dfb8bfd7b26c4827a74527cc430466567311726cb54881406cad", + "proposals/application-proof-2104/configuration-fixture.sql": "b15593f26c58a856ea4dedf98a7d42f1bbe7cf229f6b15aa8a80bd9d0d598c80", + "proposals/application-proof-2104/test_transactions.py": "addd5fc3a09129bbdd429059ae7b47b402192092853eecd9d3ebe1c1ca16eaf2", + "proposals/application-proof-2104/fixture-authority.sql": "0a2715a5a4f93c349df06d25a6334d513350f225a36af71ae8694fe1914c4c99", + "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", + "acceptedApiComposition": "a2a6d6b70644fcda5b89c5bbec281573b2dab9e9" +} diff --git a/scripts/application-registration-proposal/sql-composition/supervise.py b/scripts/application-registration-proposal/sql-composition/supervise.py new file mode 100644 index 000000000..2362384ac --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/supervise.py @@ -0,0 +1,111 @@ +"""Compose Node qualification with the exact reviewed Database lease supervisor.""" +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import signal +import time +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +API = HERE.parents[2] + + +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(): + 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' + spec = importlib.util.spec_from_file_location('registration_lifecycle', source) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def run_worker(database, node, fault=None): + """Use the validated existing lease, load exact SQL and run only composition tests.""" + module = database_module(Path(database)) + socket, pg_bin = module.prepare_worker_environment() + module.Registration.setUpClass() + 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])} + descriptor = root / 'composition-scope.json' + descriptor.write_text(json.dumps(scope)) + descriptor.chmod(0o600) + env = {**module.fixture_environment(root, pg_bin), + 'PRIVY_PROJECT_SECRET': 'synthetic-registration-secret', 'PRIVY_APP_ID': 'synthetic-app', + 'NODE_ENV': 'test'} + command = [node, '--import', str(HERE/'socket-guard.mjs'), + str((API/'node_modules/vitest/vitest.mjs').resolve(strict=True)), 'run', '--config', str(HERE/'vitest.config.ts')] + # No new session: Node/Vitest descendants remain in the reviewed worker's owned group. + if fault: + # A real preloaded Node descendant announces readiness before controlled failure. + marker = root / 'fault-node-ready' + code = "import {writeFileSync} from 'node:fs';writeFileSync(" + json.dumps(str(marker)) + ",String(process.pid));setInterval(()=>{},1000)" + command = [node, '--import', str(HERE/'socket-guard.mjs'), '--input-type=module', '-e', code] + child = subprocess.Popen(command, cwd=API, env=env) + deadline = time.monotonic() + 10 + while not marker.exists(): + if child.poll() is not None or time.monotonic() > deadline: + raise RuntimeError('Fault descendant failed to initialize') + time.sleep(.02) + if int(marker.read_text()) != child.pid: + raise RuntimeError('Fault descendant identity mismatch') + print('COMPOSITION_FAULT_READY ' + json.dumps({'fault': fault, 'node_pid': child.pid, 'driver_pid': os.getpid(), 'supervisor_pid': os.getppid()}), flush=True) + if fault == 'signal': + os.kill(os.getppid(), signal.SIGTERM) + child.wait(timeout=10) + elif fault == 'worker-exit': + raise SystemExit(23) + else: + child.wait(timeout=.3) + raise RuntimeError('Fault unexpectedly returned') + result = subprocess.run(command, cwd=API, env=env, timeout=90) + raise SystemExit(result.returncode) + + +def main(): + """Delegate lifecycle/cleanup unchanged; preserve trampoline on ambiguous failure.""" + parser = argparse.ArgumentParser() + parser.add_argument('--database-root', required=True) + parser.add_argument('--node', required=True) + parser.add_argument('--fault', choices=['signal', 'timeout', 'worker-exit']) + args = parser.parse_args() + database = Path(args.database_root).resolve(strict=True) + node = str(Path(args.node).resolve(strict=True)) + pg_bin = str(Path(os.environ['PG_BIN']).resolve(strict=True)) + # Scrub again before loading fixture code; never forward an ambient credential variable. + clean = {key: os.environ[key] for key in ['HOME', 'TMPDIR', 'PATH', 'LANG', 'LC_ALL', 'TZ']} + os.environ.clear() + os.environ.update({**clean, 'PG_BIN': pg_bin}) + module = database_module(database) + trampoline_root = Path(tempfile.mkdtemp(prefix='composition-driver-')).resolve() + trampoline = trampoline_root / 'worker.py' + trampoline.write_text( + "import importlib.util\n" + + "spec=importlib.util.spec_from_file_location('composition_driver'," + repr(str(Path(__file__).resolve())) + ")\n" + + "driver=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(driver)\n" + + "driver.run_worker(" + repr(str(database)) + "," + repr(node) + "," + repr(args.fault) + ")\n") + # HERE stays bound to exact Database sources; only the supervised worker entry is changed. + module.__file__ = str(trampoline) + try: + result = module.supervise() + except BaseException: + print('PRESERVED_COMPOSITION_DRIVER ' + str(trampoline_root), file=sys.stderr, flush=True) + raise + else: + # supervise returns only after lease-bound worker/cluster cleanup succeeds. + shutil.rmtree(trampoline_root) + raise SystemExit(result) + + +if __name__ == '__main__': + main() diff --git a/scripts/application-registration-proposal/sql-composition/vitest.config.ts b/scripts/application-registration-proposal/sql-composition/vitest.config.ts new file mode 100644 index 000000000..41cf757b6 --- /dev/null +++ b/scripts/application-registration-proposal/sql-composition/vitest.config.ts @@ -0,0 +1,22 @@ +import { defineConfig } from "vitest/config"; +import { fileURLToPath } from "node:url"; +const root = fileURLToPath(new URL("../../../", import.meta.url)); +export default defineConfig({ + root, + envDir: false, + resolve: { alias: { "@": root } }, + test: { + include: ["scripts/application-registration-proposal/sql-composition/qualification.test.ts"], + setupFiles: ["scripts/application-registration-proposal/setup.ts"], + pool: "forks", + poolOptions: { + forks: { + execArgv: ["--import", fileURLToPath(new URL("./socket-guard.mjs", import.meta.url))], + }, + }, + fileParallelism: false, + maxWorkers: 1, + testTimeout: 15000, + hookTimeout: 15000, + }, +}); diff --git a/vitest.config.ts b/vitest.config.ts index bfc35da56..9249ed641 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -9,6 +9,8 @@ export default defineConfig({ ...configDefaults.exclude, // Requires explicit no-dotenv/no-network qualification before auth imports. "lib/applications/proposedRegistration/**", + // Requires its explicit owned disposable PostgreSQL supervisor. + "scripts/application-registration-proposal/sql-composition/**", "scripts/mcp-oauth/**", // This fixture owns node:test lifecycle cases and a separate compiled runtime runner. "scripts/pack-scheduler-workflow-fixture/**",