feat(sessions): material downloads unlock when the session ends
Private materials bucket + RLS read gate (admins/own speakers anytime, all attendees after the scheduled slot end, event-local Amsterdam time); always visible uploaded-state, locked download panel, authenticated client downloads, admin signed URLs. 12 new assertions in material_time_lock_tests.sql.
This commit is contained in:
1 parent
a2b87602b4
commit
d4e4637e7c
13 files changed
+333
-29
No files matched your search
@@ -538,9 +538,12 @@ export async function removeSessionMaterial(sessionId: string): Promise<void> {
|
|||||||
if (error) throw new ApiError(error.message);
|
if (error) throw new ApiError(error.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sessionMaterialUrl(path: string): string {
|
/** Open a session material in a new tab via a short-lived signed URL. The
|
||||||
const { data } = supabase.storage.from('materials').getPublicUrl(path);
|
* materials bucket is private; storage RLS always allows admins. */
|
||||||
return data.publicUrl;
|
export async function openSessionMaterial(path: string): Promise<void> {
|
||||||
|
const { data, error } = await supabase.storage.from('materials').createSignedUrl(path, 600);
|
||||||
|
if (error) throw new ApiError(error.message);
|
||||||
|
window.open(data.signedUrl, '_blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
getSessions,
|
getSessions,
|
||||||
getSlots,
|
getSlots,
|
||||||
removeSessionMaterial,
|
removeSessionMaterial,
|
||||||
sessionMaterialUrl,
|
openSessionMaterial,
|
||||||
setSessionSpeakers,
|
setSessionSpeakers,
|
||||||
uploadSessionMaterial,
|
uploadSessionMaterial,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
@@ -573,9 +573,19 @@ function SessionModal({
|
|||||||
<label>Material</label>
|
<label>Material</label>
|
||||||
{session.material_path ? (
|
{session.material_path ? (
|
||||||
<div className="row" style={{ gap: 10 }}>
|
<div className="row" style={{ gap: 10 }}>
|
||||||
<a className="btn small" href={sessionMaterialUrl(session.material_path)} target="_blank" rel="noreferrer">
|
<button
|
||||||
|
className="btn small"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await openSessionMaterial(session.material_path!);
|
||||||
|
} catch (e) {
|
||||||
|
onSaved(e instanceof Error ? e.message : 'Could not open material');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
📎 View current
|
📎 View current
|
||||||
</a>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn small danger"
|
className="btn small danger"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { useRef } from 'react';
|
import { useRef } from 'react';
|
||||||
import {
|
import {
|
||||||
clearPreference,
|
clearPreference,
|
||||||
|
downloadSessionMaterial,
|
||||||
removeSessionMaterial,
|
removeSessionMaterial,
|
||||||
sessionMaterialUrl,
|
|
||||||
setPreference,
|
setPreference,
|
||||||
uploadSessionMaterial,
|
uploadSessionMaterial,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import { fmtRange, slotStatus } from '../lib/time';
|
import { fmtRange, fmtTime, slotStatus } from '../lib/time';
|
||||||
import type { Session, Slot } from '../lib/types';
|
import type { Session, Slot } from '../lib/types';
|
||||||
import { useToast } from '../context/ToastContext';
|
import { useToast } from '../context/ToastContext';
|
||||||
import { Sheet } from './ui';
|
import { Sheet } from './ui';
|
||||||
@@ -100,6 +100,15 @@ export function SessionDetail({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleDownloadMaterial() {
|
||||||
|
if (!session?.material_path) return;
|
||||||
|
try {
|
||||||
|
await downloadSessionMaterial(session.material_path);
|
||||||
|
} catch (err) {
|
||||||
|
toast(err instanceof Error ? err.message : 'Download failed', 'err');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const range = fmtRange(slot);
|
const range = fmtRange(slot);
|
||||||
// Talk slots are auto-named "Slot 10:15–11:00", which merely repeats the
|
// Talk slots are auto-named "Slot 10:15–11:00", which merely repeats the
|
||||||
// time range shown next to it, and service slots are often named exactly
|
// time range shown next to it, and service slots are often named exactly
|
||||||
@@ -189,11 +198,26 @@ export function SessionDetail({
|
|||||||
{picked ? 'Remove my pick' : 'Pick this session'}
|
{picked ? 'Remove my pick' : 'Pick this session'}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{/* Material download (all attendees) — pinned to the bottom. */}
|
{/* Material: its existence is ALWAYS surfaced once uploaded, but the
|
||||||
|
download stays locked until the session's scheduled end so slides
|
||||||
|
don't distract mid-session. `status === 'done'` (client) mirrors
|
||||||
|
the server-side storage RLS rule; speakers bypass the lock for
|
||||||
|
their own talk. After the end anyone can download — attendance is
|
||||||
|
not required, only the clock. */}
|
||||||
{session.material_path && (
|
{session.material_path && (
|
||||||
<a className="btn primary" href={sessionMaterialUrl(session.material_path)} target="_blank" rel="noreferrer">
|
isSpeaker || status === 'done' ? (
|
||||||
|
<button className="btn primary" data-testid="material-download" onClick={handleDownloadMaterial}>
|
||||||
📎 Download material
|
📎 Download material
|
||||||
</a>
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="material-notice" data-testid="material-locked">
|
||||||
|
<div className="mn-title">📎 Material uploaded</div>
|
||||||
|
<div className="muted small">
|
||||||
|
The speaker has uploaded material for this session.
|
||||||
|
The download unlocks when the session ends at {fmtTime(slot.end_time)}.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
)}
|
)}
|
||||||
{/* Speakers can remove their own material to re-upload. */}
|
{/* Speakers can remove their own material to re-upload. */}
|
||||||
{isSpeaker && session.material_path && (
|
{isSpeaker && session.material_path && (
|
||||||
|
|||||||
@@ -236,10 +236,28 @@ export async function getMyPointsLog(email: string): Promise<PointsLogRow[]> {
|
|||||||
return data as PointsLogRow[];
|
return data as PointsLogRow[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Public URL for a session material stored in the `materials` bucket. */
|
/** Filename of a material object path (`sessions/<id>/<ts>-<name>`). */
|
||||||
export function sessionMaterialUrl(path: string): string {
|
export function materialFilename(path: string): string {
|
||||||
const { data } = supabase.storage.from('materials').getPublicUrl(path);
|
const base = path.slice(path.lastIndexOf('/') + 1);
|
||||||
return data.publicUrl;
|
return base.replace(/^\d+-/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Download a session material through authenticated storage. The materials
|
||||||
|
* bucket is private and server-side RLS only releases the file to the
|
||||||
|
* session's own speakers/admins at any time, and to everyone else once the
|
||||||
|
* session's scheduled end has passed — so this legitimately fails before the
|
||||||
|
* end for plain attendees even if the UI clock disagrees. */
|
||||||
|
export async function downloadSessionMaterial(path: string): Promise<void> {
|
||||||
|
const { data, error } = await supabase.storage.from('materials').download(path);
|
||||||
|
if (error) throw new ApiError('Download failed — material unlocks when the session ends.');
|
||||||
|
const url = URL.createObjectURL(data);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = materialFilename(path);
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Session ids the signed-in contact is a speaker of (for material upload). */
|
/** Session ids the signed-in contact is a speaker of (for material upload). */
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { Session } from '@supabase/supabase-js';
|
|||||||
import { LoaderCircle, Paperclip } from 'lucide-react';
|
import { LoaderCircle, Paperclip } from 'lucide-react';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
import { getSpeakerPortalSessions, speakerPortalSession, type SpeakerSession } from '../lib/speakerPortal';
|
import { getSpeakerPortalSessions, speakerPortalSession, type SpeakerSession } from '../lib/speakerPortal';
|
||||||
import { removeSessionMaterial, sessionMaterialUrl, uploadSessionMaterial } from '../lib/api';
|
import { downloadSessionMaterial, removeSessionMaterial, uploadSessionMaterial } from '../lib/api';
|
||||||
|
|
||||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
||||||
const FILE_TYPES = '.pdf,.ppt,.pptx,.odp,.zip,.txt';
|
const FILE_TYPES = '.pdf,.ppt,.pptx,.odp,.zip,.txt';
|
||||||
@@ -110,7 +110,7 @@ export function SpeakerPortal() {
|
|||||||
<p className="small muted">{talk.event_name} · {talk.is_active ? 'Active event' : 'Inactive event'}</p>
|
<p className="small muted">{talk.event_name} · {talk.is_active ? 'Active event' : 'Inactive event'}</p>
|
||||||
<h3 className="h2">{talk.title}</h3>
|
<h3 className="h2">{talk.title}</h3>
|
||||||
<p className="small">{talk.slot_date} · {talk.start_time.slice(0, 5)} - {talk.end_time.slice(0, 5)}{talk.room && ` · ${talk.room}`}</p>
|
<p className="small">{talk.slot_date} · {talk.start_time.slice(0, 5)} - {talk.end_time.slice(0, 5)}{talk.room && ` · ${talk.room}`}</p>
|
||||||
{talk.material_path ? <a className="speaker-download" href={sessionMaterialUrl(talk.material_path)} target="_blank" rel="noreferrer">Download material</a> : <p className="small muted">No material uploaded</p>}
|
{talk.material_path ? <button className="speaker-download" onClick={async () => { try { await downloadSessionMaterial(talk.material_path!); } catch (failure) { setError(messageOf(failure)); } }}>Download material</button> : <p className="small muted">No material uploaded</p>}
|
||||||
<label className="speaker-upload" htmlFor={`material-${talk.session_id}`}>
|
<label className="speaker-upload" htmlFor={`material-${talk.session_id}`}>
|
||||||
{workingTalk === talk.session_id ? <LoaderCircle aria-hidden="true" className="speaker-upload-spinner" /> : <Paperclip aria-hidden="true" />}
|
{workingTalk === talk.session_id ? <LoaderCircle aria-hidden="true" className="speaker-upload-spinner" /> : <Paperclip aria-hidden="true" />}
|
||||||
<span>{workingTalk === talk.session_id ? 'Saving material...' : talk.material_path ? 'Replace material' : 'Upload material'}</span>
|
<span>{workingTalk === talk.session_id ? 'Saving material...' : talk.material_path ? 'Replace material' : 'Upload material'}</span>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
.speaker-talk { display: grid; gap: 10px; padding: 18px 0; border-top: 1px solid var(--line); }
|
.speaker-talk { display: grid; gap: 10px; padding: 18px 0; border-top: 1px solid var(--line); }
|
||||||
.speaker-portal input { width: 100%; min-width: 0; }
|
.speaker-portal input { width: 100%; min-width: 0; }
|
||||||
.speaker-portal progress { width: 100%; accent-color: var(--accent-2); }
|
.speaker-portal progress { width: 100%; accent-color: var(--accent-2); }
|
||||||
.speaker-download { color: var(--accent-2); }
|
.speaker-download { color: var(--accent-2); background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline; }
|
||||||
.speaker-upload {
|
.speaker-upload {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
+12
-2
@@ -123,12 +123,15 @@ create policy "points_log_select_own_or_admin" on public.points_log for select t
|
|||||||
|
|
||||||
## Storage — `materials` bucket
|
## Storage — `materials` bucket
|
||||||
|
|
||||||
The `materials` bucket (public read) stores session material. Policies on
|
The `materials` bucket is **private** and stores session material. Downloads
|
||||||
|
unlock when the session's scheduled end has passed (event-local Amsterdam
|
||||||
|
time) — until then only the session's own speakers and admins can read the
|
||||||
|
object, so a known path/URL does not release the bytes early. Policies on
|
||||||
`storage.objects`:
|
`storage.objects`:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
create policy "materials_read" on storage.objects for select to authenticated
|
create policy "materials_read" on storage.objects for select to authenticated
|
||||||
using (bucket_id = 'materials');
|
using (public.can_read_session_material(bucket_id, name));
|
||||||
create policy "materials_write" on storage.objects for insert to authenticated
|
create policy "materials_write" on storage.objects for insert to authenticated
|
||||||
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||||
create policy "materials_update" on storage.objects for update to authenticated
|
create policy "materials_update" on storage.objects for update to authenticated
|
||||||
@@ -138,6 +141,13 @@ create policy "materials_delete" on storage.objects for delete to authenticated
|
|||||||
using (bucket_id = 'materials' and public.can_write_session_material(name));
|
using (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`can_read_session_material` (security definer, `20261021180000_material_time_lock.sql`)
|
||||||
|
parses `sessions/<uuid>/<file>` paths, allows `is_admin()` and
|
||||||
|
`owns_speaker_session(uuid)` at any time, everyone else only once
|
||||||
|
`session_material_unlocked(uuid)` holds (slot `slot_date + end_time <=
|
||||||
|
timezone('Europe/Amsterdam', now())`). Anything malformed or in another bucket
|
||||||
|
is denied by this policy (other buckets keep their own policies).
|
||||||
|
|
||||||
Registered speakers can write only their own non-service session paths; admins
|
Registered speakers can write only their own non-service session paths; admins
|
||||||
retain material management access. Any authenticated attendee can read (download).
|
retain material management access. Any authenticated attendee can read (download).
|
||||||
Because the `sessions` table is admin-write only, a speaker attaches their
|
Because the `sessions` table is admin-write only, a speaker attaches their
|
||||||
|
|||||||
@@ -366,7 +366,10 @@ enqueuing, claiming, completing and dead-lettering all go through the RPCs in
|
|||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
|
|
||||||
A **`materials`** bucket (public read) stores session material. Speakers + admins
|
A **`materials`** bucket (**private** since `20261021180000_material_time_lock.sql`)
|
||||||
can write (see [rls.md](./rls.md#storage--materials-bucket)). A session's
|
stores session material. Speakers + admins can write (see
|
||||||
`material_path` points at the object; the public URL is
|
[rls.md](./rls.md#storage--materials-bucket)). A session's `material_path`
|
||||||
`/storage/v1/object/public/materials/{material_path}`.
|
points at the object. Files are fetched through **authenticated** storage
|
||||||
|
requests (attendee app) or short-lived signed URLs (admin app); the read policy
|
||||||
|
releases a file to plain attendees only after the session's scheduled end —
|
||||||
|
`/storage/v1/object/public/...` URLs no longer serve materials.
|
||||||
@@ -80,8 +80,10 @@ client-side to avoid leaking other people's data:
|
|||||||
|
|
||||||
- **`groupAgenda(rows)`** — turns the flat `get_agenda()` rows into
|
- **`groupAgenda(rows)`** — turns the flat `get_agenda()` rows into
|
||||||
`{ slot, sessions[] }[]` ordered by slot id. Used by `useEvent()`.
|
`{ slot, sessions[] }[]` ordered by slot id. Used by `useEvent()`.
|
||||||
- **`sessionMaterialUrl(path)`** — builds the public URL for a session material
|
- **`downloadSessionMaterial(path)`** — downloads a material file through
|
||||||
in the `materials` bucket.
|
authenticated storage (private bucket; server-side RLS allows it for the
|
||||||
|
session's speakers/admins anytime, everyone else after the session ended).
|
||||||
|
**`materialFilename(path)`** strips the `sessions/<id>/<ts>-` prefix.
|
||||||
|
|
||||||
## Admin Email Entry
|
## Admin Email Entry
|
||||||
|
|
||||||
|
|||||||
@@ -213,9 +213,14 @@ the agenda list, its slot count, and Home's Now/Next cards all agree.
|
|||||||
and no material is uploaded yet, a **non-dismissible** "📎 Upload your session
|
and no material is uploaded yet, a **non-dismissible** "📎 Upload your session
|
||||||
material" notice with a file input. Uploading stores the file in the
|
material" notice with a file input. Uploading stores the file in the
|
||||||
`materials` bucket and calls `set_session_material` (via
|
`materials` bucket and calls `set_session_material` (via
|
||||||
`uploadSessionMaterial`). Once uploaded, the notice is gone and a **📎
|
`uploadSessionMaterial`). Once uploaded, the notice is gone. Attendees
|
||||||
Download material** button appears (visible to **all** attendees), pinned to
|
**always see that material exists** (📎 on the agenda card, and in the
|
||||||
the **bottom** of the sheet's button stack (below "Pick this session").
|
sheet), but downloads **unlock when the session ends**: before `slot end`
|
||||||
|
non-speakers see a "📎 Material uploaded — unlocks at HH:MM" panel
|
||||||
|
(`material-locked`), after it (or as the session's speaker) a **📎
|
||||||
|
Download material** button (`downloadSessionMaterial`, authenticated
|
||||||
|
storage — the private bucket's RLS enforces the same rule server-side;
|
||||||
|
attendance is irrelevant, only the clock).
|
||||||
- **Remove material** — a speaker of the session can also **🗑 Remove material**
|
- **Remove material** — a speaker of the session can also **🗑 Remove material**
|
||||||
(to re-upload). This deletes the storage object and clears `material_path` via
|
(to re-upload). This deletes the storage object and clears `material_path` via
|
||||||
`set_session_material` (null) — `removeSessionMaterial`.
|
`set_session_material` (null) — `removeSessionMaterial`.
|
||||||
|
|||||||
@@ -610,6 +610,30 @@ in `transform-excel.test.js`; verified against the real Sessionize demo payload
|
|||||||
(10/11 sessions get a language, service sessions stay null → now forced
|
(10/11 sessions get a language, service sessions stay null → now forced
|
||||||
English by the RPCs).
|
English by the RPCs).
|
||||||
|
|
||||||
|
## Material downloads unlock at the session end — ✅ complete (2026-10-21)
|
||||||
|
|
||||||
|
Product rule (Sabrina): uploaded session material must not distract attendees
|
||||||
|
mid-session, but must be available to **everyone** (time-based, attendance not
|
||||||
|
required) once the session's schedule ends — and users must always *see* that
|
||||||
|
a speaker uploaded material even while the download is locked.
|
||||||
|
|
||||||
|
- **Enforced at the storage layer**, not the UI: `20261021180000_material_time_lock.sql`
|
||||||
|
makes the `materials` bucket **private** and replaces `materials_read` with
|
||||||
|
`can_read_session_material(bucket, name)`: admins and the session's own
|
||||||
|
speakers anytime; everyone else only after `slot_date + end_time`
|
||||||
|
(Europe/Amsterdam wall time, matching the client's existing `slotStatus ===
|
||||||
|
'done'` rule). A leaked path/URL releases nothing early.
|
||||||
|
- **Always-visible existence**: the agenda card 📎 pill already renders from
|
||||||
|
`material_path` (unchanged, `get_agenda` still returns it); SessionDetail
|
||||||
|
shows a "📎 Material uploaded — unlocks at HH:MM" panel (`material-locked`)
|
||||||
|
while locked, and a download button once unlocked or for the speaker.
|
||||||
|
- **Clients**: attendee app downloads via authenticated
|
||||||
|
`storage.from('materials').download()` (blob + filename); admin app switched
|
||||||
|
to short-lived `createSignedUrl`. No `getPublicUrl` remains in any app.
|
||||||
|
- **Tests**: `supabase/tests/material_time_lock_tests.sql` — 12 assertions
|
||||||
|
(bucket private, outsider locked/unlocked by time, speaker/admin bypass,
|
||||||
|
malformed/foreign-bucket rejection, event-local boundary, anon exclusion).
|
||||||
|
|
||||||
## Known work (open as of 2026-10-19)
|
## Known work (open as of 2026-10-19)
|
||||||
|
|
||||||
- **E2E seed drift — 42 specs currently red.** The pretix reseed removed the
|
- **E2E seed drift — 42 specs currently red.** The pretix reseed removed the
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
-- =============================================================================
|
||||||
|
-- Session materials unlock at the scheduled session end.
|
||||||
|
--
|
||||||
|
-- Product rule: once a speaker uploads material, attendees must ALWAYS see
|
||||||
|
-- that material exists — but the download stays locked until the session's
|
||||||
|
-- slot has ended, so slides are not a distraction mid-session. After the
|
||||||
|
-- scheduled end everyone (any signed-in attendee, attendance not required —
|
||||||
|
-- purely time-based) can download. The session's own speakers and admins keep
|
||||||
|
-- access at any time.
|
||||||
|
--
|
||||||
|
-- Enforcement is at the STORAGE layer, not the UI: the `materials` bucket
|
||||||
|
-- becomes private (the /object/public/ endpoint stops serving files) and the
|
||||||
|
-- read policy only releases an object to admins, the owning speakers, or after
|
||||||
|
-- the slot end. Knowing the exact path/URL no longer yields the bytes before
|
||||||
|
-- the session ends.
|
||||||
|
-- =============================================================================
|
||||||
|
|
||||||
|
-- Unlock = the session's slot has ended, on event-local wall time
|
||||||
|
-- (APPE events run in Amsterdam; slot_date + end_time are event-local).
|
||||||
|
create or replace function public.session_material_unlocked(p_session_id uuid)
|
||||||
|
returns boolean
|
||||||
|
language sql stable security definer set search_path = '' as $$
|
||||||
|
select exists (
|
||||||
|
select 1
|
||||||
|
from public.sessions s
|
||||||
|
join public.slots sl on sl.id = s.slot_id
|
||||||
|
where s.id = p_session_id
|
||||||
|
and (sl.slot_date + sl.end_time) <= (timezone('Europe/Amsterdam', now()))
|
||||||
|
);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Storage read gate for the private `materials` bucket. Object paths are
|
||||||
|
-- `sessions/<session-uuid>/<file>` (see uploadSessionMaterial); anything else
|
||||||
|
-- in that bucket, and every other bucket, is denied here (other buckets have
|
||||||
|
-- their own policies).
|
||||||
|
create or replace function public.can_read_session_material(p_bucket text, p_name text)
|
||||||
|
returns boolean
|
||||||
|
language plpgsql stable security definer set search_path = '' as $$
|
||||||
|
declare
|
||||||
|
v_session uuid;
|
||||||
|
begin
|
||||||
|
if p_bucket is distinct from 'materials' then return false; end if;
|
||||||
|
if public.is_admin() then return true; end if;
|
||||||
|
if p_name ~ '^sessions/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/[^/]+$' then
|
||||||
|
v_session := split_part(p_name, '/', 2)::uuid;
|
||||||
|
if public.owns_speaker_session(v_session) then return true; end if;
|
||||||
|
return public.session_material_unlocked(v_session);
|
||||||
|
end if;
|
||||||
|
return false;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
grant execute on function public.session_material_unlocked(uuid) to authenticated;
|
||||||
|
grant execute on function public.can_read_session_material(text, text) to authenticated;
|
||||||
|
|
||||||
|
-- Private bucket: kills every public (unauthenticated) material URL.
|
||||||
|
update storage.buckets set public = false where id = 'materials';
|
||||||
|
|
||||||
|
-- Replace the blanket read policy with the time/ownership gate above. The
|
||||||
|
-- Storage API evaluates this as the requesting user, so it applies both to
|
||||||
|
-- /object/materials/... fetches and to createSignedUrl issuance.
|
||||||
|
drop policy if exists "materials_read" on storage.objects;
|
||||||
|
create policy "materials_read" on storage.objects for select to authenticated
|
||||||
|
using (public.can_read_session_material(bucket_id, name));
|
||||||
|
|
||||||
|
comment on column public.sessions.material_path is
|
||||||
|
'Storage object path in the private materials bucket; downloads unlock at the scheduled session end (storage RLS), speakers/admins bypass';
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
\set ON_ERROR_STOP on
|
||||||
|
begin;
|
||||||
|
|
||||||
|
create function pg_temp.assert_lock(p_condition boolean, p_name text)
|
||||||
|
returns void language plpgsql as $$
|
||||||
|
begin
|
||||||
|
if p_condition is distinct from true then
|
||||||
|
raise exception 'FAIL: %', p_name;
|
||||||
|
end if;
|
||||||
|
raise notice 'PASS: %', p_name;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Fixtures: one ended and one upcoming event/slot/session (both inactive; the
|
||||||
|
-- real active event is untouched), plus identities.
|
||||||
|
create temporary table lock_fixture as
|
||||||
|
select kind, gen_random_uuid() as event_id, gen_random_uuid() as session_id,
|
||||||
|
(select least(coalesce(min(id), 0), 0) from public.slots) - row_number() over ()::integer as slot_id,
|
||||||
|
case when kind = 'ended' then current_date - 3 else current_date + 3 end as the_date
|
||||||
|
from unnest(array['ended', 'upcoming']) as kind;
|
||||||
|
create temporary table lock_identity as
|
||||||
|
select 'lock-outsider-' || gen_random_uuid() || '@example.invalid' as outsider_email,
|
||||||
|
'lock-speaker-' || gen_random_uuid() || '@example.invalid' as speaker_email,
|
||||||
|
'lock-admin-' || gen_random_uuid() || '@appe.at' as admin_email;
|
||||||
|
grant select on lock_fixture, lock_identity to authenticated;
|
||||||
|
|
||||||
|
insert into public.contacts(email, full_name)
|
||||||
|
select outsider_email, 'Lock Outsider' from lock_identity
|
||||||
|
union all select speaker_email, 'Lock Speaker' from lock_identity
|
||||||
|
union all select admin_email, 'Lock Admin' from lock_identity;
|
||||||
|
update public.contacts set is_admin = true
|
||||||
|
where email = (select admin_email from lock_identity);
|
||||||
|
insert into public.events(id, name, start_date, end_date, is_active)
|
||||||
|
select event_id, 'Lock regression ' || kind, the_date, the_date, false from lock_fixture;
|
||||||
|
insert into public.slots(id, event_id, name, type, slot_date, start_time, end_time)
|
||||||
|
select slot_id, event_id, 'Lock slot', 'session', the_date, '09:00', '10:00' from lock_fixture;
|
||||||
|
insert into public.sessions(id, event_id, slot_id, title)
|
||||||
|
select session_id, event_id, slot_id, 'Lock talk ' || kind from lock_fixture;
|
||||||
|
-- The speaker is assigned (with a speaker registration) to the UPCOMING talk,
|
||||||
|
-- proving the ownership bypass of the time gate.
|
||||||
|
insert into public.registrations(event_id, contact_email, type, points, checked_in)
|
||||||
|
select f.event_id, i.speaker_email, 'speaker', 0, false
|
||||||
|
from lock_fixture f cross join lock_identity i where f.kind = 'upcoming';
|
||||||
|
insert into public.session_speakers(session_id, contact_email)
|
||||||
|
select f.session_id, i.speaker_email
|
||||||
|
from lock_fixture f cross join lock_identity i where f.kind = 'upcoming';
|
||||||
|
|
||||||
|
-- Storage rows (objects) — inserted as superuser; only RLS visibility is
|
||||||
|
-- under test. Also one object in a foreign bucket and one malformed path.
|
||||||
|
insert into storage.buckets(id, name, public) values ('lock-other', 'lock-other', false);
|
||||||
|
create temporary table lock_object as
|
||||||
|
select 'ended'::text as kind, 'materials'::text as bucket_id,
|
||||||
|
('sessions/' || (select session_id from lock_fixture where kind = 'ended') || '/1729000000000-slides.pdf')::text as name
|
||||||
|
union all select 'upcoming', 'materials',
|
||||||
|
'sessions/' || (select session_id from lock_fixture where kind = 'upcoming') || '/1729000000000-slides.pdf'
|
||||||
|
union all select 'foreign-bucket', 'lock-other', 'whatever.pdf'
|
||||||
|
union all select 'malformed', 'materials', 'sessions/not-a-uuid/slides.pdf';
|
||||||
|
insert into storage.objects(bucket_id, name) select bucket_id, name from lock_object;
|
||||||
|
grant select on lock_object to authenticated;
|
||||||
|
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
(select not public from storage.buckets where id = 'materials'),
|
||||||
|
'materials bucket is private');
|
||||||
|
|
||||||
|
-- Structural rejections hold regardless of caller (time/ownership not even
|
||||||
|
-- consulted for these shapes).
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
not public.can_read_session_material('materials', name),
|
||||||
|
'gate rejects malformed path')
|
||||||
|
from lock_object where kind = 'malformed';
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
not public.can_read_session_material('lock-other', 'whatever.pdf')
|
||||||
|
and not public.can_read_session_material(null, null)
|
||||||
|
and not public.can_read_session_material('materials', null)
|
||||||
|
and not public.can_read_session_material('materials', 'sessions/../escape.pdf'),
|
||||||
|
'gate rejects foreign bucket, null and escape-shaped paths');
|
||||||
|
|
||||||
|
|
||||||
|
-- 1) Outsider: hidden before the end, visible after it.
|
||||||
|
select set_config('request.jwt.claims',
|
||||||
|
json_build_object('email', outsider_email, 'role', 'authenticated')::text, true)
|
||||||
|
from lock_identity;
|
||||||
|
set local role authenticated;
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
not exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind = 'upcoming'),
|
||||||
|
'outsider cannot read material of an upcoming session');
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind = 'ended'),
|
||||||
|
'outsider can read material once the session has ended');
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
not exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind in ('foreign-bucket', 'malformed')),
|
||||||
|
'outsider sees neither foreign-bucket nor malformed-path objects');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- 2) Assigned speaker of the upcoming session: visible at any time.
|
||||||
|
select set_config('request.jwt.claims',
|
||||||
|
json_build_object('email', speaker_email, 'role', 'authenticated')::text, true)
|
||||||
|
from lock_identity;
|
||||||
|
set local role authenticated;
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind = 'upcoming'),
|
||||||
|
'assigned speaker reads their upcoming session material before the end');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- 3) Admin: visible at any time.
|
||||||
|
select set_config('request.jwt.claims',
|
||||||
|
json_build_object('email', admin_email, 'role', 'authenticated')::text, true)
|
||||||
|
from lock_identity;
|
||||||
|
set local role authenticated;
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
public.is_admin()
|
||||||
|
and exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind = 'upcoming')
|
||||||
|
and exists (select 1 from storage.objects o join lock_object l using (bucket_id, name) where l.kind = 'ended'),
|
||||||
|
'admin reads any session material at any time');
|
||||||
|
reset role;
|
||||||
|
|
||||||
|
-- 4) Unlock boundary follows event-local (Amsterdam) wall time.
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
public.session_material_unlocked(session_id)
|
||||||
|
= ((the_date + time '10:00') <= (timezone('Europe/Amsterdam', now()))),
|
||||||
|
'unlock boundary is event-local wall time: ' || kind)
|
||||||
|
from lock_fixture;
|
||||||
|
|
||||||
|
-- 5) No policy row grants anon the read (storage serves anonymous object
|
||||||
|
-- requests as the anon role, which the policy excludes).
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
(select count(*) = 0 from pg_policies where schemaname = 'storage'
|
||||||
|
and tablename = 'objects' and policyname = 'materials_read' and 'anon' = any (roles)),
|
||||||
|
'materials_read does not apply to anon');
|
||||||
|
|
||||||
|
-- 6) Active event untouched by the fixtures.
|
||||||
|
select pg_temp.assert_lock(
|
||||||
|
not exists (select 1 from public.events where is_active and name like 'Lock regression %'),
|
||||||
|
'active event untouched');
|
||||||
|
|
||||||
|
update public.contacts set is_admin = false
|
||||||
|
where email = (select admin_email from lock_identity);
|
||||||
|
rollback;
|
||||||
Reference in new issue
Block a user