diff --git a/evals/docs/build-docs-034-vault/EVAL.ts b/evals/docs/build-docs-034-vault/EVAL.ts new file mode 100644 index 00000000..181a1f97 --- /dev/null +++ b/evals/docs/build-docs-034-vault/EVAL.ts @@ -0,0 +1,81 @@ +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 { + checkKeyHidden, + checkKeyNotInDatabase, + checkKeyNotInRepo, + checkKeyStored, + checkLinkAccepted, + checkLinkFollowsRotation, + type Run, + requestLink, +} from './probes.js'; + +const GUIDE_PATH = 'guides/database/vault'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const inRepo = await checkKeyNotInRepo(ctx); + const migrations = await applyPendingMigrations(ctx); + const run: Run = (sql) => execSql(ctx, sql, { tuplesOnly: true }); + + const stored = await checkKeyStored(run, ctx.hostWorkspace); + const inDatabase = await checkKeyNotInDatabase(run); + const hidden = await checkKeyHidden(run); + const link = checkLinkAccepted(await requestLink(run)); + const rotated = await checkLinkFollowsRotation(run); + + const checks: CheckResult[] = [ + checkMigrationsWereApplied(migrations), + stored, + inDatabase, + inRepo, + link, + rotated, + hidden, + 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 how the signing key is kept', + 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 Vault 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-034-vault/PROMPT.md b/evals/docs/build-docs-034-vault/PROMPT.md new file mode 100644 index 00000000..3c38c77a --- /dev/null +++ b/evals/docs/build-docs-034-vault/PROMPT.md @@ -0,0 +1,35 @@ +--- +stage: build +interface: cli +product: + - database +topic: + - security + - sql +services: [] +motivation: >- + A database function that calls out with a credential needs somewhere to keep + it. Customers and agents put the key in the function body, a trigger, a + migration, or a database setting the platform refuses. This checks that an + agent reading the Vault guide stores a signing key encrypted, keeps it out of + the repo and away from app users, and signs links with whatever key is + current. The prompt omits the guide's vocabulary on purpose, so read + README.md before editing it. +--- + +Plantly's reports sit on a CDN that only serves signed links. When someone +signed in to the app opens a report, the app should get a signed download link +from the database. DOWNLOAD_LINKS.md has the link format and says where the +CDN's signing key is. + +The repo is shared with contractors, and so are copies of the database they +debug with, so the key can't be readable in either. People using the app must +never be able to get the key. Ops changes the key now and then, and links have +to keep working when they do without anyone touching the code. Set that 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/vault.md diff --git a/evals/docs/build-docs-034-vault/README.md b/evals/docs/build-docs-034-vault/README.md new file mode 100644 index 00000000..d1325751 --- /dev/null +++ b/evals/docs/build-docs-034-vault/README.md @@ -0,0 +1,75 @@ +# build-docs-034-vault + +## What this eval measures + +The subject is [Vault](https://supabase.com/docs/guides/database/vault), 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 keeps a key a database function needs. + +One claim: a database function signs links with a key that is stored encrypted, is in no repo file, is unreadable by app +users, and is read at call time so a changed key takes effect at once. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +vault, secret, encrypt, decrypt, decrypted_secrets, create_secret, update_secret, pgsodium, security definer, grant, +revoke, privilege, role, anon, authenticated, setting, config.toml, `[db.vault]`, env(). + +## The seed carries the contract + +- `local/DOWNLOAD_LINKS.md` fixes the function name, its argument, the link format and the signature. The link check + needs a fixed shape to verify, so the contract is given rather than discovered. +- `local/.env` holds the key, and `local/.gitignore` ignores it. The key is a random value, so no memorized answer + produces a valid signature. +- `public.reports` lets an agent look a report up before signing. The scorer adds a report row for each path it asks for, + so an agent that checks the path exists is not refused. +- `config.toml` has no `[db.vault]` section. An agent can add one that reads the key from `.env`, or create the entry + with SQL that stays out of the repo. Both pass. + +## Do not drop the positive controls + +`app users cannot read the signing key` passes for a project with no key at all. `a signed-in user gets a link the CDN +accepts` makes it mean something, because a valid signature needs the key. `the signing key is not in plain text +in the database` and `the signing key is not in a file the repo would commit` pass for a project that never stored the +key, and `the signing key is stored in the vault` pairs with them. + +## How the checks read the end state + +- `the signing key is not in a file the repo would commit` runs `git init` in the workspace, lists every file git would + commit outside `node_modules`, and searches them for the key. +- `the signing key is not in plain text in the database` reads every table outside `vault` and `supabase_migrations`, + plus function bodies and settings, trigger arguments, view definitions, policies, check constraints, column defaults, + comments, and database and role settings. `supabase_migrations` is left to the repo check, so a key in a migration + costs one check. +- Both are literal matches on the key. An encoded or split key passes them. A function that hardcodes one still fails + the rotation check. +- `app users cannot read the signing key` runs as `anon` and as `authenticated`. It reads every table and view the role + can select. It calls every function in `public` the role can execute that takes no arguments, or one text or uuid + argument, which it passes each name and id of the vault entries holding the key. A read the database refuses is not a + leak. A view over the decrypted view is refused to both roles, so it does not count. +- The link is requested as `authenticated` through SQL with the role set, not through the API. +- A `[db.vault]` section lands only when the stack is reset or restarted. An agent that adds one and never applies it + fails `the signing key is stored in the vault`, and the note says so. + +## Order of the scorer + +The repo check runs first, before anything writes. The scorer then applies pending migrations with `supabase migration +up --local`, which writes to the database, so score once per stack. `links follow a change of the signing key` rotates +every vault entry that holds the key, so it runs last. + +## The guide has to actually be read + +`the agent read the Vault 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 signing key is stored in the vault`, and `app users cannot read the signing key`. The signal +is expected in the repo check, the link check, and the rotation check. + +## What this eval does not score + +- **The API path.** The function is called with the role set in SQL, so whether PostgREST exposes it is not scored. +- **Who besides signed-in users can get a link.** The prompt does not say. +- **Whether a teammate gets the key from a fresh clone.** An agent that created the entry with SQL passes. +- **Hosted projects.** The root key, key portability and the dashboard are out of reach locally. diff --git a/evals/docs/build-docs-034-vault/local/.env b/evals/docs/build-docs-034-vault/local/.env new file mode 100644 index 00000000..59e15714 --- /dev/null +++ b/evals/docs/build-docs-034-vault/local/.env @@ -0,0 +1 @@ +CDN_SIGNING_KEY=7c1e94b0a3f25d68e0b947c2d51a8f36b2e07d4c9a15f803 diff --git a/evals/docs/build-docs-034-vault/local/.gitignore b/evals/docs/build-docs-034-vault/local/.gitignore new file mode 100644 index 00000000..4c49bd78 --- /dev/null +++ b/evals/docs/build-docs-034-vault/local/.gitignore @@ -0,0 +1 @@ +.env diff --git a/evals/docs/build-docs-034-vault/local/DOWNLOAD_LINKS.md b/evals/docs/build-docs-034-vault/local/DOWNLOAD_LINKS.md new file mode 100644 index 00000000..322aadf2 --- /dev/null +++ b/evals/docs/build-docs-034-vault/local/DOWNLOAD_LINKS.md @@ -0,0 +1,31 @@ +# Download links + +Reports live on our CDN. The CDN serves a file only when the link carries a valid +signature, so every link the app shows has to be signed. + +The CDN checks links with the signing key in `.env` (`CDN_SIGNING_KEY`). Ops can +change that key at any time, and links signed with the old key stop working the +moment they do. + +## What the app calls + +The app asks the database for a link through the API: + +```ts +const { data: url } = await supabase.rpc('signed_download_url', { + file_path: 'reports/2026-q3.pdf', +}) +``` + +`signed_download_url(file_path text)` returns the full link as text. + +## Link format + +``` +https://cdn.plantly.example/?expires=&signature= +``` + +- `expires` is 15 minutes from when the link was made. +- `signature` is the HMAC-SHA256 of `:`, written as + lowercase hex. The HMAC key is the signing key as text, exactly as it appears + in `.env`. diff --git a/evals/docs/build-docs-034-vault/local/supabase/config.toml b/evals/docs/build-docs-034-vault/local/supabase/config.toml new file mode 100644 index 00000000..3d98f8ae --- /dev/null +++ b/evals/docs/build-docs-034-vault/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-vault" + +[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-034-vault/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-034-vault/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..665d3efe --- /dev/null +++ b/evals/docs/build-docs-034-vault/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,17 @@ +create table public.reports ( + id bigint generated always as identity primary key, + title text not null, + file_path text not null unique, + created_at timestamptz not null default now() +); + +alter table public.reports enable row level security; + +create policy "Signed-in users can read reports" + on public.reports for select + to authenticated + using (true); + +insert into public.reports (title, file_path) values + ('Q2 2026 sales', 'reports/2026-q2.pdf'), + ('Q3 2026 sales', 'reports/2026-q3.pdf'); diff --git a/evals/docs/build-docs-034-vault/migrations.ts b/evals/docs/build-docs-034-vault/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-034-vault/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-034-vault/probes.ts b/evals/docs/build-docs-034-vault/probes.ts new file mode 100644 index 00000000..4a022bdf --- /dev/null +++ b/evals/docs/build-docs-034-vault/probes.ts @@ -0,0 +1,444 @@ +import { createHmac, randomBytes, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; +import type { SqlResult } from '../lib/exec-sql.js'; + +const SEEDED_KEY = '7c1e94b0a3f25d68e0b947c2d51a8f36b2e07d4c9a15f803'; + +const CHECK = { + stored: 'the signing key is stored in the vault', + notInDatabase: 'the signing key is not in plain text in the database', + notInRepo: 'the signing key is not in a file the repo would commit', + link: 'a signed-in user gets a link the CDN accepts', + rotated: 'links follow a change of the signing key', + hidden: 'app users cannot read the signing key', +} as const; + +const CDN_ORIGIN = 'https://cdn.plantly.example/'; +const LINK_LIFETIME_SECONDS = 15 * 60; +const LIFETIME_SLACK_SECONDS = 120; +const APP_ROLES = ['anon', 'authenticated'] as const; + +export type Run = (sql: string) => Promise; +type Exec = Pick; +type Outcome = ({ ok: true } & T) | { ok: false; message: string }; + +export async function checkKeyNotInRepo(ctx: Exec): Promise { + const listed = await ctx.exec( + [ + 'git init -q >/dev/null 2>&1', + `git ls-files -z --cached --others --exclude-standard -- . ':(exclude)node_modules' ':(exclude)**/node_modules/**' | xargs -0 grep -lF -- '${SEEDED_KEY}' 2>/dev/null`, + 'echo "LISTED:$?"', + ].join('; ') + ); + const output = nonEmptyLines(listed.stdout ?? ''); + const status = output.find((line) => line.startsWith('LISTED:')); + if (!status) { + return { + name: CHECK.notInRepo, + passed: false, + notes: `could not list the repo files: ${(listed.stderr ?? '').slice(0, 300)}`, + }; + } + const hits = output.filter((line) => !line.startsWith('LISTED:')); + return { + name: CHECK.notInRepo, + passed: hits.length === 0, + notes: + hits.length === 0 + ? 'no file outside .gitignore carries the key' + : `found in ${hits.join(', ')}`, + }; +} + +export async function checkKeyStored( + run: Run, + workspace: string +): Promise { + const result = await run( + `select count(*) from vault.decrypted_secrets where decrypted_secret = ${sqlLiteral(SEEDED_KEY)};` + ); + if (!result.ok) { + return { name: CHECK.stored, passed: false, notes: result.message }; + } + const count = Number(result.stdout.trim()); + if (count > 0) { + return { + name: CHECK.stored, + passed: true, + notes: `${count} vault entr${count === 1 ? 'y holds' : 'ies hold'} the key`, + }; + } + return { + name: CHECK.stored, + passed: false, + notes: configNamesVault(workspace) + ? 'no vault entry holds the key; config.toml has a [db.vault] section, but the stack was not reset or restarted after it was added' + : 'no vault entry holds the key', + }; +} + +function configNamesVault(workspace: string): boolean { + try { + return readFileSync( + join(workspace, 'supabase', 'config.toml'), + 'utf8' + ).includes('[db.vault]'); + } catch { + return false; + } +} + +export async function checkKeyNotInDatabase(run: Run): Promise { + const result = await run(plainTextScan()); + if (!result.ok) { + return { name: CHECK.notInDatabase, passed: false, notes: result.message }; + } + const hits = nonEmptyLines(result.stdout); + return { + name: CHECK.notInDatabase, + passed: hits.length === 0, + notes: + hits.length === 0 + ? 'no table, function, trigger, view, policy, constraint, default, comment or setting carries the key' + : `found in ${hits.join(', ')}`, + }; +} + +function plainTextScan(): string { + const pattern = sqlLiteral(`%${SEEDED_KEY}%`); + return ` + create function pg_temp.tables_containing(pattern text) returns setof text + language plpgsql as $$ + declare + target record; + hit boolean; + begin + for target in + select n.nspname, c.relname + from pg_class c + join pg_namespace n on n.oid = c.relnamespace + where c.relkind in ('r', 'p') + and n.nspname not in ('pg_catalog', 'information_schema', 'vault', 'supabase_migrations') + and n.nspname not like 'pg_toast%' + and n.nspname not like 'pg_temp%' + loop + begin + execute format('select exists (select 1 from %I.%I t where t::text like %L)', target.nspname, target.relname, pattern) + into hit; + if hit then + return next format('table %I.%I', target.nspname, target.relname); + end if; + exception when others then + null; + end; + end loop; + end $$; + + with user_namespaces as ( + select n.oid, n.nspname + from pg_namespace n + where n.nspname not in ('pg_catalog', 'information_schema', 'vault') + and n.nspname not like 'pg_toast%' + and n.nspname not like 'pg_temp%' + ), + user_functions as ( + select p.*, n.nspname + from pg_proc p + join user_namespaces n on n.oid = p.pronamespace + where not exists ( + select 1 from pg_depend d + where d.classid = 'pg_proc'::regclass and d.objid = p.oid and d.deptype = 'e' + ) + ) + select place from ( + select pg_temp.tables_containing(${pattern}) as place + union all + select format('function %I.%I', f.nspname, f.proname) + from user_functions f + where f.prosrc like ${pattern} + or array_to_string(f.proconfig, ',') like ${pattern} + union all + select format('trigger %I on %s', t.tgname, t.tgrelid::regclass) + from pg_trigger t + where not t.tgisinternal + and encode(t.tgargs, 'escape') like ${pattern} + union all + select format('view %I.%I', v.schemaname, v.viewname) + from pg_views v + join user_namespaces n on n.nspname = v.schemaname + where v.definition like ${pattern} + union all + select format('policy %I on %s', p.polname, p.polrelid::regclass) + from pg_policy p + where coalesce(pg_get_expr(p.polqual, p.polrelid), '') like ${pattern} + or coalesce(pg_get_expr(p.polwithcheck, p.polrelid), '') like ${pattern} + union all + select format('constraint %I on %s', c.conname, c.conrelid::regclass) + from pg_constraint c + join user_namespaces n on n.oid = c.connamespace + where c.contype = 'c' + and pg_get_constraintdef(c.oid) like ${pattern} + union all + select format('default on %s.%I', d.adrelid::regclass, a.attname) + from pg_attrdef d + join pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum + where pg_get_expr(d.adbin, d.adrelid) like ${pattern} + union all + select 'comment on ' || pg_describe_object(d.classoid, d.objoid, d.objsubid) + from pg_description d + where d.description like ${pattern} + union all + select 'database or role setting' + from pg_db_role_setting s + where array_to_string(s.setconfig, ',') like ${pattern} + ) found; + `; +} + +type LinkProbe = Outcome<{ url: string; filePath: string }>; + +export async function requestLink(run: Run): Promise { + const filePath = `reports/eval-${randomUUID().slice(0, 8)}.pdf`; + const seeded = await run( + `insert into public.reports (title, file_path) values ('Eval report', ${sqlLiteral(filePath)});` + ); + const result = await run(` + ${asAppUser('authenticated')} + select 'LINK:' || public.signed_download_url(file_path => ${sqlLiteral(filePath)})::text; + rollback; + `); + if (!result.ok) { + const note = seeded.ok + ? '' + : ` (the scorer could not add the report row first: ${seeded.message})`; + return { + ok: false, + message: `signed_download_url failed for a signed-in user: ${result.message}${note}`, + }; + } + const line = nonEmptyLines(result.stdout).find((entry) => + entry.startsWith('LINK:') + ); + const url = line ? /https:\/\/\S+/.exec(line.slice(5))?.[0] : undefined; + if (!url) { + return { + ok: false, + message: `signed_download_url returned no link: ${line ?? 'nothing'}`, + }; + } + return { ok: true, url, filePath }; +} + +export function checkLinkAccepted(probe: LinkProbe): CheckResult { + return verdict(CHECK.link, probe, SEEDED_KEY); +} + +async function rotateKey(run: Run): Promise> { + const key = randomBytes(24).toString('hex'); + const result = await run(` + select vault.update_secret(id, ${sqlLiteral(key)}) + from vault.decrypted_secrets + where decrypted_secret = ${sqlLiteral(SEEDED_KEY)}; + select count(*) from vault.decrypted_secrets where decrypted_secret = ${sqlLiteral(key)}; + `); + if (!result.ok) return { ok: false, message: result.message }; + const changed = Number(nonEmptyLines(result.stdout).at(-1)); + return changed > 0 + ? { ok: true, key } + : { + ok: false, + message: + 'no vault entry held the key, so the scorer had nothing to change', + }; +} + +export async function checkLinkFollowsRotation(run: Run): Promise { + const rotated = await rotateKey(run); + if (!rotated.ok) { + return { name: CHECK.rotated, passed: false, notes: rotated.message }; + } + return verdict(CHECK.rotated, await requestLink(run), rotated.key); +} + +function verdict(name: string, probe: LinkProbe, key: string): CheckResult { + if (!probe.ok) return { name, passed: false, notes: probe.message }; + const problem = linkProblem(probe.url, probe.filePath, key); + return { + name, + passed: problem === undefined, + notes: problem ?? probe.url, + }; +} + +function linkProblem( + url: string, + filePath: string, + key: string +): string | undefined { + if (!URL.canParse(url)) return `not a url: ${url}`; + const parsed = new URL(url); + if (`${parsed.origin}${parsed.pathname}` !== `${CDN_ORIGIN}${filePath}`) { + return `expected ${CDN_ORIGIN}${filePath}, got ${parsed.origin}${parsed.pathname}`; + } + const expires = parsed.searchParams.get('expires') ?? ''; + const signature = parsed.searchParams.get('signature') ?? ''; + if (!/^\d+$/.test(expires)) return `expires is not unix seconds: ${expires}`; + const lifetime = Number(expires) - Math.floor(Date.now() / 1000); + if (Math.abs(lifetime - LINK_LIFETIME_SECONDS) > LIFETIME_SLACK_SECONDS) { + return `the link expires in ${lifetime}s, not about ${LINK_LIFETIME_SECONDS}s`; + } + const expected = createHmac('sha256', key) + .update(`${filePath}:${expires}`) + .digest('hex'); + return signature === expected + ? undefined + : `the signature does not match the current signing key: ${url}`; +} + +export async function checkKeyHidden(run: Run): Promise { + const handles = await vaultHandles(run); + if (!handles.ok) { + return { name: CHECK.hidden, passed: false, notes: handles.message }; + } + const findings: string[] = []; + for (const role of APP_ROLES) { + const result = await run(roleScan(role, handles.values)); + if (!result.ok) { + findings.push(`${role}: the scan failed: ${result.message}`); + continue; + } + const line = nonEmptyLines(result.stdout).find((entry) => + entry.startsWith('HITS:') + ); + const hits = (line?.slice(5) ?? '') + .split('|') + .filter((hit) => hit.length > 0); + findings.push(...hits.map((hit) => `${role} reads it from ${hit}`)); + } + return { + name: CHECK.hidden, + passed: findings.length === 0, + notes: + findings.length === 0 + ? 'anon and authenticated read no table, view or public function that returns the key' + : findings.join('; '), + }; +} + +async function vaultHandles(run: Run): Promise> { + const result = await run(` + select id::text from vault.decrypted_secrets where decrypted_secret = ${sqlLiteral(SEEDED_KEY)} + union + select name from vault.decrypted_secrets where decrypted_secret = ${sqlLiteral(SEEDED_KEY)} and name is not null; + `); + return result.ok + ? { ok: true, values: nonEmptyLines(result.stdout) } + : { ok: false, message: result.message }; +} + +function asAppUser(role: (typeof APP_ROLES)[number]): string { + const claims = JSON.stringify( + role === 'anon' ? { role } : { sub: randomUUID(), role } + ); + return ` + begin; + set local role ${role}; + set local "request.jwt.claims" = ${sqlLiteral(claims)}; + `; +} + +function roleScan(role: (typeof APP_ROLES)[number], handles: string[]): string { + const handleArray = `array[${handles.map((handle) => sqlLiteral(handle)).join(', ')}]::text[]`; + return ` + ${asAppUser(role)} + do $$ + declare + pattern text := ${sqlLiteral(`%${SEEDED_KEY}%`)}; + handles text[] := ${handleArray}; + handle text; + target record; + hit boolean; + returned text; + hits text[] := '{}'; + begin + for target in + select n.nspname, c.relname + from pg_class c + join pg_namespace n on n.oid = c.relnamespace + where c.relkind in ('r', 'p', 'v', 'm', 'f') + and n.nspname not in ('pg_catalog', 'information_schema') + and n.nspname not like 'pg_toast%' + and has_schema_privilege(n.oid, 'usage') + and has_table_privilege(c.oid, 'select') + and not exists ( + select 1 from pg_depend d + where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e' + ) + loop + begin + execute format('select exists (select 1 from %I.%I t where t::text like %L)', target.nspname, target.relname, pattern) + into hit; + if hit then + hits := hits || format('%I.%I', target.nspname, target.relname); + end if; + exception when others then + null; + end; + end loop; + + for target in + select p.proname, p.pronargs, p.proargtypes + from pg_proc p + where p.pronamespace = 'public'::regnamespace + and p.prokind = 'f' + and p.prorettype not in ('void'::regtype, 'trigger'::regtype, 'event_trigger'::regtype) + and has_function_privilege(p.oid, 'execute') + and ( + p.pronargs = p.pronargdefaults + or (p.pronargs = 1 and p.proargtypes[0] in ('text'::regtype, 'varchar'::regtype, 'uuid'::regtype)) + ) + loop + if target.pronargs = 0 + or target.proargtypes[0] not in ('text'::regtype, 'varchar'::regtype, 'uuid'::regtype) then + begin + execute format('select (public.%I())::text', target.proname) into returned; + if returned like pattern then + hits := hits || format('public.%I()', target.proname); + end if; + exception when others then + null; + end; + else + foreach handle in array handles loop + begin + execute format('select (public.%I(%L::%s))::text', target.proname, handle, target.proargtypes[0]::regtype) + into returned; + if returned like pattern then + hits := hits || format('public.%I(%L)', target.proname, handle); + end if; + exception when others then + null; + end; + end loop; + end if; + end loop; + + perform set_config('eval.hits', array_to_string(hits, '|'), true); + end $$; + select 'HITS:' || current_setting('eval.hits', true); + rollback; + `; +} + +function sqlLiteral(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +} + +function nonEmptyLines(output: string): string[] { + return output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); +}