safegres
Agent skill
The fastest start: give your coding agent the safegres skill and ask it to audit your database.
npx skills add constructive-io/constructive --skill safegres
Install
npm i -D safegres
npx safegres doctor # connection, catalog visibility, and what's missing
npx safegres audit --perf # two scores, from the catalog
Standard libpq environment (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE), a full
--connection <url>, or per-field flags. No agent, no traffic, no application framework, nothing
executed and nothing written — safe to point at a production replica.
No database handy? See CI: one service container plus the migration command you
already have.
Features
- 🛡️ Complete RLS Auditing – Grants, RLS enforcement, policy coverage and policy behavior, across every schema and role in the database
- 🎯 Operation-Level Coverage – Every granted
SELECT/INSERT/UPDATE/DELETE checked against the policies that actually cover it, per role
- 🔍 Risky Policy Detection – Permissive checks, volatile and session-dependent predicates, definer escalation and role bypass, found in the parsed AST rather than by regex
- ⚡ Performance on Its Own Axis – Policy predicates that no index can serve, per-row function calls, missing foreign-key indexes — scored separately, so hardening never reads as a regression
- 🧭 Exposure Planes – The declared API surface is the headline grade; direct-connection and per-role planes are graded beside it, so "what can an anonymous caller reach?" is a number
- 📊 Security Scoring & Grades – Scores, grades, severity counts and per-rule deductions with the payoff of fixing each one
- 🐘 Pure PostgreSQL Analysis – Reads the catalog and parses SQL; no agent, no traffic, no ORM, no application changes, nothing executed
- ⚙️ Built for CI – Summaries, Markdown, JSON and SARIF, GitHub job summaries, annotations and a sticky PR comment, with configurable failure thresholds
- Δ Change-Aware Audits – Compare two reports to show exactly what a branch introduced, fixed or worsened; baselines accept inherited debt and gate only what's new
- 🧪 Graded Against a Corpus –
safegres eval scores the auditor itself on fixtures with known answers, sealed against config that could game the number
- 📦 CLI and Library APIs – Run it from the command line, or import the analysis, report and renderers into your own tooling
What you get
safegres 1.16.1 (2026-02-14T09:31:07.884Z)
exposure: 2 schema(s) via config — 41/318 tables exposed
score: 91.4 (A) — model: density
top deductions: A2 −10 (×1) R3 −4 (×1)
by rule: A2 B (+8.4) R3 A (+3.5)
unscored: A4 (×3) A6 (×7) — zero-weight, fixing these cannot move the score
perf score: 78.1 (C) — model: density
top deductions: X2 −12 (×3) X1 −8 (×2) X9 −4 (×1)
by rule: X2 C (+11.2) X1 D (+7.6) X9 B (+3.8)
summary: 0 critical 1 high 4 medium 3 low 7 info
[HIGH] A2 app_public.webhook_deliveries
Roles [authenticated] have grants on app_public.webhook_deliveries but RLS is disabled
[MED ] X2 app_public.posts (posts_tenant)
Policy "posts_tenant" on app_public.posts filters by tenant_id, which is not the
leading column of any index
Also available as --format json, json-pretty, markdown (job summaries and PR comments) and
sarif (GitHub code scanning).
How it works
safegres is a static analyzer for a live PostgreSQL database. It reads the system catalog and
parses every policy predicate and function body into an AST, then answers two questions the
catalog already contains the answers to — who can actually reach this row, and what does
checking that cost per row — and scores them on two independent axes.
Two scores, never mixed. Hardening a table can't show up as a performance regression; adding an
index can't show up as a security win. That is the whole design: the trade you make between them
becomes visible instead of netting out to a single number.
Three analyses over three different representations. None of them run your queries.
1. The catalog, as a relation. pg_class, pg_namespace, pg_policy, pg_roles,
pg_auth_members, pg_index and aclexplode() are joined into one snapshot per relation:
grants, RLS flags, policies with their expressions, indexes, ownership.
2. Policy predicates, as ASTs. Every USING / WITH CHECK expression is parsed with
pgsql-parser (libpg_query — the actual PostgreSQL
grammar, not a regex) and traversed. That is what makes the interesting rules possible: a literal
true in a write policy (A7), a cast wrapping the policy's own column so no plain index can serve
it (X3), a non-IMMUTABLE call whose arguments reference no column of the row and which sits
outside an uncorrelated scalar sub-select — i.e. a per-row call the planner will not hoist into an
InitPlan (X9). Structural detection, not a list of known function names: a GUC-reading helper
somebody adds next year is caught without configuration.
3. Effective access, as a lattice. ACL rows are not access. A privilege also arrives via
GRANT … TO PUBLIC and via role inheritance (pg_auth_members, INHERIT-following), and it is
only reachable if the role also holds USAGE on the schema. safegres computes the effective
cell each (relation, role, privilege) triple lands in, with pg_has_role membership semantics,
and reports the ones that are inconsistent in either direction:
| grant |
RLS |
policy |
verdict |
| yes |
on |
yes |
normal — policy-mediated access |
| yes |
on |
no |
dead grant (L1 indirect; A4/A5 direct) |
| yes |
off |
— |
unmediated (A2 table-level; L5 per untrusted role, indirect) |
| no |
— |
yes |
dead policy (L2) |
The same closure answers the direct question — what can role X actually reach? — as
report.roleAccess, with provenance (direct, PUBLIC, member of <role>) per relation.
Two optional analyses go further: --explain plans each finding's query shape with
EXPLAIN (GENERIC_PLAN) and lets the planner refute the tool's own static claim; --call-graph
computes the transitive closure of function calls from the exposed entry points and enumerates the
trust boundaries on the way.
What it checks
45 rules across two dimensions — 34 security, 11 performance — plus four opt-in runtime-statistics
rules and a four-rule source-level convention linter. The prefix letter is a family, not the
dimension: P1/P1b are performance, P5 is security.
Security (34 rules)
| Code |
Severity |
Direction |
Check |
| A1 |
low |
fail-closed |
RLS enabled but 0 policies (deny-all — confirm the lock is intended) |
| A2 |
high |
fail-open |
Grants exist on a table with RLS disabled |
| A3 |
low |
fail-open |
RLS enabled but FORCE ROW LEVEL SECURITY not set (table-owner bypass) |
| A4 |
low |
fail-closed |
INSERT/UPDATE/DELETE grant with no covering policy — writes denied at runtime |
| A5 |
low |
fail-closed |
SELECT grant with no policy — queries silently return 0 rows |
| A6 |
info |
fail-closed |
UPDATE has USING but no WITH CHECK (row-smuggling surface) |
| A7 |
critical |
fail-open |
Trivially-permissive write policy (literal true) |
| A8 |
low |
fail-open |
Trivially-permissive SELECT policy (USING (true)) |
| P5 |
high |
fail-open |
Policy references session_user / current_user / pg_has_role(...) |
| R1 |
critical |
fail-open |
An untrusted role holds a write privilege † |
| R2 |
high |
fail-open |
A permissive write policy applies to an untrusted role or PUBLIC † |
| R3 |
medium |
fail-open |
An RLS table has grants TO PUBLIC |
| L1 |
low |
fail-closed |
Dead indirect grant — arrives via PUBLIC/inheritance, no policy admits it |
| L2 |
low |
fail-closed |
Dead policy — applies to a role holding no corresponding grant |
| L3 |
low |
fail-closed |
Unreachable grant — object privilege without schema USAGE |
| L4 |
info |
neutral |
Dead schema USAGE — reaches no relation and no function |
| L5 |
info |
fail-open |
An untrusted role reaches an RLS-off table via PUBLIC/inheritance † |
| L6 |
info |
neutral |
Unaddressable grant — an API role holds privileges on a relation its API cannot name ‡ |
| L7 |
info |
fail-open |
Role escalation — an untrusted role can SET ROLE to a role with more reach † |
| L8 |
info |
fail-open |
DEFINER view bypass — an untrusted role reads a base relation, and named columns of it, as the view's owner † |
| L9 |
info |
fail-open |
DEFINER view write — an auto-updatable definer view writes a base relation as its owner † |
| L10 |
info |
fail-open |
Rewrite-rule bypass — a rule on a view writes a relation as the view's owner, security_invoker notwithstanding † |
| L11 |
info |
fail-open |
Materialized-view snapshot — stored rows serve an untrusted role what the base relation's grants and policies would not † |
| L12 |
info |
fail-open |
Non-barrier filtering view — a view is an untrusted role's only path to a relation, but its row filter is not a boundary † |
| L13 |
info |
fail-open |
Column-level grant — an untrusted role reaches a relation through pg_attribute.attacl, which no relation ACL shows † |
| L14 |
info |
neutral |
Unaudited base relation — a definer view reads a relation in a schema the audit never introspected † |
| L15 |
info |
neutral |
Unreadable body — an untrusted role reaches through a definer view or function whose body the analysis could not follow † |
| L16 |
info |
fail-open |
Sequence privilege — an untrusted role can advance or read a sequence, which no policy filters † |
| L17 |
info |
fail-open |
Foreign-table grant — an untrusted role reaches a relation that cannot carry RLS at all † |
| L18 |
info |
fail-open |
Writable filtering view without WITH CHECK OPTION — an untrusted role writes rows the view's own filter excludes † |
| L19 |
info |
fail-open |
Definer-function reach — an untrusted role touches a relation by executing a SECURITY DEFINER function, which runs as its owner † |
| L20 |
info |
fail-open |
INSTEAD OF trigger write — a write against a view becomes a trigger function's body, and a definer one lands it as the function's owner † |
| L21 |
info |
fail-closed |
Revocable grant — a role holds EXECUTE that no reachable path exercises † |
| W1 |
medium |
— |
No exposure surface configured — whole database assumed reachable, score capped |
† The untrusted-role rules are no-ops until there is an untrusted role: named outright
("R1": ["critical", { "roles": ["anonymous"] }]) or resolved from the exposure surface
(rolesFrom: "anon", which safegres:recommended and the stack presets set — see
Configuration). They cost nothing on databases without an untrusted-role model.
‡ L6 needs an adapter that can compute API reach;
without one nothing is unaddressable and it never fires.
Exposure is asked per subject. A relation finding is exposed when the API can address the
relation. A routine finding — the convention rules, L19, L20 — is exposed when an untrusted role
can call the function: USAGE on its schema and EXECUTE on the function, directly, by
inheritance, or through Postgres's default EXECUTE TO PUBLIC. Grading a definer function by the
schema it sits in is not conservative, it is wrong in the dangerous direction: the function is
private precisely so that calling it is the only way in.
Direction is the load-bearing idea. fail-open findings are exposure — the untrusted side
reaches more than intended. fail-closed findings are denied by Postgres at runtime: an
availability and hygiene concern, not a leak. They contribute zero to the score by default
(scoring.failClosedWeight). safegres does not cry wolf about a grant the database already refuses.
Convention (source-level lint, 4 rules — safegres:constructive)
House-style rules that read function definitions (pg_get_functiondef), not the catalog. They
are pure source → findings — they come from @pgsql/lint,
which has no pg dependency — and are off outside the safegres:constructive preset, which
enables them. A function on a non-exposed schema costs nothing, like every other rule.
| Code |
Severity |
Direction |
Check |
| C1 |
high |
fail-open |
Function sets search_path (house rule: never set it — fully-qualify instead) |
| C2 |
medium |
neutral |
Function uses a #variable_conflict directive |
| C3 |
low |
neutral |
Function has an unqualified relation reference (relies on search_path) |
| C4 |
high |
fail-open |
Function uses dynamic SQL (EXECUTE / EXECUTE … USING / FOR … IN EXECUTE) |