feat(supabase): sheet asset Storage bucket + read policy through the sheet, shim storage tables, seeds in the PGlite harness, upload script
This commit is contained in:
1 parent
12f0b21fdf
commit
f4682cdba5
10 files changed
+294
-7
No files matched your search
+2
-1
@@ -25,7 +25,8 @@
|
||||
"db:reset": "supabase db reset",
|
||||
"db:test": "supabase test db",
|
||||
"db:types": "supabase gen types typescript --local --schema public | prettier --parser typescript > packages/supabase/src/database.types.ts",
|
||||
"db:types:check": "supabase gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts"
|
||||
"db:types:check": "supabase gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts",
|
||||
"assets:upload": "pnpm --filter @faunosteo/supabase assets:upload"
|
||||
},
|
||||
"devDependencies": {
|
||||
"pnpm": "10.13.1",
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"lint": "eslint . --max-warnings 0",
|
||||
"build": "tsc -p tsconfig.json --noEmit"
|
||||
"build": "tsc -p tsconfig.json --noEmit",
|
||||
"assets:upload": "node scripts/upload-sheet-assets.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@faunosteo/domain": "workspace:*",
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Uploads the SVG assets of a generated sheet seed into the Storage bucket
|
||||
* anatomical-sheet-assets, content-addressed (<sha256>.svg).
|
||||
*
|
||||
* Operator tool: needs the service key, which never ships to the browser.
|
||||
* Reads SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY from the environment
|
||||
* (local stack: `pnpm supabase status` prints them). Idempotent: an object
|
||||
* whose sha256 already exists is skipped, a mismatching upload is refused.
|
||||
*
|
||||
* pnpm assets:upload supabase/seed/anatomical-sheets/equine/v1
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const BUCKET = 'anatomical-sheet-assets'
|
||||
|
||||
interface AssetEntry {
|
||||
file: string
|
||||
sha256: string
|
||||
byte_size: number
|
||||
}
|
||||
|
||||
function requireEnv(name: string): string {
|
||||
const value = process.env[name]
|
||||
if (!value) throw new Error(`${name} is required`)
|
||||
return value
|
||||
}
|
||||
|
||||
async function readManifest(dir: string): Promise<AssetEntry[]> {
|
||||
const raw = await readFile(join(dir, 'assets.json'), 'utf8')
|
||||
return JSON.parse(raw) as AssetEntry[]
|
||||
}
|
||||
|
||||
/** The bytes on disk must still match what the seed recorded. */
|
||||
async function readVerified(dir: string, entry: AssetEntry): Promise<Buffer> {
|
||||
const bytes = await readFile(join(dir, 'assets', entry.file))
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
||||
if (sha256 !== entry.sha256 || bytes.length !== entry.byte_size) {
|
||||
throw new Error(`${entry.file}: bytes differ from assets.json`)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const dir = resolve(process.argv[2] ?? '.')
|
||||
const client = createClient(
|
||||
requireEnv('SUPABASE_URL'),
|
||||
requireEnv('SUPABASE_SERVICE_ROLE_KEY'),
|
||||
{ auth: { persistSession: false } },
|
||||
)
|
||||
for (const entry of await readManifest(dir)) {
|
||||
const key = `${entry.sha256}.svg`
|
||||
const bytes = await readVerified(dir, entry)
|
||||
const { error } = await client.storage
|
||||
.from(BUCKET)
|
||||
.upload(key, bytes, { contentType: 'image/svg+xml', upsert: false })
|
||||
if (error && !/already exists/i.test(error.message)) {
|
||||
throw new Error(`${key}: ${error.message}`)
|
||||
}
|
||||
console.log(`${error ? 'kept' : 'uploaded'} ${key} (${entry.file})`)
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* PGlite harness: a real PostgreSQL (WASM) that applies the Supabase shim,
|
||||
* then every migration under supabase/migrations, in filename order.
|
||||
* then every migration under supabase/migrations, in filename order, then
|
||||
* the versioned seeds under supabase/seed (same files `supabase db reset`
|
||||
* applies through config.toml sql_paths).
|
||||
* Lets the pgTAP suite and the schema checks run without Docker. The same
|
||||
* SQL runs unchanged under `supabase test db` on the real stack.
|
||||
*/
|
||||
@@ -15,6 +17,8 @@ export const repoRoot = resolve(here, '../../../..')
|
||||
export const supabaseDir = join(repoRoot, 'supabase')
|
||||
export const migrationsDir = join(supabaseDir, 'migrations')
|
||||
export const pgTapTestsDir = join(supabaseDir, 'tests')
|
||||
/** Versioned seeds (reference data such as the official sheets); seed.sql itself needs the real auth schema and stays out. */
|
||||
export const seedDir = join(supabaseDir, 'seed')
|
||||
|
||||
async function listSqlFiles(dir: string): Promise<string[]> {
|
||||
const entries = await readdir(dir)
|
||||
@@ -29,6 +33,12 @@ export async function listPgTapTests(): Promise<string[]> {
|
||||
return listSqlFiles(pgTapTestsDir)
|
||||
}
|
||||
|
||||
/** Every .sql under supabase/seed, recursively, in path order. */
|
||||
export async function listSeeds(): Promise<string[]> {
|
||||
const entries = await readdir(seedDir, { recursive: true }).catch(() => [])
|
||||
return entries.filter((f) => f.endsWith('.sql')).sort()
|
||||
}
|
||||
|
||||
/** Boots PGlite, installs the shim and applies all migrations. */
|
||||
export async function createMigratedDatabase(): Promise<PGlite> {
|
||||
const db = await PGlite.create({ extensions: { pgtap } })
|
||||
@@ -39,6 +49,9 @@ export async function createMigratedDatabase(): Promise<PGlite> {
|
||||
for (const file of await listMigrations()) {
|
||||
await db.exec(await readFile(join(migrationsDir, file), 'utf8'))
|
||||
}
|
||||
for (const file of await listSeeds()) {
|
||||
await db.exec(await readFile(join(seedDir, file), 'utf8'))
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
|
||||
@@ -73,3 +73,35 @@ grant usage on schema extensions to anon, authenticated, service_role;
|
||||
alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
|
||||
alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
|
||||
alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;
|
||||
|
||||
-- Storage schema stand-in (buckets + objects only, the columns the
|
||||
-- migrations and tests touch). The real stack ships the full schema owned by
|
||||
-- supabase_storage_admin; policies declared on storage.objects apply there.
|
||||
create schema storage;
|
||||
grant usage on schema storage to anon, authenticated, service_role;
|
||||
|
||||
create table storage.buckets (
|
||||
id text primary key,
|
||||
name text not null,
|
||||
owner uuid,
|
||||
public boolean default false,
|
||||
file_size_limit bigint,
|
||||
allowed_mime_types text[],
|
||||
created_at timestamptz default now(),
|
||||
updated_at timestamptz default now()
|
||||
);
|
||||
|
||||
create table storage.objects (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
bucket_id text references storage.buckets (id),
|
||||
name text,
|
||||
owner uuid,
|
||||
metadata jsonb,
|
||||
created_at timestamptz default now(),
|
||||
updated_at timestamptz default now(),
|
||||
last_accessed_at timestamptz default now()
|
||||
);
|
||||
|
||||
alter table storage.objects enable row level security;
|
||||
grant select on storage.buckets to anon, authenticated, service_role;
|
||||
grant select, insert, update, delete on storage.objects to anon, authenticated, service_role;
|
||||
@@ -16,6 +16,6 @@
|
||||
"types": ["node", "vitest/globals"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src", "tests"],
|
||||
"include": ["src", "tests", "scripts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -31,8 +31,10 @@ schema_paths = []
|
||||
|
||||
[db.seed]
|
||||
enabled = true
|
||||
# Local development data only (dev accounts + first owner). Never run in prod.
|
||||
sql_paths = ["./seed.sql"]
|
||||
# seed.sql: local development accounts + first owner, never run in prod.
|
||||
# seed/**: versioned reference data (official anatomical sheets as drafts),
|
||||
# idempotent, applied in every environment (docs/development/SUPABASE.md §3).
|
||||
sql_paths = ["./seed.sql", "./seed/anatomical-sheets/equine/v1/equine_v1.sql"]
|
||||
|
||||
[realtime]
|
||||
# Not used before the cloud-reports step.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
-- Storage for the SVG assets of anatomical sheets (business architecture
|
||||
-- §15, ANATOMICAL_SHEET_MODEL.md §3 "assets").
|
||||
--
|
||||
-- Bucket anatomical-sheet-assets, private. Objects are content-addressed:
|
||||
-- key = <sha256>.svg, so two sheets with the same drawing share one object
|
||||
-- and a copy of a sheet never copies bytes. Reading an object is authorised
|
||||
-- THROUGH a sheet (an asset row the caller may use or edit), never through
|
||||
-- the hash alone; drafts stay visible to editors only, as the sheet rows do.
|
||||
-- No API role writes objects: uploads are an operator / server task
|
||||
-- (import tool with the service key) until the editor step adds a signed
|
||||
-- upload path.
|
||||
|
||||
insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
|
||||
values ('anatomical-sheet-assets', 'anatomical-sheet-assets', false, 20971520, array['image/svg+xml'])
|
||||
on conflict (id) do nothing;
|
||||
|
||||
-- An object is readable when a usable sheet publishes it (a non-draft
|
||||
-- version references the asset) or when the caller edits the sheet.
|
||||
create or replace function private.can_read_sheet_asset_object(p_user_id uuid, p_object_name text)
|
||||
returns boolean
|
||||
language sql
|
||||
stable
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
select exists (
|
||||
select 1
|
||||
from public.anatomical_sheet_assets a
|
||||
where a.sha256 || '.svg' = p_object_name
|
||||
and (
|
||||
private.can_edit_sheet(p_user_id, a.sheet_id)
|
||||
or (
|
||||
private.can_use_sheet(p_user_id, a.sheet_id)
|
||||
and exists (
|
||||
select 1 from public.anatomical_sheet_versions v
|
||||
where v.sheet_id = a.sheet_id
|
||||
and v.status <> 'draft'
|
||||
and a.id::text = any (private.sheet_document_asset_ids(v.content))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
$$;
|
||||
|
||||
comment on function private.can_read_sheet_asset_object(uuid, text) is
|
||||
'Storage read predicate for bucket anatomical-sheet-assets: object <sha256>.svg referenced by a published version of a usable sheet, or by any version of a sheet the caller edits.';
|
||||
|
||||
revoke all on function private.can_read_sheet_asset_object(uuid, text) from public;
|
||||
grant execute on function private.can_read_sheet_asset_object(uuid, text) to authenticated;
|
||||
|
||||
create policy anatomical_sheet_assets_read
|
||||
on storage.objects
|
||||
for select
|
||||
to authenticated
|
||||
using (
|
||||
bucket_id = 'anatomical-sheet-assets'
|
||||
and private.can_read_sheet_asset_object((select auth.uid()), name)
|
||||
);
|
||||
|
||||
-- No INSERT / UPDATE / DELETE policy for API roles on this bucket.
|
||||
@@ -62,7 +62,7 @@ select is(
|
||||
(select string_agg(p.proname::text, ',' order by p.proname::text collate "C")
|
||||
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')),
|
||||
'can_edit_sheet,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
|
||||
'can_edit_sheet,can_read_sheet_asset_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
|
||||
'authenticated executes only the policy predicates in private'
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
-- Storage read policy on bucket anatomical-sheet-assets: an object is readable
|
||||
-- through a sheet (published reference for users, any version for editors),
|
||||
-- never through its hash alone. No API writes.
|
||||
begin;
|
||||
select plan(14);
|
||||
|
||||
insert into auth.users (id, email) values
|
||||
('30000000-0000-0000-0000-00000000000a', 'alice-assets@test.local'),
|
||||
('30000000-0000-0000-0000-00000000000b', 'bob-assets@test.local');
|
||||
|
||||
create table pg_temp.ids (key text primary key, id uuid not null);
|
||||
create function pg_temp.id(p_key text) returns uuid language sql stable
|
||||
as $$ select id from pg_temp.ids where key = p_key $$;
|
||||
grant all on pg_temp.ids to anon, authenticated;
|
||||
grant execute on function pg_temp.id(text) to anon, authenticated;
|
||||
|
||||
-- Minimal publishable document with one main view on a given asset.
|
||||
create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$
|
||||
select jsonb_build_object(
|
||||
'schema_version', 1, 'species_id', 'equine',
|
||||
'name', jsonb_build_object('fr', 'A', 'en', 'A'),
|
||||
'description', '{}'::jsonb, 'scope_disclaimer', '{}'::jsonb,
|
||||
'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null),
|
||||
'vertebral_config', jsonb_build_object('regions', '[]'::jsonb),
|
||||
'categories', '[]'::jsonb,
|
||||
'views', jsonb_build_array(jsonb_build_object('id', 'main', 'kind', 'main',
|
||||
'name', jsonb_build_object('fr', 'V', 'en', 'V'), 'svg_asset_id', p_asset, 'view_box', null)),
|
||||
'annotations', '[]'::jsonb, 'finding_zones', '[]'::jsonb);
|
||||
$$;
|
||||
grant execute on function pg_temp.doc(uuid) to authenticated;
|
||||
|
||||
-- 1. Bucket contract
|
||||
select is((select public from storage.buckets where id = 'anatomical-sheet-assets'), false, 'bucket is private');
|
||||
select is(
|
||||
(select allowed_mime_types from storage.buckets where id = 'anatomical-sheet-assets'),
|
||||
array['image/svg+xml'], 'bucket accepts SVG only'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from pg_policies where schemaname = 'storage' and tablename = 'objects'
|
||||
and policyname = 'anatomical_sheet_assets_read' and cmd = 'SELECT'),
|
||||
1::bigint, 'one SELECT policy on storage.objects for the bucket'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from pg_policies where schemaname = 'storage' and tablename = 'objects'
|
||||
and policyname like 'anatomical_sheet_assets%' and cmd <> 'SELECT'),
|
||||
0::bigint, 'no write policy on the bucket for API roles'
|
||||
);
|
||||
|
||||
-- 2. Alice: sheet with published v1 on asset A, draft v2 on asset B; C is registered but unreferenced
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
insert into pg_temp.ids select 'sheet', public.create_anatomical_sheet('equine', 'Assets', 'assets-test', pg_temp.doc(null));
|
||||
insert into pg_temp.ids select 'a', public.register_sheet_asset(pg_temp.id('sheet'), repeat('a', 64), 100, 'A.svg');
|
||||
insert into pg_temp.ids select 'b', public.register_sheet_asset(pg_temp.id('sheet'), repeat('b', 64), 100, 'B.svg');
|
||||
insert into pg_temp.ids select 'c', public.register_sheet_asset(pg_temp.id('sheet'), repeat('c', 64), 100, 'C.svg');
|
||||
insert into pg_temp.ids select 'v1', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet');
|
||||
update public.anatomical_sheet_versions set content = pg_temp.doc(pg_temp.id('a')) where id = pg_temp.id('v1');
|
||||
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v1')) $$, 'v1 published on asset A');
|
||||
insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet'));
|
||||
update public.anatomical_sheet_versions set content = pg_temp.doc(pg_temp.id('b')) where id = pg_temp.id('v2');
|
||||
|
||||
-- Objects uploaded by the operator (owner session)
|
||||
reset role;
|
||||
insert into storage.objects (bucket_id, name) values
|
||||
('anatomical-sheet-assets', repeat('a', 64) || '.svg'),
|
||||
('anatomical-sheet-assets', repeat('b', 64) || '.svg'),
|
||||
('anatomical-sheet-assets', repeat('c', 64) || '.svg'),
|
||||
('anatomical-sheet-assets', repeat('d', 64) || '.svg');
|
||||
|
||||
-- 3. Editor reads every object of her sheet (published, draft, unreferenced), not foreign ones
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select results_eq(
|
||||
$$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$,
|
||||
$$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg'), (repeat('c', 64) || '.svg') $$,
|
||||
'editor reads the objects of her sheet; the object no sheet registered stays hidden'
|
||||
);
|
||||
|
||||
-- 4. Bob: private sheet → nothing; public sheet → published reference only
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'other user reads nothing from a private sheet');
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public');
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select results_eq(
|
||||
$$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$,
|
||||
$$ values (repeat('a', 64) || '.svg') $$,
|
||||
'other user reads only the object a published version references (not the draft asset, not the unreferenced one)'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ insert into storage.objects (bucket_id, name) values ('anatomical-sheet-assets', 'x.svg') $$,
|
||||
'42501', null, 'authenticated cannot upload into the bucket'
|
||||
);
|
||||
delete from storage.objects where bucket_id = 'anatomical-sheet-assets';
|
||||
reset role;
|
||||
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 4::bigint, 'authenticated DELETE touches no bucket object');
|
||||
set local role authenticated;
|
||||
|
||||
-- 5. Archived sheet hides objects from others; anon sees nothing
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives');
|
||||
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'archived sheet: others read nothing');
|
||||
set local role anon;
|
||||
select set_config('request.jwt.claims', '', true);
|
||||
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'anon reads nothing');
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
Reference in new issue
Block a user