rlsautotest 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 rlsautotest / UnitAutogen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ rlsautotest
2
+ Copyright 2026 Munaf Ibrahim Khatri
3
+
4
+ This product includes software developed by Munaf Ibrahim Khatri (the UnitAutogen project).
5
+
6
+ Licensed under the Apache License, Version 2.0. See the LICENSE file.
7
+
8
+ This tool generates tests that run on pgTAP (https://pgtap.org) and is
9
+ compatible with the basejump Supabase test helpers
10
+ (https://github.com/usebasejump/supabase-test-helpers). It parses SQL using
11
+ pglast / libpg_query (https://github.com/lelit/pglast). These are independent
12
+ projects under their own licenses and are not distributed as part of this work.
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.4
2
+ Name: rlsautotest
3
+ Version: 0.1.0
4
+ Summary: Deterministic pgTAP test generation for Postgres/Supabase Row-Level Security (RLS) policies.
5
+ Author: Munaf Ibrahim Khatri
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/unitautogen/rlsautotest
8
+ Project-URL: Issues, https://github.com/unitautogen/rlsautotest/issues
9
+ Keywords: postgres,postgresql,supabase,rls,row-level-security,pgtap,testing,security
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Topic :: Software Development :: Testing
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: Database
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ License-File: NOTICE
20
+ Requires-Dist: psycopg[binary]>=3.1
21
+ Requires-Dist: pglast>=7
22
+ Dynamic: license-file
23
+
24
+ # rlsautotest
25
+
26
+ **Deterministic pgTAP test generation for Postgres / Supabase Row-Level Security.**
27
+
28
+ > **Status: beta (v0.x).** Actively developed and the CLI may still change - but it's built to **never emit a false-passing test**: anything it can't verify soundly is marked, not faked.
29
+
30
+ Point it at your database. It reads your RLS policies from the catalog and **auto-generates both the tests and the seed data** — a native [pgTAP](https://pgtap.org) suite that *proves*, per table, per command, per identity, who can `SELECT` / `INSERT` / `UPDATE` / `DELETE` which rows, plus a per-identity access-matrix report and a CI gate that fails the build on any leak or unprotected table.
31
+
32
+ ```bash
33
+ pip install rlsautotest
34
+ rlsautotest --db-url "$DATABASE_URL" --schema public --emit supabase/
35
+ supabase test db # the generated suite runs natively
36
+ rlsautotest --db-url "$DATABASE_URL" --schema public --report
37
+ ```
38
+
39
+ ## What it does
40
+
41
+ RLS is the security boundary of a Supabase app, and Supabase's own docs note that writing pgTAP tests for it is "inaccessible to most web developers." So most RLS goes untested. `rlsautotest` closes that gap — without you writing a line of test SQL.
42
+
43
+ You point it at your database and it:
44
+
45
+ 1. **reads your RLS policies** from the catalog,
46
+ 2. **generates the test data and identities** that exercise each policy (owners, other users, anon, role-holders, tenants),
47
+ 3. **proves — per table, per command, per identity — who can `SELECT` / `INSERT` / `UPDATE` / `DELETE` which rows**,
48
+ 4. **emits a native pgTAP suite you commit and run** with `supabase test db`, `pg_prove`, or `psql`,
49
+ 5. and gives you a **per-identity access report** plus a **CI gate** that fails the build on a leak or an unprotected table.
50
+
51
+ ## How it does it
52
+
53
+ - **Auto-generates the data, not just the tests — this is what makes the generated tests mean something.** An auto-generated test only proves anything if the data driving it is also generated to match the policy and the identity; otherwise it passes against empty or mismatched rows and proves nothing. rlsautotest does this with **reverse-predicate seeding** — it works backward from each policy's predicate to the exact rows *and* identities (owner, other user, other tenant, role-holder, anon) that drive it true and false. So "the owner can see their row" is checked against a row that is actually theirs, and "another tenant can't" against a real, different tenant. You don't hand-write fixtures or scenarios.
54
+ - **Proves policies are correct, not just present.** It becomes each identity (owner, other user, anon, role-holder) and checks actual access, so a policy that's enabled but wrong — `USING (true)`, the wrong column, an always-true predicate — is caught, not just "RLS is on."
55
+ - **Every test asserts a real, owned row.** Assertions check the exact rows an identity can and can't see, so a passing suite means something: break a policy and the test turns red.
56
+ - **Proves multi-tenant isolation.** It seeds two tenants' data and claims and verifies one tenant sees only its own rows — the core invariant of most apps, checked directly.
57
+ - **Models "denied" the right way.** Row-level filtering is verified as zero rows visible; a missing grant is verified as a permission error — the two are distinguished, so a block is proven for the right reason.
58
+ - **Handles real schemas.** It seeds foreign-key parents in dependency order, so tables with required relationships are actually tested, and it handles the tricky policies: owner (`auth.uid()`), tenant/JWT-claim, membership (`EXISTS`/`IN`), array membership (`= ANY`), RBAC functions (`authorize()` / `has_role()`), recursive hierarchies, escape-hatch `OR` admin grants, and permissive + `AS RESTRICTIVE` composition.
59
+ - **Sound by design — never a false pass.** Tests are derived from your policies and the catalog, not guessed by an LLM. When a policy can't be proven soundly (e.g. an opaque function) it's marked clearly instead of turned into a green checkmark.
60
+ - **Native, ownable output.** Standard pgTAP into `supabase/tests/database/rls/`, runnable by `supabase test db`, `pg_prove`, or plain `psql`. Uses the [basejump test helpers](https://github.com/usebasejump/supabase-test-helpers) when present, or ships a tiny offline shim when they aren't — online or air-gapped.
61
+ - **Static checks too.** It flags open `USING (true)` reads, `WITH CHECK (true)` writes, asymmetric `USING`/`WITH CHECK`, self-referential (recursive) policies, RLS-on-but-no-policy, and policy drift via snapshot/diff.
62
+
63
+ ## What it generates
64
+
65
+ ```
66
+ supabase/tests/database/rls/ # our own folder, separate from your hand-written tests
67
+ 000-setup-tests-hooks.sql # pgTAP + helpers (or offline shim if basejump absent)
68
+ 010-rls-enabled.test.sql # guard: fails if any API-reachable table has RLS OFF
69
+ 101-rls-profiles.test.sql # one file per table, native flat pgTAP
70
+ 102-rls-notes.test.sql
71
+ .rlsautotest/debug/ # nested/structured copies for debugging
72
+ ```
73
+
74
+ Each test is Arrange-Act-Assert: seed as a privileged role (RLS bypassed), act as a mocked identity (`authenticate_as` / `set_config('request.jwt.claims', …)` + `SET ROLE`), assert the visible/affected rows — with `SAVEPOINT` isolation so a write test can't corrupt the next one.
75
+
76
+ ## Modes
77
+
78
+ | Command | What you get |
79
+ |---|---|
80
+ | `--emit DIR` | full suite layout under `DIR/` (default; helper-based, looks native) |
81
+ | `--no-helpers` | fully self-contained tests (inline `set_config`/`SET ROLE`, no helper/000 dependency) |
82
+ | `--report` | run the suite and print the per-identity access matrix (`--report-json` for CI) |
83
+ | `--html FILE` | run the suite and write the access matrix as an HTML report |
84
+ | `--no-fail` | with `--report`/`--html`: don't exit non-zero on problems (default **does** — for CI gating) |
85
+ | `--table T` | a single table instead of the whole schema |
86
+ | `--describe` | show the identity classes the generator derived for a table |
87
+
88
+ ## The report
89
+
90
+ One grid per table — rows are identities, columns are commands — so it reads like a permissions table:
91
+
92
+ ```
93
+ notes SELECT INSERT UPDATE DELETE
94
+ service_role ✓ ✓ ✓ ✓ bypasses RLS
95
+ authenticated, authorized ✓ ✓ ✓ ✓
96
+ authenticated, not authorized · · · ·
97
+ anon · · · ·
98
+ ```
99
+
100
+ `✓` = can, `·` = blocked. The one thing that lights up red is a `✓` where it should be `·` — an *authenticated-but-not-authorized* user or *anon* that can act (a security hole) — so it jumps out without decoding anything. `service_role` is shown for completeness; it bypasses RLS by design. A table with **RLS off** is flagged loud (it has no row-level protection at all).
101
+
102
+ The identity rows are deliberately worded so they aren't mistaken for database roles: `authenticated, authorized` and `authenticated, not authorized` are the **same Postgres role** (`authenticated`) under different JWT identities/claims — only `service_role`, `authenticated`, and `anon` are actual Postgres roles. "Authorized" vs "not authorized" is simply whether that identity passes the table's policies (owns the row, is in the right tenant/org, or has the required role).
103
+
104
+ ## Catching unprotected tables in CI (important)
105
+
106
+ A naive "generate tests, commit them, run them" setup has a dangerous blind spot: a table with **no RLS at all** generates no test, so the suite stays green and the exposure ships silently. `rlsautotest` closes that hole from **two** directions:
107
+
108
+ **1. The report is a CI gate.** `--report` and `--html` **exit non-zero (1)** when they find a problem — a table that's RLS-off-but-reachable (`anon`/`authenticated` can touch it), a check where a forbidden identity can act, or a **broken/unreadable** table (e.g. a self-referential policy that throws *infinite recursion detected in policy*, locking out every client role). So a single command fails the build:
109
+
110
+ ```bash
111
+ rlsautotest --db-url "$DATABASE_URL" --schema public --report # exits 1 if anything is exposed/leaking
112
+ ```
113
+
114
+ Pass `--no-fail` to print the report without failing the pipeline (local or non-blocking use). Exit codes: `0` = clean, `1` = problems found.
115
+
116
+ **2. A schema-wide guard test.** `--emit` also writes `010-rls-enabled.test.sql`, which asserts that **every table reachable by `anon`/`authenticated` has RLS enabled**. A table shipped without RLS becomes a real `not ok` — so even teams that only run `supabase test db` on the committed files (and never re-run the generator) get a red build:
117
+
118
+ ```
119
+ not ok 1 - public.exposed_tbl: RLS must be enabled (table is reachable by anon/authenticated)
120
+ ```
121
+
122
+ It's scoped to *reachable* tables, so a genuinely-internal table with no client grant won't raise a false alarm.
123
+
124
+ ### GitHub Actions
125
+
126
+ ```yaml
127
+ name: rls
128
+ on: [push, pull_request]
129
+ jobs:
130
+ rls:
131
+ runs-on: ubuntu-latest
132
+ services:
133
+ postgres:
134
+ image: postgres:16
135
+ env: { POSTGRES_PASSWORD: postgres }
136
+ ports: ["5432:5432"]
137
+ options: >-
138
+ --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
139
+ steps:
140
+ - uses: actions/checkout@v4
141
+ - uses: actions/setup-python@v5
142
+ with: { python-version: "3.12" }
143
+ - run: pip install rlsautotest
144
+ # apply your migrations into the throwaway DB first, then:
145
+ - name: Verify RLS
146
+ env:
147
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
148
+ run: rlsautotest --db-url "$DATABASE_URL" --schema public --report
149
+ ```
150
+
151
+ The build goes red the moment a policy leaks or a reachable table is missing RLS.
152
+
153
+ ## What it's tested on
154
+
155
+ The `examples/` folder is the runnable test corpus, covering the common and the hard RLS patterns: owner (`auth.uid()`), tenant/JWT-claim, membership (`EXISTS`), array claims (`= ANY`), RBAC functions, recursive policies, session-GUC, and permissive + `AS RESTRICTIVE` composition. On every commit, CI loads the owner-scoped and the multi-tenant example schemas, generates the suite, and runs it — so the core validation is reproducible rather than a claim. (The corpus also includes a deliberately broken, self-referential policy to demonstrate that the tool *catches* problems.) It's been exercised against real-world Supabase schemas too, to harden the generator.
156
+
157
+ ## Honest limitations
158
+
159
+ `rlsautotest` proves your database *enforces what your policies declare*. It cannot know your *intent* — a wrong policy will be faithfully (and greenly) confirmed. It tests the permissions your policies define; commands left with no policy show as `·` (implicit deny) and aren't asserted unless you opt in. Policies behind opaque/external functions it can't reason about are reported, not faked.
160
+
161
+ ## Requirements
162
+
163
+ - Python 3.10+
164
+ - A Postgres database. **pgTAP is handled for you** — rlsautotest uses your database's pgTAP if present (Supabase ships it) and otherwise loads a small built-in copy, so there's nothing to install on the server.
165
+ - For generation: read access to the catalog. For running: a throwaway/local DB (the suite seeds data) — never production.
166
+
167
+ ## Part of the UnitAutogen family
168
+
169
+ `rlsautotest` is the free, open-source PostgreSQL member of **UnitAutogen** — we build *automated unit-test generators for databases*: tools that read your schema and generate the tests for you, instead of you hand-writing them. The test frameworks themselves are open source (pgTAP on Postgres, tSQLt on SQL Server); what UnitAutogen adds is the generator that writes the tests — and the data — for them.
170
+
171
+ The same idea runs deeper on other engines:
172
+
173
+ - **PostgreSQL** — `rlsautotest` (this project, free) and automated unit-test + branch-coverage generation for PL/pgSQL functions, emitting **pgTAP**.
174
+ - **SQL Server** — automated unit-test generation and branch coverage for stored procedures, emitting **tSQLt** (the open-source SQL Server test framework).
175
+ - **Oracle, Azure SQL** — in development.
176
+
177
+ If your team needs automated database test *generation* beyond Postgres RLS — SQL Server, Oracle, Azure — [get in touch](https://github.com/unitautogen).
178
+
179
+ ## Credits
180
+
181
+ Built on [pgTAP](https://pgtap.org) and `pg_prove` (David Wheeler), the [basejump Supabase test helpers](https://github.com/usebasejump/supabase-test-helpers), and [pglast](https://github.com/lelit/pglast) / libpg_query for parsing. Thanks to the Supabase and PostgreSQL communities.
182
+
183
+ ## License
184
+
185
+ Apache-2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,162 @@
1
+ # rlsautotest
2
+
3
+ **Deterministic pgTAP test generation for Postgres / Supabase Row-Level Security.**
4
+
5
+ > **Status: beta (v0.x).** Actively developed and the CLI may still change - but it's built to **never emit a false-passing test**: anything it can't verify soundly is marked, not faked.
6
+
7
+ Point it at your database. It reads your RLS policies from the catalog and **auto-generates both the tests and the seed data** — a native [pgTAP](https://pgtap.org) suite that *proves*, per table, per command, per identity, who can `SELECT` / `INSERT` / `UPDATE` / `DELETE` which rows, plus a per-identity access-matrix report and a CI gate that fails the build on any leak or unprotected table.
8
+
9
+ ```bash
10
+ pip install rlsautotest
11
+ rlsautotest --db-url "$DATABASE_URL" --schema public --emit supabase/
12
+ supabase test db # the generated suite runs natively
13
+ rlsautotest --db-url "$DATABASE_URL" --schema public --report
14
+ ```
15
+
16
+ ## What it does
17
+
18
+ RLS is the security boundary of a Supabase app, and Supabase's own docs note that writing pgTAP tests for it is "inaccessible to most web developers." So most RLS goes untested. `rlsautotest` closes that gap — without you writing a line of test SQL.
19
+
20
+ You point it at your database and it:
21
+
22
+ 1. **reads your RLS policies** from the catalog,
23
+ 2. **generates the test data and identities** that exercise each policy (owners, other users, anon, role-holders, tenants),
24
+ 3. **proves — per table, per command, per identity — who can `SELECT` / `INSERT` / `UPDATE` / `DELETE` which rows**,
25
+ 4. **emits a native pgTAP suite you commit and run** with `supabase test db`, `pg_prove`, or `psql`,
26
+ 5. and gives you a **per-identity access report** plus a **CI gate** that fails the build on a leak or an unprotected table.
27
+
28
+ ## How it does it
29
+
30
+ - **Auto-generates the data, not just the tests — this is what makes the generated tests mean something.** An auto-generated test only proves anything if the data driving it is also generated to match the policy and the identity; otherwise it passes against empty or mismatched rows and proves nothing. rlsautotest does this with **reverse-predicate seeding** — it works backward from each policy's predicate to the exact rows *and* identities (owner, other user, other tenant, role-holder, anon) that drive it true and false. So "the owner can see their row" is checked against a row that is actually theirs, and "another tenant can't" against a real, different tenant. You don't hand-write fixtures or scenarios.
31
+ - **Proves policies are correct, not just present.** It becomes each identity (owner, other user, anon, role-holder) and checks actual access, so a policy that's enabled but wrong — `USING (true)`, the wrong column, an always-true predicate — is caught, not just "RLS is on."
32
+ - **Every test asserts a real, owned row.** Assertions check the exact rows an identity can and can't see, so a passing suite means something: break a policy and the test turns red.
33
+ - **Proves multi-tenant isolation.** It seeds two tenants' data and claims and verifies one tenant sees only its own rows — the core invariant of most apps, checked directly.
34
+ - **Models "denied" the right way.** Row-level filtering is verified as zero rows visible; a missing grant is verified as a permission error — the two are distinguished, so a block is proven for the right reason.
35
+ - **Handles real schemas.** It seeds foreign-key parents in dependency order, so tables with required relationships are actually tested, and it handles the tricky policies: owner (`auth.uid()`), tenant/JWT-claim, membership (`EXISTS`/`IN`), array membership (`= ANY`), RBAC functions (`authorize()` / `has_role()`), recursive hierarchies, escape-hatch `OR` admin grants, and permissive + `AS RESTRICTIVE` composition.
36
+ - **Sound by design — never a false pass.** Tests are derived from your policies and the catalog, not guessed by an LLM. When a policy can't be proven soundly (e.g. an opaque function) it's marked clearly instead of turned into a green checkmark.
37
+ - **Native, ownable output.** Standard pgTAP into `supabase/tests/database/rls/`, runnable by `supabase test db`, `pg_prove`, or plain `psql`. Uses the [basejump test helpers](https://github.com/usebasejump/supabase-test-helpers) when present, or ships a tiny offline shim when they aren't — online or air-gapped.
38
+ - **Static checks too.** It flags open `USING (true)` reads, `WITH CHECK (true)` writes, asymmetric `USING`/`WITH CHECK`, self-referential (recursive) policies, RLS-on-but-no-policy, and policy drift via snapshot/diff.
39
+
40
+ ## What it generates
41
+
42
+ ```
43
+ supabase/tests/database/rls/ # our own folder, separate from your hand-written tests
44
+ 000-setup-tests-hooks.sql # pgTAP + helpers (or offline shim if basejump absent)
45
+ 010-rls-enabled.test.sql # guard: fails if any API-reachable table has RLS OFF
46
+ 101-rls-profiles.test.sql # one file per table, native flat pgTAP
47
+ 102-rls-notes.test.sql
48
+ .rlsautotest/debug/ # nested/structured copies for debugging
49
+ ```
50
+
51
+ Each test is Arrange-Act-Assert: seed as a privileged role (RLS bypassed), act as a mocked identity (`authenticate_as` / `set_config('request.jwt.claims', …)` + `SET ROLE`), assert the visible/affected rows — with `SAVEPOINT` isolation so a write test can't corrupt the next one.
52
+
53
+ ## Modes
54
+
55
+ | Command | What you get |
56
+ |---|---|
57
+ | `--emit DIR` | full suite layout under `DIR/` (default; helper-based, looks native) |
58
+ | `--no-helpers` | fully self-contained tests (inline `set_config`/`SET ROLE`, no helper/000 dependency) |
59
+ | `--report` | run the suite and print the per-identity access matrix (`--report-json` for CI) |
60
+ | `--html FILE` | run the suite and write the access matrix as an HTML report |
61
+ | `--no-fail` | with `--report`/`--html`: don't exit non-zero on problems (default **does** — for CI gating) |
62
+ | `--table T` | a single table instead of the whole schema |
63
+ | `--describe` | show the identity classes the generator derived for a table |
64
+
65
+ ## The report
66
+
67
+ One grid per table — rows are identities, columns are commands — so it reads like a permissions table:
68
+
69
+ ```
70
+ notes SELECT INSERT UPDATE DELETE
71
+ service_role ✓ ✓ ✓ ✓ bypasses RLS
72
+ authenticated, authorized ✓ ✓ ✓ ✓
73
+ authenticated, not authorized · · · ·
74
+ anon · · · ·
75
+ ```
76
+
77
+ `✓` = can, `·` = blocked. The one thing that lights up red is a `✓` where it should be `·` — an *authenticated-but-not-authorized* user or *anon* that can act (a security hole) — so it jumps out without decoding anything. `service_role` is shown for completeness; it bypasses RLS by design. A table with **RLS off** is flagged loud (it has no row-level protection at all).
78
+
79
+ The identity rows are deliberately worded so they aren't mistaken for database roles: `authenticated, authorized` and `authenticated, not authorized` are the **same Postgres role** (`authenticated`) under different JWT identities/claims — only `service_role`, `authenticated`, and `anon` are actual Postgres roles. "Authorized" vs "not authorized" is simply whether that identity passes the table's policies (owns the row, is in the right tenant/org, or has the required role).
80
+
81
+ ## Catching unprotected tables in CI (important)
82
+
83
+ A naive "generate tests, commit them, run them" setup has a dangerous blind spot: a table with **no RLS at all** generates no test, so the suite stays green and the exposure ships silently. `rlsautotest` closes that hole from **two** directions:
84
+
85
+ **1. The report is a CI gate.** `--report` and `--html` **exit non-zero (1)** when they find a problem — a table that's RLS-off-but-reachable (`anon`/`authenticated` can touch it), a check where a forbidden identity can act, or a **broken/unreadable** table (e.g. a self-referential policy that throws *infinite recursion detected in policy*, locking out every client role). So a single command fails the build:
86
+
87
+ ```bash
88
+ rlsautotest --db-url "$DATABASE_URL" --schema public --report # exits 1 if anything is exposed/leaking
89
+ ```
90
+
91
+ Pass `--no-fail` to print the report without failing the pipeline (local or non-blocking use). Exit codes: `0` = clean, `1` = problems found.
92
+
93
+ **2. A schema-wide guard test.** `--emit` also writes `010-rls-enabled.test.sql`, which asserts that **every table reachable by `anon`/`authenticated` has RLS enabled**. A table shipped without RLS becomes a real `not ok` — so even teams that only run `supabase test db` on the committed files (and never re-run the generator) get a red build:
94
+
95
+ ```
96
+ not ok 1 - public.exposed_tbl: RLS must be enabled (table is reachable by anon/authenticated)
97
+ ```
98
+
99
+ It's scoped to *reachable* tables, so a genuinely-internal table with no client grant won't raise a false alarm.
100
+
101
+ ### GitHub Actions
102
+
103
+ ```yaml
104
+ name: rls
105
+ on: [push, pull_request]
106
+ jobs:
107
+ rls:
108
+ runs-on: ubuntu-latest
109
+ services:
110
+ postgres:
111
+ image: postgres:16
112
+ env: { POSTGRES_PASSWORD: postgres }
113
+ ports: ["5432:5432"]
114
+ options: >-
115
+ --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
116
+ steps:
117
+ - uses: actions/checkout@v4
118
+ - uses: actions/setup-python@v5
119
+ with: { python-version: "3.12" }
120
+ - run: pip install rlsautotest
121
+ # apply your migrations into the throwaway DB first, then:
122
+ - name: Verify RLS
123
+ env:
124
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
125
+ run: rlsautotest --db-url "$DATABASE_URL" --schema public --report
126
+ ```
127
+
128
+ The build goes red the moment a policy leaks or a reachable table is missing RLS.
129
+
130
+ ## What it's tested on
131
+
132
+ The `examples/` folder is the runnable test corpus, covering the common and the hard RLS patterns: owner (`auth.uid()`), tenant/JWT-claim, membership (`EXISTS`), array claims (`= ANY`), RBAC functions, recursive policies, session-GUC, and permissive + `AS RESTRICTIVE` composition. On every commit, CI loads the owner-scoped and the multi-tenant example schemas, generates the suite, and runs it — so the core validation is reproducible rather than a claim. (The corpus also includes a deliberately broken, self-referential policy to demonstrate that the tool *catches* problems.) It's been exercised against real-world Supabase schemas too, to harden the generator.
133
+
134
+ ## Honest limitations
135
+
136
+ `rlsautotest` proves your database *enforces what your policies declare*. It cannot know your *intent* — a wrong policy will be faithfully (and greenly) confirmed. It tests the permissions your policies define; commands left with no policy show as `·` (implicit deny) and aren't asserted unless you opt in. Policies behind opaque/external functions it can't reason about are reported, not faked.
137
+
138
+ ## Requirements
139
+
140
+ - Python 3.10+
141
+ - A Postgres database. **pgTAP is handled for you** — rlsautotest uses your database's pgTAP if present (Supabase ships it) and otherwise loads a small built-in copy, so there's nothing to install on the server.
142
+ - For generation: read access to the catalog. For running: a throwaway/local DB (the suite seeds data) — never production.
143
+
144
+ ## Part of the UnitAutogen family
145
+
146
+ `rlsautotest` is the free, open-source PostgreSQL member of **UnitAutogen** — we build *automated unit-test generators for databases*: tools that read your schema and generate the tests for you, instead of you hand-writing them. The test frameworks themselves are open source (pgTAP on Postgres, tSQLt on SQL Server); what UnitAutogen adds is the generator that writes the tests — and the data — for them.
147
+
148
+ The same idea runs deeper on other engines:
149
+
150
+ - **PostgreSQL** — `rlsautotest` (this project, free) and automated unit-test + branch-coverage generation for PL/pgSQL functions, emitting **pgTAP**.
151
+ - **SQL Server** — automated unit-test generation and branch coverage for stored procedures, emitting **tSQLt** (the open-source SQL Server test framework).
152
+ - **Oracle, Azure SQL** — in development.
153
+
154
+ If your team needs automated database test *generation* beyond Postgres RLS — SQL Server, Oracle, Azure — [get in touch](https://github.com/unitautogen).
155
+
156
+ ## Credits
157
+
158
+ Built on [pgTAP](https://pgtap.org) and `pg_prove` (David Wheeler), the [basejump Supabase test helpers](https://github.com/usebasejump/supabase-test-helpers), and [pglast](https://github.com/lelit/pglast) / libpg_query for parsing. Thanks to the Supabase and PostgreSQL communities.
159
+
160
+ ## License
161
+
162
+ Apache-2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rlsautotest"
7
+ version = "0.1.0"
8
+ description = "Deterministic pgTAP test generation for Postgres/Supabase Row-Level Security (RLS) policies."
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Munaf Ibrahim Khatri" }]
13
+ keywords = ["postgres", "postgresql", "supabase", "rls", "row-level-security", "pgtap", "testing", "security"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Topic :: Software Development :: Testing",
19
+ "Topic :: Security",
20
+ "Topic :: Database",
21
+ ]
22
+ dependencies = [
23
+ "psycopg[binary]>=3.1",
24
+ "pglast>=7",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/unitautogen/rlsautotest"
29
+ Issues = "https://github.com/unitautogen/rlsautotest/issues"
30
+
31
+ [project.scripts]
32
+ rlsautotest = "rlsautotest.cli:main"
33
+
34
+ [tool.setuptools]
35
+ packages = ["rlsautotest"]
@@ -0,0 +1,7 @@
1
+ # Copyright 2026 Munaf Ibrahim Khatri
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """rlsautotest — deterministic pgTAP test generation for Postgres/Supabase Row-Level Security."""
4
+ from .cli import main
5
+
6
+ __all__ = ["main"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ # Copyright 2026 Munaf Ibrahim Khatri
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()