test(supabase): isolated Supabase stack and real-stack suite for M1
scripts/db-sandbox.sh (pnpm db:sandbox): DEV images on an own network, loopback ports distinct from DEV, no volume, secrets generated outside Git; fresh and upgrade modes through the CLI's migration up, test db and gen types with --db-url. packages/supabase/tests/sandbox: M1 sign-up and confirmation, reads and refusals per role, residual GoTrue admin path, correlation cap, concurrent sessions.
This commit is contained in:
1 parent
6bf69787cb
commit
08abe42c48
6 files changed
+791
-1
No files matched your search
@@ -34,6 +34,7 @@
|
||||
"db:test": "bash scripts/supabase.sh test db",
|
||||
"db:types": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript > packages/supabase/src/database.types.ts",
|
||||
"db:types:check": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts",
|
||||
"db:sandbox": "bash scripts/db-sandbox.sh",
|
||||
"assets:upload": "bash scripts/upload-sheet-assets.sh",
|
||||
"e2e:sheet-assets": "bash scripts/sheet-assets-e2e.sh",
|
||||
"build:preview": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build",
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
"test:run": "vitest run",
|
||||
"lint": "eslint . --max-warnings 0",
|
||||
"build": "tsc -p tsconfig.json --noEmit",
|
||||
"test:e2e": "vitest run --config vitest.e2e.config.ts"
|
||||
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
||||
"test:sandbox": "vitest run --config vitest.sandbox.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@supabase/supabase-js": "^2.100.0",
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Access to the throwaway stack of `pnpm db:sandbox` (scripts/db-sandbox.sh):
|
||||
* real GoTrue, PostgREST and PostgreSQL sessions, never the DEV stack. The
|
||||
* script passes the endpoints and the generated keys through the environment;
|
||||
* the database password reaches `docker exec` through the environment too,
|
||||
* never through a command argument.
|
||||
*/
|
||||
import { execFile } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
const need = (name: string): string => {
|
||||
const value = process.env[name]
|
||||
if (!value)
|
||||
throw new Error(`${name} missing: run through pnpm db:sandbox test`)
|
||||
return value
|
||||
}
|
||||
|
||||
export const stack = {
|
||||
container: need('SANDBOX_DB_CONTAINER'),
|
||||
authUrl: need('SANDBOX_AUTH_URL'),
|
||||
restUrl: need('SANDBOX_REST_URL'),
|
||||
mailUrl: need('SANDBOX_MAIL_URL'),
|
||||
anonKey: need('SANDBOX_ANON_KEY'),
|
||||
serviceKey: need('SANDBOX_SERVICE_KEY'),
|
||||
}
|
||||
const PG_PASSWORD = need('SANDBOX_PG_PASSWORD')
|
||||
export const PASSWORD = 'Sandbox-only-pw-1'
|
||||
|
||||
/** One psql session as postgres; resolves with stdout (tuples only) or rejects with stderr. */
|
||||
export function sql(script: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = execFile(
|
||||
'docker',
|
||||
[
|
||||
'exec',
|
||||
'-i',
|
||||
'-e',
|
||||
'PGPASSWORD',
|
||||
stack.container,
|
||||
'psql',
|
||||
'-X',
|
||||
'-q',
|
||||
'-t',
|
||||
'-A',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-U',
|
||||
'postgres',
|
||||
'-d',
|
||||
'postgres',
|
||||
'-v',
|
||||
'ON_ERROR_STOP=1',
|
||||
],
|
||||
{
|
||||
env: { ...process.env, PGPASSWORD: PG_PASSWORD },
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
},
|
||||
(error, stdout, stderr) =>
|
||||
error
|
||||
? reject(new Error(stderr || error.message))
|
||||
: resolve(stdout.trim()),
|
||||
)
|
||||
child.stdin?.end(script)
|
||||
})
|
||||
}
|
||||
|
||||
/** Same session, but settles with the outcome instead of throwing (for refusal checks). */
|
||||
export async function sqlOutcome(
|
||||
script: string,
|
||||
): Promise<{ ok: boolean; out: string }> {
|
||||
try {
|
||||
return { ok: true, out: await sql(script) }
|
||||
} catch (error) {
|
||||
return { ok: false, out: (error as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
export const uniqueEmail = (tag: string) =>
|
||||
`${tag}-${randomUUID().slice(0, 8)}@sandbox.local`
|
||||
|
||||
async function authCall(
|
||||
path: string,
|
||||
body: unknown,
|
||||
key = stack.anonKey,
|
||||
): Promise<Response> {
|
||||
return fetch(stack.authUrl + path, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
apikey: stack.anonKey,
|
||||
Authorization: `Bearer ${key}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function signIn(
|
||||
email: string,
|
||||
password = PASSWORD,
|
||||
): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
const res = await authCall('/token?grant_type=password', { email, password })
|
||||
return {
|
||||
status: res.status,
|
||||
body: (await res.json()) as Record<string, unknown>,
|
||||
}
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
id: string
|
||||
email: string
|
||||
token: string
|
||||
}
|
||||
|
||||
/** A confirmed account created by the admin API, signed in. */
|
||||
export async function confirmedAccount(tag: string): Promise<Account> {
|
||||
const email = uniqueEmail(tag)
|
||||
const res = await authCall(
|
||||
'/admin/users',
|
||||
{ email, password: PASSWORD, email_confirm: true },
|
||||
stack.serviceKey,
|
||||
)
|
||||
const user = (await res.json()) as { id: string }
|
||||
const session = await signIn(email)
|
||||
return { id: user.id, email, token: session.body.access_token as string }
|
||||
}
|
||||
|
||||
/** Public sign-up (no session until confirmation). */
|
||||
export async function signUp(
|
||||
email: string,
|
||||
): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
const res = await authCall('/signup', { email, password: PASSWORD })
|
||||
return {
|
||||
status: res.status,
|
||||
body: (await res.json()) as Record<string, unknown>,
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the confirmation link GoTrue mailed to this address; returns the HTTP status. */
|
||||
export async function confirmByMail(email: string): Promise<number> {
|
||||
const search = (await (
|
||||
await fetch(
|
||||
`${stack.mailUrl}/api/v1/search?query=${encodeURIComponent('to:' + email)}`,
|
||||
)
|
||||
).json()) as {
|
||||
messages: { ID: string }[]
|
||||
}
|
||||
const message = (await (
|
||||
await fetch(`${stack.mailUrl}/api/v1/message/${search.messages[0].ID}`)
|
||||
).json()) as { Text: string }
|
||||
const link = message.Text.match(
|
||||
new RegExp(
|
||||
`${stack.authUrl.replace(/[.:/]/g, '\\$&')}/verify\\?[^\\s)\\]]+`,
|
||||
),
|
||||
)?.[0]
|
||||
if (!link) throw new Error('no confirmation link in the mail')
|
||||
return (await fetch(link.replace(/&/g, '&'), { redirect: 'manual' }))
|
||||
.status
|
||||
}
|
||||
|
||||
/** GoTrue admin link for any account: the residual path of contract §6.3. */
|
||||
export async function adminMagicLinkSession(
|
||||
email: string,
|
||||
): Promise<string | null> {
|
||||
const res = await authCall(
|
||||
'/admin/generate_link',
|
||||
{ type: 'magiclink', email },
|
||||
stack.serviceKey,
|
||||
)
|
||||
const body = (await res.json()) as {
|
||||
action_link?: string
|
||||
properties?: { action_link?: string }
|
||||
}
|
||||
const link = body.action_link ?? body.properties?.action_link
|
||||
if (!link) return null
|
||||
const verify = await fetch(link, { redirect: 'manual' })
|
||||
return new URLSearchParams(
|
||||
(verify.headers.get('location') ?? '').split('#')[1] ?? '',
|
||||
).get('access_token')
|
||||
}
|
||||
|
||||
export async function adminDeleteUser(id: string): Promise<number> {
|
||||
const res = await fetch(`${stack.authUrl}/admin/users/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
apikey: stack.anonKey,
|
||||
Authorization: `Bearer ${stack.serviceKey}`,
|
||||
},
|
||||
})
|
||||
return res.status
|
||||
}
|
||||
|
||||
export interface RestResult {
|
||||
status: number
|
||||
body: unknown
|
||||
text: string
|
||||
headers: Headers
|
||||
}
|
||||
|
||||
/** A PostgREST request with the given bearer token (a user's, or the anon / service key). */
|
||||
export async function rest(
|
||||
path: string,
|
||||
token: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<RestResult> {
|
||||
const res = await fetch(stack.restUrl + path, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(init.headers ?? {}),
|
||||
},
|
||||
})
|
||||
const text = await res.text()
|
||||
let body: unknown = text
|
||||
try {
|
||||
body = JSON.parse(text)
|
||||
} catch {
|
||||
// not JSON: keep the text
|
||||
}
|
||||
return { status: res.status, body, text, headers: res.headers }
|
||||
}
|
||||
|
||||
/** POST /rpc/<fn>: the way the app calls every RPC (terms stay out of URLs). */
|
||||
export function rpc(
|
||||
fn: string,
|
||||
args: Record<string, unknown>,
|
||||
token: string,
|
||||
headers: Record<string, string> = {},
|
||||
) {
|
||||
return rest(`/rpc/${fn}`, token, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(args),
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
/** The PostgREST error code of a refusal, or null. */
|
||||
export const errorCode = (result: RestResult): string | null =>
|
||||
typeof result.body === 'object' &&
|
||||
result.body !== null &&
|
||||
'code' in result.body
|
||||
? String((result.body as { code: unknown }).code)
|
||||
: null
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* V1-1.1 workspaces (M1) on the real stack of `pnpm db:sandbox`: the sign-up
|
||||
* chain, reads and refusals through PostgREST per role, the residual GoTrue
|
||||
* admin path, the audit correlation cap, and concurrent sessions.
|
||||
* Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8.1, §9.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import {
|
||||
adminDeleteUser,
|
||||
adminMagicLinkSession,
|
||||
confirmByMail,
|
||||
confirmedAccount,
|
||||
errorCode,
|
||||
rest,
|
||||
rpc,
|
||||
signIn,
|
||||
signUp,
|
||||
sql,
|
||||
sqlOutcome,
|
||||
stack,
|
||||
uniqueEmail,
|
||||
type Account,
|
||||
} from './stack'
|
||||
|
||||
const workspaceOf = (userId: string) =>
|
||||
sql(`select id from public.workspaces where personal_user_id = '${userId}'`)
|
||||
const holderCount = (userId: string) =>
|
||||
sql(`select count(*) from public.workspaces w join public.workspace_members m
|
||||
on m.workspace_id = w.id and m.user_id = w.personal_user_id and m.member_role = 'holder'
|
||||
where w.personal_user_id = '${userId}'`)
|
||||
|
||||
describe('sign-up and confirmation', () => {
|
||||
it('creates the workspace in the sign-up transaction, readable only after confirmation', async () => {
|
||||
const email = uniqueEmail('ws-signup')
|
||||
const signup = await signUp(email)
|
||||
expect(signup.status).toBe(200)
|
||||
expect(signup.body.access_token).toBeUndefined()
|
||||
const id = signup.body.id as string
|
||||
expect(await holderCount(id)).toBe('1')
|
||||
const early = await signIn(email)
|
||||
expect(early.body.error_code).toBe('email_not_confirmed')
|
||||
expect(await confirmByMail(email)).toBe(303)
|
||||
const session = await signIn(email)
|
||||
const read = await rest(
|
||||
'/workspaces?select=id,kind,personal_user_id',
|
||||
session.body.access_token as string,
|
||||
)
|
||||
expect(read.body).toEqual([
|
||||
{ id: await workspaceOf(id), kind: 'personal', personal_user_id: id },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('reads and refusals per role', () => {
|
||||
let a: Account
|
||||
let b: Account
|
||||
let wA: string
|
||||
let wB: string
|
||||
|
||||
beforeAll(async () => {
|
||||
a = await confirmedAccount('ws-a')
|
||||
b = await confirmedAccount('ws-b')
|
||||
wA = await workspaceOf(a.id)
|
||||
wB = await workspaceOf(b.id)
|
||||
})
|
||||
|
||||
it('each account reads exactly its workspace and membership', async () => {
|
||||
expect((await rest('/workspaces?select=id', a.token)).body).toEqual([
|
||||
{ id: wA },
|
||||
])
|
||||
expect(
|
||||
(await rest('/workspace_members?select=user_id,member_role', a.token))
|
||||
.body,
|
||||
).toEqual([{ user_id: a.id, member_role: 'holder' }])
|
||||
const head = await rest('/workspaces?select=id', b.token, {
|
||||
method: 'HEAD',
|
||||
headers: { Prefer: 'count=exact' },
|
||||
})
|
||||
expect(head.headers.get('content-range')).toBe('0-0/1')
|
||||
})
|
||||
|
||||
it('naming another account or workspace returns nothing', async () => {
|
||||
expect(
|
||||
(await rest(`/workspaces?select=id&id=eq.${wA}`, b.token)).body,
|
||||
).toEqual([])
|
||||
expect(
|
||||
(await rest(`/workspaces?select=id&personal_user_id=eq.${a.id}`, b.token))
|
||||
.body,
|
||||
).toEqual([])
|
||||
expect(
|
||||
(
|
||||
await rest(
|
||||
`/workspace_members?select=user_id&workspace_id=eq.${wA}`,
|
||||
b.token,
|
||||
)
|
||||
).body,
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses every write, for a user, the anon key and the service key', async () => {
|
||||
const attempts: [string, string, RequestInit, number][] = [
|
||||
[
|
||||
'/workspaces',
|
||||
b.token,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ kind: 'personal', personal_user_id: b.id }),
|
||||
},
|
||||
403,
|
||||
],
|
||||
[
|
||||
'/workspace_members',
|
||||
b.token,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
workspace_id: wA,
|
||||
user_id: b.id,
|
||||
member_role: 'holder',
|
||||
}),
|
||||
},
|
||||
403,
|
||||
],
|
||||
[
|
||||
`/workspaces?id=eq.${wB}`,
|
||||
b.token,
|
||||
{ method: 'PATCH', body: JSON.stringify({ personal_user_id: a.id }) },
|
||||
403,
|
||||
],
|
||||
[
|
||||
`/workspace_members?user_id=eq.${b.id}`,
|
||||
b.token,
|
||||
{ method: 'DELETE' },
|
||||
403,
|
||||
],
|
||||
['/workspaces?select=id', stack.anonKey, {}, 401],
|
||||
['/workspace_members?select=user_id', stack.anonKey, {}, 401],
|
||||
['/workspaces?select=id', stack.serviceKey, {}, 403],
|
||||
[
|
||||
'/workspace_members',
|
||||
stack.serviceKey,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
workspace_id: wA,
|
||||
user_id: b.id,
|
||||
member_role: 'holder',
|
||||
}),
|
||||
},
|
||||
403,
|
||||
],
|
||||
]
|
||||
for (const [path, token, init, status] of attempts) {
|
||||
const result = await rest(path, token, init)
|
||||
expect([path, result.status, errorCode(result)]).toEqual([
|
||||
path,
|
||||
status,
|
||||
'42501',
|
||||
])
|
||||
expect(result.text).not.toContain(wA)
|
||||
expect(result.text).not.toContain(a.id)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the private helpers out of the API', async () => {
|
||||
expect((await rpc('caller_workspace_ids', {}, b.token)).status).toBe(404)
|
||||
expect(
|
||||
(await rpc('ensure_personal_workspace', { p_user_id: b.id }, b.token))
|
||||
.status,
|
||||
).toBe(404)
|
||||
const profile = await rest('/rpc/backfill_personal_workspaces', b.token, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
headers: { 'Content-Profile': 'private' },
|
||||
})
|
||||
expect([profile.status, errorCode(profile)]).toEqual([406, 'PGRST106'])
|
||||
})
|
||||
|
||||
it('cuts a deactivated account at its next request, same token', async () => {
|
||||
await sql(`update public.profiles set active = false where id = '${b.id}'`)
|
||||
expect((await rest('/workspaces?select=id', b.token)).body).toEqual([])
|
||||
await sql(`update public.profiles set active = true where id = '${b.id}'`)
|
||||
expect((await rest('/workspaces?select=id', b.token)).body).toEqual([
|
||||
{ id: wB },
|
||||
])
|
||||
})
|
||||
|
||||
it('RESIDUAL (contract §6.3): the service key mints a session for any account through GoTrue admin', async () => {
|
||||
const token = await adminMagicLinkSession(a.email)
|
||||
expect(token).toBeTruthy()
|
||||
expect((await rest('/workspaces?select=id', token ?? '')).body).toEqual([
|
||||
{ id: wA },
|
||||
])
|
||||
})
|
||||
|
||||
it('stores an oversized correlation header as null and keeps a short token', async () => {
|
||||
const owner = await signIn(
|
||||
'owner@faunosteo.local',
|
||||
'LocalDev-only-password-1',
|
||||
)
|
||||
const token = owner.body.access_token as string
|
||||
const grant = await rpc(
|
||||
'grant_platform_role',
|
||||
{ target_user_id: b.id, role: 'support' },
|
||||
token,
|
||||
{
|
||||
'x-correlation-id': 'x'.repeat(6000),
|
||||
},
|
||||
)
|
||||
const revoke = await rpc(
|
||||
'revoke_platform_role',
|
||||
{ target_user_id: b.id, role: 'support', reason: 'sandbox' },
|
||||
token,
|
||||
{
|
||||
'x-correlation-id': 'req-sandbox-01',
|
||||
},
|
||||
)
|
||||
expect([grant.status, revoke.status]).toEqual([200, 200])
|
||||
expect(
|
||||
await sql(`select string_agg(coalesce(correlation_id, 'NULL'), '|' order by occurred_at, action)
|
||||
from audit.audit_logs where target_user_id = '${b.id}'`),
|
||||
).toBe('NULL|req-sandbox-01')
|
||||
})
|
||||
|
||||
it('deletes an empty account through GoTrue admin with its workspace', async () => {
|
||||
const e = await confirmedAccount('ws-e')
|
||||
expect(await adminDeleteUser(e.id)).toBe(200)
|
||||
expect(
|
||||
await sql(
|
||||
`select count(*) from public.workspace_members where user_id = '${e.id}'`,
|
||||
),
|
||||
).toBe('0')
|
||||
expect(await workspaceOf(e.id)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('concurrent sessions', () => {
|
||||
const ids = Array.from({ length: 20 }, () => randomUUID())
|
||||
|
||||
beforeAll(async () => {
|
||||
const values = ids
|
||||
.map(
|
||||
(id, i) =>
|
||||
`('${id}', 'race-${i}-${id.slice(0, 8)}@sandbox.local', now())`,
|
||||
)
|
||||
.join(',')
|
||||
await sql(`begin;
|
||||
alter table public.profiles disable trigger profiles_create_personal_workspace;
|
||||
insert into auth.users (id, email, email_confirmed_at) values ${values};
|
||||
alter table public.profiles enable trigger profiles_create_personal_workspace;
|
||||
commit;`)
|
||||
})
|
||||
|
||||
it('two sessions creating one workspace: the second waits for the commit, then writes nothing', async () => {
|
||||
const first = sql(
|
||||
`begin; select private.ensure_personal_workspace('${ids[0]}'); select pg_sleep(1.5); commit;`,
|
||||
)
|
||||
await new Promise((resolve) => setTimeout(resolve, 400))
|
||||
const started = Date.now()
|
||||
const second = await sql(
|
||||
`select private.ensure_personal_workspace('${ids[0]}')`,
|
||||
)
|
||||
expect(Date.now() - started).toBeGreaterThan(700)
|
||||
expect(await first).toContain('t')
|
||||
expect(second).toBe('f')
|
||||
expect(await holderCount(ids[0])).toBe('1')
|
||||
})
|
||||
|
||||
it('refuses at COMMIT a workspace without its holder or with a foreign member', async () => {
|
||||
const alone = await sqlOutcome(
|
||||
`begin; insert into public.workspaces (kind, personal_user_id) values ('personal', '${ids[1]}'); commit;`,
|
||||
)
|
||||
expect(alone.ok).toBe(false)
|
||||
expect(alone.out).toContain(
|
||||
'personal workspace must have exactly its account as holder',
|
||||
)
|
||||
expect(await workspaceOf(ids[1])).toBe('')
|
||||
const foreign =
|
||||
await sqlOutcome(`begin; insert into public.workspace_members (workspace_id, user_id, member_role)
|
||||
select id, '${ids[1]}', 'holder' from public.workspaces where personal_user_id = '${ids[0]}'; commit;`)
|
||||
expect(foreign.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('a rolled-back creation leaves nothing; the retry creates once', async () => {
|
||||
await sql(
|
||||
`begin; select private.ensure_personal_workspace('${ids[1]}'); rollback;`,
|
||||
)
|
||||
expect(await workspaceOf(ids[1])).toBe('')
|
||||
expect(
|
||||
await sql(`select private.ensure_personal_workspace('${ids[1]}')`),
|
||||
).toBe('t')
|
||||
expect(
|
||||
await sql(`select private.ensure_personal_workspace('${ids[1]}')`),
|
||||
).toBe('f')
|
||||
})
|
||||
|
||||
it('two racing backfills create each missing workspace once', async () => {
|
||||
const [x, y] = await Promise.all([
|
||||
sql('select private.backfill_personal_workspaces()'),
|
||||
sql('select private.backfill_personal_workspaces()'),
|
||||
])
|
||||
expect(Number(x) + Number(y)).toBe(18)
|
||||
const counts = await Promise.all(ids.map(holderCount))
|
||||
expect(counts.every((c) => c === '1')).toBe(true)
|
||||
})
|
||||
|
||||
it('parallel GoTrue sign-ups each get one workspace', async () => {
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 8 }, () => signUp(uniqueEmail('ws-par'))),
|
||||
)
|
||||
expect(results.map((r) => r.status)).toEqual(Array(8).fill(200))
|
||||
const counts = await Promise.all(
|
||||
results.map((r) => holderCount(r.body.id as string)),
|
||||
)
|
||||
expect(counts).toEqual(Array(8).fill('1'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
/**
|
||||
* Real-stack suite on the throwaway stack of `pnpm db:sandbox` (tests/sandbox):
|
||||
* HTTP through GoTrue and PostgREST, concurrent SQL sessions. Run only through
|
||||
* `pnpm db:sandbox test`, which provides the endpoints and the generated keys;
|
||||
* kept out of the default `test:run` include on purpose.
|
||||
*/
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
globals: true,
|
||||
include: ['tests/sandbox/**/*.sandbox.ts'],
|
||||
fileParallelism: false,
|
||||
testTimeout: 120_000,
|
||||
hookTimeout: 120_000,
|
||||
},
|
||||
})
|
||||
Executable
+210
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env bash
|
||||
# Throwaway Supabase stack for testing migrations without touching the DEV
|
||||
# stack (docs/development/SUPABASE.md §5.1). Same images as the CLI stack,
|
||||
# its own Docker network, ports published on 127.0.0.1 only and distinct from
|
||||
# DEV, no Docker volume (the images declare none and nothing is mounted), so
|
||||
# `down` removes only the containers and network named below.
|
||||
#
|
||||
# pnpm db:sandbox up fresh all migrations, then the seeds (= db reset)
|
||||
# pnpm db:sandbox up upgrade <version> migrations before <version>, seeds, two
|
||||
# GoTrue accounts, then `migration up` (= DEV path)
|
||||
# pnpm db:sandbox test-db the pgTAP files (`supabase test db`)
|
||||
# pnpm db:sandbox types [--check] generated types (write, or diff with the committed file)
|
||||
# pnpm db:sandbox test packages/supabase/tests/sandbox (HTTP, concurrency)
|
||||
# pnpm db:sandbox sql psql as postgres on stdin
|
||||
# pnpm db:sandbox down
|
||||
#
|
||||
# Secrets are generated at `up` (random password, JWT secret, keys) into a
|
||||
# 600 file under $FAUNOSTEO_SANDBOX_DIR (default ~/.cache/faunosteo-db-sandbox),
|
||||
# outside the repository, and never printed. Every Supabase CLI call names the
|
||||
# sandbox with --db-url: none may fall back to the local DEV database.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
. scripts/dev-env.sh
|
||||
|
||||
PG_IMAGE=public.ecr.aws/supabase/postgres:17.11.0.004
|
||||
AUTH_IMAGE=public.ecr.aws/supabase/gotrue:v2.197.0
|
||||
REST_IMAGE=public.ecr.aws/supabase/postgrest:v16.4
|
||||
STORAGE_IMAGE=public.ecr.aws/supabase/storage-api:v1.79.36
|
||||
MAIL_IMAGE=public.ecr.aws/supabase/mailpit:v1.31.3
|
||||
NET=faunosteo_dbsandbox_net
|
||||
DB=faunosteo_dbsandbox_db
|
||||
AUTH=faunosteo_dbsandbox_auth
|
||||
REST=faunosteo_dbsandbox_rest
|
||||
STORAGE=faunosteo_dbsandbox_storage
|
||||
MAIL=faunosteo_dbsandbox_mail
|
||||
PORT_DB=57432 PORT_AUTH=57999 PORT_REST=57300 PORT_STORAGE=57500 PORT_MAIL=57025
|
||||
STATE="${FAUNOSTEO_SANDBOX_DIR:-$HOME/.cache/faunosteo-db-sandbox}"
|
||||
SECRETS="$STATE/secrets.sh"
|
||||
CLI=node_modules/.bin/supabase
|
||||
|
||||
die() { echo "db-sandbox: $*" >&2; exit 1; }
|
||||
load_secrets() { [ -f "$SECRETS" ] || die "not running (pnpm db:sandbox up fresh)"; . "$SECRETS"; }
|
||||
db_url() { printf 'postgresql://postgres:%s@127.0.0.1:%s/postgres?sslmode=disable' "$SB_PW" "$PORT_DB"; }
|
||||
sb_psql() {
|
||||
docker exec -i -e PGPASSWORD="$SB_PW" "$DB" \
|
||||
psql -X -q -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 "$@"
|
||||
}
|
||||
wait_for() {
|
||||
local what="$1"; shift
|
||||
for _ in $(seq 1 120); do "$@" >/dev/null 2>&1 && return 0; sleep 1; done
|
||||
die "timeout waiting for $what"
|
||||
}
|
||||
|
||||
new_secrets() {
|
||||
mkdir -p "$STATE"; chmod 700 "$STATE"
|
||||
( umask 077; node -e '
|
||||
const c = require("crypto");
|
||||
const secret = c.randomBytes(32).toString("hex");
|
||||
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url");
|
||||
const jwt = (p) => { const h = b64({ alg: "HS256", typ: "JWT" }), b = b64(p);
|
||||
return h + "." + b + "." + c.createHmac("sha256", secret).update(h + "." + b).digest("base64url"); };
|
||||
const exp = Math.floor(Date.now() / 1000) + 30 * 86400;
|
||||
console.log("SB_PW=" + c.randomBytes(24).toString("hex"));
|
||||
console.log("SB_JWT_SECRET=" + secret);
|
||||
console.log("SB_ANON_KEY=" + jwt({ role: "anon", iss: "db-sandbox", exp }));
|
||||
console.log("SB_SERVICE_KEY=" + jwt({ role: "service_role", iss: "db-sandbox", exp }));
|
||||
' > "$SECRETS" )
|
||||
}
|
||||
|
||||
# The role passwords the CLI sets at db start (its /etc/postgresql.schema.sql),
|
||||
# reduced to what the sandbox services use.
|
||||
DB_INIT='cat <<'"'"'EOF'"'"' > /etc/postgresql.schema.sql && exec docker-entrypoint.sh postgres -D /etc/postgresql
|
||||
\set pgpass `echo "$PGPASSWORD"`
|
||||
\set jwt_secret `echo "$JWT_SECRET"`
|
||||
ALTER DATABASE postgres SET "app.settings.jwt_secret" TO :'"'"'jwt_secret'"'"';
|
||||
ALTER DATABASE postgres SET "app.settings.jwt_exp" TO '"'"'3600'"'"';
|
||||
ALTER USER postgres WITH PASSWORD :'"'"'pgpass'"'"';
|
||||
ALTER USER authenticator WITH PASSWORD :'"'"'pgpass'"'"';
|
||||
ALTER USER supabase_auth_admin WITH PASSWORD :'"'"'pgpass'"'"';
|
||||
ALTER USER supabase_storage_admin WITH PASSWORD :'"'"'pgpass'"'"';
|
||||
EOF'
|
||||
|
||||
start_services() {
|
||||
docker network create "$NET" >/dev/null
|
||||
docker run -d --name "$DB" --network "$NET" -p 127.0.0.1:$PORT_DB:5432 \
|
||||
-e POSTGRES_PASSWORD="$SB_PW" -e PGPASSWORD="$SB_PW" -e POSTGRES_HOST=/var/run/postgresql \
|
||||
-e JWT_SECRET="$SB_JWT_SECRET" -e JWT_EXP=3600 \
|
||||
-e POSTGRES_INITDB_ARGS="--allow-group-access --locale-provider=icu --encoding=UTF-8 --icu-locale=en_US.UTF-8" \
|
||||
--entrypoint sh "$PG_IMAGE" -c "$DB_INIT" >/dev/null
|
||||
wait_for "database roles" docker exec -e PGPASSWORD="$SB_PW" "$DB" \
|
||||
psql -h 127.0.0.1 -U supabase_auth_admin -d postgres -c 'select 1'
|
||||
wait_for "database" docker exec -e PGPASSWORD="$SB_PW" "$DB" \
|
||||
psql -h 127.0.0.1 -U postgres -d postgres -c 'select 1'
|
||||
|
||||
docker run -d --name "$MAIL" --network "$NET" -p 127.0.0.1:$PORT_MAIL:8025 "$MAIL_IMAGE" >/dev/null
|
||||
docker run -d --name "$AUTH" --network "$NET" -p 127.0.0.1:$PORT_AUTH:9999 \
|
||||
-e GOTRUE_API_HOST=0.0.0.0 -e GOTRUE_API_PORT=9999 -e API_EXTERNAL_URL=http://127.0.0.1:$PORT_AUTH \
|
||||
-e GOTRUE_DB_DRIVER=postgres \
|
||||
-e GOTRUE_DB_DATABASE_URL="postgresql://supabase_auth_admin:$SB_PW@$DB:5432/postgres" \
|
||||
-e GOTRUE_DB_MIGRATIONS_PATH=/usr/local/etc/auth/migrations \
|
||||
-e GOTRUE_SITE_URL=http://127.0.0.1:5173 -e GOTRUE_DISABLE_SIGNUP=false \
|
||||
-e GOTRUE_JWT_SECRET="$SB_JWT_SECRET" -e GOTRUE_JWT_EXP=3600 \
|
||||
-e GOTRUE_JWT_AUD=authenticated -e GOTRUE_JWT_DEFAULT_GROUP_NAME=authenticated \
|
||||
-e GOTRUE_JWT_ADMIN_ROLES=service_role \
|
||||
-e GOTRUE_EXTERNAL_EMAIL_ENABLED=true -e GOTRUE_EXTERNAL_PHONE_ENABLED=false \
|
||||
-e GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED=false -e GOTRUE_MAILER_AUTOCONFIRM=false \
|
||||
-e GOTRUE_MAILER_URLPATHS_CONFIRMATION=http://127.0.0.1:$PORT_AUTH/verify \
|
||||
-e GOTRUE_SMTP_HOST="$MAIL" -e GOTRUE_SMTP_PORT=1025 \
|
||||
-e GOTRUE_SMTP_ADMIN_EMAIL=admin@sandbox.local -e GOTRUE_SMTP_SENDER_NAME=sandbox \
|
||||
-e GOTRUE_SMTP_MAX_FREQUENCY=1s -e GOTRUE_RATE_LIMIT_EMAIL_SENT=10000 \
|
||||
-e GOTRUE_RATE_LIMIT_VERIFY=10000 -e GOTRUE_RATE_LIMIT_TOKEN_REFRESH=10000 \
|
||||
-e GOTRUE_PASSWORD_MIN_LENGTH=12 "$AUTH_IMAGE" >/dev/null
|
||||
wait_for "auth" curl -fsS http://127.0.0.1:$PORT_AUTH/health
|
||||
docker run -d --name "$STORAGE" --network "$NET" -p 127.0.0.1:$PORT_STORAGE:5000 \
|
||||
-e ANON_KEY="$SB_ANON_KEY" -e SERVICE_KEY="$SB_SERVICE_KEY" -e AUTH_JWT_SECRET="$SB_JWT_SECRET" \
|
||||
-e DATABASE_URL="postgresql://supabase_storage_admin:$SB_PW@$DB:5432/postgres" \
|
||||
-e FILE_SIZE_LIMIT=52428800 -e STORAGE_BACKEND=file -e FILE_STORAGE_BACKEND_PATH=/mnt \
|
||||
-e TENANT_ID=stub -e STORAGE_S3_REGION=local -e GLOBAL_S3_BUCKET=stub \
|
||||
-e ENABLE_IMAGE_TRANSFORMATION=false -e IMAGE_TRANSFORMATION_ENABLED=false \
|
||||
-e S3_PROTOCOL_ENABLED=false -e DB_MIGRATIONS_FREEZE_AT= "$STORAGE_IMAGE" >/dev/null
|
||||
wait_for "storage" curl -fsS http://127.0.0.1:$PORT_STORAGE/status
|
||||
}
|
||||
|
||||
start_rest() {
|
||||
docker run -d --name "$REST" --network "$NET" -p 127.0.0.1:$PORT_REST:3000 \
|
||||
-e PGRST_DB_URI="postgresql://authenticator:$SB_PW@$DB:5432/postgres" \
|
||||
-e PGRST_DB_SCHEMAS=public -e PGRST_DB_EXTRA_SEARCH_PATH=public,extensions \
|
||||
-e PGRST_DB_ANON_ROLE=anon -e PGRST_JWT_SECRET="$SB_JWT_SECRET" -e PGRST_DB_MAX_ROWS=1000 \
|
||||
"$REST_IMAGE" >/dev/null
|
||||
wait_for "postgrest" curl -fsS -o /dev/null http://127.0.0.1:$PORT_REST/
|
||||
}
|
||||
|
||||
# The CLI's own migration runner, always against the sandbox URL.
|
||||
migrate_up() { # workdir
|
||||
"$CLI" --workdir "$1" migration up --db-url "$(db_url)"
|
||||
}
|
||||
|
||||
seed() {
|
||||
local paths
|
||||
paths="$(sed -n 's/^sql_paths = \[\(.*\)\]/\1/p' supabase/config.toml | tr -d '" ' | tr ',' ' ')"
|
||||
for f in $paths; do
|
||||
echo " seed ${f#./}"; sb_psql --single-transaction < "supabase/${f#./}" >/dev/null
|
||||
done
|
||||
}
|
||||
|
||||
gotrue_accounts() {
|
||||
curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/admin/users \
|
||||
-H "Authorization: Bearer $SB_SERVICE_KEY" -H 'Content-Type: application/json' \
|
||||
-d '{"email":"pre-confirmed@sandbox.local","password":"Sandbox-only-pw-1","email_confirm":true}' >/dev/null
|
||||
curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/signup -H 'Content-Type: application/json' \
|
||||
-d '{"email":"pre-unconfirmed@sandbox.local","password":"Sandbox-only-pw-1"}' >/dev/null
|
||||
}
|
||||
|
||||
cmd_up() {
|
||||
local mode="${1:-}"
|
||||
docker ps -a --format '{{.Names}}' | grep -q '^faunosteo_dbsandbox_' && die "already up (pnpm db:sandbox down)"
|
||||
new_secrets; . "$SECRETS"
|
||||
start_services
|
||||
case "$mode" in
|
||||
fresh)
|
||||
migrate_up . ; seed ;;
|
||||
upgrade)
|
||||
local version="${2:?upgrade needs the first new migration version, e.g. 20261025100000}"
|
||||
# A CLI workdir holding only the migrations before <version>; kept in the
|
||||
# state folder and refilled at each upgrade run (the CLI writes .temp there).
|
||||
local base="$STATE/upgrade-base"
|
||||
mkdir -p "$base/supabase/migrations"
|
||||
rm -f "$base"/supabase/migrations/*.sql
|
||||
cp supabase/config.toml "$base/supabase/"
|
||||
for f in supabase/migrations/*.sql; do
|
||||
if [ "$(basename "$f" | cut -d_ -f1)" \< "$version" ]; then cp "$f" "$base/supabase/migrations/"; fi
|
||||
done
|
||||
migrate_up "$base"
|
||||
seed; gotrue_accounts
|
||||
echo "== before: $(sb_psql -t -A -c 'select count(*) from public.profiles') profiles"
|
||||
migrate_up . ;;
|
||||
*) die "up fresh | up upgrade <version>" ;;
|
||||
esac
|
||||
start_rest
|
||||
echo "== sandbox up ($mode): db 127.0.0.1:$PORT_DB, auth :$PORT_AUTH, rest :$PORT_REST, mail :$PORT_MAIL"
|
||||
}
|
||||
|
||||
cmd_down() {
|
||||
docker rm -f "$REST" "$STORAGE" "$AUTH" "$MAIL" "$DB" >/dev/null 2>&1 || true
|
||||
docker network rm "$NET" >/dev/null 2>&1 || true
|
||||
rm -f "$SECRETS"
|
||||
echo "== sandbox removed"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
up) shift; cmd_up "$@" ;;
|
||||
down) cmd_down ;;
|
||||
test-db) load_secrets; "$CLI" test db --db-url "$(db_url)" ;;
|
||||
types)
|
||||
load_secrets
|
||||
out="$("$CLI" gen types typescript --db-url "$(db_url)" --schema public | node_modules/.bin/prettier --parser typescript)"
|
||||
if [ "${2:-}" = --check ]; then
|
||||
diff <(printf '%s\n' "$out") packages/supabase/src/database.types.ts && echo "== types match"
|
||||
else
|
||||
printf '%s\n' "$out" > packages/supabase/src/database.types.ts; echo "== types written"
|
||||
fi ;;
|
||||
test)
|
||||
load_secrets
|
||||
SANDBOX_DB_CONTAINER="$DB" SANDBOX_PG_PASSWORD="$SB_PW" SANDBOX_AUTH_URL="http://127.0.0.1:$PORT_AUTH" \
|
||||
SANDBOX_REST_URL="http://127.0.0.1:$PORT_REST" SANDBOX_MAIL_URL="http://127.0.0.1:$PORT_MAIL" \
|
||||
SANDBOX_ANON_KEY="$SB_ANON_KEY" SANDBOX_SERVICE_KEY="$SB_SERVICE_KEY" \
|
||||
node_modules/.bin/pnpm --filter @faunosteo/supabase test:sandbox ;;
|
||||
sql) load_secrets; sb_psql ;;
|
||||
*) sed -n '2,23p' "$0"; exit 1 ;;
|
||||
esac
|
||||
Reference in new issue
Block a user