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
119 changes: 119 additions & 0 deletions evals/docs/build-docs-038-storage-s3-authentication/EVAL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
buildDocsResult,
type CheckResult,
type LocalStackEvalContext,
type LocalStackScorer,
} from '@supabase-evals/core';
import { messageOf } from '../lib/local-stack.js';
import {
applyPendingMigrations,
checkMigrationsWereApplied,
} from './migrations.js';
import {
checkBackup,
checkDesktop,
checkNoFullAccessKey,
installDependencies,
notRun,
PROBE_CHECKS,
probeBackup,
probeDesktop,
readBodies,
readStack,
removeScratch,
type Stack,
setupWorld,
} from './probes.js';

const GUIDE_PATH = 'guides/storage/s3/authentication';

const scorer: LocalStackScorer = async (ctx) => {
try {
const stack = await readStack(ctx).then(
(value): { stack: Stack } => ({ stack: value }),
(error: unknown) => ({ failure: messageOf(error) })
);
const noFullAccessKey = checkNoFullAccessKey(
ctx.hostWorkspace,
'stack' in stack ? stack.stack : undefined
);
const migrations = await applyPendingMigrations(ctx);
const installed = await installDependencies(ctx);

const probes =
'stack' in stack
? await runProbes(ctx, stack.stack, installed)
: PROBE_CHECKS.map((name) => notRun(name, stack.failure));

const checks: CheckResult[] = [
checkMigrationsWereApplied(migrations),
installed,
...probes,
noFullAccessKey,
checkGuideWasRead(ctx),
];

return { passed: checks.every((check) => check.passed), checks };
} catch (error) {
return {
passed: false,
checks: [
{
name: 'scorer evaluated who can reach the notes',
passed: false,
notes: messageOf(error),
},
],
};
}
};

export default scorer;

async function runProbes(
ctx: LocalStackEvalContext,
stack: Stack,
installed: CheckResult
): Promise<CheckResult[]> {
if (!installed.passed) {
return PROBE_CHECKS.map((name) =>
notRun(name, 'the dependencies did not install')
);
}
const setup = await setupWorld(ctx, stack);
if ('failure' in setup) {
return PROBE_CHECKS.map((name) => notRun(name, setup.failure));
}
const { world } = setup;
const backup = await probeBackup(ctx, world);
const desktop = await probeDesktop(ctx, world);
const bodies = await readBodies(ctx, world);
await removeScratch(ctx, world.scratch);

const results = [
...checkDesktop(world, desktop, bodies),
checkBackup(world, backup),
];
return PROBE_CHECKS.map(
(name) =>
results.find((result) => result.name === name) ??
notRun(name, `no result for ${name}`)
);
}

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 S3 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',
};
}
40 changes: 40 additions & 0 deletions evals/docs/build-docs-038-storage-s3-authentication/PROMPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
stage: build
interface: cli
product:
- storage
- auth
topic:
- security
- sdk
services:
- gotrue
- kong
- postgrest
- storage-api
motivation: >-
An S3 client reaches Supabase Storage either with the project's S3 keys,
which skip every access rule, or as a signed-in person, which keeps them.
Customers ask which one limits a person to their own files, and report
signature errors locally when the person's token goes with the wrong key.
This checks that an agent reading the S3 Authentication guide gives a shipped
desktop app access scoped to each person and a server job access to
everything. The prompt omits the guide's vocabulary on purpose, so read
README.md before editing it.
---

Fernnotes has a desktop app that syncs each person's notes to our Supabase
project, and a nightly backup job on our server that copies all of them. Both
use the AWS S3 SDK. STORAGE.md explains how it fits together. The two
storage.js files that hand out the clients are still empty.

People sign in to sync. Each person must only ever be able to see and change
their own notes, even with a tampered copy of the desktop app, since everything
in desktop/ ships to customers. The backup job has to get everyone's notes. Set
that up in the local project and make sure it works on the local stack.

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/storage/s3/authentication.md
98 changes: 98 additions & 0 deletions evals/docs/build-docs-038-storage-s3-authentication/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# build-docs-038-storage-s3-authentication

## What this eval measures

The subject is [S3 Authentication](https://supabase.com/docs/guides/storage/s3/authentication), 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 gives each S3
client the access it should have.

One claim: an S3 client made for a signed-in person reaches only that person's notes, and the server job's client
reaches everyone's.

The starting claim was that the S3 endpoint accepts valid keys and refuses others. That held on the local stack, and it
is narrowed here to which credential goes where.

## Does an existing eval cover it?

No. `build-docs-008-storage-access-control` scores policies and bucket visibility through the Storage REST API from a
browser. `build-docs-023-storage-bucket-fundamentals` scores bucket visibility and limits. Neither uses the S3 protocol
or chooses between credentials. Here the bucket is given, and the policies are part of the task because a per-person
S3 client goes through them.

`a signed-in user can sync a note again` overlaps the access control page, and 008 leaves replacing a file out of
scope. It belongs here because over S3 every upload is an upsert. Even a first upload needs the read rule as well as the
insert rule, and an overwrite also needs the update rule, which a REST upload without upsert does not.

## Do not reintroduce the vocabulary

Keep all of these out of `PROMPT.md`:

access key, secret access key, session token, token, JWT, anon, publishable, service role, secret key, credentials,
RLS, row level security, policy, `storage.objects`, bypass, region, endpoint, `forcePathStyle`, stub, project ref,
`supabase status`.

"S3" stays, because `package.json` and `STORAGE.md` already name the SDK. `STORAGE.md` names the factory's argument
`accessToken`, as the app's own code would.

## The seed carries the contract

- `local/STORAGE.md` fixes the bucket, the folder per user id, the two factory names and their arguments, which folder
ships, and which env file each side reads. The probes need named entry points.
- The init migration makes the `notes` bucket, private, with no policies on it.
- `local/desktop/.env` holds the api url and the publishable key, as the app already has. On the pinned Storage the
S3 endpoint does not accept the publishable key, so a client built from what the file holds fails to sign.
- `local/backup/.env` holds the api url only.
- `local/package.json` and `local/package-lock.json` pin `@aws-sdk/client-s3`, `@supabase/supabase-js` and everything
under them.

## The scorer installs packages

The scorer runs `npm ci` in the sandbox, so it needs network access to the npm registry. When the install fails, every
probe check reports not run and the eval fails. A failed `project dependencies installed` is a lost run, not evidence
about the page. An agent that adds a package has to leave the lockfile in step with `package.json`.

## How the checks read the end state

- The scorer copies `desktop/` on its own into a fresh temporary directory outside the workspace, links the
workspace's `node_modules` beside it, and loads `storage.js` from there with only that folder's `.env` and an
otherwise empty environment. A desktop client that reads a relative path into `backup/` fails to load, as it would in
the installer. An absolute path into the workspace is not caught.
- `backup/storage.js` loads in place with `backup/.env`.
- Each run signs up two users and adds one note for each, with names scoped to the run. The scorer sets `owner` and
`owner_id` on each note to its user, so policies keyed on the folder and policies keyed on the owner both pass.
- A read refusal counts only as `NoSuchKey` or `AccessDenied`, and a write refusal only as `AccessDenied`. A signature
error means the client never signed in, and the check reads it as not measured.
- `a signed-in user cannot change another user's notes` overwrites their note and adds one to their folder. The second
fails the check under owner-keyed policies too, because it takes a key that person's sync would write.
- `no file in the desktop app holds a full-access key from the project` is a literal match. It scans `desktop/` for
the S3 secret, service role key, secret key and JWT secret that `supabase status` reports, so an encoded or fetched
copy slips past it. The refusal checks catch a desktop client that gets such a key another way and uses it.
- The scorer applies pending migrations, so score once per stack.

## Do not drop the positive controls

The two refusal checks and the key scan pass for a desktop app that reaches nothing. `a signed-in user can list and read
their own notes`, `a signed-in user can upload a new note` and `a signed-in user can sync a note again` make them mean
something. `the backup job reads every user's notes` is the positive control for the server side.

## The guide has to actually be read

`the agent read the S3 authentication 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, install and key scan checks, and both refusal checks for an agent that gives the desktop the per-person
client. The signal is expected in `a signed-in user can sync a note again`, which fails a solution with read and insert
rules only. The own-notes control fails an agent that uses the publishable key from `desktop/.env`.

## What this eval does not score

- **What Storage accepts.** Refusing the publishable key and signing a person in only with `stub` and the legacy anon
key are what the storage-api of CLI 2.117.0 (v1.72.1) does. When Storage accepts the new keys, an agent that uses the
publishable key turns green with no docs change. Read a change in verdict after a CLI upgrade that way first.
- **Deleting notes.** `STORAGE.md` does not ask for it.
- **Token expiry.** The factory takes a token on every call.
- **Whether `backup/.env` stays out of git.** The prompt does not say.
- **Hosted and self-hosted values.** The project ref, the direct storage hostname and the self-hosted tenant id are out
of reach locally.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# How Fernnotes stores notes

Notes are files in the `notes` bucket of our Supabase project. Each person's notes sit in a folder named after their
user id: `<user id>/<note name>.md`.

## Desktop app

`desktop/` is the desktop app. Everything in that folder ships in the installer, and customers can open and change any
of it. The app reads its settings from `desktop/.env`.

`desktop/sync.js` signs the person in, then gets a client from `createStorageClient(accessToken)` in
`desktop/storage.js`. It passes the signed-in person's access token, and gets back an `S3Client` from
`@aws-sdk/client-s3`. Sync lists the person's folder, downloads their notes, and uploads each changed note to the same
key again.

## Backup job

`backup/` runs on our own server and never ships. It reads its settings from `backup/.env`.

`backup/nightly.js` gets a client from `createBackupClient()` in `backup/storage.js`, which returns an `S3Client`. It
lists the whole bucket and copies every note.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SUPABASE_URL=http://127.0.0.1:54321
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { GetObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';
import { createBackupClient } from './storage.js';

const BUCKET = 'notes';

export async function backUpEverything(targetDir) {
const client = await createBackupClient();
let token;
do {
const page = await client.send(
new ListObjectsV2Command({ Bucket: BUCKET, ContinuationToken: token })
);
for (const object of page.Contents ?? []) {
const { Body } = await client.send(
new GetObjectCommand({ Bucket: BUCKET, Key: object.Key })
);
const path = join(targetDir, object.Key);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, await Body.transformToByteArray());
}
token = page.IsTruncated ? page.NextContinuationToken : undefined;
} while (token);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function createBackupClient() {
throw new Error('createBackupClient is not set up yet');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SUPABASE_URL=http://127.0.0.1:54321
SUPABASE_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function createStorageClient(accessToken) {
throw new Error('createStorageClient is not set up yet');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
GetObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
} from '@aws-sdk/client-s3';
import { createClient } from '@supabase/supabase-js';
import { createStorageClient } from './storage.js';

const BUCKET = 'notes';

export async function signIn(email, password) {
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_PUBLISHABLE_KEY
);
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
return data.session;
}

export async function listNotes(session) {
const client = await createStorageClient(session.access_token);
const { Contents = [] } = await client.send(
new ListObjectsV2Command({ Bucket: BUCKET, Prefix: `${session.user.id}/` })
);
return Contents.map((object) => object.Key);
}

export async function readNote(session, name) {
const client = await createStorageClient(session.access_token);
const { Body } = await client.send(
new GetObjectCommand({ Bucket: BUCKET, Key: `${session.user.id}/${name}` })
);
return Body.transformToString();
}

export async function saveNote(session, name, text) {
const client = await createStorageClient(session.access_token);
await client.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: `${session.user.id}/${name}`,
Body: text,
ContentType: 'text/markdown',
})
);
}
Loading
Loading