TL;DR
3 本の
| クエリ | 目的 | 危険度 |
|---|---|---|
| A | 全ポリシー一覧(USING / WITH CHECK 付き) | — |
| B | RLS 有効なのにポリシーが 0 件のテーブル | 高(データが全員に不可視) |
| C | RLS が無効なテーブル | 中(全行が認証なしに露出) |
なぜ棚卸しが必要か
BoardLink をboards テーブルに
原因を 40 分かけてto authenticated をto anon と
pg_policies ビューを
pg_policies ビューの構造
PostgreSQL 公式pg_policies は
| カラム | 型 | 内容 |
|---|---|---|
schemaname | name | スキーマ名 |
tablename | name | テーブル名 |
policyname | name | ポリシー名 |
permissive | text | PERMISSIVE または RESTRICTIVE |
roles | name[] | 適用ロール(空配列 = PUBLIC) |
cmd | text | SELECT / INSERT / UPDATE / DELETE / ALL |
qual | text | USING 式(NULL の場合あり) |
with_check | text | WITH CHECK 式(NULL の場合あり) |
qual と with_check が
クエリ A: 全ポリシーを USING / WITH CHECK 付きで一覧する
select
tablename,
policyname,
permissive,
roles,
cmd,
qual as using_expr,
with_check as with_check_expr
from pg_policies
where schemaname = 'public'
order by tablename, cmd;
私はcmd = 'UPDATE' のusing_expr がroles が {} のPUBLIC
掲載時点roles は、{public} として{} のroles を
クエリ B: RLS 有効なのにポリシーが 0 件のテーブルを探す
これがALTER TABLE xxx ENABLE ROW LEVEL SECURITY で RLS を
select t.tablename
from pg_tables t
left join pg_policies p
on p.schemaname = t.schemaname
and p.tablename = t.tablename
where t.schemaname = 'public'
and t.rowsecurity = true
and p.policyname is null;
pg_tables は PostgreSQL 9.5 以降で
私のconnections テーブルが
クエリ C: RLS が無効なテーブルを探す
select tablename, tableowner
from pg_tables
where schemaname = 'public'
and rowsecurity = false;
Supabase の anon キーから
3 つをまとめてひとつのクエリで把握する
select
t.tablename,
t.rowsecurity as rls_on,
count(p.policyname) as policy_count,
array_agg(distinct p.cmd order by p.cmd)
filter (where p.cmd is not null) as commands
from pg_tables t
left join pg_policies p
on p.schemaname = t.schemaname
and p.tablename = t.tablename
where t.schemaname = 'public'
group by t.tablename, t.rowsecurity
order by t.tablename;
結果の
| rls_on | policy_count | 意味 |
|---|---|---|
true | 0 | 危険:全員に 0 行が返る |
true | 1 以上 | 正常 |
false | — | 要確認:RLS なしで全行露出 |
はまりどころ: SQL エディタは RLS をバイパスする
Supabase の SQL エディタは postgres ロールでpostgres ロールは BYPASSRLS 属性を
ポリシーのsupabase-js など)から
set local role authenticated;
set local "request.jwt.claim.sub" = '<user-uuid>';
select * from boards;
reset role;
<user-uuid> はauth.users で
まとめ
pg_policiesでプロジェクト 全体の ポリシーを 一覧できる pg_tablesかつ.rowsecurity = true pg_policiesに行なし → 全員に 0 行が 返る 、エラーなしの 罠 rowsecurity = falseのテーブルは RLS なしで 全行が 露出 - SQL エディタは
BYPASSRLSなので SDK 経由またはset local roleで動作確認する
RLS の USING / WITH CHECK のauth.uid() の
SparMate — 格闘技の
NetaPair —
BoardLink — ボドゲ・
Cosoado Lab