Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 재현) |
Expand All @@ -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` 에 이 객체들이 아예 없어서 복원해도 아무것도 안 생기기 때문이다.

Expand Down
14 changes: 14 additions & 0 deletions scripts/_schema_dump.sh
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ normalize_dump() {
# · storage.buckets 설정 (공개 여부·용량·MIME 제한)
# · storage.objects RLS 정책 (사용자 사진의 접근 제어)
# · cron.job (보존기간 파기 배치)
# · 확장 소유 테이블에 건 트리거 (spatial_ref_sys 쓰기 가드 — 테이블은
# public 에 있지만 확장 소속이라 덤프에서 빠진다)
#
# 즉 "마이그레이션 없이 친 DDL 을 즉시 잡는다" 는 이 저장소의 보증이 **사진 접근
# 제어와 파기 배치에는 적용되지 않았다**. 실제로 publication 드리프트가 하나 있었고
Expand Down Expand Up @@ -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
}
28 changes: 23 additions & 5 deletions scripts/replay_check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 출력은 되먹였을 때 글자 그대로 재현되지 않는다. 예컨대
Expand Down Expand Up @@ -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)" \
Expand All @@ -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"
# 기본 권한은 베이스라인 '다음' 에 건다 — 이유는 그 파일 주석 참고.
Expand Down Expand Up @@ -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
Expand Down
75 changes: 75 additions & 0 deletions supabase/migrations/20260915100000_spatial_ref_sys_write_guard.sql
Original file line number Diff line number Diff line change
@@ -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 $$;
18 changes: 0 additions & 18 deletions supabase/schema/baseline.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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: -
--
Expand Down
1 change: 1 addition & 0 deletions supabase/schema/outofband.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
27 changes: 27 additions & 0 deletions supabase/schema/replay-platform-grants.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- 플랫폼이 확장 소유 테이블에 주는 권한 — 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 별 카탈로그다). 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 가 덤프에 실리든
-- 안 실리든 양쪽 덤프가 같아 비교 결과에 섞이지 않는다.
grant all on table public.spatial_ref_sys to postgres, anon, authenticated, service_role;
52 changes: 52 additions & 0 deletions supabase/tests/t27_spatial_ref_sys_guard_test.sql
Original file line number Diff line number Diff line change
@@ -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;
Loading