From 18e2f83be49b1c3b64535cd61f46eccf1a1d88ed Mon Sep 17 00:00:00 2001 From: Miranda Limonczenko Date: Wed, 25 Nov 2026 11:32:28 -0800 Subject: [PATCH] feat(docs): add a Postgres Triggers guide eval --- .../build-docs-035-postgres-triggers/EVAL.ts | 80 ++++ .../PROMPT.md | 34 ++ .../README.md | 68 +++ .../local/ORDERS.md | 34 ++ .../local/supabase/config.toml | 165 +++++++ .../migrations/20240101000000_init.sql | 46 ++ .../migrations.ts | 97 ++++ .../probes.ts | 432 ++++++++++++++++++ 8 files changed, 956 insertions(+) create mode 100644 evals/docs/build-docs-035-postgres-triggers/EVAL.ts create mode 100644 evals/docs/build-docs-035-postgres-triggers/PROMPT.md create mode 100644 evals/docs/build-docs-035-postgres-triggers/README.md create mode 100644 evals/docs/build-docs-035-postgres-triggers/local/ORDERS.md create mode 100644 evals/docs/build-docs-035-postgres-triggers/local/supabase/config.toml create mode 100644 evals/docs/build-docs-035-postgres-triggers/local/supabase/migrations/20240101000000_init.sql create mode 100644 evals/docs/build-docs-035-postgres-triggers/migrations.ts create mode 100644 evals/docs/build-docs-035-postgres-triggers/probes.ts diff --git a/evals/docs/build-docs-035-postgres-triggers/EVAL.ts b/evals/docs/build-docs-035-postgres-triggers/EVAL.ts new file mode 100644 index 00000000..caeb41d9 --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/EVAL.ts @@ -0,0 +1,80 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + checkBackOfficeChange, + checkBulkCancel, + checkCustomerChange, + checkCustomersCannotWrite, + checkCustomersReadOwn, + checkUnchangedStatus, + type Run, +} from './probes.js'; + +const GUIDE_PATH = 'guides/database/postgres/triggers'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const migrations = await applyPendingMigrations(ctx); + const run: Run = (sql) => execSql(ctx, sql, { tuplesOnly: true }); + + const backOffice = await checkBackOfficeChange(run); + const customer = await checkCustomerChange(run); + const bulk = await checkBulkCancel(run); + const unchanged = await checkUnchangedStatus(run); + const read = await checkCustomersReadOwn(run); + const write = await checkCustomersCannotWrite(run); + + const checks: CheckResult[] = [ + checkMigrationsWereApplied(migrations), + backOffice, + customer, + bulk, + unchanged, + read, + write, + checkGuideWasRead(ctx), + ]; + + return { passed: checks.every((check) => check.passed), checks }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + passed: false, + checks: [ + { + name: 'scorer evaluated the order status timeline', + passed: false, + notes: message, + }, + ], + }; + } +}; + +export default scorer; + +function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult { + const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) => + call.pages?.some((page) => page.url.includes(GUIDE_PATH)) + ); + const withContent = calls.filter((call) => call.hasContent); + return { + name: 'the agent read the Postgres Triggers guide the prompt referenced', + passed: withContent.length > 0, + notes: + withContent.length > 0 + ? withContent.map((call) => call.source).join(', ') + : calls.length > 0 + ? `reached the guide via ${calls.map((call) => call.source).join(', ')} but retrieved no page content` + : 'no docs call reached the guide', + }; +} diff --git a/evals/docs/build-docs-035-postgres-triggers/PROMPT.md b/evals/docs/build-docs-035-postgres-triggers/PROMPT.md new file mode 100644 index 00000000..4d58b23f --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/PROMPT.md @@ -0,0 +1,34 @@ +--- +stage: build +interface: cli +product: + - database +topic: + - sql + - security +services: [] +motivation: >- + A trigger runs with the rights of whoever made the change. Developers and + agents write one that works when tested as the database owner and fails for + signed-in users, or open the target table to those users to make it work. + This checks that an agent reading the Postgres Triggers guide records every + real status change, from customers and the back office alike, while + customers cannot write the record. The prompt omits the guide's vocabulary + on purpose, so read README.md before editing it. +--- + +Parcelo's order page should show a timeline of every status an order has been +through. The order_status_history table is already there, but nothing fills +it. Fill it in automatically whenever an order's status changes, no matter who +changes it. Customers change their own orders from the app, and the warehouse +updates orders from the back office. ORDERS.md shows how the app saves orders. + +Customers can see the timeline of their own orders, but they must never be +able to add, edit or remove entries. It has to be a record we can trust. Set +it up in the local project and make sure it works on the local database. + +Read the guide below before you start and rely on it for how to set this up, +rather than on what you already know. + +REFERENCE +https://supabase.com/docs/guides/database/postgres/triggers.md diff --git a/evals/docs/build-docs-035-postgres-triggers/README.md b/evals/docs/build-docs-035-postgres-triggers/README.md new file mode 100644 index 00000000..b48762ee --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/README.md @@ -0,0 +1,68 @@ +# build-docs-035-postgres-triggers + +## What this eval measures + +The subject is [Postgres Triggers](https://supabase.com/docs/guides/database/postgres/triggers), not the agent. The prompt +is a product request plus the page's url, and the checks say whether an agent that read the page records a side effect of +a change that app users cannot write themselves. + +One claim: every real status change is recorded once, whether a signed-in customer or the back office makes it, and +customers cannot write the record themselves. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +trigger, function, security definer, security invoker, row level security, RLS, policy, for each row, for each statement, +update of, distinct, plpgsql, search_path, schema-qualified, grant, revoke, privilege, role, authenticated, +service_role, insert, and `before`, `after`, `new`, `old` and `when` as SQL keywords. + +## The seed carries the contract + +- `order_status_history` exists with row level security on and a read policy for the order's customer. It has no write + policy, so app users cannot write it. The agent has to make a status change record itself without opening the table. +- `orders` lets customers read and update their own orders, so a customer's update reaches the database as that customer. +- `ORDERS.md` fixes the two app calls the probes replay: the order form saves `status` with `delivery_note` even when the + status is unchanged, and "Cancel all open orders" changes several rows in one statement. +- `old_status` is nullable, so an agent that also records the first status of a new order passes. The probes count only + the entry for the change they make. + +## Do not drop the positive controls + +`saving an order without changing its status adds no entry` and `customers cannot add, change or remove timeline entries` +pass for an agent that built nothing. `a status change by a signed-in customer is recorded on the timeline` makes both +mean something, because it proves the same customer's change does write an entry. The write check also inserts the same +row as the scorer in a rolled-back transaction first, so a row the schema refuses for everyone is not counted as a +refusal. + +## How the checks read the end state + +- Every probe runs SQL with the role and `request.jwt.claims` set, as `authenticated` for a customer and `service_role` + for the back office. Each probe makes its own orders for a fresh customer id, so the probes do not share rows. +- The scorer applies pending migrations first with `supabase migration up --local`, so correct SQL that the agent did not + apply costs one check. That step writes to the database, so score a workspace once per stack. +- `a status change from the back office is recorded on the timeline` passes for a recording step that runs with the + caller's rights. It separates "nothing records" from "only customers' changes fail". +- The back office, customer and bulk checks also require the order's status to have changed, so a step that drops the + update fails. + +## The guide has to actually be read + +`the agent read the Postgres Triggers guide the prompt referenced` requires a docs call that reached the page with +content. Read `docs.calls` before reading a score. + +## Checks expected to saturate + +The migration check, the back office check, `customers see the timeline of their own orders only`, and the write check. +The signal is expected in the customer, bulk and unchanged checks. + +## What this eval does not score + +- **The API path.** The probes set the role in SQL rather than calling PostgREST. +- **Who made a change.** The timeline has no column for it. +- **Changes to an order other than its status.** The prompt asks only for status. +- **Where the change lives.** The prompt says to set it up in the local project. The checks read the database, so a + change applied with no migration file passes. +- **Hardening of the recording step's `search_path`.** App users reach the database only through the API, so the scorer + does not probe name resolution. +- **Hosted projects and the dashboard.** Out of reach locally. diff --git a/evals/docs/build-docs-035-postgres-triggers/local/ORDERS.md b/evals/docs/build-docs-035-postgres-triggers/local/ORDERS.md new file mode 100644 index 00000000..11f494b6 --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/local/ORDERS.md @@ -0,0 +1,34 @@ +# Orders + +## How orders change + +Customers change their own orders from the app. The app writes to `orders` +directly through the API while the customer is signed in. + +Saving the order form sends every field on the form: + +```ts +await supabase + .from('orders') + .update({ status, delivery_note }) + .eq('id', orderId) +``` + +The "Cancel all open orders" button cancels every order still placed in one +request: + +```ts +await supabase + .from('orders') + .update({ status: 'cancelled' }) + .eq('status', 'placed') +``` + +The warehouse moves orders along from the back office, which uses the service +key. + +## Timeline + +The order page shows a timeline from `order_status_history`. Each entry is one +status change: the order, the status it left, the status it moved to, and +when. diff --git a/evals/docs/build-docs-035-postgres-triggers/local/supabase/config.toml b/evals/docs/build-docs-035-postgres-triggers/local/supabase/config.toml new file mode 100644 index 00000000..441c9ba8 --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-postgres-triggers" + +[api] +enabled = true +port = 54321 +schemas = ["public", "graphql_public"] +extra_search_path = ["public", "extensions"] +max_rows = 1000 + +[api.tls] +enabled = false + +[db] +port = 54322 +shadow_port = 54320 +major_version = 17 + +[db.pooler] +enabled = false +port = 54329 +pool_mode = "transaction" +default_pool_size = 20 +max_client_conn = 100 + +[db.migrations] +enabled = true +schema_paths = [] + +[db.seed] +enabled = false + +[realtime] +enabled = true + +[studio] +enabled = true +port = 54323 +api_url = "http://127.0.0.1" +openai_api_key = "env(OPENAI_API_KEY)" + +[inbucket] +enabled = true +port = 54324 + +[storage] +enabled = true +file_size_limit = "50MiB" + +[storage.s3_protocol] +enabled = true + +[storage.analytics] +enabled = false +max_namespaces = 5 +max_tables = 10 +max_catalogs = 2 + +[storage.vector] +enabled = false +max_buckets = 10 +max_indexes = 5 + +[auth] +enabled = true +site_url = "http://127.0.0.1:3000" +additional_redirect_urls = ["https://127.0.0.1:3000"] +jwt_expiry = 3600 +enable_refresh_token_rotation = true +refresh_token_reuse_interval = 10 +enable_signup = true +enable_anonymous_sign_ins = false +enable_manual_linking = false +minimum_password_length = 6 +password_requirements = "" + +[auth.rate_limit] +email_sent = 2 +sms_sent = 30 +anonymous_users = 30 +token_refresh = 150 +sign_in_sign_ups = 30 +token_verifications = 30 +web3 = 30 + +[auth.email] +enable_signup = true +double_confirm_changes = true +enable_confirmations = false +secure_password_change = false +max_frequency = "1s" +otp_length = 6 +otp_expiry = 3600 + +[auth.sms] +enable_signup = false +enable_confirmations = false +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.sms.twilio] +enabled = false +account_sid = "" +message_service_sid = "" +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +[auth.mfa] +max_enrolled_factors = 10 + +[auth.mfa.totp] +enroll_enabled = false +verify_enabled = false + +[auth.mfa.phone] +enroll_enabled = false +verify_enabled = false +otp_length = 6 +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.external.apple] +enabled = false +client_id = "" +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +redirect_uri = "" +url = "" +skip_nonce_check = false +email_optional = false + +[auth.web3.solana] +enabled = false + +[auth.third_party.firebase] +enabled = false + +[auth.third_party.auth0] +enabled = false + +[auth.third_party.aws_cognito] +enabled = false + +[auth.third_party.clerk] +enabled = false + +[auth.oauth_server] +enabled = false +authorization_url_path = "/oauth/consent" +allow_dynamic_registration = false + +[edge_runtime] +enabled = true +policy = "per_worker" +inspector_port = 8083 +deno_version = 2 + +[analytics] +enabled = true +port = 54327 +backend = "postgres" + +[experimental] +orioledb_version = "" +s3_host = "env(S3_HOST)" +s3_region = "env(S3_REGION)" +s3_access_key = "env(S3_ACCESS_KEY)" +s3_secret_key = "env(S3_SECRET_KEY)" diff --git a/evals/docs/build-docs-035-postgres-triggers/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-035-postgres-triggers/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..a9ecf834 --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,46 @@ +create table public.orders ( + id bigint generated always as identity primary key, + customer_id uuid not null, + status text not null default 'placed' + check (status in ('placed', 'packed', 'shipped', 'delivered', 'cancelled')), + delivery_note text, + created_at timestamptz not null default now() +); + +alter table public.orders enable row level security; + +create policy "Customers can read their own orders" + on public.orders for select + to authenticated + using (customer_id = (select auth.uid())); + +create policy "Customers can update their own orders" + on public.orders for update + to authenticated + using (customer_id = (select auth.uid())) + with check (customer_id = (select auth.uid())); + +create table public.order_status_history ( + id bigint generated always as identity primary key, + order_id bigint not null references public.orders (id) on delete cascade, + old_status text, + new_status text not null, + changed_at timestamptz not null default now() +); + +alter table public.order_status_history enable row level security; + +create policy "Customers can read the history of their own orders" + on public.order_status_history for select + to authenticated + using ( + exists ( + select 1 from public.orders o + where o.id = order_id and o.customer_id = (select auth.uid()) + ) + ); + +insert into public.orders (customer_id, status, delivery_note) values + ('8d0f6c1e-2b7a-4c39-9e51-3f4a7b2d6c10', 'shipped', 'Leave it with the neighbour'), + ('8d0f6c1e-2b7a-4c39-9e51-3f4a7b2d6c10', 'placed', null), + ('c45e2a90-71d3-4f8b-a6e2-9b1c0d3e5f27', 'packed', 'Ring twice'); diff --git a/evals/docs/build-docs-035-postgres-triggers/migrations.ts b/evals/docs/build-docs-035-postgres-triggers/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/migrations.ts @@ -0,0 +1,97 @@ +import { readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; + +export type MigrationState = { + pending: string[]; + applyFailed?: string; +}; + +export async function applyPendingMigrations( + ctx: LocalStackEvalContext +): Promise { + try { + return await apply(ctx); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { pending: ['unknown'], applyFailed: message.slice(0, 300) }; + } +} + +async function apply(ctx: LocalStackEvalContext): Promise { + const pending = await pendingVersions(ctx); + + if (pending.length === 0) { + return { pending }; + } + + const applied = await ctx.exec('supabase migration up --local', { + timeoutMs: 300_000, + }); + if (applied.exitCode !== 0) { + return { + pending, + applyFailed: firstError( + `${applied.stderr ?? ''}\n${applied.stdout ?? ''}` + ), + }; + } + return { pending }; +} + +export function checkMigrationsWereApplied(state: MigrationState): CheckResult { + return { + name: 'the agent applied the migrations it wrote', + passed: state.pending.length === 0, + notes: + state.pending.length === 0 + ? 'nothing pending' + : state.applyFailed + ? `pending: ${state.pending.join(', ')}; the scorer could not apply them: ${state.applyFailed}` + : `pending: ${state.pending.join(', ')}; the scorer applied them so the rest of the checks could run`, + }; +} + +async function pendingVersions(ctx: LocalStackEvalContext): Promise { + const onDisk = migrationVersionsOnDisk(ctx.hostWorkspace); + if (onDisk.length === 0) { + return []; + } + + const { rows: history } = await ctx.query( + "SELECT to_regclass('supabase_migrations.schema_migrations') IS NOT NULL AS present;" + ); + if (history[0]?.present !== true) { + return onDisk; + } + + const { rows } = await ctx.query( + 'SELECT version FROM supabase_migrations.schema_migrations;' + ); + const applied = new Set(rows.map((row) => String(row.version))); + return onDisk.filter((version) => !applied.has(version)); +} + +function migrationVersionsOnDisk(hostWorkspace: string): string[] { + let entries: string[]; + try { + entries = readdirSync(join(hostWorkspace, 'supabase', 'migrations')); + } catch { + return []; + } + return entries + .map((entry) => /^(\d+)(?:_.*)?\.sql$/.exec(entry)?.[1]) + .filter((version): version is string => version !== undefined) + .sort(); +} + +function firstError(output: string): string { + const lines = output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + const named = lines.find((line) => + /^(ERROR|FATAL|DETAIL|HINT)\b/i.test(line) + ); + return (named ?? lines[0] ?? 'no output').slice(0, 300); +} diff --git a/evals/docs/build-docs-035-postgres-triggers/probes.ts b/evals/docs/build-docs-035-postgres-triggers/probes.ts new file mode 100644 index 00000000..21b0fc25 --- /dev/null +++ b/evals/docs/build-docs-035-postgres-triggers/probes.ts @@ -0,0 +1,432 @@ +import { randomUUID } from 'node:crypto'; +import type { CheckResult } from '@supabase-evals/core'; +import type { SqlResult } from '../lib/exec-sql.js'; + +export type Run = (sql: string) => Promise; + +const CHECK = { + backOffice: + 'a status change from the back office is recorded on the timeline', + customer: + 'a status change by a signed-in customer is recorded on the timeline', + bulk: 'cancelling several orders at once records one entry per order', + unchanged: 'saving an order without changing its status adds no entry', + read: 'customers see the timeline of their own orders only', + write: 'customers cannot add, change or remove timeline entries', +} as const; + +type Entry = { orderId: number; oldStatus: string; newStatus: string }; +type Order = { id: number; status: string; note: string }; +type Outcome = { ok: true; value: T } | { ok: false; message: string }; + +type Role = 'authenticated' | 'service_role'; + +const BACK_OFFICE_CLAIMS = { role: 'service_role' }; + +export async function checkBackOfficeChange(run: Run): Promise { + const placed = await placeOrders(run, randomUUID(), ['placed']); + if (!placed.ok) return fail(CHECK.backOffice, placed.message); + const [id] = placed.value; + const updated = await run( + asRole( + 'service_role', + BACK_OFFICE_CLAIMS, + `update public.orders set status = 'packed' where id = ${id};` + ) + ); + if (!updated.ok) { + return fail( + CHECK.backOffice, + `the back office update failed: ${updated.message}` + ); + } + return checkRecorded(run, CHECK.backOffice, id, 'placed', 'packed'); +} + +export async function checkCustomerChange(run: Run): Promise { + const customer = randomUUID(); + const placed = await placeOrders(run, customer, ['placed']); + if (!placed.ok) return fail(CHECK.customer, placed.message); + const [id] = placed.value; + const updated = await run( + asRole( + 'authenticated', + customerClaims(customer), + `update public.orders set status = 'cancelled' where id = ${id};` + ) + ); + if (!updated.ok) { + return fail( + CHECK.customer, + `the customer's update failed: ${updated.message}` + ); + } + return checkRecorded(run, CHECK.customer, id, 'placed', 'cancelled'); +} + +export async function checkBulkCancel(run: Run): Promise { + const customer = randomUUID(); + const placed = await placeOrders(run, customer, [ + 'placed', + 'placed', + 'placed', + 'shipped', + ]); + if (!placed.ok) return fail(CHECK.bulk, placed.message); + const ids = placed.value; + const open = ids.slice(0, 3); + const shipped = ids[3] as number; + const updated = await run( + asRole( + 'authenticated', + customerClaims(customer), + `update public.orders set status = 'cancelled' where status = 'placed';` + ) + ); + if (!updated.ok) { + return fail( + CHECK.bulk, + `the customer's cancel-all update failed: ${updated.message}` + ); + } + const orders = await readOrders(run, ids); + const entries = await readEntries(run, ids); + if (!orders.ok) return fail(CHECK.bulk, orders.message); + if (!entries.ok) return fail(CHECK.bulk, entries.message); + const problems = [ + ...open.flatMap((id) => { + const status = orders.value.find((order) => order.id === id)?.status; + if (status !== 'cancelled') { + return [`order ${id} is ${status ?? 'missing'}, not cancelled`]; + } + const count = matching(entries.value, id, 'placed', 'cancelled'); + return count === 1 + ? [] + : [`order ${id} has ${count} placed to cancelled entries`]; + }), + ...entries.value + .filter((entry) => entry.orderId === shipped) + .filter((entry) => entry.newStatus === 'cancelled') + .map(() => `the shipped order ${shipped} got a cancelled entry`), + ]; + return { + name: CHECK.bulk, + passed: problems.length === 0, + notes: + problems.length === 0 + ? `three orders cancelled in one statement, one entry each: ${open.join(', ')}` + : `${problems.join('; ')}. Entries: ${describe(entries.value)}`, + }; +} + +export async function checkUnchangedStatus(run: Run): Promise { + const customer = randomUUID(); + const placed = await placeOrders(run, customer, ['placed']); + if (!placed.ok) return fail(CHECK.unchanged, placed.message); + const [id] = placed.value; + const before = await readEntries(run, [id]); + if (!before.ok) return fail(CHECK.unchanged, before.message); + const note = `note-${randomUUID().slice(0, 8)}`; + const updated = await run( + asRole( + 'authenticated', + customerClaims(customer), + `update public.orders set status = 'placed', delivery_note = ${literal(note)} where id = ${id};` + ) + ); + if (!updated.ok) { + return fail( + CHECK.unchanged, + `saving the order form failed: ${updated.message}` + ); + } + const orders = await readOrders(run, [id]); + const after = await readEntries(run, [id]); + if (!orders.ok) return fail(CHECK.unchanged, orders.message); + if (!after.ok) return fail(CHECK.unchanged, after.message); + const saved = orders.value[0]?.note === note; + const added = after.value.length - before.value.length; + return { + name: CHECK.unchanged, + passed: saved && added === 0, + notes: !saved + ? `the delivery note did not save, so the edit did not go through: ${orders.value[0]?.note ?? 'order missing'}` + : added === 0 + ? 'the note saved and the timeline is unchanged' + : `the note saved and the timeline gained ${added} entr${added === 1 ? 'y' : 'ies'}: ${describe(after.value.slice(before.value.length))}`, + }; +} + +export async function checkCustomersReadOwn(run: Run): Promise { + const customer = randomUUID(); + const placed = await placeOrders(run, customer, ['packed']); + if (!placed.ok) return fail(CHECK.read, placed.message); + const [id] = placed.value; + const added = await addEntry(run, id); + if (!added.ok) return fail(CHECK.read, added.message); + const query = `select 'COUNT:' || count(*) from public.order_status_history where order_id = ${id};`; + const own = await readCount( + run, + asRole('authenticated', customerClaims(customer), query) + ); + const other = await readCount( + run, + asRole('authenticated', customerClaims(randomUUID()), query) + ); + if (!own.ok) + return fail(CHECK.read, `the owner's read failed: ${own.message}`); + if (!other.ok) { + return fail(CHECK.read, `another customer's read failed: ${other.message}`); + } + const passed = own.value > 0 && other.value === 0; + return { + name: CHECK.read, + passed, + notes: `the owner sees ${own.value} entr${own.value === 1 ? 'y' : 'ies'} for order ${id}, another customer sees ${other.value}`, + }; +} + +export async function checkCustomersCannotWrite( + run: Run +): Promise { + const customer = randomUUID(); + const placed = await placeOrders(run, customer, ['packed']); + if (!placed.ok) return fail(CHECK.write, placed.message); + const [id] = placed.value; + const added = await addEntry(run, id); + if (!added.ok) return fail(CHECK.write, added.message); + const entry = added.value; + const forgery = `insert into public.order_status_history (order_id, old_status, new_status) values (${id}, 'packed', 'delivered');`; + const control = await run(`begin; ${forgery} rollback;`); + if (!control.ok) { + return fail( + CHECK.write, + `could not measure: the scorer's entry is refused even to the scorer's own connection: ${control.message}` + ); + } + const attempts = [ + forgery, + `update public.order_status_history set new_status = 'delivered' where id = ${entry};`, + `delete from public.order_status_history where id = ${entry};`, + ] + .map((statement) => swallow(statement)) + .join('\n'); + const tried = await run( + asRole('authenticated', customerClaims(customer), attempts) + ); + if (!tried.ok) { + return fail( + CHECK.write, + `the customer's write attempts did not run: ${tried.message}` + ); + } + const entries = await readEntries(run, [id]); + const rows = await run( + `select 'KEPT:' || coalesce(new_status, '') from public.order_status_history where id = ${entry};` + ); + if (!entries.ok) return fail(CHECK.write, entries.message); + if (!rows.ok) return fail(CHECK.write, rows.message); + const forged = matching(entries.value, id, 'packed', 'delivered'); + const kept = tagged(rows.stdout, 'KEPT')[0]; + const problems = [ + forged > 0 ? 'the customer added an entry' : undefined, + kept === undefined ? 'the customer removed an entry' : undefined, + kept !== undefined && kept !== 'packed' + ? 'the customer changed an entry' + : undefined, + ].filter((problem): problem is string => problem !== undefined); + return { + name: CHECK.write, + passed: problems.length === 0, + notes: + problems.length === 0 + ? 'insert, update and delete as the customer left the timeline as it was' + : `${problems.join('; ')}. Entries: ${describe(entries.value)}`, + }; +} + +async function checkRecorded( + run: Run, + name: string, + id: number, + from: string, + to: string +): Promise { + const orders = await readOrders(run, [id]); + const entries = await readEntries(run, [id]); + if (!orders.ok) return fail(name, orders.message); + if (!entries.ok) return fail(name, entries.message); + const status = orders.value[0]?.status; + if (status !== to) { + return fail( + name, + `order ${id} is ${status ?? 'missing'} after the update, not ${to}, so the change did not land` + ); + } + const count = matching(entries.value, id, from, to); + return { + name, + passed: count === 1, + notes: + count === 1 + ? `order ${id} has one ${from} to ${to} entry` + : `order ${id} has ${count} ${from} to ${to} entries. Entries: ${describe(entries.value)}`, + }; +} + +async function placeOrders( + run: Run, + customer: string, + statuses: string[] +): Promise> { + const values = statuses + .map((status) => `(${literal(customer)}, ${literal(status)})`) + .join(', '); + const result = await run( + `insert into public.orders (customer_id, status) values ${values} returning 'ID:' || id;` + ); + if (!result.ok) { + return { + ok: false, + message: `the scorer could not add orders: ${result.message}`, + }; + } + const ids = tagged(result.stdout, 'ID').map((id) => Number(id)); + return ids.length === statuses.length + ? { ok: true, value: ids } + : { + ok: false, + message: `the scorer added ${ids.length} of ${statuses.length} orders`, + }; +} + +async function addEntry(run: Run, orderId: number): Promise> { + const result = await run( + `insert into public.order_status_history (order_id, old_status, new_status) values (${orderId}, 'placed', 'packed') returning 'ID:' || id;` + ); + if (!result.ok) { + return { + ok: false, + message: `the scorer could not add a timeline entry: ${result.message}`, + }; + } + const id = tagged(result.stdout, 'ID')[0]; + return id + ? { ok: true, value: Number(id) } + : { ok: false, message: 'the scorer added no timeline entry' }; +} + +async function readOrders(run: Run, ids: number[]): Promise> { + const result = await run( + `select 'ORDER:' || id || '|' || status || '|' || coalesce(delivery_note, '') from public.orders where id in (${ids.join(', ')});` + ); + if (!result.ok) { + return { + ok: false, + message: `the scorer could not read orders: ${result.message}`, + }; + } + return { + ok: true, + value: tagged(result.stdout, 'ORDER').map((row) => { + const [id, status, note] = row.split('|'); + return { id: Number(id), status: status ?? '', note: note ?? '' }; + }), + }; +} + +async function readEntries(run: Run, ids: number[]): Promise> { + const result = await run( + `select 'ENTRY:' || order_id || '|' || coalesce(old_status, '') || '|' || coalesce(new_status, '') from public.order_status_history where order_id in (${ids.join(', ')}) order by id;` + ); + if (!result.ok) { + return { + ok: false, + message: `the scorer could not read the timeline: ${result.message}`, + }; + } + return { + ok: true, + value: tagged(result.stdout, 'ENTRY').map((row) => { + const [orderId, oldStatus, newStatus] = row.split('|'); + return { + orderId: Number(orderId), + oldStatus: oldStatus ?? '', + newStatus: newStatus ?? '', + }; + }), + }; +} + +async function readCount(run: Run, sql: string): Promise> { + const result = await run(sql); + if (!result.ok) return { ok: false, message: result.message }; + const count = tagged(result.stdout, 'COUNT')[0]; + return count + ? { ok: true, value: Number(count) } + : { ok: false, message: 'no count came back' }; +} + +function matching( + entries: Entry[], + orderId: number, + from: string, + to: string +): number { + return entries.filter( + (entry) => + entry.orderId === orderId && + entry.oldStatus === from && + entry.newStatus === to + ).length; +} + +function customerClaims(customer: string): Record { + return { sub: customer, role: 'authenticated' }; +} + +function asRole( + role: Role, + claims: Record, + sql: string +): string { + return ` + begin; + set local role ${role}; + set local "request.jwt.claims" = ${literal(JSON.stringify(claims))}; + ${sql} + commit; + `; +} + +function swallow(statement: string): string { + return `do $$ begin ${statement} exception when others then null; end $$;`; +} + +function describe(entries: Entry[]): string { + return entries.length === 0 + ? 'none' + : entries + .map( + (entry) => + `${entry.orderId}: ${entry.oldStatus || 'null'} to ${entry.newStatus}` + ) + .join(', '); +} + +function fail(name: string, notes: string): CheckResult { + return { name, passed: false, notes }; +} + +function literal(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +} + +function tagged(output: string, tag: string): string[] { + const prefix = `${tag}:`; + return output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.startsWith(prefix)) + .map((line) => line.slice(prefix.length)); +}