返回 CodeWhale
cloud_facts.test.sql
根目录 / web / supabase / tests / cloud_facts.test.sql
1 -- Database tests for web/supabase/migrations/20260909000113_cloud_facts_publication.sql.
2 --
3 -- These run real statements as the real roles (anon, authenticated,
4 -- service_role) against a real PostgreSQL 15+ database; nothing here inspects
5 -- SQL text. pgTAP is not required — failures raise, and ON_ERROR_STOP aborts.
6 --
7 -- createdb cw_facts_test
8 -- psql -v ON_ERROR_STOP=1 -d cw_facts_test -f web/supabase/tests/cloud_facts.test.sql
9 --
10 -- Run it against a disposable local database only: it creates the anon /
11 -- authenticated / service_role roles when they are missing (service_role needs
12 -- BYPASSRLS, as on Supabase, which needs a superuser connection), applies the
13 -- migration, and ends with ROLLBACK so the database is left untouched.
14 --
15 -- The base64 blobs below are syntactically valid placeholders, not keys and
16 -- not signatures: the database never verifies a signature, clients do, against
17 -- keys pinned in the binary and in web/lib/cloud-facts/keys.ts.
18
19 \set ON_ERROR_STOP on
20
21 begin;
22
23 -- ---------------------------------------------------------------------------
24 -- Roles and schema under test
25 -- ---------------------------------------------------------------------------
26
27 do $roles$
28 begin
29 if not exists (select 1 from pg_roles where rolname = 'anon') then
30 create role anon nologin noinherit;
31 end if;
32 if not exists (select 1 from pg_roles where rolname = 'authenticated') then
33 create role authenticated nologin noinherit;
34 end if;
35 if not exists (select 1 from pg_roles where rolname = 'service_role') then
36 create role service_role nologin noinherit bypassrls;
37 end if;
38 if not (select rolbypassrls from pg_roles where rolname = 'service_role') then
39 raise exception 'service_role must have BYPASSRLS for the publisher path to work';
40 end if;
41 execute format('grant anon, authenticated, service_role to %I', current_user);
42 end
43 $roles$;
44
45 \ir ../migrations/20260909000113_cloud_facts_publication.sql
46 \ir ../migrations/20261117000114_registry_channel_publication.sql
47
48 -- ---------------------------------------------------------------------------
49 -- Fixture helpers (rolled back with everything else)
50 -- ---------------------------------------------------------------------------
51
52 create function public.tst_ts(t timestamptz) returns text
53 language sql as $$
54 select to_char(t at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
55 $$;
56
57 -- The shape web/scripts/facts-publish.mjs signs, minus the parts the database
58 -- does not constrain.
59 create function public.tst_payload(
60 p_channel text, p_version bigint, p_published timestamptz,
61 p_not_after timestamptz default null, p_applies text default '*'
62 ) returns jsonb
63 language sql as $$
64 select jsonb_strip_nulls(jsonb_build_object(
65 'schema_version', 1,
66 'channel', p_channel,
67 'facts_version', p_version,
68 'published_at', public.tst_ts(p_published),
69 'not_after', public.tst_ts(p_not_after),
70 'applies_to', p_applies))
71 || jsonb_build_object('models', '[]'::jsonb, 'provider_defaults', '{}'::jsonb,
72 'release', null, 'announcements', '[]'::jsonb)
73 $$;
74
75 -- encode(..., 'base64') wraps at 76 columns; the publisher never emits newlines
76 -- and neither may a hand-written insert.
77 create function public.tst_b64(p jsonb) returns text
78 language sql as $$
79 select translate(encode(convert_to(p::text, 'utf8'), 'base64'), E'\n', '')
80 $$;
81
82 create function public.tst_release(
83 p_slug text, p_version bigint,
84 p_published timestamptz default null, p_not_after timestamptz default null,
85 p_applies text default '*', p_key text default 'cwf-test-registry',
86 p_payload jsonb default null, p_b64 text default null,
87 p_sig text default null, p_sigs jsonb default '[]'::jsonb
88 ) returns void
89 language plpgsql as $$
90 declare
91 pub timestamptz := date_trunc('second', coalesce(p_published, now() - interval '1 minute'));
92 expires timestamptz := date_trunc('second', p_not_after);
93 payload jsonb := coalesce(p_payload, public.tst_payload(p_slug, p_version, pub, expires, p_applies));
94 inserted int;
95 begin
96 insert into public.facts_release (
97 channel_id, facts_version, schema_version, envelope_version, applies_to, key_id,
98 payload_b64, sig_b64, sigs, payload, published_at, not_after, published_by, notes)
99 select c.id, p_version, 1, 1, p_applies, p_key,
100 coalesce(p_b64, public.tst_b64(payload)), coalesce(p_sig, repeat('A', 86) || '=='),
101 p_sigs, payload, pub, expires, 'operator@example.test', 'internal note'
102 from public.facts_channel c
103 where c.scope = 'global' and c.slug = p_slug;
104 get diagnostics inserted = row_count;
105 if inserted <> 1 then
106 raise exception 'fixture channel % is missing', p_slug;
107 end if;
108 end
109 $$;
110
111 -- ---------------------------------------------------------------------------
112 -- Fixtures, written the way the publisher writes them: as service_role
113 -- ---------------------------------------------------------------------------
114
115 do $fixtures$
116 begin
117 set local role service_role;
118 insert into public.facts_key (key_id, scope, algorithm, public_key, status)
119 values ('cwf-test-registry', 'global', 'ed25519', repeat('A', 43) || '=', 'active');
120 insert into public.facts_channel (scope, slug, visibility) values
121 ('global', 'stable', 'public'),
122 ('global', 'beta', 'private'),
123 ('global', 'future', 'public'),
124 ('global', 'expired', 'public'),
125 ('global', 'rollback', 'public');
126 perform public.tst_release('stable', 7);
127 perform public.tst_release('beta', 3);
128 perform public.tst_release('future', 2, now() + interval '1 hour');
129 perform public.tst_release('expired', 4, now() - interval '2 hours', now() - interval '1 hour');
130 perform public.tst_release('rollback', 1);
131 perform public.tst_release('rollback', 2);
132 reset role;
133 end
134 $fixtures$;
135
136 -- ---------------------------------------------------------------------------
137 -- 1. The publishable-key read path returns exactly one verifiable row
138 -- ---------------------------------------------------------------------------
139
140 do $published_read$
141 declare
142 rows_seen int;
143 v_release_id uuid; v_facts_version bigint;
144 v_schema_version int; v_envelope_version int; v_applies_to text; v_key_id text;
145 v_payload_b64 text; v_sig_b64 text; v_sigs jsonb; v_payload_sha256 text;
146 v_published_at timestamptz; v_not_after timestamptz;
147 v_payload jsonb;
148 begin
149 set local role anon;
150 -- Exactly the query web/lib/cloud-facts.ts sends over PostgREST.
151 select count(*) into rows_seen
152 from public.facts_current f where f.channel = 'stable' and f.scope = 'global';
153 select f.release_id, f.facts_version, f.schema_version,
154 f.envelope_version, f.applies_to, f.key_id, f.payload_b64, f.sig_b64,
155 f.sigs, f.payload_sha256, f.published_at, f.not_after
156 into v_release_id, v_facts_version, v_schema_version,
157 v_envelope_version, v_applies_to, v_key_id, v_payload_b64, v_sig_b64,
158 v_sigs, v_payload_sha256, v_published_at, v_not_after
159 from public.facts_current f
160 where f.channel = 'stable' and f.scope = 'global'
161 limit 1;
162 reset role;
163
164 if rows_seen <> 1 then
165 raise exception 'expected exactly 1 current row for stable, got %', rows_seen;
166 end if;
167 if v_facts_version <> 7 or v_schema_version <> 1 or v_envelope_version <> 1
168 or v_applies_to <> '*' or v_key_id <> 'cwf-test-registry' or v_sigs <> '[]'::jsonb
169 or v_release_id is null or v_not_after is not null or v_published_at is null then
170 raise exception 'facts_current row does not carry the published contract: v=% schema=% envelope=% applies=% key=% sigs=%',
171 v_facts_version, v_schema_version, v_envelope_version, v_applies_to, v_key_id, v_sigs;
172 end if;
173 -- The digest is derived from the decoded signed bytes, not supplied.
174 if v_payload_sha256 is distinct from encode(sha256(decode(v_payload_b64, 'base64')), 'hex')
175 or v_payload_sha256 !~ '^[a-f0-9]{64}$' then
176 raise exception 'payload_sha256 % does not hash the decoded payload', v_payload_sha256;
177 end if;
178 v_payload := convert_from(decode(v_payload_b64, 'base64'), 'utf8')::jsonb;
179 if v_payload -> 'channel' <> to_jsonb('stable'::text)
180 or v_payload -> 'facts_version' <> to_jsonb(7::bigint)
181 or (v_payload ->> 'published_at')::timestamptz <> v_published_at then
182 raise exception 'signed payload disagrees with the row metadata';
183 end if;
184 if v_sig_b64 !~ '^[A-Za-z0-9+/]{86}==$' then
185 raise exception 'envelope columns are not well formed';
186 end if;
187 raise notice 'ok 1: facts_current serves one verifiable head row to anon';
188 end
189 $published_read$;
190
191 -- ---------------------------------------------------------------------------
192 -- 2. anon and authenticated cannot write anything, or read operator columns
193 -- ---------------------------------------------------------------------------
194
195 do $write_refusals$
196 declare
197 role_name text;
198 stmt text;
199 refused boolean;
200 releases_before bigint;
201 releases_after bigint;
202 begin
203 select count(*) into releases_before from public.facts_release;
204 foreach role_name in array array['anon', 'authenticated'] loop
205 foreach stmt in array array[
206 'insert into public.facts_channel (scope, slug, visibility) values (''global'', ''rogue'', ''public'')',
207 'update public.facts_channel set visibility = ''public''',
208 'delete from public.facts_channel',
209 'insert into public.facts_key (key_id, public_key) values (''cwf-rogue'', ''x'')',
210 'update public.facts_key set status = ''active''',
211 'select public_key from public.facts_key',
212 'insert into public.facts_release (channel_id, facts_version, applies_to, key_id, payload_b64, sig_b64, payload, published_at) values (gen_random_uuid(), 99, ''*'', ''cwf-test-registry'', ''e30='', ''x'', ''{}''::jsonb, now())',
213 'update public.facts_release set status = ''revoked''',
214 'delete from public.facts_release',
215 'select payload from public.facts_release',
216 'select published_by from public.facts_release',
217 'select notes from public.facts_release',
218 'select revoke_reason from public.facts_release',
219 'select created_at from public.facts_channel'
220 ] loop
221 execute format('set local role %I', role_name);
222 refused := false;
223 begin
224 execute stmt;
225 exception when insufficient_privilege then
226 refused := true;
227 end;
228 reset role;
229 if not refused then
230 raise exception 'role % was not refused: %', role_name, stmt;
231 end if;
232 end loop;
233
234 -- The read view is not a write surface either.
235 execute format('set local role %I', role_name);
236 refused := false;
237 begin
238 execute 'insert into public.facts_current (channel, facts_version) values (''stable'', 99)';
239 exception when others then
240 refused := true;
241 end;
242 reset role;
243 if not refused then
244 raise exception 'role % was allowed to insert into facts_current', role_name;
245 end if;
246 end loop;
247
248 select count(*) into releases_after from public.facts_release;
249 if releases_before <> releases_after then
250 raise exception 'refused writes still changed facts_release (% -> %)', releases_before, releases_after;
251 end if;
252 raise notice 'ok 2: anon and authenticated are refused every write and every operator column';
253 end
254 $write_refusals$;
255
256 -- ---------------------------------------------------------------------------
257 -- 3. Private, future-dated and expired releases never reach the public read
258 -- ---------------------------------------------------------------------------
259
260 do $exclusions$
261 declare
262 hidden_channel text;
263 anon_rows int;
264 service_rows int;
265 anon_channels int;
266 anon_beta_releases int;
267 begin
268 foreach hidden_channel in array array['beta', 'future', 'expired'] loop
269 set local role anon;
270 select count(*) into anon_rows from public.facts_current where channel = hidden_channel;
271 reset role;
272 set local role service_role;
273 select count(*) into service_rows from public.facts_current where channel = hidden_channel;
274 reset role;
275 if anon_rows <> 0 then
276 raise exception 'channel % leaked % row(s) to anon', hidden_channel, anon_rows;
277 end if;
278 -- service_role bypasses RLS, so this proves the view predicate itself.
279 if service_rows <> 0 then
280 raise exception 'channel % leaked % row(s) through the view predicate', hidden_channel, service_rows;
281 end if;
282 end loop;
283
284 set local role anon;
285 select count(*) into anon_channels from public.facts_channel where slug = 'beta';
286 select count(*) into anon_beta_releases from public.facts_release where facts_version = 3;
287 reset role;
288 if anon_channels <> 0 or anon_beta_releases <> 0 then
289 raise exception 'private channel is visible on the base tables: % channel row(s), % release row(s)',
290 anon_channels, anon_beta_releases;
291 end if;
292 raise notice 'ok 3: private, future-dated and expired releases are excluded from both surfaces';
293 end
294 $exclusions$;
295
296 -- ---------------------------------------------------------------------------
297 -- 4. Revoking the head does not silently roll back to an older version
298 -- ---------------------------------------------------------------------------
299
300 do $revocation$
301 declare
302 served bigint;
303 rows_seen int;
304 refused_code text;
305 begin
306 set local role anon;
307 select facts_version into served from public.facts_current where channel = 'rollback';
308 reset role;
309 if served is distinct from 2::bigint then
310 raise exception 'expected the head version 2 before revocation, got %', coalesce(served::text, 'no row');
311 end if;
312
313 set local role service_role;
314 update public.facts_release r
315 set status = 'revoked', revoked_at = now(), revoke_reason = 'fixture revocation'
316 from public.facts_channel c
317 where c.id = r.channel_id and c.slug = 'rollback' and r.facts_version = 2;
318 reset role;
319
320 set local role anon;
321 select count(*) into rows_seen from public.facts_current where channel = 'rollback';
322 reset role;
323 if rows_seen <> 0 then
324 raise exception 'revoking the head served % row(s); version 1 must not come back', rows_seen;
325 end if;
326
327 -- The supported repair is a higher version, not un-revocation or mutation.
328 set local role service_role;
329 refused_code := null;
330 begin
331 update public.facts_release r
332 set status = 'published', revoked_at = null, revoke_reason = null
333 from public.facts_channel c
334 where c.id = r.channel_id and c.slug = 'rollback' and r.facts_version = 2;
335 exception when others then refused_code := sqlstate;
336 end;
337 if refused_code is distinct from '23001' then
338 raise exception 'un-revoking a release was not refused (sqlstate %)', coalesce(refused_code, 'none');
339 end if;
340
341 refused_code := null;
342 begin
343 update public.facts_release r
344 set payload_b64 = 'QUFBQQ=='
345 from public.facts_channel c
346 where c.id = r.channel_id and c.slug = 'rollback' and r.facts_version = 1;
347 exception when others then refused_code := sqlstate;
348 end;
349 if refused_code is distinct from '23001' then
350 raise exception 'mutating a signed column was not refused (sqlstate %)', coalesce(refused_code, 'none');
351 end if;
352
353 perform public.tst_release('rollback', 3);
354 reset role;
355
356 set local role anon;
357 select count(*) into rows_seen from public.facts_current where channel = 'rollback';
358 select facts_version into served from public.facts_current where channel = 'rollback';
359 reset role;
360 if rows_seen <> 1 or served is distinct from 3::bigint then
361 raise exception 'republishing above the revoked head served % row(s) at version %',
362 rows_seen, coalesce(served::text, 'none');
363 end if;
364 raise notice 'ok 4: a revoked head blocks delivery, stays revoked, and is repaired by a higher version';
365 end
366 $revocation$;
367
368 -- ---------------------------------------------------------------------------
369 -- 5. Versions are unique and monotonic per channel; the read stays one row
370 -- ---------------------------------------------------------------------------
371
372 do $monotonic$
373 declare
374 code text;
375 rows_seen int;
376 served bigint;
377 stale bigint;
378 begin
379 set local role service_role;
380 foreach stale in array array[3::bigint, 7::bigint] loop
381 code := null;
382 begin
383 perform public.tst_release('stable', stale);
384 exception when others then code := sqlstate;
385 end;
386 if code is distinct from '23505' then
387 raise exception 'republishing stable version % was not refused (sqlstate %)', stale, coalesce(code, 'none');
388 end if;
389 end loop;
390 perform public.tst_release('stable', 8);
391 reset role;
392
393 set local role anon;
394 select count(*), max(facts_version) into rows_seen, served
395 from public.facts_current where channel = 'stable' and scope = 'global';
396 reset role;
397 if rows_seen <> 1 or served is distinct from 8::bigint then
398 raise exception 'expected one row at version 8 after publishing, got % row(s) at %',
399 rows_seen, coalesce(served::text, 'none');
400 end if;
401 raise notice 'ok 5: facts_version is unique and monotonic, and the read stays deterministic at one row';
402 end
403 $monotonic$;
404
405 -- ---------------------------------------------------------------------------
406 -- 6. Rows whose metadata, bytes, size or signatures do not hold are rejected
407 -- ---------------------------------------------------------------------------
408
409 do $consistency$
410 declare
411 pub timestamptz := date_trunc('second', now() - interval '1 minute');
412 code text;
413 rows_seen int;
414 served bigint;
415 field text;
416 candidate jsonb;
417 begin
418 set local role service_role;
419
420 -- The signed payload's channel must be the channel it is published on.
421 code := null;
422 begin
423 perform public.tst_release('stable', 20, p_published => pub,
424 p_payload => public.tst_payload('beta', 20, pub));
425 exception when others then code := sqlstate;
426 end;
427 if code is distinct from '23514' then
428 raise exception 'cross-channel payload accepted (sqlstate %)', coalesce(code, 'none');
429 end if;
430
431 -- Outer facts_version must repeat the signed one.
432 code := null;
433 begin
434 perform public.tst_release('stable', 21, p_published => pub,
435 p_payload => public.tst_payload('stable', 22, pub));
436 exception when others then code := sqlstate;
437 end;
438 if code is distinct from '23514' then
439 raise exception 'facts_version mismatch accepted (sqlstate %)', coalesce(code, 'none');
440 end if;
441
442 -- SQL CHECK accepts NULL unless the full predicate is explicitly true.
443 -- Missing signed metadata must not pass through three-valued SQL logic.
444 foreach field in array array['facts_version', 'schema_version', 'applies_to', 'published_at'] loop
445 for candidate in
446 select public.tst_payload('stable', 22, pub) - field
447 union all
448 select public.tst_payload('stable', 22, pub) || jsonb_build_object(field, null)
449 loop
450 code := null;
451 begin
452 perform public.tst_release('stable', 22, p_published => pub, p_payload => candidate);
453 exception when others then code := sqlstate;
454 end;
455 if code is distinct from '23514' then
456 raise exception 'missing/null signed % accepted (sqlstate %)', field, coalesce(code, 'none');
457 end if;
458 end loop;
459 end loop;
460
461 -- payload must be the decode of payload_b64.
462 code := null;
463 begin
464 perform public.tst_release('stable', 23, p_published => pub,
465 p_b64 => public.tst_b64(public.tst_payload('stable', 23, pub, null, '>=1.0.0')));
466 exception when others then code := sqlstate;
467 end;
468 if code is distinct from '23514' then
469 raise exception 'payload divergent from the signed bytes accepted (sqlstate %)', coalesce(code, 'none');
470 end if;
471
472 -- Newline-wrapped base64 (what encode() produces) is not canonical.
473 code := null;
474 begin
475 perform public.tst_release('stable', 24, p_published => pub,
476 p_b64 => encode(convert_to(public.tst_payload('stable', 24, pub)::text, 'utf8'), 'base64'));
477 exception when others then code := sqlstate;
478 end;
479 if code is distinct from '23514' then
480 raise exception 'newline-wrapped payload_b64 accepted (sqlstate %)', coalesce(code, 'none');
481 end if;
482
483 -- Bounded size: a self-consistent payload above MAX_PAYLOAD_BYTES.
484 code := null;
485 begin
486 perform public.tst_release('stable', 25, p_published => pub,
487 p_payload => public.tst_payload('stable', 25, pub) || jsonb_build_object('pad', repeat('x', 600000)));
488 exception when others then code := sqlstate;
489 end;
490 if code is distinct from '23514' then
491 raise exception 'oversized payload_b64 accepted (sqlstate %)', coalesce(code, 'none');
492 end if;
493
494 -- A signature must at least be 64 bytes of canonical base64.
495 code := null;
496 begin
497 perform public.tst_release('stable', 26, p_published => pub, p_sig => repeat('A', 40));
498 exception when others then code := sqlstate;
499 end;
500 if code is distinct from '23514' then
501 raise exception 'malformed sig_b64 accepted (sqlstate %)', coalesce(code, 'none');
502 end if;
503
504 -- Extra rotation signatures: bounded count and well-formed elements.
505 code := null;
506 begin
507 perform public.tst_release('stable', 27, p_published => pub,
508 p_sigs => (select jsonb_agg(jsonb_build_object('key_id', 'cwf-rotation', 'sig_b64', repeat('A', 86) || '=='))
509 from generate_series(1, 8)));
510 exception when others then code := sqlstate;
511 end;
512 if code is distinct from '23514' then
513 raise exception 'more than seven extra signatures accepted (sqlstate %)', coalesce(code, 'none');
514 end if;
515
516 code := null;
517 begin
518 perform public.tst_release('stable', 28, p_published => pub,
519 p_sigs => '[{"key_id": "bad id", "sig_b64": "AAAA"}]'::jsonb);
520 exception when others then code := sqlstate;
521 end;
522 if code is distinct from '23514' then
523 raise exception 'malformed extra signature accepted (sqlstate %)', coalesce(code, 'none');
524 end if;
525
526 -- Expiry must follow publication.
527 code := null;
528 begin
529 perform public.tst_release('stable', 29, p_published => pub, p_not_after => pub - interval '1 hour');
530 exception when others then code := sqlstate;
531 end;
532 if code is distinct from '23514' then
533 raise exception 'not_after before published_at accepted (sqlstate %)', coalesce(code, 'none');
534 end if;
535
536 -- An unregistered key cannot be referenced.
537 code := null;
538 begin
539 perform public.tst_release('stable', 30, p_published => pub, p_key => 'cwf-not-registered');
540 exception when others then code := sqlstate;
541 end;
542 if code is distinct from '23503' then
543 raise exception 'unregistered key_id accepted (sqlstate %)', coalesce(code, 'none');
544 end if;
545
546 -- Only global-scope channels may be public.
547 code := null;
548 begin
549 insert into public.facts_channel (scope, slug, visibility) values ('org-acme', 'stable', 'public');
550 exception when others then code := sqlstate;
551 end;
552 if code is distinct from '23514' then
553 raise exception 'a non-global channel was made public (sqlstate %)', coalesce(code, 'none');
554 end if;
555 reset role;
556
557 -- None of the rejected inserts moved the channel high-water mark.
558 set local role anon;
559 select count(*), max(facts_version) into rows_seen, served
560 from public.facts_current where channel = 'stable' and scope = 'global';
561 reset role;
562 if rows_seen <> 1 or served is distinct from 8::bigint then
563 raise exception 'rejected publications disturbed the channel: % row(s) at version %',
564 rows_seen, coalesce(served::text, 'none');
565 end if;
566 raise notice 'ok 6: metadata, byte, size, signature, key and scope constraints all hold';
567 end
568 $consistency$;
569
570 -- ---------------------------------------------------------------------------
571 -- 7. The exposed surface is exactly the contract (no wildcard exposure)
572 -- ---------------------------------------------------------------------------
573
574 do $surface$
575 declare
576 view_columns text[];
577 expected text[] := array[
578 'channel', 'scope', 'release_id', 'facts_version', 'schema_version',
579 'envelope_version', 'applies_to', 'key_id', 'payload_b64', 'sig_b64',
580 'sigs', 'payload_sha256', 'published_at', 'not_after'];
581 reader_role text;
582 hidden text;
583 visible text;
584 guarded text;
585 options text[];
586 begin
587 select array_agg(column_name::text order by ordinal_position) into view_columns
588 from information_schema.columns
589 where table_schema = 'public' and table_name = 'facts_current';
590 if view_columns is distinct from expected then
591 raise exception 'facts_current exposes % but the reader contract is %', view_columns, expected;
592 end if;
593
594 select c.reloptions into options
595 from pg_class c join pg_namespace n on n.oid = c.relnamespace
596 where n.nspname = 'public' and c.relname = 'facts_current' and c.relkind = 'v';
597 if options is null or not ('security_invoker=true' = any(options)) then
598 raise exception 'facts_current is not a security_invoker view (reloptions %)', options;
599 end if;
600
601 foreach guarded in array array['facts_channel', 'facts_key', 'facts_release'] loop
602 if not (select relrowsecurity from pg_class c join pg_namespace n on n.oid = c.relnamespace
603 where n.nspname = 'public' and c.relname = guarded) then
604 raise exception 'row level security is not enabled on public.%', guarded;
605 end if;
606 end loop;
607
608 foreach reader_role in array array['anon', 'authenticated'] loop
609 if not has_table_privilege(reader_role, 'public.facts_current', 'select') then
610 raise exception 'role % cannot read facts_current', reader_role;
611 end if;
612 if has_table_privilege(reader_role, 'public.facts_key', 'select') then
613 raise exception 'role % can read the key registry', reader_role;
614 end if;
615 foreach guarded in array array['public.facts_channel', 'public.facts_key', 'public.facts_release', 'public.facts_current'] loop
616 if has_table_privilege(reader_role, guarded, 'insert')
617 or has_table_privilege(reader_role, guarded, 'update')
618 or has_table_privilege(reader_role, guarded, 'delete') then
619 raise exception 'role % holds a write privilege on %', reader_role, guarded;
620 end if;
621 end loop;
622 foreach hidden in array array['payload', 'published_by', 'notes', 'revoked_at', 'revoke_reason', 'created_at'] loop
623 if has_column_privilege(reader_role, 'public.facts_release', hidden, 'select') then
624 raise exception 'role % can read operator column facts_release.%', reader_role, hidden;
625 end if;
626 end loop;
627 foreach visible in array array['payload_b64', 'sig_b64', 'sigs', 'payload_sha256', 'published_at', 'not_after'] loop
628 if not has_column_privilege(reader_role, 'public.facts_release', visible, 'select') then
629 raise exception 'role % cannot read published column facts_release.%', reader_role, visible;
630 end if;
631 end loop;
632 end loop;
633
634 if not has_table_privilege('service_role', 'public.facts_release', 'insert')
635 or not has_table_privilege('service_role', 'public.facts_release', 'update')
636 or not has_table_privilege('service_role', 'public.facts_key', 'insert') then
637 raise exception 'the publisher role cannot publish';
638 end if;
639 if has_table_privilege('service_role', 'public.facts_release', 'delete') then
640 raise exception 'the publisher role can delete publication history';
641 end if;
642 raise notice 'ok 7: grants, policies and the view surface match the delivery contract';
643 end
644 $surface$;
645
646 do $registry_channel$
647 declare
648 pub timestamptz := date_trunc('second', now() - interval '1 minute');
649 reg_payload jsonb;
650 large_reg_payload jsonb;
651 rows_seen int;
652 served_version bigint;
653 rejected boolean;
654 begin
655 set local role service_role;
656 insert into public.facts_channel (scope, slug, visibility)
657 values ('global', 'registry', 'public');
658
659 reg_payload := jsonb_build_object(
660 'schema', 'codewhale.registry.v1',
661 'revision', 1,
662 'content_hash', 'sha256:' || repeat('a', 64),
663 'generated_at', public.tst_ts(pub),
664 'providers', '[]'::jsonb,
665 'models', '[]'::jsonb,
666 'offerings', '[]'::jsonb,
667 'dialects', '{}'::jsonb
668 );
669 perform public.tst_release('registry', 1, pub, null, '*', 'cwf-test-registry', reg_payload);
670
671 large_reg_payload := reg_payload || jsonb_build_object(
672 'revision', 2,
673 'engine_compat', jsonb_build_object('pad', repeat('x', 540000))
674 );
675 perform public.tst_release('registry', 2, pub, pub + interval '1 day', '*', 'cwf-test-registry',
676 large_reg_payload || jsonb_build_object('not_after', public.tst_ts(pub + interval '1 day')));
677
678 rejected := false;
679 begin
680 perform public.tst_release('stable', 99, pub, null, '*', 'cwf-test-registry',
681 reg_payload || jsonb_build_object('revision', 99));
682 exception when check_violation then
683 rejected := true;
684 end;
685 if not rejected then
686 raise exception 'stable channel accepted a codewhale.registry.v1 payload';
687 end if;
688
689 rejected := false;
690 begin
691 perform public.tst_release('registry', 3, pub, null, '*', 'cwf-test-registry',
692 public.tst_payload('registry', 3, pub));
693 exception when check_violation then
694 rejected := true;
695 end;
696 if not rejected then
697 raise exception 'registry channel accepted a non-registry facts payload';
698 end if;
699
700 rejected := false;
701 begin
702 perform public.tst_release('registry', 3, pub, null, '>=99.0.0', 'cwf-test-registry',
703 reg_payload || jsonb_build_object('revision', 3));
704 exception when check_violation then
705 rejected := true;
706 end;
707 if not rejected then
708 raise exception 'registry channel accepted tampered outer applies_to';
709 end if;
710 reset role;
711
712 set local role anon;
713 select count(*), max(f.facts_version) into rows_seen, served_version
714 from public.facts_current f where f.channel = 'registry' and f.scope = 'global';
715 reset role;
716 if rows_seen <> 1 or served_version <> 2 then
717 raise exception 'expected registry head v2 for anon, saw % row(s) at %', rows_seen, served_version;
718 end if;
719 raise notice 'ok 8: registry channel accepts >512 KiB codewhale.registry.v1 releases and isolates channel schemas';
720 end
721 $registry_channel$;
722
723 select 'cloud facts storage: all assertions passed' as result;
724
725 rollback;
726
726 lines SQL