From 9cf6b3506b451261f0d3e6984528ec7b0f2f35fb Mon Sep 17 00:00:00 2001 From: seizeh Date: Wed, 11 Nov 2026 12:10:13 +0900 Subject: [PATCH 1/3] =?UTF-8?q?chore(db):=20spatial=5Fref=5Fsys=20?= =?UTF-8?q?=EC=93=B0=EA=B8=B0=20=EA=B0=80=EB=93=9C(09-15=20=EC=9A=B4?= =?UTF-8?q?=EC=98=81=20=EC=A0=81=EC=9A=A9=EB=B6=84)=EB=A5=BC=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=EC=86=8C=EC=97=90=20=EA=B8=B0=EB=A1=9D=20=E2=80=94=20?= =?UTF-8?q?=EB=A7=88=EC=9D=B4=EA=B7=B8=EB=A0=88=EC=9D=B4=EC=85=98=C2=B7t27?= =?UTF-8?q?=C2=B7outofband?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 09-15 에 운영에 적용한 가드 트리거(schema_migrations 의 spatial_ref_sys_write_guard)의 마이그레이션 파일과 테스트가 커밋되지 않은 채 로컬에만 있었다. 스냅샷에는 함수만 실려 있고(pg_dump 는 확장 소유 테이블의 트리거를 싣지 않는다) 베이스라인이 그 함수를 흡수해 리플레이는 초록이었지만, 트리거 자체는 아무도 대조하지 않았고 t27 도 CI 에 없었다. docs/supabase-db.md 는 이미 이 마이그레이션과 t27 을 가리키고 있다. - supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql: 운영 적용본 그대로. - supabase/tests/t27_spatial_ref_sys_guard_test.sql: anon/authenticated 의 INSERT·UPDATE· DELETE 는 42501, 운영 롤은 통과, 4326 행은 그대로 읽힌다(7 단언). - scripts/_schema_dump.sh + outofband.txt: 확장 소유 테이블에 건 트리거를 밖 객체 스냅샷에 포함(+1줄). 리플레이가 이 줄을 대조하므로 트리거가 빠지면 빨간불이 된다. - supabase/schema/baseline.sql: 재생성 — 함수가 마이그레이션 쪽으로 옮겨가 -18줄. - supabase/schema/replay-platform-grants.sql + scripts/replay_check.sh: 작업용 DB 는 새로 만든 DB 라 플랫폼이 확장 테이블에 주는 권한(supabase_admin 의 기본 권한)이 없다. 그대로면 create trigger 가 permission denied 다. prelude 직후 수퍼유저로 같은 권한을 줘서 운영과 같은 출발점을 만든다. - README: 재현 절차 표와 밖 객체 목록 갱신. 검증: 운영 스키마를 다시 덤프해 커밋된 schema.sql 과 바이트 동일함을 확인(드리프트 없음), outofband.txt 차이는 트리거 한 줄뿐. t27 은 운영 DB 와 테스트 서버에서 7/7 (전부 롤백). 리플레이 잡의 수퍼유저 단계는 로컬에 docker 가 없어 CI 에서 확인한다. Co-Authored-By: Claude --- README.md | 5 +- scripts/_schema_dump.sh | 14 ++++ scripts/replay_check.sh | 28 +++++-- ...0915100000_spatial_ref_sys_write_guard.sql | 75 +++++++++++++++++++ supabase/schema/baseline.sql | 18 ----- supabase/schema/outofband.txt | 1 + supabase/schema/replay-platform-grants.sql | 22 ++++++ .../tests/t27_spatial_ref_sys_guard_test.sql | 52 +++++++++++++ 8 files changed, 191 insertions(+), 24 deletions(-) create mode 100644 supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql create mode 100644 supabase/schema/replay-platform-grants.sql create mode 100644 supabase/tests/t27_spatial_ref_sys_guard_test.sql diff --git a/README.md b/README.md index e2d970f..7802f45 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ docker run -d --name pm -e POSTGRES_PASSWORD=postgres -p 54323:5432 \ | 파일 | 역할 | |---|---| | `supabase/schema/prelude.sql` | 확장(postgis·pg_net·pgcrypto…)과 Supabase 기본 롤 | +| `supabase/schema/replay-platform-grants.sql` | 플랫폼이 확장 소유 테이블(`spatial_ref_sys`)에 주는 권한 — 수퍼유저(`supabase_admin`)로 적용 | | `supabase/schema/replay-stubs.sql` | 컨테이너에 없는 플랫폼 객체 흉내(storage 버킷/정책, realtime 퍼블리케이션) | | `supabase/schema/baseline.sql` | 2026-06-08 이전, 저장소 밖에서 적용됐던 기반 스키마 | | `supabase/schema/replay-default-privs.sql` | Supabase 기본 권한(마이그레이션이 만드는 객체의 ACL 재현) | @@ -89,13 +90,15 @@ docker run -d --name pm -e POSTGRES_PASSWORD=postgres -p 54323:5432 \ - `storage.buckets` 설정 (공개 여부·용량·MIME 제한) - `storage.objects` RLS 정책 (**사용자 사진의 접근 제어**) - `cron.job` (**보존기간 파기 배치**) +- 확장 소유 테이블에 건 트리거 (`spatial_ref_sys` 쓰기 가드, 20260915100000 — 테이블은 + `public` 에 있지만 확장 소속이라 `pg_dump` 가 트리거를 싣지 않는다) 즉 "직접 친 DDL 을 즉시 잡는다" 는 보증이 사진 접근 제어와 파기 배치에는 **적용되지 않았다.** 실제로 퍼블리케이션 드리프트가 하나 있었고(`notifications`, 20260804120000) 그동안 아무도 몰랐다 — 마이그레이션만으로 세운 DB 에서는 알림 realtime 이 조용히 죽는 상태였다. -그래서 그 넷만 골라 텍스트로 뽑아 `outofband.txt` 에 두고(`dump_schema.sh` 가 생성), +그래서 이것들만 골라 텍스트로 뽑아 `outofband.txt` 에 두고(`dump_schema.sh` 가 생성), `replay` 잡이 리플레이 DB 와 대조한다. 스냅샷 DB 가 아니라 **커밋된 파일**과 대는 이유는 `schema.sql` 에 이 객체들이 아예 없어서 복원해도 아무것도 안 생기기 때문이다. diff --git a/scripts/_schema_dump.sh b/scripts/_schema_dump.sh index fe97868..47ed985 100644 --- a/scripts/_schema_dump.sh +++ b/scripts/_schema_dump.sh @@ -37,6 +37,8 @@ normalize_dump() { # · storage.buckets 설정 (공개 여부·용량·MIME 제한) # · storage.objects RLS 정책 (사용자 사진의 접근 제어) # · cron.job (보존기간 파기 배치) +# · 확장 소유 테이블에 건 트리거 (spatial_ref_sys 쓰기 가드 — 테이블은 +# public 에 있지만 확장 소속이라 덤프에서 빠진다) # # 즉 "마이그레이션 없이 친 DDL 을 즉시 잡는다" 는 이 저장소의 보증이 **사진 접근 # 제어와 파기 배치에는 적용되지 않았다**. 실제로 publication 드리프트가 하나 있었고 @@ -83,5 +85,17 @@ select 'CRON ' || jobname || ' active=' || active::text || ' :: ' || regexp_replace(btrim(command), '\s+', ' ', 'g') from cron.job order by jobname; + +-- 확장 소유 테이블에 우리가 건 트리거. pg_dump 는 확장 소유 테이블의 트리거를 +-- 덤프하지 않아 schema.sql 에 실리지 않는다(20260915100000 spatial_ref_sys 가드). +select 'TRIGGER ' || n.nspname || '.' || c.relname || ' ' || t.tgname + || ' enabled=' || t.tgenabled::text + || ' :: ' || pg_get_triggerdef(t.oid) + from pg_trigger t + join pg_class c on c.oid = t.tgrelid + join pg_namespace n on n.oid = c.relnamespace + where not t.tgisinternal + and n.nspname = 'public' and c.relname = 'spatial_ref_sys' + order by t.tgname; SQL } diff --git a/scripts/replay_check.sh b/scripts/replay_check.sh index 2f8c7ee..4436b64 100755 --- a/scripts/replay_check.sh +++ b/scripts/replay_check.sh @@ -6,8 +6,9 @@ # # 작업용 DB 두 개를 새로 만들어 같은 조건에서 각각 채운 뒤, 양쪽을 pg_dump 해서 비교한다. # -# A(스냅샷) prelude → schema.sql -# B(리플레이) prelude → replay-stubs → baseline.sql → replay-default-privs → migrations/*.sql +# A(스냅샷) prelude → platform-grants → schema.sql +# B(리플레이) prelude → platform-grants → replay-stubs → baseline.sql → replay-default-privs +# → migrations/*.sql # # 스냅샷을 파일 그대로 비교하지 않고 A 로 한 번 복원했다 다시 덤프하는 이유: # pg_dump 출력은 되먹였을 때 글자 그대로 재현되지 않는다. 예컨대 @@ -51,6 +52,20 @@ trap 'rm -rf "$WORK"' EXIT apply() { psql "$1" -X -q -v ON_ERROR_STOP=1 -f "$2"; } +# 같은 DB 에 수퍼유저로 붙어 적용한다 — 확장 소유 테이블의 권한처럼 postgres 롤로는 +# 손댈 수 없는 것에만 쓴다(replay-platform-grants.sql). supabase/postgres 이미지는 +# supabase_admin 의 비밀번호를 POSTGRES_PASSWORD 로 맞춰 두므로 연결문자열의 사용자 +# 이름만 갈아끼우면 된다. 다른 환경이면 REPLAY_SUPERUSER 로 수퍼유저 이름을 넘긴다. +apply_as_superuser() { + local su="${REPLAY_SUPERUSER:-supabase_admin}" url + url="$(sed -E "s#^([a-z]+://)[^:/@]+#\\1${su}#" <<<"$1")" + if ! psql "$url" -X -q -v ON_ERROR_STOP=1 -f "$2"; then + echo "-- 수퍼유저(${su}) 적용 실패: $2" >&2 + echo " supabase/postgres 이미지가 아니면 REPLAY_SUPERUSER 로 수퍼유저 이름을 넘길 것" >&2 + exit 1 + fi +} + echo "== 1/5 작업용 DB 재생성 ($SNAPSHOT_DB, $REPLAY_DB)" psql "$ADMIN_URL" -X -q -v ON_ERROR_STOP=1 \ -c "drop database if exists ${SNAPSHOT_DB} with (force)" \ @@ -64,10 +79,13 @@ psql "$ADMIN_URL" -X -q -v ON_ERROR_STOP=1 \ # A 에 기본 권한을 걸면 그 위에 또 얹혀 운영보다 넓은 권한이 되어 버린다. echo "== 2/5 A: 스냅샷 복원" apply "$SNAPSHOT_URL" "$SCHEMA_DIR/prelude.sql" +# 확장을 만든 직후에, 양쪽에 똑같이 — 이유는 그 파일 주석 참고. +apply_as_superuser "$SNAPSHOT_URL" "$SCHEMA_DIR/replay-platform-grants.sql" apply "$SNAPSHOT_URL" "$SCHEMA_DIR/schema.sql" echo "== 3/5 B: 베이스라인 + 마이그레이션 리플레이" apply "$REPLAY_URL" "$SCHEMA_DIR/prelude.sql" +apply_as_superuser "$REPLAY_URL" "$SCHEMA_DIR/replay-platform-grants.sql" apply "$REPLAY_URL" "$SCHEMA_DIR/replay-stubs.sql" apply "$REPLAY_URL" "$SCHEMA_DIR/baseline.sql" # 기본 권한은 베이스라인 '다음' 에 건다 — 이유는 그 파일 주석 참고. @@ -103,15 +121,15 @@ if diff -u "$WORK/a.sql" "$WORK/b.sql" > "$WORK/diff.txt"; then # 리플레이 DB 를 직접 댄다. baseline.sql 과 같은 성격의 생성물이다. OOB_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../supabase/schema/outofband.txt" if [ -f "$OOB_FILE" ]; then - echo "== 5b/5 퍼블리케이션·storage·cron 대조" + echo "== 5b/5 퍼블리케이션·storage·cron·확장 테이블 트리거 대조" dump_outofband_to "$REPLAY_URL" "$WORK/oob_replay.txt" if diff -u "$OOB_FILE" "$WORK/oob_replay.txt" > "$WORK/oob_diff.txt"; then - echo "✅ 퍼블리케이션·storage·cron 도 일치 ($(wc -l < "$WORK/oob_replay.txt" | tr -d ' ') 줄)" + echo "✅ 퍼블리케이션·storage·cron·확장 테이블 트리거도 일치 ($(wc -l < "$WORK/oob_replay.txt" | tr -d ' ') 줄)" exit 0 fi cat "$WORK/oob_diff.txt" >> "$OUT_DIFF" echo "❌ public·app **밖** 객체가 다름 — 스키마는 맞는데 여기서 갈렸다." - echo " 대상: supabase_realtime 퍼블리케이션 · storage 버킷/정책 · cron 잡" + echo " 대상: supabase_realtime 퍼블리케이션 · storage 버킷/정책 · cron 잡 · 확장 테이블 트리거" echo " · 운영에 직접 친 것이면 마이그레이션으로 남길 것" echo " · 마이그레이션이 맞다면 ./scripts/dump_schema.sh 로 스냅샷 갱신" echo diff --git a/supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql b/supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql new file mode 100644 index 0000000..3b8f9ea --- /dev/null +++ b/supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql @@ -0,0 +1,75 @@ +-- spatial_ref_sys 쓰기 차단 — anon/authenticated 가 REST 로 좌표계 참조표를 지울 수 있었다. +-- +-- ── 무엇이 열려 있었나 ────────────────────────────────────────────────── +-- +-- public.spatial_ref_sys 는 PostGIS 가 설치하는 좌표계(SRID) 참조표다(EPSG 공개 +-- 데이터 8,500행). 소유자가 supabase_admin 이고 Supabase 기본권한 상속으로 +-- anon/authenticated 에 INSERT/UPDATE/DELETE/TRUNCATE 가 붙어 있으며, 확장 소유라 +-- 우리 롤로는 RLS 를 못 켠다. 20260630160000 의 revoke 는 소유자가 아니라서 +-- no-op 였다(그 파일에 기록됨). 2026-09-15 재확인: 트랜잭션 안에서 anon 롤로 전환해 +-- DELETE 를 실행하면 권한 오류 없이 통과한다. +-- +-- 위험은 유출이 아니라 가용성이다. SRID 4326 행을 지우거나 proj4text 를 바꾸면 +-- facilities.geom(geography) 의 거리 연산(facilities_within·facilities_search)이 +-- 깨진다. publishable 키만 있으면 되는 REST DELETE 한 번이면 충분하다. +-- +-- ── 왜 트리거인가 ────────────────────────────────────────────────────── +-- +-- revoke 는 소유자(supabase_admin)만 할 수 있다. 대신 postgres 는 이 테이블에 +-- TRIGGER 권한이 있다(ACL: postgres=arwdDxtm). BEFORE 문장 트리거는 소유자가 아니어도 +-- 걸 수 있고, 트리거 함수는 호출자의 EXECUTE 권한과 무관하게 발화한다(anon 에게 +-- EXECUTE 가 없어도 막힌다 — 적용 전 트랜잭션 안에서 실증했다). +-- +-- 막는 대상은 API 롤 둘뿐이다. 다음은 전부 그대로 통과한다: +-- · postgres(마이그레이션·pg_cron), service_role(Edge Function) +-- · supabase_admin — PostGIS 업그레이드가 spatial_ref_sys 를 갱신한다 +-- · SECURITY DEFINER RPC 내부 — current_user 가 정의자(postgres)다 +-- · 백업 복원 — session_replication_role=replica 에서 일반 트리거는 발화하지 않는다 +-- 즉 "API 롤이 REST 로 직접 치는 것" 만 정확히 막는다. 읽기는 건드리지 않는다 +-- (문장 트리거는 쓰기에만 걸리고, 좌표계 표는 공개 데이터라 읽혀도 무해). +-- +-- ── 되돌리기 ──────────────────────────────────────────────────────────── +-- +-- ⚠️ DROP TRIGGER / DISABLE TRIGGER 는 테이블 소유자만 할 수 있어 postgres 로는 +-- 불가(적용 전 실증). 끄려면 함수 본문을 `return null` 만 남기도록 create or replace +-- 하면 된다 — 함수는 postgres 소유라 언제든 바꿀 수 있다. 같은 이유로 트리거 생성은 +-- 존재 검사로 감싼다(drop-if-exists 가 안 되므로). +-- +-- ── 스냅샷 주의 ───────────────────────────────────────────────────────── +-- +-- pg_dump 는 확장 소유 테이블의 트리거를 덤프하지 않는다 → schema.sql 에는 함수만 +-- 들어가고 트리거는 안 들어간다. 그래서 트리거는 outofband.txt 로 잡는다 +-- (_schema_dump.sh). 테스트(t27)는 이 파일을 \ir 로 재적용해 스냅샷 복원 DB 에서도 +-- 같은 것을 검증한다 — 그래서 이 파일은 멱등이어야 한다. +-- +-- advisor 의 rls_disabled_in_public 경고는 relrowsecurity 만 보므로 남는다. 경고를 +-- 지우려면 PostGIS 를 extensions 스키마로 옮겨야 하는데 facilities.geom 드롭·재생성이 +-- 필요해 하지 않는다. 목적은 경고가 아니라 구멍이다. + +create or replace function app.spatial_ref_sys_guard() +returns trigger +language plpgsql +set search_path = '' +as $$ +begin + if current_user in ('anon', 'authenticated') then + raise exception 'spatial_ref_sys is read-only for API roles' + using errcode = '42501'; -- insufficient_privilege — 클라이언트에는 권한 오류로 보인다 + end if; + return null; -- 문장 트리거의 반환값은 무시된다 +end +$$; + +do $$ +begin + if not exists ( + select 1 from pg_trigger + where tgrelid = 'public.spatial_ref_sys'::regclass + and tgname = 'spatial_ref_sys_guard' + and not tgisinternal + ) then + create trigger spatial_ref_sys_guard + before insert or update or delete or truncate on public.spatial_ref_sys + for each statement execute function app.spatial_ref_sys_guard(); + end if; +end $$; diff --git a/supabase/schema/baseline.sql b/supabase/schema/baseline.sql index ef41337..9114de7 100644 --- a/supabase/schema/baseline.sql +++ b/supabase/schema/baseline.sql @@ -484,24 +484,6 @@ end $$; COMMENT ON FUNCTION app.revoke_device_tokens_on_session_revoke() IS '세션 회수(token_version 증가·비활성 전환) 시 그 사용자의 기기 푸시 토큰을 끈다.'; --- --- Name: spatial_ref_sys_guard(); Type: FUNCTION; Schema: app; Owner: - --- - -CREATE FUNCTION app.spatial_ref_sys_guard() RETURNS trigger - LANGUAGE plpgsql - SET search_path TO '' - AS $$ -begin - if current_user in ('anon', 'authenticated') then - raise exception 'spatial_ref_sys is read-only for API roles' - using errcode = '42501'; -- insufficient_privilege — 클라이언트에는 권한 오류로 보인다 - end if; - return null; -- 문장 트리거의 반환값은 무시된다 -end -$$; - - -- -- Name: tg_applications_block_insert(); Type: FUNCTION; Schema: app; Owner: - -- diff --git a/supabase/schema/outofband.txt b/supabase/schema/outofband.txt index d53a66a..c87b00b 100644 --- a/supabase/schema/outofband.txt +++ b/supabase/schema/outofband.txt @@ -23,3 +23,4 @@ CRON push-sweep [* * * * *] active=true :: select net.http_post( url := (sel CRON retention-purge [23 3 * * *] active=true :: select app.cleanup_retention(); CRON vaccine-reminder-sweep [0 0 * * *] active=true :: with due as ( update app.vaccination_events e set notified_at = now() where e.done_at is null and e.notified_at is null and e.due_date <= (now() at time zone 'Asia/Seoul')::date + 1 returning e.pet_id, e.label, e.due_date ) insert into public.notifications (user_id, notification_type, is_system, title, body, resource_type, resource_id) select g.user_id, 'vaccine_reminder', true, p.name || ' 접종일이 다가와요', d.label || ' — ' || case when d.due_date <= (now() at time zone 'Asia/Seoul')::date then '오늘' else '내일' end || ' 예정이에요. 병원 일정을 확인해 주세요.', 'pet', d.pet_id from due d join public.pets p on p.id = d.pet_id and p.pet_status = 'active' join public.pet_guardians g on g.pet_id = d.pet_id where d.due_date >= (now() at time zone 'Asia/Seoul')::date CRON withdrawn-users-purge [43 3 * * *] active=true :: delete from app.withdrawn_users where withdrawn_at < now() - interval '30 days'; +TRIGGER public.spatial_ref_sys spatial_ref_sys_guard enabled=O :: CREATE TRIGGER spatial_ref_sys_guard BEFORE INSERT OR DELETE OR UPDATE OR TRUNCATE ON public.spatial_ref_sys FOR EACH STATEMENT EXECUTE FUNCTION app.spatial_ref_sys_guard() diff --git a/supabase/schema/replay-platform-grants.sql b/supabase/schema/replay-platform-grants.sql new file mode 100644 index 0000000..3ce66b1 --- /dev/null +++ b/supabase/schema/replay-platform-grants.sql @@ -0,0 +1,22 @@ +-- 플랫폼이 확장 소유 테이블에 주는 권한 — prelude.sql 다음에 **수퍼유저로** 적용한다. +-- +-- Supabase 프로젝트의 DB 에는 "supabase_admin 이 public 에 만드는 테이블은 +-- postgres·anon·authenticated·service_role 에 ALL" 이라는 기본 권한이 걸려 있다 +-- (pg_default_acl, defaclrole = supabase_admin). postgis 는 supabase_admin 이 설치하므로 +-- 운영의 spatial_ref_sys ACL 은 다음과 같다(2026-11-11 실측): +-- +-- supabase_admin=arwdDxtm postgres=arwdDxtm anon=arwdDxtm +-- authenticated=arwdDxtm service_role=arwdDxtm PUBLIC=r +-- +-- 20260915100000 은 이 중 postgres 의 TRIGGER 권한으로 쓰기 가드 트리거를 걸고, +-- t27 은 "anon/authenticated 에 쓰기 권한이 있는데도 트리거가 막는다" 를 본다. +-- +-- 리플레이가 쓰는 작업용 DB 는 새로 만든 DB 라 그 기본 권한이 없다(pg_default_acl 은 +-- DB 별 카탈로그다). 그대로면 create trigger 가 permission denied 로 멈추고, 트리거가 +-- 걸리더라도 anon 의 쓰기는 가드가 아니라 테이블 권한에서 먼저 막혀 t27 이 다른 것을 +-- 재게 된다. 테이블 소유자가 supabase_admin 이라 postgres 로는 스스로 줄 수 없어 +-- 수퍼유저 접속이 필요하다(replay_check.sh 의 apply_as_superuser). +-- +-- 스냅샷 쪽(A)과 리플레이 쪽(B)에 똑같이 적용한다 — 그래야 이 GRANT 가 덤프에 실리든 +-- 안 실리든 양쪽 덤프가 같아 비교 결과에 섞이지 않는다. +grant all on table public.spatial_ref_sys to postgres, anon, authenticated, service_role; diff --git a/supabase/tests/t27_spatial_ref_sys_guard_test.sql b/supabase/tests/t27_spatial_ref_sys_guard_test.sql new file mode 100644 index 0000000..f06f6a5 --- /dev/null +++ b/supabase/tests/t27_spatial_ref_sys_guard_test.sql @@ -0,0 +1,52 @@ +-- spatial_ref_sys 쓰기 가드 — API 롤은 막히고, 나머지는 통과하는가. +-- +-- 이 가드의 실패 방식은 "잘못 막음" 보다 **"안 막힘"** 이 무섭다. 좌표계 표는 아무도 +-- 안 쓰는 것처럼 보여서, 열려 있어도 누가 지우기 전까지 아무 증상이 없다. 그래서 +-- 막혀야 할 세 경로(INSERT/UPDATE/DELETE × anon/authenticated)와 열려 있어야 할 +-- 경로(운영 롤)를 함께 못 박는다. +-- +-- 스냅샷(schema.sql)에는 확장 소유 테이블의 트리거가 안 실린다(pg_dump 제한). 마이그 +-- 레이션이 멱등이라 여기서 다시 적용해, 스냅샷 복원 DB 에서도 정본 그대로를 검증한다. +-- TRUNCATE 는 검증하지 않는다 — 롤백되더라도 운영 테이블에 ACCESS EXCLUSIVE 락을 거는 +-- 시험은 하지 않는다(같은 트리거·같은 분기라 DML 세 경로로 충분하다). +begin; +set local search_path = public, app, extensions; +\ir ../migrations/20260915100000_spatial_ref_sys_write_guard.sql +select plan(7); + +select has_trigger('public', 'spatial_ref_sys', 'spatial_ref_sys_guard', + '가드 트리거가 걸려 있다'); + +-- 역할 전환은 throws_ok 의 서브트랜잭션 안에서 일어나므로 예외와 함께 되돌아간다. +-- 대상 행은 존재하지 않는 srid(-1) — 문장 트리거는 0행이어도 발화한다. +select throws_ok( + $$ set local role anon; delete from public.spatial_ref_sys where srid = -1 $$, + '42501', 'spatial_ref_sys is read-only for API roles', + 'anon DELETE 는 권한 오류'); +select throws_ok( + $$ set local role anon; update public.spatial_ref_sys set srtext = srtext where srid = -1 $$, + '42501', 'spatial_ref_sys is read-only for API roles', + 'anon UPDATE 는 권한 오류'); +select throws_ok( + $$ set local role anon; + insert into public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) + values (-1, 't27', -1, 'x', 'x') $$, + '42501', 'spatial_ref_sys is read-only for API roles', + 'anon INSERT 는 권한 오류'); +select throws_ok( + $$ set local role authenticated; delete from public.spatial_ref_sys where srid = -1 $$, + '42501', 'spatial_ref_sys is read-only for API roles', + 'authenticated DELETE 도 권한 오류 — 로그인했다고 열리지 않는다'); + +-- 운영 롤(이 테스트를 돌리는 롤 = postgres 계열)은 막히지 않는다. +select lives_ok( + $$ update public.spatial_ref_sys set srtext = srtext where srid = -1 $$, + '운영 롤의 UPDATE 는 통과 — PostGIS 업그레이드·마이그레이션이 막히면 안 된다'); + +-- 읽기는 건드리지 않는다 — 거리 연산이 여전히 4326 을 찾는다. +select ok( + (select count(*) from public.spatial_ref_sys where srid = 4326) = 1, + 'SRID 4326 행이 그대로 읽힌다'); + +select * from finish(); +rollback; From 62f19293fe5891fed8ac6db8d7fb4432b0f9b2be Mon Sep 17 00:00:00 2001 From: seizeh Date: Wed, 11 Nov 2026 12:14:15 +0900 Subject: [PATCH 2/3] =?UTF-8?q?ci:=20(=EC=9E=84=EC=8B=9C)=20spatial=5Fref?= =?UTF-8?q?=5Fsys=20=EA=B6=8C=ED=95=9C=20=EC=A7=84=EB=8B=A8=20=EC=B6=9C?= =?UTF-8?q?=EB=A0=A5=20=E2=80=94=20=EB=8B=A4=EC=9D=8C=20=EC=BB=A4=EB=B0=8B?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리플레이 작업용 DB 와 이미지 기본 DB 에서 확장 테이블의 소유자·ACL 을 찍어, replay-platform-grants.sql 이 실제로 필요한지 실측한다. Co-Authored-By: Claude --- .github/workflows/db-tests.yml | 3 +++ scripts/replay_check.sh | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/.github/workflows/db-tests.yml b/.github/workflows/db-tests.yml index e40105a..724e467 100644 --- a/.github/workflows/db-tests.yml +++ b/.github/workflows/db-tests.yml @@ -107,6 +107,9 @@ jobs: - name: 스키마 스냅샷 복원 (prelude → schema) run: | psql "$DB_URL" -v ON_ERROR_STOP=1 -q -f supabase/schema/prelude.sql + # DIAG(임시 — 다음 커밋에서 제거) + echo "DIAG 기본 DB: $(psql "$DB_URL" -X -At -c "select 'owner=' || pg_get_userbyid(relowner) || ' acl=' || coalesce(relacl::text, '(null)') || ' postgres_TRIGGER=' || has_table_privilege('postgres', oid, 'TRIGGER') || ' anon_DELETE=' || has_table_privilege('anon', oid, 'DELETE') from pg_class where oid = 'public.spatial_ref_sys'::regclass")" + echo "DIAG 기본 DB supabase_admin 의 public 테이블 기본 권한: $(psql "$DB_URL" -X -At -c "select coalesce((select defaclacl::text from pg_default_acl where defaclrole = 'supabase_admin'::regrole and defaclnamespace = 'public'::regnamespace and defaclobjtype = 'r'), '(없음)')")" psql "$DB_URL" -v ON_ERROR_STOP=1 -q -f supabase/schema/schema.sql - name: pgTAP 테스트 diff --git a/scripts/replay_check.sh b/scripts/replay_check.sh index 4436b64..c7ef63e 100755 --- a/scripts/replay_check.sh +++ b/scripts/replay_check.sh @@ -85,7 +85,13 @@ apply "$SNAPSHOT_URL" "$SCHEMA_DIR/schema.sql" echo "== 3/5 B: 베이스라인 + 마이그레이션 리플레이" apply "$REPLAY_URL" "$SCHEMA_DIR/prelude.sql" +# ── DIAG(임시 — 다음 커밋에서 제거) ───────────────────────────────────────── +DIAG_Q="select 'owner=' || pg_get_userbyid(relowner) || ' acl=' || coalesce(relacl::text, '(null)') || ' postgres_TRIGGER=' || has_table_privilege('postgres', oid, 'TRIGGER') || ' anon_DELETE=' || has_table_privilege('anon', oid, 'DELETE') from pg_class where oid = 'public.spatial_ref_sys'::regclass" +echo "DIAG B(새 DB) 권한 주기 전: $(psql "$REPLAY_URL" -X -At -c "$DIAG_Q" 2>&1)" +echo "DIAG B(새 DB) 권한 주기 전 create trigger: $(psql "$REPLAY_URL" -X -q -v ON_ERROR_STOP=1 -c "begin" -c "create function public._diag_trg() returns trigger language plpgsql as 'begin return null; end'" -c "create trigger _diag before insert on public.spatial_ref_sys for each statement execute function public._diag_trg()" -c "rollback" 2>&1 | tr '\n' ' ' || true) [끝]" +echo "DIAG B(새 DB) pg_default_acl 행 수: $(psql "$REPLAY_URL" -X -At -c "select count(*) from pg_default_acl" 2>&1)" apply_as_superuser "$REPLAY_URL" "$SCHEMA_DIR/replay-platform-grants.sql" +echo "DIAG B(새 DB) 권한 준 뒤: $(psql "$REPLAY_URL" -X -At -c "$DIAG_Q" 2>&1)" apply "$REPLAY_URL" "$SCHEMA_DIR/replay-stubs.sql" apply "$REPLAY_URL" "$SCHEMA_DIR/baseline.sql" # 기본 권한은 베이스라인 '다음' 에 건다 — 이유는 그 파일 주석 참고. From 503e92a8bf4ea9f4e4a97b7aaa9b89e3f304ed55 Mon Sep 17 00:00:00 2001 From: seizeh Date: Wed, 11 Nov 2026 12:16:06 +0900 Subject: [PATCH 3/3] =?UTF-8?q?ci:=20=EC=A7=84=EB=8B=A8=20=EC=B6=9C?= =?UTF-8?q?=EB=A0=A5=20=EC=A0=9C=EA=B1=B0=20+=20=EC=8B=A4=EC=B8=A1?= =?UTF-8?q?=EA=B0=92=EC=9D=84=20replay-platform-grants.sql=20=EC=A3=BC?= =?UTF-8?q?=EC=84=9D=EC=97=90=20=EA=B8=B0=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 직전 커밋의 진단으로 확인한 것(supabase/postgres 17.6.1.121): - 리플레이 작업용 DB: pg_default_acl 0행, spatial_ref_sys ACL 은 소유자 + PUBLIC=r 뿐, postgres 의 create trigger 는 permission denied for table spatial_ref_sys. - 이미지 기본 DB(pgtap 잡): 운영과 같은 ACL — 추가 권한이 필요 없다. Co-Authored-By: Claude --- .github/workflows/db-tests.yml | 3 --- scripts/replay_check.sh | 6 ------ supabase/schema/replay-platform-grants.sql | 13 +++++++++---- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/.github/workflows/db-tests.yml b/.github/workflows/db-tests.yml index 724e467..e40105a 100644 --- a/.github/workflows/db-tests.yml +++ b/.github/workflows/db-tests.yml @@ -107,9 +107,6 @@ jobs: - name: 스키마 스냅샷 복원 (prelude → schema) run: | psql "$DB_URL" -v ON_ERROR_STOP=1 -q -f supabase/schema/prelude.sql - # DIAG(임시 — 다음 커밋에서 제거) - echo "DIAG 기본 DB: $(psql "$DB_URL" -X -At -c "select 'owner=' || pg_get_userbyid(relowner) || ' acl=' || coalesce(relacl::text, '(null)') || ' postgres_TRIGGER=' || has_table_privilege('postgres', oid, 'TRIGGER') || ' anon_DELETE=' || has_table_privilege('anon', oid, 'DELETE') from pg_class where oid = 'public.spatial_ref_sys'::regclass")" - echo "DIAG 기본 DB supabase_admin 의 public 테이블 기본 권한: $(psql "$DB_URL" -X -At -c "select coalesce((select defaclacl::text from pg_default_acl where defaclrole = 'supabase_admin'::regrole and defaclnamespace = 'public'::regnamespace and defaclobjtype = 'r'), '(없음)')")" psql "$DB_URL" -v ON_ERROR_STOP=1 -q -f supabase/schema/schema.sql - name: pgTAP 테스트 diff --git a/scripts/replay_check.sh b/scripts/replay_check.sh index c7ef63e..4436b64 100755 --- a/scripts/replay_check.sh +++ b/scripts/replay_check.sh @@ -85,13 +85,7 @@ apply "$SNAPSHOT_URL" "$SCHEMA_DIR/schema.sql" echo "== 3/5 B: 베이스라인 + 마이그레이션 리플레이" apply "$REPLAY_URL" "$SCHEMA_DIR/prelude.sql" -# ── DIAG(임시 — 다음 커밋에서 제거) ───────────────────────────────────────── -DIAG_Q="select 'owner=' || pg_get_userbyid(relowner) || ' acl=' || coalesce(relacl::text, '(null)') || ' postgres_TRIGGER=' || has_table_privilege('postgres', oid, 'TRIGGER') || ' anon_DELETE=' || has_table_privilege('anon', oid, 'DELETE') from pg_class where oid = 'public.spatial_ref_sys'::regclass" -echo "DIAG B(새 DB) 권한 주기 전: $(psql "$REPLAY_URL" -X -At -c "$DIAG_Q" 2>&1)" -echo "DIAG B(새 DB) 권한 주기 전 create trigger: $(psql "$REPLAY_URL" -X -q -v ON_ERROR_STOP=1 -c "begin" -c "create function public._diag_trg() returns trigger language plpgsql as 'begin return null; end'" -c "create trigger _diag before insert on public.spatial_ref_sys for each statement execute function public._diag_trg()" -c "rollback" 2>&1 | tr '\n' ' ' || true) [끝]" -echo "DIAG B(새 DB) pg_default_acl 행 수: $(psql "$REPLAY_URL" -X -At -c "select count(*) from pg_default_acl" 2>&1)" apply_as_superuser "$REPLAY_URL" "$SCHEMA_DIR/replay-platform-grants.sql" -echo "DIAG B(새 DB) 권한 준 뒤: $(psql "$REPLAY_URL" -X -At -c "$DIAG_Q" 2>&1)" apply "$REPLAY_URL" "$SCHEMA_DIR/replay-stubs.sql" apply "$REPLAY_URL" "$SCHEMA_DIR/baseline.sql" # 기본 권한은 베이스라인 '다음' 에 건다 — 이유는 그 파일 주석 참고. diff --git a/supabase/schema/replay-platform-grants.sql b/supabase/schema/replay-platform-grants.sql index 3ce66b1..c20e174 100644 --- a/supabase/schema/replay-platform-grants.sql +++ b/supabase/schema/replay-platform-grants.sql @@ -12,10 +12,15 @@ -- t27 은 "anon/authenticated 에 쓰기 권한이 있는데도 트리거가 막는다" 를 본다. -- -- 리플레이가 쓰는 작업용 DB 는 새로 만든 DB 라 그 기본 권한이 없다(pg_default_acl 은 --- DB 별 카탈로그다). 그대로면 create trigger 가 permission denied 로 멈추고, 트리거가 --- 걸리더라도 anon 의 쓰기는 가드가 아니라 테이블 권한에서 먼저 막혀 t27 이 다른 것을 --- 재게 된다. 테이블 소유자가 supabase_admin 이라 postgres 로는 스스로 줄 수 없어 --- 수퍼유저 접속이 필요하다(replay_check.sh 의 apply_as_superuser). +-- DB 별 카탈로그다). CI 실측(2026-11-11, supabase/postgres 17.6.1.121): +-- +-- 새 작업용 DB pg_default_acl 0행, ACL = supabase_admin=arwdDxtm + PUBLIC=r 뿐 +-- → postgres 의 create trigger 는 permission denied for table spatial_ref_sys +-- 이미지 기본 DB 운영과 같은 ACL(기본 권한이 이미 걸려 있다) → pgtap 잡은 이 파일이 필요 없다 +-- +-- 트리거가 걸리더라도 anon 에 쓰기 권한이 없으면 가드가 아니라 테이블 권한에서 먼저 +-- 막혀 t27 이 다른 것을 재게 된다. 테이블 소유자가 supabase_admin 이라 postgres 로는 +-- 스스로 줄 수 없어 수퍼유저 접속이 필요하다(replay_check.sh 의 apply_as_superuser). -- -- 스냅샷 쪽(A)과 리플레이 쪽(B)에 똑같이 적용한다 — 그래야 이 GRANT 가 덤프에 실리든 -- 안 실리든 양쪽 덤프가 같아 비교 결과에 섞이지 않는다.