Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions lib/applications/proposedRegistration/__tests__/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { assertProposedRegistrationReceipt } from "../assertProposedRegistration
import { projectProposedRegistration } from "../projectProposedRegistration";
import {
ProposedStorageFailure,
proposedCreateInputSchema,
type ProposedDependencies,
type ProposedCreateCall,
} from "../proposedRegistrationContract";
Expand Down Expand Up @@ -403,3 +404,63 @@ describe("strict receipt acceptance", () => {
}
});
});

const invalidText = [[0], [0xd800], [0xdc00], [0xd800, 0x61], [0xdc00, 0xd800]];
describe("proposal-local PostgreSQL text boundary", () => {
it.each(
invalidText.flatMap(units => [
{ field: "key", units },
{ field: "name", units },
]),
)("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}` }
: { ...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 音楽",
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}` },
});
});
});
Original file line number Diff line number Diff line change
@@ -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);
}
Original file line number Diff line number Diff line change
@@ -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"),
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown>[] }>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
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("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,
{},
{ 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();
});
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();
});

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();
},
);
Original file line number Diff line number Diff line change
@@ -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);
Comment thread
sidneyswift marked this conversation as resolved.
Resolved
if (typeof registration !== "string") throw new Error();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return [
call.actor,
call.workspace,
call.environment,
call.key,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
sidneyswift marked this conversation as resolved.
Resolved
call.entitlementRevision,
registration,
];
} catch {
throw new ProposedStorageFailure("outcome_unknown");
}
}
Original file line number Diff line number Diff line change
@@ -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");
}
}
Original file line number Diff line number Diff line change
@@ -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");
}
Original file line number Diff line number Diff line change
@@ -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");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
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 single call; the domain owns authentication and strict receipt validation. */
export async function insertProposedApplicationRegistration(
client: ProposedRegistrationSqlClient,
call: ProposedCreateCall,
): Promise<unknown> {
const values = getProposedCreateSqlValues(call);
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) {
throw getProposedSqlFailure(error, "create");
}
return getProposedSqlReceipt(result);
}
Loading
Loading