diff --git a/README.md b/README.md index 2c3cf03..2b623e2 100644 --- a/README.md +++ b/README.md @@ -66,9 +66,10 @@ Send `Authorization: Bearer ` on authenticated routes and `Accept: | `PUT /api/location` | Bearer | JSON `lat` and `lon` | `200` with the saved location row | `validation_failed`, `no_space`, `unauthorized`, `internal` | | `DELETE /api/location` | Bearer | — | `204`, including when the caller has no saved location | `unauthorized`, `internal` | | `GET /api/dashboard` | Bearer | — | `200` with `serverTime`, `nextMeeting`, twelve UTC `datesByMonth` totals, and historical `categoriesByMonth` grouped by UTC month and category key | `unauthorized`, `internal` | -| `GET /api/photos` | Bearer | Optional `offset` | `200` with up to 30 uploads newest first, with signed URLs valid for five minutes | `validation_failed`, `no_space`, `unauthorized`, `internal` | -| `POST /api/photos` | Bearer | Raw JPEG, PNG, or WebP bytes with matching `Content-Type`, up to 5 MiB in Nitro | `200` with Storage `id`, `path`, and `fullPath` | `validation_failed`, `no_space`, `unauthorized`, `internal` | -| `DELETE /api/photos/:name` | Bearer | UUID `name` from the gallery | `204`, including when the name is absent from the caller's gallery | `validation_failed`, `no_space`, `unauthorized`, `internal` | +| `GET /api/photos` | Bearer | Optional `offset` | `200` with up to 30 confirmed photos newest first. Each includes its metadata and a five-minute signed URL when available. | `validation_failed`, `no_space`, `unauthorized`, `internal` | +| `POST /api/photos/upload-url` | Bearer | JSON `mime` and `size` in bytes, up to 5 MiB | `200` with `uploadId`, `path`, `signedUrl`, and `token` | `validation_failed`, `quota_exceeded`, `no_space`, `unauthorized`, `internal` | +| `POST /api/photos/confirm` | Bearer | JSON `uploadId` from the reservation | `200` with the confirmed photo row. The uploader can retry using the same ID. | `validation_failed`, `not_found`, `no_space`, `unauthorized`, `internal` | +| `DELETE /api/photos/:name` | Bearer | UUID `name` from the gallery | `204` when a confirmed photo is removed | `validation_failed`, `not_found`, `no_space`, `unauthorized`, `internal` | ### Date category keys @@ -117,6 +118,23 @@ For a space with three dates created in November 2026 and no upcoming meeting, t Apply migration `006` before the frontend depends on `datesByMonth`. +### Direct photo uploads + +1. Send `POST /api/photos/upload-url` with JSON such as `{"mime":"image/png","size":5242880}`. Supported MIME types are `image/jpeg`, `image/png`, and `image/webp`. Use the final compressed file's MIME and size. +2. Send the bytes directly to the private `gallery` bucket with the Supabase SDK. The signed token is for that path only. Keep it out of application logs. + + ```ts + const { error } = await supabase.storage.from('gallery') + .uploadToSignedUrl(reservation.path, reservation.token, file, { contentType: file.type }) + if (error) throw error + ``` + +3. Send `POST /api/photos/confirm` with `{"uploadId":""}`. The server checks the stored MIME and byte count, then returns the registered photo. Retry confirmation with the same ID after an interrupted response. The gallery lists confirmed rows and may return a null URL when a file cannot be signed. + +The old binary `POST /api/photos` returns `405`. Both upload POSTs carry JSON so the image bypasses the Vercel Function request-body limit. A space has a **50 MiB** quota. An open, unconfirmed upload holds **5 MiB** through the signing window, the signed token's lifetime, and a 15-minute transfer grace period. Confirmation releases the hold and counts the stored file size. Deleting the file frees those bytes immediately. If a hold expires with an unconfirmed file still in Storage, that file counts toward the quota until it is removed. [Supabase signed upload URLs](https://supabase.com/docs/reference/javascript/storage-from-createsigneduploadurl) + +Apply migration `005` before serving this API version. Existing gallery objects with a compatible path, MIME, and size are backfilled. Objects without compatible metadata stay in Storage and count toward the quota. + ### Error codes and statuses | `data.code` | HTTP | Meaning | @@ -124,8 +142,9 @@ Apply migration `006` before the frontend depends on `datesByMonth`. | `invite_invalid` | 400 | The invite is unknown or already consumed. | | `already_paired` | 409 | The caller already belongs to a space when creating or joining, or the space already has two members when rotating an invite. | | `no_space` | 403 | The operation requires the caller to belong to a space. | -| `not_found` | 404 | The date is missing or outside the caller's visible rows. | -| `validation_failed` | 400, 413, 415 | Input is invalid, an upload is too large, or the media type or signature is unsupported. | +| `not_found` | 404 | A date, photo, or upload is missing or outside the caller's visible rows. | +| `quota_exceeded` | 409 | Counted Storage bytes, active unconfirmed holds, and a new 5 MiB hold would exceed the space's 50 MiB quota. | +| `validation_failed` | 400, 405, 413, 415 | Input is invalid, the removed binary upload route was called, an upload is too large, or the media type is unsupported. | | `unauthorized` | 401 | The access token is missing or rejected. | | `internal` | 500, 503 | An unexpected server failure occurred or a dependency is unavailable. | diff --git a/server/api/photos/[name].delete.ts b/server/api/photos/[name].delete.ts index caef3b7..da22305 100644 --- a/server/api/photos/[name].delete.ts +++ b/server/api/photos/[name].delete.ts @@ -1,10 +1,13 @@ -import { defineApiHandler } from '../../utils/api-error' +import { defineApiHandler, toApiError } from '../../utils/api-error' import { photoParamsSchema } from '../../../shared/api-contract' export default defineApiHandler(async event => { const { name } = await getValidatedRouterParams(event, photoParamsSchema.parse) const db = client(event) const space = await room(db) - result(await db.storage.from('gallery').remove([space + '/' + name])) + const photo = result(await db.from('photos').select('path').eq('space_id', space).eq('id', name).maybeSingle()) + if (!photo) throw toApiError('not_found') + result(await db.storage.from('gallery').remove([photo.path])) + result(await db.rpc('forget_photo', { photo_id: name }), 'photo') return sendNoContent(event) }) diff --git a/server/api/photos/confirm.post.ts b/server/api/photos/confirm.post.ts new file mode 100644 index 0000000..f11e7c1 --- /dev/null +++ b/server/api/photos/confirm.post.ts @@ -0,0 +1,7 @@ +import { confirmPhotoRequestSchema } from '../../../shared/api-contract' +import { defineApiHandler } from '../../utils/api-error' + +export default defineApiHandler(async event => { + const { uploadId } = await readValidatedBody(event, confirmPhotoRequestSchema.parse) + return result(await client(event).rpc('confirm_photo', { photo_upload_id: uploadId }), 'photo') +}) diff --git a/server/api/photos/index.get.ts b/server/api/photos/index.get.ts deleted file mode 100644 index 8b053e3..0000000 --- a/server/api/photos/index.get.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { photosQuerySchema } from '../../../shared/api-contract' -import { defineApiHandler } from '../../utils/api-error' - -export default defineApiHandler(async event => { - const db = client(event) - const space = await room(db) - const { offset } = await getValidatedQuery(event, photosQuerySchema.parse) - const gallery = db.storage.from('gallery') - const files = result(await gallery.list(space,{offset,limit:30,sortBy:{column:'created_at',order:'desc'}})) ?? [] - if (!files.length) return [] - const urls = result(await gallery.createSignedUrls(files.map(f => space + '/' + f.name),300)) ?? [] - return files.map((f,i) => ({name:f.name,createdAt:f.created_at,url:urls[i]?.signedUrl})) -}) diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts deleted file mode 100644 index 0443cf9..0000000 --- a/server/api/photos/index.post.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { photoContentTypeSchema, photoUploadMaxBytes } from '../../../shared/api-contract' -import { defineApiHandler, toApiError } from '../../utils/api-error' - -export default defineApiHandler(async event => { - const db = client(event) - const space = await room(db) - const mediaType = photoContentTypeSchema.safeParse(getHeader(event, 'content-type')) - if (!mediaType.success) throw toApiError('validation_failed', 415) - const mime = mediaType.data - const chunks: Buffer[] = [] - let length = 0 - for await (const chunk of event.node.req) { - const bytes = Buffer.from(chunk) - length += bytes.length - if (length > photoUploadMaxBytes) throw toApiError('validation_failed', 413) - chunks.push(bytes) - } - const bytes = Buffer.concat(chunks) - const valid = mime === 'image/jpeg' ? bytes.subarray(0,3).equals(Buffer.from([255,216,255])) - : mime === 'image/png' ? bytes.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex')) - : bytes.toString('ascii',0,4) === 'RIFF' && bytes.toString('ascii',8,12) === 'WEBP' - if (!valid) throw toApiError('validation_failed', 415) - const path = space + '/' + randomUUID() - return result(await db.storage.from('gallery').upload(path,bytes,{contentType:mime})) -}) diff --git a/server/api/photos/index.ts b/server/api/photos/index.ts new file mode 100644 index 0000000..1127628 --- /dev/null +++ b/server/api/photos/index.ts @@ -0,0 +1,26 @@ +import { isMethod, setResponseHeader } from 'h3' +import { photosQuerySchema } from '../../../shared/api-contract' +import { defineApiHandler, toApiError } from '../../utils/api-error' + +export default defineApiHandler(async event => { + if (!isMethod(event, 'GET', true)) { + setResponseHeader(event, 'Allow', 'GET, HEAD') + throw toApiError('validation_failed', 405) + } + const db = client(event) + const space = await room(db) + const { offset } = await getValidatedQuery(event, photosQuerySchema.parse) + const photos = result(await db.from('photos').select('id,path,mime,size,uploaded_by,created_at') + .eq('space_id', space).order('created_at', { ascending: false }).order('id').range(offset, offset + 29)) ?? [] + if (!photos.length) return [] + const urls = result(await db.storage.from('gallery').createSignedUrls(photos.map(photo => photo.path), 300)) ?? [] + const urlsByPath = new Map(urls.map(url => [url.path, url.signedUrl])) + return photos.map(photo => ({ + name: photo.id, + createdAt: photo.created_at, + url: urlsByPath.get(photo.path) ?? null, + mime: photo.mime, + size: photo.size, + uploadedBy: photo.uploaded_by, + })) +}) diff --git a/server/api/photos/upload-url.post.ts b/server/api/photos/upload-url.post.ts new file mode 100644 index 0000000..24fe1e9 --- /dev/null +++ b/server/api/photos/upload-url.post.ts @@ -0,0 +1,24 @@ +import { photoUploadMaxBytes, photoUploadUrlRequestSchema } from '../../../shared/api-contract' +import { defineApiHandler, toApiError } from '../../utils/api-error' + +export default defineApiHandler(async event => { + const body = await readBody(event) + const parsed = photoUploadUrlRequestSchema.safeParse(body) + if (!parsed.success) { + if (parsed.error.issues.some(issue => issue.path[0] === 'mime')) { + throw toApiError('validation_failed', 415) + } + if (typeof body?.size === 'number' && body.size > photoUploadMaxBytes) { + throw toApiError('validation_failed', 413) + } + throw toApiError('validation_failed') + } + const db = client(event) + const reservation = result(await db.rpc('reserve_photo_upload', { + upload_mime: parsed.data.mime, + upload_size: parsed.data.size, + }), 'photo') + const { signedUrl, token } = result(await db.storage.from('gallery') + .createSignedUploadUrl(reservation.path, { upsert: false })) + return { ...reservation, signedUrl, token } +}) diff --git a/server/utils/api-error.ts b/server/utils/api-error.ts index fe52234..adf4437 100644 --- a/server/utils/api-error.ts +++ b/server/utils/api-error.ts @@ -6,6 +6,7 @@ const errorDetails = { already_paired: { statusCode: 409, statusMessage: 'Already paired' }, no_space: { statusCode: 403, statusMessage: 'Join or create a space first' }, not_found: { statusCode: 404, statusMessage: 'Not found' }, + quota_exceeded: { statusCode: 409, statusMessage: 'Photo quota exceeded' }, validation_failed: { statusCode: 400, statusMessage: 'Validation failed' }, unauthorized: { statusCode: 401, statusMessage: 'Unauthorized' }, internal: { statusCode: 500, statusMessage: 'Internal server error' }, diff --git a/server/utils/backend.ts b/server/utils/backend.ts index 03d2d02..96c7557 100644 --- a/server/utils/backend.ts +++ b/server/utils/backend.ts @@ -24,7 +24,7 @@ type SupabaseResult = { status?: number } -export function result(response: SupabaseResult, operation?: 'createSpace' | 'joinSpace' | 'mutateDate' | 'regenerateInvite') { +export function result(response: SupabaseResult, operation?: 'createSpace' | 'joinSpace' | 'mutateDate' | 'regenerateInvite' | 'photo') { if (!response.error) { return response.data } @@ -48,6 +48,12 @@ export function result(response: SupabaseResult, operation?: 'createSpace' if (operation === 'regenerateInvite' && code === 'PT409') { throw toApiError('already_paired') } + if (operation === 'photo') { + if (code === 'PT403') throw toApiError('no_space') + if (code === 'PT404') throw toApiError('not_found') + if (code === 'PT400') throw toApiError('validation_failed') + if (code === 'PT409') throw toApiError('quota_exceeded') + } console.error('Unexpected Supabase request failure', response.error) throw toApiError('internal', response.status === 503 || status === 503 || statusCode === '503' ? 503 : 500) diff --git a/shared/api-contract.ts b/shared/api-contract.ts index 19c9490..20202e0 100644 --- a/shared/api-contract.ts +++ b/shared/api-contract.ts @@ -34,9 +34,27 @@ export const photosQuerySchema = z.object({ offset }) export const photoParamsSchema = z.object({ name: uuid }) export const photoContentTypeSchema = z.enum(['image/jpeg', 'image/png', 'image/webp']) export const photoUploadMaxBytes = 5 * 1024 * 1024 -export const uploadPhotoRequestSchema = z.object({ - contentType: photoContentTypeSchema, - body: z.instanceof(Uint8Array).refine(bytes => bytes.byteLength <= photoUploadMaxBytes), +export const photoSpaceQuotaBytes = 50 * 1024 * 1024 +const photoSizeSchema = z.number().int().positive().max(photoUploadMaxBytes) +export const photoUploadUrlRequestSchema = z.strictObject({ + mime: photoContentTypeSchema, + size: photoSizeSchema, +}) +export const photoUploadUrlResponseSchema = z.object({ + uploadId: uuid, + path: z.string(), + signedUrl: z.url(), + token: z.string().min(1), +}) +export const confirmPhotoRequestSchema = z.strictObject({ uploadId: uuid }) +export const photoResponseSchema = z.object({ + id: uuid, + space_id: uuid, + path: z.string(), + mime: photoContentTypeSchema, + size: photoSizeSchema, + uploaded_by: uuid.nullable(), + created_at: timestamp, }) export const healthResponseSchema = z.object({ status: z.literal('ok') }) @@ -85,8 +103,10 @@ export const photosResponseSchema = z.array(z.object({ name: uuid, createdAt: timestamp, url: z.url().nullish(), + mime: photoContentTypeSchema, + size: photoSizeSchema, + uploadedBy: uuid.nullable(), })) -export const uploadPhotoResponseSchema = z.object({ id: uuid, path: z.string(), fullPath: z.string() }) export type JoinSpaceRequest = z.input export type CreateDateRequest = z.input @@ -97,7 +117,10 @@ export type UpdateLocationRequest = z.input export type PhotosQuery = z.input export type PhotoParams = z.input export type PhotoContentType = z.infer -export type UploadPhotoRequest = z.input +export type PhotoUploadUrlRequest = z.input +export type PhotoUploadUrlResponse = z.infer +export type ConfirmPhotoRequest = z.input +export type PhotoResponse = z.infer export type HealthResponse = z.infer export type UpdateProfileRequest = z.input export type ProfileResponse = z.infer @@ -111,4 +134,3 @@ export type LocationResponse = z.infer export type SavedLocationResponse = z.infer export type DashboardResponse = z.infer export type PhotosResponse = z.infer -export type UploadPhotoResponse = z.infer diff --git a/shared/api-errors.ts b/shared/api-errors.ts index 001b5ad..ddcf3d9 100644 --- a/shared/api-errors.ts +++ b/shared/api-errors.ts @@ -5,6 +5,7 @@ export const apiErrorCodeSchema = z.enum([ 'already_paired', 'no_space', 'not_found', + 'quota_exceeded', 'validation_failed', 'unauthorized', 'internal', diff --git a/supabase/migrations/005_signed_gallery.sql b/supabase/migrations/005_signed_gallery.sql new file mode 100644 index 0000000..0434924 --- /dev/null +++ b/supabase/migrations/005_signed_gallery.sql @@ -0,0 +1,189 @@ +create table public.photos ( + id uuid primary key, + space_id uuid not null references public.spaces on delete cascade, + path text not null unique check (path = space_id::text || '/' || id::text), + mime text not null check (mime in ('image/jpeg', 'image/png', 'image/webp')), + size integer not null check (size between 1 and 5242880), + uploaded_by uuid references auth.users on delete set null, + created_at timestamptz not null default now() +); +create index photos_space_order on public.photos (space_id, created_at desc, id); + +create table public.photo_upload_reservations ( + id uuid primary key default gen_random_uuid(), + space_id uuid not null references public.spaces on delete cascade, + uploaded_by uuid references auth.users on delete set null, + mime text not null, + size integer not null, + sign_before timestamptz not null, + hold_until timestamptz not null, + closed boolean not null default false +); +create index photo_reservations_space on public.photo_upload_reservations (space_id, hold_until); + +alter table public.photos enable row level security; +alter table public.photo_upload_reservations enable row level security; +revoke all on public.photos, public.photo_upload_reservations from public, anon, authenticated; +grant select (id, space_id, path, mime, size, uploaded_by, created_at) on public.photos to authenticated; +create policy read_space_photos on public.photos for select to authenticated +using (space_id = public.my_space()); + +create function public.gallery_object_size(metadata jsonb) returns bigint language sql immutable +set search_path = '' as $$ + select case when metadata->>'size' ~ '^[0-9]{1,12}$' then (metadata->>'size')::bigint end +$$; +revoke all on function public.gallery_object_size(jsonb) from public, anon, authenticated; + +-- Keep compatible legacy objects visible without modifying Storage's metadata tables. +with legacy as ( + select object.*, regexp_match(object.name, + '^([0-9a-f-]{36})/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$') as parts + from storage.objects as object where object.bucket_id = 'gallery' +) +insert into public.photos (id, space_id, path, mime, size, uploaded_by, created_at) +select legacy.parts[2]::uuid, space.id, legacy.name, legacy.metadata->>'mimetype', + public.gallery_object_size(legacy.metadata), uploader.id, legacy.created_at +from legacy +join public.spaces as space on space.id::text = legacy.parts[1] +left join auth.users as uploader on uploader.id::text = legacy.owner_id +where public.gallery_object_size(legacy.metadata) between 1 and 5242880 + and legacy.metadata->>'mimetype' in ('image/jpeg', 'image/png', 'image/webp'); + +create function public.reserve_photo_upload(upload_mime text, upload_size integer) returns jsonb +language plpgsql security definer set search_path = '' as $$ +declare + room uuid; + reserved_id uuid; + held_bytes bigint; + stored_bytes bigint; + requested_at timestamptz; +begin + if upload_size is null or upload_size not between 1 and 5242880 + or upload_mime is null or upload_mime not in ('image/jpeg', 'image/png', 'image/webp') then + raise exception 'Unsupported photo metadata' using errcode = 'PT400'; + end if; + + select id into room from public.spaces where id = public.my_space() for update; + if room is null or public.my_space() is distinct from room then + raise exception 'No space' using errcode = 'PT403'; + end if; + requested_at := clock_timestamp(); + + -- Count each active reservation at the bucket limit and all other objects at their stored size. + with held_reservations as ( + select reservation.id + from public.photo_upload_reservations as reservation + where reservation.space_id = room and reservation.hold_until > requested_at + and not reservation.closed + and not exists (select 1 from public.photos as photo where photo.id = reservation.id) + ) + select + (select count(*) * 5242880 from held_reservations), + ( + select coalesce(sum(coalesce(public.gallery_object_size(object.metadata), 5242880)), 0) + from storage.objects as object + where object.bucket_id = 'gallery' and (storage.foldername(object.name))[1] = room::text + and not exists ( + select 1 from held_reservations as reservation + where object.name = room::text || '/' || reservation.id::text + ) + ) + into held_bytes, stored_bytes; + if held_bytes + stored_bytes + 5242880 > 52428800 then + raise exception 'Photo quota exceeded' using errcode = 'PT409'; + end if; + + -- Allow signing for one minute, then cover the two-hour token and a transfer grace period. + insert into public.photo_upload_reservations (space_id, uploaded_by, mime, size, sign_before, hold_until) + values (room, auth.uid(), upload_mime, upload_size, requested_at + interval '1 minute', + requested_at + interval '2 hours 16 minutes') + returning id into reserved_id; + return jsonb_build_object('uploadId', reserved_id, 'path', room::text || '/' || reserved_id::text); +end +$$; + +create function public.may_upload_gallery_object(object_path text) returns boolean +language sql stable security definer set search_path = '' as $$ + select exists ( + select 1 from public.photo_upload_reservations as reservation + where reservation.space_id = public.my_space() + and reservation.uploaded_by = auth.uid() + and not reservation.closed + and reservation.sign_before > statement_timestamp() + and object_path = reservation.space_id::text || '/' || reservation.id::text + ) +$$; + +drop policy gallery_upload on storage.objects; +create policy gallery_upload on storage.objects for insert to authenticated +with check (bucket_id = 'gallery' and public.may_upload_gallery_object(name)); + +create function public.confirm_photo(photo_upload_id uuid) returns jsonb +language plpgsql security definer set search_path = '' as $$ +declare + room uuid; + reservation public.photo_upload_reservations%rowtype; + photo public.photos%rowtype; + object_path text; + object_size bigint; + object_mime text; +begin + select id into room from public.spaces where id = public.my_space() for update; + if room is null or public.my_space() is distinct from room then + raise exception 'No space' using errcode = 'PT403'; + end if; + select * into reservation from public.photo_upload_reservations + where id = photo_upload_id and space_id = room and uploaded_by = auth.uid() + and ( + not closed or exists ( + select 1 from public.photos as existing_photo + where existing_photo.id = photo_upload_id and existing_photo.space_id = room + ) + ); + if not found then + raise exception 'Upload not found' using errcode = 'PT404'; + end if; + + object_path := room::text || '/' || photo_upload_id::text; + select public.gallery_object_size(metadata), metadata->>'mimetype' into object_size, object_mime + from storage.objects where bucket_id = 'gallery' and name = object_path; + if not found then + raise exception 'Photo not found' using errcode = 'PT404'; + end if; + if object_size is distinct from reservation.size or object_mime is distinct from reservation.mime then + raise exception 'Uploaded photo does not match its reservation' using errcode = 'PT400'; + end if; + + insert into public.photos (id, space_id, path, mime, size, uploaded_by) + values (photo_upload_id, room, object_path, object_mime, object_size, auth.uid()) + on conflict (id) do nothing; + update public.photo_upload_reservations set closed = true + where id = photo_upload_id and space_id = room and not closed; + select * into photo from public.photos where id = photo_upload_id and space_id = room; + return to_jsonb(photo); +end +$$; + +create function public.forget_photo(photo_id uuid) returns void +language plpgsql security definer set search_path = '' as $$ +declare + room uuid; + object_path text; +begin + select id into room from public.spaces where id = public.my_space() for update; + select path into object_path from public.photos where id = photo_id and space_id = room; + if object_path is null or public.my_space() is distinct from room then + raise exception 'Photo not found' using errcode = 'PT404'; + end if; + if exists (select 1 from storage.objects where bucket_id = 'gallery' and name = object_path) then + raise exception 'Photo object still exists'; + end if; + delete from public.photos where id = photo_id and space_id = room; + update public.photo_upload_reservations set closed = true where id = photo_id and space_id = room; +end +$$; + +revoke all on function public.reserve_photo_upload(text, integer), public.may_upload_gallery_object(text), + public.confirm_photo(uuid), public.forget_photo(uuid) from public, anon; +grant execute on function public.reserve_photo_upload(text, integer), public.may_upload_gallery_object(text), + public.confirm_photo(uuid), public.forget_photo(uuid) to authenticated; diff --git a/tests/api-errors.test.ts b/tests/api-errors.test.ts index 5708b4a..485c912 100644 --- a/tests/api-errors.test.ts +++ b/tests/api-errors.test.ts @@ -33,7 +33,7 @@ const dashboard = { const photo = { id, path: id + '/' + id, fullPath: 'gallery/' + id + '/' + id } beforeAll(async () => { - for (const name of ['defineEventHandler', 'createError', 'getHeader', 'getRouterParam', 'getValidatedRouterParams', 'getValidatedQuery', 'readValidatedBody', 'sendNoContent'] as const) { + for (const name of ['defineEventHandler', 'createError', 'getHeader', 'getRouterParam', 'getValidatedRouterParams', 'getValidatedQuery', 'readBody', 'readValidatedBody', 'sendNoContent'] as const) { vi.stubGlobal(name, h3[name]) } for (const [name, value] of Object.entries(backend)) { @@ -61,8 +61,9 @@ beforeAll(async () => { router.delete('/api/space/membership', (await import('../server/api/space/membership.delete')).default) router.delete('/api/location', (await import('../server/api/location.delete')).default) router.get('/api/dashboard', (await import('../server/api/dashboard.get')).default) - router.post('/api/photos', (await import('../server/api/photos/index.post')).default) - router.get('/api/photos', (await import('../server/api/photos/index.get')).default) + router.post('/api/photos/upload-url', (await import('../server/api/photos/upload-url.post')).default) + router.post('/api/photos/confirm', (await import('../server/api/photos/confirm.post')).default) + router.use('/api/photos', (await import('../server/api/photos/index')).default) router.delete('/api/photos/:name', (await import('../server/api/photos/[name].delete')).default) server = createServer(h3.toNodeListener(h3.createApp().use(router))).listen(0, '127.0.0.1') await once(server, 'listening') @@ -142,15 +143,34 @@ test.each([ expect(upstream).not.toHaveBeenCalled() }) -test('returns validation_failed and retains 415 for unsupported photo media', async () => { - upstream.mockResolvedValueOnce(Response.json(id)) - await expectError(await request('POST', '/photos', 'plain text', true, 'text/plain'), 415, 'validation_failed') +test('does not route binary uploads through Nitro', async () => { + const response = await request('POST', '/photos', 'bytes', true, 'image/png') + await expectError(response, 405, 'validation_failed') + expect(response.headers.get('allow')).toBe('GET, HEAD') + expect(upstream).not.toHaveBeenCalled() }) -test('returns validation_failed and retains 413 for oversized photos', async () => { +test.each([ + [{ mime: 'text/plain', size: 5 }, 415], + [{ mime: 'image/png', size: 5242881 }, 413], +] as const)('rejects invalid signed-upload metadata %j', async (body, status) => { + await expectError(await request('POST', '/photos/upload-url', JSON.stringify(body)), status, 'validation_failed') + expect(upstream).not.toHaveBeenCalled() +}) + +test('rejects an over-quota reservation before signing', async () => { + postgresError('PT409', 409) + const response = await request('POST', '/photos/upload-url', '{"mime":"image/png","size":42}') + expect(response.status).toBe(409) + expect(await response.json()).toMatchObject({ data: { code: 'quota_exceeded' } }) + expect(upstream).toHaveBeenCalledTimes(1) +}) + +test('returns the same not_found for an invisible or missing photo', async () => { upstream.mockResolvedValueOnce(Response.json(id)) - const body = new Uint8Array(5 * 1024 * 1024 + 1) - await expectError(await request('POST', '/photos', body, true, 'image/png'), 413, 'validation_failed') + upstream.mockResolvedValueOnce(Response.json([])) + await expectError(await request('DELETE', '/photos/' + id), 404, 'not_found') + expect(upstream).toHaveBeenCalledTimes(2) }) test('returns unauthorized for missing and rejected bearer tokens', async () => { @@ -209,7 +229,7 @@ test.each([ schema: contract.photosResponseSchema, upstreamData: [ id, - [{ name: id, created_at: now }], + [{ id, path: photo.path, mime: 'image/png', size: 10, uploaded_by: id, created_at: now }], [{ path: photo.path, error: null, signedURL: '/object/sign/' + photo.fullPath + '?token=test' }], ], }, @@ -222,20 +242,22 @@ test.each([ schema.parse(await response.json()) }) -test('photo uploads match the shared response schema', async () => { - upstream.mockResolvedValueOnce(Response.json(id)) - upstream.mockImplementationOnce(async input => { - const key = new URL(String(input)).pathname.split('/object/')[1] - return Response.json({ Id: photo.id, Key: key }) +test('signs the reserved path and confirms stored photo metadata', async () => { + upstream.mockResolvedValueOnce(Response.json({ uploadId: id, path: photo.path })) + upstream.mockResolvedValueOnce(Response.json({ url: '/object/upload/sign/' + photo.fullPath + '?token=test-token' })) + const requestBody = contract.photoUploadUrlRequestSchema.parse({ mime: 'image/png', size: 5242880 }) + const signed = await request('POST', '/photos/upload-url', JSON.stringify(requestBody)) + expect(signed.status).toBe(200) + expect(contract.photoUploadUrlResponseSchema.parse(await signed.json())).toMatchObject({ + uploadId: id, path: photo.path, token: 'test-token', }) - const png = Uint8Array.from(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aE1sAAAAASUVORK5CYII=', 'base64')) - const uploadRequest = contract.uploadPhotoRequestSchema.parse({ body: png, contentType: 'image/png' }) - const response = await request('POST', '/photos', uploadRequest.body, true, uploadRequest.contentType) - expect(response.status).toBe(200) - const upload = contract.uploadPhotoResponseSchema.parse(await response.json()) - expect(upload.id).toBe(photo.id) - expect(upload.path).toMatch(new RegExp('^' + id + '/[a-f0-9-]{36}$')) - expect(upload.fullPath).toBe('gallery/' + upload.path) + expect(String(upstream.mock.calls[1][0])).toContain('/object/upload/sign/' + photo.fullPath) + + const stored = { id, space_id: id, path: photo.path, mime: 'image/png', size: 5242880, uploaded_by: id, created_at: now } + upstream.mockResolvedValueOnce(Response.json(stored)) + const confirmed = await request('POST', '/photos/confirm', JSON.stringify({ uploadId: id })) + expect(confirmed.status).toBe(200) + expect(contract.photoResponseSchema.parse(await confirmed.json())).toEqual(stored) }) test('filters dates by a category key and returns the shared date shape', async () => { @@ -302,7 +324,7 @@ test.each(['/space/membership', '/location'])('returns an empty 204 for DELETE % test.each([ { method: 'GET', path: '/space', upstreamData: [null] }, { method: 'DELETE', path: '/dates/' + id, upstreamData: [{ id }] }, - { method: 'DELETE', path: '/photos/' + id, upstreamData: [id, []] }, + { method: 'DELETE', path: '/photos/' + id, upstreamData: [id, [{ path: photo.path }], [], null] }, ])('$method $path returns the shared empty response', async ({ method, path, upstreamData }) => { for (const data of upstreamData) { upstream.mockResolvedValueOnce(Response.json(data)) diff --git a/tests/isolation.test.mjs b/tests/isolation.test.mjs index 4a264fc..95ae271 100644 --- a/tests/isolation.test.mjs +++ b/tests/isolation.test.mjs @@ -33,6 +33,9 @@ beforeEach(async () => { create table storage.objects ( bucket_id text not null references storage.buckets(id), name text not null, + metadata jsonb, + owner_id text, + created_at timestamptz not null default now(), primary key (bucket_id, name) ); create function storage.foldername(name text) returns text[] language sql immutable as $$ @@ -47,14 +50,14 @@ beforeEach(async () => { users = (await pg.query('select id from auth.users order by id')).rows }, 15_000) -async function migrate(seedLegacyDates) { +async function migrate(seedLegacyRows) { const migrationFiles = (await readdir(migrations)) .filter(name => /^\d+_.+\.sql$/.test(name)) .sort((a, b) => a.localeCompare(b, 'en', { numeric: true })) for (const filename of migrationFiles) { await pg.exec(await readFile(new URL(filename, migrations), 'utf8')) - if (filename === '002_private_gallery.sql' && seedLegacyDates) { - await seedLegacyDates() + if (filename === '002_private_gallery.sql' && seedLegacyRows) { + await seedLegacyRows() } } @@ -67,6 +70,174 @@ afterEach(async () => { const login = i => pg.query("select set_config('request.jwt.claim.sub',$1,false)", [users[i].id]) +const mebibyte = 1024 * 1024 + +async function createPhotoSpace() { + await migrate() + await login(0) + const { id } = (await pg.query('select create_space() as id')).rows[0] + return id +} + +async function reservePhoto(size) { + const { data } = (await pg.query("select reserve_photo_upload('image/png', $1) as data", [size])).rows[0] + return data +} + +function storePhoto(path, size) { + return pg.query("insert into storage.objects(bucket_id, name, metadata) values ('gallery', $1, $2)", [ + path, { size, mimetype: 'image/png' }, + ]) +} + +async function uploadAndConfirmPhoto(size) { + const reservation = await reservePhoto(size) + await storePhoto(reservation.path, size) + await pg.query('select confirm_photo($1)', [reservation.uploadId]) + return reservation +} + +function deletePhotoObject(path) { + return pg.query("delete from storage.objects where bucket_id = 'gallery' and name = $1", [path]) +} + +test('reserves the maximum upload size before allocating signed paths', async () => { + await createPhotoSpace() + for (let index = 0; index < 10; index++) { + await reservePhoto(1) + } + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + await login(2) + await pg.query('select create_space()') + await reservePhoto(1) +}) + +test('photo quota allows twelve sequential 100 KB uploads and confirmations', async () => { + await createPhotoSpace() + for (let index = 0; index < 12; index++) { + await uploadAndConfirmPhoto(100_000) + } + assert.deepEqual((await pg.query('select size from photos')).rows, Array.from({ length: 12 }, () => ({ size: 100_000 }))) +}) + +test('photo quota charges a confirmed upload by its stored bytes and closes its signing window', async () => { + const space = await createPhotoSpace() + const size = 100_000 + const confirmed = await uploadAndConfirmPhoto(size) + for (let index = 0; index < 8; index++) { + await reservePhoto(1) + } + + const fillerPath = space + '/quota-filler' + await pg.exec('reset role') + await storePhoto(fillerPath, 5 * mebibyte - size) + await storePhoto(space + '/one-extra-byte', 1) + await pg.exec('set role authenticated') + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + await deletePhotoObject(space + '/one-extra-byte') + + // Eight holds, the two stored objects, and the new hold add up to exactly 50 MiB. + await reservePhoto(1) + const { allowed } = (await pg.query('select may_upload_gallery_object($1) as allowed', [confirmed.path])).rows[0] + assert.equal(allowed, false) +}) + +test('photo quota is available immediately after deleting a confirmed photo', async () => { + await createPhotoSpace() + const photo = await uploadAndConfirmPhoto(5 * mebibyte) + for (let index = 0; index < 9; index++) { + await reservePhoto(1) + } + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + + await deletePhotoObject(photo.path) + await pg.query('select forget_photo($1)', [photo.uploadId]) + await reservePhoto(1) + await assert.rejects(pg.query('select confirm_photo($1)', [photo.uploadId]), { code: 'PT404' }) +}) + +test('photo quota holds 5 MiB for an unconfirmed upload through hold_until', async () => { + await createPhotoSpace() + const pending = await reservePhoto(100_000) + await storePhoto(pending.path, 100_000) + for (let index = 0; index < 9; index++) { + await reservePhoto(1) + } + + await pg.exec('reset role') + await pg.query("update photo_upload_reservations set sign_before = now() - interval '1 second' where id = $1", [pending.uploadId]) + await pg.exec('set role authenticated') + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + + await pg.exec('reset role') + await pg.query("update photo_upload_reservations set hold_until = now() - interval '1 second' where id = $1", [pending.uploadId]) + await pg.exec('set role authenticated') + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + await deletePhotoObject(pending.path) + await reservePhoto(1) +}) + +test('photo quota rejects a new hold when stored bytes alone would put it over 50 MiB', async () => { + const space = await createPhotoSpace() + await pg.exec('reset role') + for (let index = 0; index < 9; index++) { + await storePhoto(space + '/stored-' + index, 5 * mebibyte) + } + await storePhoto(space + '/one-extra-byte', 1) + await pg.exec('set role authenticated') + + await assert.rejects(reservePhoto(1), { code: 'PT409' }) + await deletePhotoObject(space + '/one-extra-byte') + await reservePhoto(1) +}) + +test('confirms stored photo metadata at most once and isolates foreign spaces', async () => { + await migrate() + await login(0) + const { id: space } = (await pg.query('select create_space() as id')).rows[0] + const { uploadId, path } = (await pg.query("select reserve_photo_upload('image/png', 10) as data")).rows[0].data + assert.equal(path, space + '/' + uploadId) + await assert.rejects(pg.query('select confirm_photo($1)', [uploadId]), { code: 'PT404' }) + await pg.query("insert into storage.objects(bucket_id, name, metadata) values ('gallery', $1, $2)", [path, { size: 11, mimetype: 'image/png' }]) + await assert.rejects(pg.query('select confirm_photo($1)', [uploadId]), { code: 'PT400' }) + await pg.exec('reset role') + await pg.query('update storage.objects set metadata = $2 where name = $1', [path, { size: 10, mimetype: 'image/png' }]) + await pg.exec('set role authenticated') + const { photo } = (await pg.query('select confirm_photo($1) as photo', [uploadId])).rows[0] + assert.equal(photo.id, uploadId) + assert.equal(photo.size, 10) + assert.deepEqual((await pg.query('select confirm_photo($1) as photo', [uploadId])).rows[0].photo, photo) + await login(2) + await pg.query('select create_space()') + assert.deepEqual((await pg.query('select id from photos')).rows, []) + await assert.rejects(pg.query('select confirm_photo($1)', [uploadId]), { code: 'PT404' }) + await assert.rejects(pg.query('select forget_photo($1)', [uploadId]), { code: 'PT404' }) +}) + +test('preserves compatible legacy gallery objects and charges incompatible objects to the quota', async () => { + const id = '11111111-1111-4111-8111-111111111111' + let path + await migrate(async () => { + await pg.exec('set role authenticated') + await login(0) + const { space } = (await pg.query('select create_space() as space')).rows[0] + path = space + '/' + id + await pg.query("insert into storage.objects(bucket_id, name, metadata, owner_id) values ('gallery', $1, $2, $3)", [ + path, { size: 10, mimetype: 'image/png' }, users[0].id, + ]) + await pg.query("insert into storage.objects(bucket_id, name) values ('gallery', $1)", [space + '/legacy-missing-metadata']) + await pg.exec('reset role') + }) + await login(0) + assert.deepEqual((await pg.query('select id, path, size, uploaded_by from photos')).rows, [ + { id, path, size: 10, uploaded_by: users[0].id }, + ]) + for (let index = 0; index < 8; index++) { + await pg.query("select reserve_photo_upload('image/png', 1)") + } + await assert.rejects(pg.query("select reserve_photo_upload('image/png', 1)"), { code: 'PT409' }) +}) + test('profiles are visible to the owner and current partner, with owner-only writes', async () => { await migrate() await login(0) @@ -110,9 +281,9 @@ test('leaving removes membership and location and lets the remaining partner re- await migrate() await login(0) await pg.query('select create_space()') - const { id, invite } = (await pg.query('select id, invite from spaces')).rows[0] + const { invite } = (await pg.query('select invite from spaces')).rows[0] await pg.query("insert into dates(title, category) values ('Shared walk', 'walk')") - const photo = id + '/11111111-1111-4111-8111-111111111111' + const { path: photo } = (await pg.query("select reserve_photo_upload('image/png', 10) as data")).rows[0].data await pg.query("insert into storage.objects(bucket_id, name) values ('gallery', $1)", [photo]) await pg.query('insert into locations(lat, lon) values (52, 12)') await pg.query("insert into profiles(display_name) values ('Alex')") @@ -300,10 +471,11 @@ test('the private gallery allows shared access and enforces space boundaries for assert.deepEqual((await pg.query("select public, file_size_limit, allowed_mime_types from storage.buckets where id = 'gallery'")).rows, [ { public: false, file_size_limit: 5242880, allowed_mime_types: ['image/jpeg', 'image/png', 'image/webp'] } ]) - const photo = id + '/11111111-1111-4111-8111-111111111111' + const { path: photo } = (await pg.query("select reserve_photo_upload('image/png', 10) as data")).rows[0].data const insertPhoto = name => pg.query("insert into storage.objects(bucket_id, name) values ('gallery', $1)", [name]) const listPhotos = () => pg.query("select name from storage.objects where bucket_id = 'gallery'") const removePhoto = () => pg.query("delete from storage.objects where bucket_id = 'gallery' and name = $1 returning name", [photo]) + await assert.rejects(insertPhoto(id + '/11111111-1111-4111-8111-111111111111'), { code: '42501' }) await insertPhoto(photo) await login(2)