Skip to content
Draft
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
146 changes: 146 additions & 0 deletions evals/docs/build-docs-039-auth-mfa/EVAL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import {
buildDocsResult,
type CheckResult,
type LocalStackEvalContext,
type LocalStackScorer,
} from '@supabase-evals/core';
import { restartStack } from '../lib/local-stack.js';
import { turnCodesOn } from './config.js';
import {
applyPendingMigrations,
checkMigrationsWereApplied,
} from './migrations.js';
import {
CHECK,
checkCodesAllowed,
checkHalfway,
checkPlainReads,
checkPlainWrites,
checkSkippedReads,
checkSkippedWrites,
checkStackStarts,
checkStaleDevice,
checkTypedReads,
checkTypedWrites,
notRun,
probeCodes,
type Setup,
setupWorld,
signInWithCode,
type World,
} from './probes.js';

const GUIDE_PATH = /guides\/auth\/auth-mfa(?:\.md)?(?:[?#]|$)/;

const scorer: LocalStackScorer = async (ctx) => {
try {
const started = await restartStack(ctx);
const migrations = await applyPendingMigrations(ctx);
const codes = started.ok
? await probeCodes(ctx)
: { ok: false as const, message: started.message };
const ready = !started.ok
? started
: codes.ok
? codes
: await turnCodesOn(ctx);
const setup: Setup = ready.ok
? await setupWorld(ctx)
: { ok: false, message: ready.message };
const world = setup.ok ? setup.world : undefined;
const setupFailure = setup.ok ? '' : setup.message;
const probe = (
name: string,
run: (world: World) => Promise<CheckResult>
): Promise<CheckResult> => gated(world, setupFailure, name, run);

const plainReads = await probe(CHECK.plainReads, (w) => checkPlainReads(w));
const plainWrites = await probe(CHECK.plainWrites, (w) =>
checkPlainWrites(ctx, w)
);
const halfway = await probe(CHECK.halfway, (w) => checkHalfway(w));
const skippedReads = await probe(CHECK.skippedReads, (w) =>
checkSkippedReads(ctx, w)
);
const staleDevice = await probe(CHECK.staleDevice, (w) =>
checkStaleDevice(w)
);
const typedSignIn = world
? await signInWithCode(ctx, world)
: { ok: false as const, message: setupFailure };
const typedReads = await probe(CHECK.typedReads, (w) =>
checkTypedReads(typedSignIn, w)
);
const typedWrites = await probe(CHECK.typedWrites, (w) =>
checkTypedWrites(ctx, typedSignIn, w)
);
const skippedWrites = await probe(CHECK.skippedWrites, (w) =>
checkSkippedWrites(ctx, w)
);

const checks: CheckResult[] = [
checkStackStarts(started),
checkMigrationsWereApplied(migrations),
started.ok
? checkCodesAllowed(codes)
: notRun(CHECK.codesAllowed, started.message),
plainReads,
plainWrites,
halfway,
skippedReads,
skippedWrites,
staleDevice,
typedReads,
typedWrites,
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 who can open a journal',
passed: false,
notes: message,
},
],
};
}
};

export default scorer;

async function gated(
world: World | undefined,
setupFailure: string,
name: string,
run: (world: World) => Promise<CheckResult>
): Promise<CheckResult> {
if (!world) return notRun(name, setupFailure);
try {
return await run(world);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { name, passed: false, notes: message.slice(0, 300) };
}
}

function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult {
const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) =>
call.pages?.some((page) => GUIDE_PATH.test(page.url))
);
const withContent = calls.filter((call) => call.hasContent);
return {
name: 'the agent read the multi-factor authentication 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',
};
}
42 changes: 42 additions & 0 deletions evals/docs/build-docs-039-auth-mfa/PROMPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
stage: build
interface: cli
product:
- auth
- database
topic:
- rls
- security
services:
- gotrue
- kong
- postgrest
motivation: >-
An app that offers a second sign-in step has to lock data until people who
turned it on complete it, and keep working for everyone else. Customers end
up with rules that refuse every request, or that let a session that
skipped the code through. This checks that an agent reading the
multi-factor authentication guide locks a journal behind a code only for
the people who turned one on. The prompt omits the guide's vocabulary on
purpose, so read README.md before editing it.
---

Dayline is a journaling app, and some people want their journal behind a
second lock. Let people turn on a six-digit code from an authenticator app
like Google Authenticator. They switch it on by scanning a QR code and typing
the first code, so someone who gives up halfway has not switched it on.

Once it is on, their entries and habits stay locked after they sign in with
their password, until they type a fresh code. If they were already signed in
on another device when they switched it on, that device is locked too until a
code is typed there. People who never switch it on keep using Dayline with
just their password, the same as today.

Our front-end team builds the screens. Set up the rest 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/auth/auth-mfa.md
100 changes: 100 additions & 0 deletions evals/docs/build-docs-039-auth-mfa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# build-docs-039-auth-mfa

## What this eval measures

The subject is [Multi-Factor Authentication](https://supabase.com/docs/guides/auth/auth-mfa), 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 locks data behind a
second step only for the people who turned one on.

One claim: once someone turns on an authenticator code, their rows open only after they type it, on every device, and
everyone without a code keeps working with a password.

The eval expects a rule that answers every request. Signed-in users cannot read `auth.mfa_factors`, so the rule has to
learn whether someone has a code without reading that table as the user. A rule that tries fails every request with
`42501 permission denied for table mfa_factors`, and the controls catch it.

## Do not reintroduce the vocabulary

The prompt keeps "authenticator app", because a user has no other name for it. Keep all of these out of `PROMPT.md`:

MFA, multi-factor, two-factor, 2FA, second factor, factor, TOTP, enroll, verify, challenge, AAL, aal1, aal2, assurance
level, JWT, claim, token, session, refresh, restrictive, permissive, policy, RLS, row level security, mfa_factors,
security definer, authenticated, config.toml, `[auth.mfa.totp]`, enroll_enabled, verify_enabled.

## The seed carries the contract

`local/supabase/migrations/20240101000000_init.sql` is a journal app with two tables. Three things in the seed are
load-bearing.

- **Both tables already have a permissive rule for their owner.** A second permissive rule that asks for the code
changes nothing, because rules of that kind combine with OR. Only a rule required in addition, or a rewrite of the
existing ones, passes.
- **Two tables, not one.** Every probe reads and writes both, so a rule on one table does not pass.
- **`[auth.mfa.totp]` is off in `local/supabase/config.toml`**, as `supabase init` writes it.

`enable_confirmations = false` lets the scorer sign people up without a mailbox.

The prompt says which rule applies to people without a code: they keep working. It also says someone who gave up
halfway has not turned the code on, and that a device signed in before the code was turned on is locked too. Each of
those has its own check.

## Codes are scored once, then turned on

`the project lets people turn on an authenticator-app code` runs on the agent's own `config.toml`. The scorer signs up a
person, sets up a code and types it. That check reflects the pinned CLI's local default, which has codes off. Hosted
projects have them on.

If the check fails, the scorer sets `enroll_enabled = true` and `verify_enabled = true` under `[auth.mfa.totp]` in the
workspace's `config.toml` and restarts the stack. Every other check then measures the agent's rules, not the switch.
The scorer restores nothing afterwards, so score once per stack.

## Do not drop the positive controls

The refusal checks pass for a project where nobody can read or change anything. The controls stop that:

- `someone without a code reads their journal with a password` and `someone without a code adds, changes and removes
journal rows with a password` fail a rule that locks everyone, or one that blocks changes for everyone.
- `a person who typed their code reads their journal` and `a person who typed their code adds, changes and removes
journal rows` fail a rule that locks the code holder for good.
- `a device signed in before the code was turned on is locked once it is on` first reads the rows from that device
before the code is turned on. If that read fails, the check reports could-not-measure.

The refusal checks count rows as the superuser. An insert must write nothing, and an update or delete must leave the
seeded row as it was. Any error is accepted as a refusal once the superuser read confirms that, so a trigger that raises
its own error passes. The skipped-code reads pass on an empty result or any error.

Every person and row is made by the scorer after the agent's work, with names scoped to the run. The scorer types the
code itself, computed from the secret it gets back when it sets the code up.

## Order of the scorer

The scorer restarts the stack first, so Auth runs on the project's `config.toml` whether or not the agent restarted it.
Restarting needs the services in `services:`, so a harness that starts every service also passes. It then applies
pending migrations with `supabase migration up --local`, which writes to the database. Then it probes codes, and turns
them on and restarts if needed.

When the scorer cannot set up a code even after turning codes on, every check about a code holder reports `not run`
with the reason. The skipped-code writes run last, because a write that gets through would change rows the other probes
read.

## The guide has to actually be read

`the agent read the multi-factor authentication guide the prompt referenced` requires a docs call that reached the page
with content. A read of the TOTP or phone page alone does not count. Read `docs.calls` before reading a score.

## Checks expected to saturate

The restart, the migration check, and the two skipped-code refusals. A rule that refuses every request passes both
refusals. The device signed in before carries the same token level as a fresh password sign-in, so it moves with the
skipped-code reads. Only a rule that reads whether someone has a code from the token, such as a claim added at sign-in,
separates the two. The signal is expected in the code check and the five controls.

## What this eval does not score

- **Screens and client code.** No client is seeded, so the scorer runs the sign-in and code steps itself.
- **Removing a code.** The prompt does not ask for it.
- **Phone codes.** The prompt asks for an authenticator app only.
- **Functions that bypass the rules.** A function that runs as its owner skips row rules. The seed has none, and the
prompt does not ask for one.
- **Anyone who is not signed in.** The seed grants them nothing.
- **How the agent applied its change.** Any route that leaves it applied passes.
74 changes: 74 additions & 0 deletions evals/docs/build-docs-039-auth-mfa/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { LocalStackEvalContext } from '@supabase-evals/core';
import { readStack, restartStack, type Step } from '../lib/local-stack.js';

const CONFIG = 'supabase/config.toml';
const SECTION = '[auth.mfa.totp]';
const SWITCHES = ['enroll_enabled = true', 'verify_enabled = true'];

type Exec = Pick<LocalStackEvalContext, 'exec'>;

export async function turnCodesOn(ctx: Exec): Promise<Step> {
const read = await ctx.exec(`cat ${CONFIG}`);
if (read.exitCode !== 0) {
return { ok: false, message: `could not read ${CONFIG}` };
}
const encoded = Buffer.from(withCodesOn(read.stdout ?? ''), 'utf8').toString(
'base64'
);
const written = await ctx.exec(`echo ${encoded} | base64 -d > ${CONFIG}`);
if (written.exitCode !== 0) {
return { ok: false, message: `could not write ${CONFIG}` };
}
const restarted = await restartStack(ctx);
if (!restarted.ok) {
return {
ok: false,
message: `the stack did not restart with codes on: ${restarted.message}`,
};
}
return waitForAuth(ctx);
}

async function waitForAuth(ctx: Exec): Promise<Step> {
let last = '';
for (let attempt = 0; attempt < 30; attempt += 1) {
try {
const stack = await readStack(ctx);
const response = await fetch(`${stack.apiUrl}/auth/v1/health`, {
headers: { apikey: stack.clientKey },
});
if (response.ok) return { ok: true, message: '' };
last = `health returned ${response.status}`;
} catch (error) {
last = error instanceof Error ? error.message : String(error);
}
await new Promise((resolve) => {
setTimeout((): void => resolve(undefined), 2000);
});
}
return {
ok: false,
message: `Auth did not answer after the restart: ${last.slice(0, 200)}`,
};
}

export function withCodesOn(toml: string): string {
const lines = toml.split('\n');
const start = lines.findIndex((line) => line.trim() === SECTION);
if (start < 0) {
return `${toml.trimEnd()}\n\n${SECTION}\n${SWITCHES.join('\n')}\n`;
}
const next = lines.findIndex(
(line, index) => index > start && /^\s*\[/.test(line)
);
const end = next < 0 ? lines.length : next;
const kept = lines
.slice(start + 1, end)
.filter((line) => !/^\s*(enroll_enabled|verify_enabled)\s*=/.test(line));
return [
...lines.slice(0, start + 1),
...SWITCHES,
...kept,
...lines.slice(end),
].join('\n');
}
Loading
Loading