pgrls 0.0.1__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.
- pgrls-0.0.1/.gitignore +20 -0
- pgrls-0.0.1/LICENSE +21 -0
- pgrls-0.0.1/PKG-INFO +133 -0
- pgrls-0.0.1/README.md +80 -0
- pgrls-0.0.1/pgrls.example.toml +17 -0
- pgrls-0.0.1/pyproject.toml +54 -0
- pgrls-0.0.1/src/pgrls/__init__.py +1 -0
- pgrls-0.0.1/src/pgrls/cli.py +139 -0
- pgrls-0.0.1/src/pgrls/config.py +128 -0
- pgrls-0.0.1/src/pgrls/formatters/__init__.py +26 -0
- pgrls-0.0.1/src/pgrls/formatters/text.py +36 -0
- pgrls-0.0.1/src/pgrls/introspect.py +123 -0
- pgrls-0.0.1/src/pgrls/model.py +75 -0
- pgrls-0.0.1/src/pgrls/rules/__init__.py +64 -0
- pgrls-0.0.1/src/pgrls/rules/sec001.py +50 -0
- pgrls-0.0.1/src/pgrls/violations.py +22 -0
- pgrls-0.0.1/tests/__init__.py +0 -0
- pgrls-0.0.1/tests/conftest.py +53 -0
- pgrls-0.0.1/tests/fixtures/known_bad.sql +21 -0
- pgrls-0.0.1/tests/test_cli.py +124 -0
- pgrls-0.0.1/tests/test_config.py +119 -0
- pgrls-0.0.1/tests/test_e2e.py +54 -0
- pgrls-0.0.1/tests/test_formatter_text.py +64 -0
- pgrls-0.0.1/tests/test_introspect.py +113 -0
- pgrls-0.0.1/tests/test_model.py +132 -0
- pgrls-0.0.1/tests/test_rules_registry.py +81 -0
- pgrls-0.0.1/tests/test_sec001.py +86 -0
- pgrls-0.0.1/tests/test_smoke.py +6 -0
- pgrls-0.0.1/tests/test_violations.py +52 -0
pgrls-0.0.1/.gitignore
ADDED
pgrls-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dmitry Maranik
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pgrls-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pgrls
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Framework-agnostic linter and testing toolkit for Postgres Row-Level Security.
|
|
5
|
+
Project-URL: Homepage, https://github.com/pgrls/pgrls
|
|
6
|
+
Project-URL: Issues, https://github.com/pgrls/pgrls/issues
|
|
7
|
+
Author: Dmitry Maranik
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 Dmitry Maranik
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: linter,postgres,postgresql,rls,row-level-security,security
|
|
31
|
+
Classifier: Development Status :: 3 - Alpha
|
|
32
|
+
Classifier: Environment :: Console
|
|
33
|
+
Classifier: Intended Audience :: Developers
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Operating System :: OS Independent
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
40
|
+
Classifier: Topic :: Database
|
|
41
|
+
Classifier: Topic :: Security
|
|
42
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
43
|
+
Requires-Python: >=3.11
|
|
44
|
+
Requires-Dist: click>=8.1
|
|
45
|
+
Requires-Dist: psycopg[binary]>=3.1
|
|
46
|
+
Provides-Extra: dev
|
|
47
|
+
Requires-Dist: build>=1.0; extra == 'dev'
|
|
48
|
+
Requires-Dist: hatchling>=1.21; extra == 'dev'
|
|
49
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
50
|
+
Requires-Dist: testcontainers[postgres]>=4.0; extra == 'dev'
|
|
51
|
+
Requires-Dist: twine>=5.0; extra == 'dev'
|
|
52
|
+
Description-Content-Type: text/markdown
|
|
53
|
+
|
|
54
|
+
# pgrls
|
|
55
|
+
|
|
56
|
+
Framework-agnostic linter and testing toolkit for Postgres Row-Level Security.
|
|
57
|
+
|
|
58
|
+
> **Status: 0.0.1** — first lint rule (SEC001) shipped. The full rule catalog and the `test` / `diff` commands are on the roadmap below.
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install pgrls
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Requires Python 3.11+.
|
|
67
|
+
|
|
68
|
+
## Usage
|
|
69
|
+
|
|
70
|
+
Point `pgrls` at any Postgres database:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
export DATABASE_URL="postgres://user:pass@host:5432/db"
|
|
74
|
+
pgrls lint
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Or pass the URL directly:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pgrls lint --database-url "postgres://user:pass@host:5432/db"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Limit the scan to specific schemas:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pgrls lint --schemas public,tenant
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Point at a non-default config file, or pick an output format:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
pgrls lint --config ./config/pgrls.toml --format text
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Example output
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
ERROR SEC001 public.users
|
|
99
|
+
Table public.users does not have row-level security enabled.
|
|
100
|
+
Add ENABLE ROW LEVEL SECURITY or include the table in
|
|
101
|
+
[lint.rules.SEC001].allowlist if it is a public reference table.
|
|
102
|
+
|
|
103
|
+
pgrls: 1 error.
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Exit code is `1` when any violation meets or exceeds `fail_on` (default `warning`).
|
|
107
|
+
|
|
108
|
+
## Configuration
|
|
109
|
+
|
|
110
|
+
Drop a `pgrls.toml` next to your project. See `pgrls.example.toml` in the repo for a fully commented version.
|
|
111
|
+
|
|
112
|
+
```toml
|
|
113
|
+
[database]
|
|
114
|
+
url = "$DATABASE_URL"
|
|
115
|
+
schemas = ["public"]
|
|
116
|
+
|
|
117
|
+
[lint]
|
|
118
|
+
disable = []
|
|
119
|
+
fail_on = "warning"
|
|
120
|
+
|
|
121
|
+
[lint.rules.SEC001]
|
|
122
|
+
allowlist = ["countries", "currencies"]
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Roadmap
|
|
126
|
+
|
|
127
|
+
- **More lint rules.** Full SEC / PERF / HYG catalog, including the marquee SEC004 (inverted auth check / Lovable CVE pattern). JSON, SARIF, and Markdown output. Polished error messages.
|
|
128
|
+
- **`pgrls test`.** Code-first RLS test DSL for Python, TypeScript, and Go.
|
|
129
|
+
- **`pgrls diff`.** Semantic policy diff between branches with DANGEROUS / BREAKING / SAFE classification.
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT — see `LICENSE`.
|
pgrls-0.0.1/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# pgrls
|
|
2
|
+
|
|
3
|
+
Framework-agnostic linter and testing toolkit for Postgres Row-Level Security.
|
|
4
|
+
|
|
5
|
+
> **Status: 0.0.1** — first lint rule (SEC001) shipped. The full rule catalog and the `test` / `diff` commands are on the roadmap below.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install pgrls
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Python 3.11+.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
Point `pgrls` at any Postgres database:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
export DATABASE_URL="postgres://user:pass@host:5432/db"
|
|
21
|
+
pgrls lint
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Or pass the URL directly:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pgrls lint --database-url "postgres://user:pass@host:5432/db"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Limit the scan to specific schemas:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pgrls lint --schemas public,tenant
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Point at a non-default config file, or pick an output format:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pgrls lint --config ./config/pgrls.toml --format text
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Example output
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
ERROR SEC001 public.users
|
|
46
|
+
Table public.users does not have row-level security enabled.
|
|
47
|
+
Add ENABLE ROW LEVEL SECURITY or include the table in
|
|
48
|
+
[lint.rules.SEC001].allowlist if it is a public reference table.
|
|
49
|
+
|
|
50
|
+
pgrls: 1 error.
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Exit code is `1` when any violation meets or exceeds `fail_on` (default `warning`).
|
|
54
|
+
|
|
55
|
+
## Configuration
|
|
56
|
+
|
|
57
|
+
Drop a `pgrls.toml` next to your project. See `pgrls.example.toml` in the repo for a fully commented version.
|
|
58
|
+
|
|
59
|
+
```toml
|
|
60
|
+
[database]
|
|
61
|
+
url = "$DATABASE_URL"
|
|
62
|
+
schemas = ["public"]
|
|
63
|
+
|
|
64
|
+
[lint]
|
|
65
|
+
disable = []
|
|
66
|
+
fail_on = "warning"
|
|
67
|
+
|
|
68
|
+
[lint.rules.SEC001]
|
|
69
|
+
allowlist = ["countries", "currencies"]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Roadmap
|
|
73
|
+
|
|
74
|
+
- **More lint rules.** Full SEC / PERF / HYG catalog, including the marquee SEC004 (inverted auth check / Lovable CVE pattern). JSON, SARIF, and Markdown output. Polished error messages.
|
|
75
|
+
- **`pgrls test`.** Code-first RLS test DSL for Python, TypeScript, and Go.
|
|
76
|
+
- **`pgrls diff`.** Semantic policy diff between branches with DANGEROUS / BREAKING / SAFE classification.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
MIT — see `LICENSE`.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Copy this file to `pgrls.toml` and adjust.
|
|
2
|
+
# Environment variables can be referenced as `$VAR` or `${VAR}`.
|
|
3
|
+
|
|
4
|
+
[database]
|
|
5
|
+
url = "$DATABASE_URL"
|
|
6
|
+
schemas = ["public"]
|
|
7
|
+
|
|
8
|
+
[lint]
|
|
9
|
+
# Rule IDs to skip entirely.
|
|
10
|
+
disable = []
|
|
11
|
+
# Severity that triggers a nonzero exit code: "error" | "warning" | "info".
|
|
12
|
+
fail_on = "warning"
|
|
13
|
+
|
|
14
|
+
# Per-rule options.
|
|
15
|
+
[lint.rules.SEC001]
|
|
16
|
+
# Tables where missing RLS is acceptable. Entries can be unqualified (countries) or qualified (tenant.things).
|
|
17
|
+
allowlist = []
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pgrls"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Framework-agnostic linter and testing toolkit for Postgres Row-Level Security."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { file = "LICENSE" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Dmitry Maranik" }]
|
|
13
|
+
keywords = ["postgres", "postgresql", "rls", "row-level-security", "linter", "security"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Database",
|
|
25
|
+
"Topic :: Security",
|
|
26
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"click>=8.1",
|
|
30
|
+
"psycopg[binary]>=3.1",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
dev = [
|
|
35
|
+
"hatchling>=1.21",
|
|
36
|
+
"pytest>=8.0",
|
|
37
|
+
"testcontainers[postgres]>=4.0",
|
|
38
|
+
"build>=1.0",
|
|
39
|
+
"twine>=5.0",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[project.scripts]
|
|
43
|
+
pgrls = "pgrls.cli:main"
|
|
44
|
+
|
|
45
|
+
[project.urls]
|
|
46
|
+
Homepage = "https://github.com/pgrls/pgrls"
|
|
47
|
+
Issues = "https://github.com/pgrls/pgrls/issues"
|
|
48
|
+
|
|
49
|
+
[tool.hatch.build.targets.wheel]
|
|
50
|
+
packages = ["src/pgrls"]
|
|
51
|
+
|
|
52
|
+
[tool.pytest.ini_options]
|
|
53
|
+
testpaths = ["tests"]
|
|
54
|
+
addopts = ["-ra", "--strict-markers", "--strict-config"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Click entry point for the `pgrls` console script."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sys
|
|
5
|
+
from typing import cast
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
import psycopg
|
|
9
|
+
|
|
10
|
+
from pgrls import __version__
|
|
11
|
+
from pgrls.config import Config, ConfigError, load_config
|
|
12
|
+
from pgrls.formatters import SUPPORTED_FORMATS, format_violations
|
|
13
|
+
from pgrls.introspect import introspect
|
|
14
|
+
from pgrls.model import Schema
|
|
15
|
+
from pgrls.rules import default_registry
|
|
16
|
+
from pgrls.violations import Severity, Violation, is_at_or_above
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@click.group()
|
|
20
|
+
@click.version_option(__version__, prog_name="pgrls")
|
|
21
|
+
def main() -> None:
|
|
22
|
+
"""Framework-agnostic linter and testing toolkit for Postgres Row-Level Security."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@main.command()
|
|
26
|
+
@click.option(
|
|
27
|
+
"--database-url",
|
|
28
|
+
envvar="DATABASE_URL",
|
|
29
|
+
help="Postgres connection string. Falls back to $DATABASE_URL.",
|
|
30
|
+
)
|
|
31
|
+
@click.option(
|
|
32
|
+
"--config",
|
|
33
|
+
"config_path",
|
|
34
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
35
|
+
default=None,
|
|
36
|
+
help="Path to pgrls.toml. Defaults to ./pgrls.toml if present.",
|
|
37
|
+
)
|
|
38
|
+
@click.option(
|
|
39
|
+
"--schemas",
|
|
40
|
+
default=None,
|
|
41
|
+
help="Comma-separated schemas to lint (overrides config).",
|
|
42
|
+
)
|
|
43
|
+
@click.option(
|
|
44
|
+
"--fail-on",
|
|
45
|
+
type=click.Choice(["error", "warning", "info"], case_sensitive=False),
|
|
46
|
+
default=None,
|
|
47
|
+
help="Severity threshold that triggers nonzero exit.",
|
|
48
|
+
)
|
|
49
|
+
@click.option(
|
|
50
|
+
"--format",
|
|
51
|
+
"output_format",
|
|
52
|
+
type=click.Choice(SUPPORTED_FORMATS, case_sensitive=False),
|
|
53
|
+
default="text",
|
|
54
|
+
show_default=True,
|
|
55
|
+
help="Output format.",
|
|
56
|
+
)
|
|
57
|
+
def lint(
|
|
58
|
+
database_url: str | None,
|
|
59
|
+
config_path: str | None,
|
|
60
|
+
schemas: str | None,
|
|
61
|
+
fail_on: str | None,
|
|
62
|
+
output_format: str,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Lint Postgres RLS policies for security and hygiene issues."""
|
|
65
|
+
try:
|
|
66
|
+
config = load_config(config_path)
|
|
67
|
+
except ConfigError as exc:
|
|
68
|
+
raise click.ClickException(str(exc))
|
|
69
|
+
|
|
70
|
+
effective = _merge_overrides(
|
|
71
|
+
config,
|
|
72
|
+
database_url=database_url,
|
|
73
|
+
schemas_csv=schemas,
|
|
74
|
+
fail_on=fail_on,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
if effective.database_url is None:
|
|
78
|
+
raise click.ClickException(
|
|
79
|
+
"No database connection: pass --database-url or set DATABASE_URL."
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
with psycopg.connect(effective.database_url) as conn:
|
|
84
|
+
schema = introspect(conn, schemas=effective.schemas)
|
|
85
|
+
except psycopg.Error as exc:
|
|
86
|
+
raise click.ClickException(f"Database error: {exc}")
|
|
87
|
+
except ValueError as exc:
|
|
88
|
+
raise click.ClickException(str(exc))
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
violations = _run_rules(schema, config=effective)
|
|
92
|
+
except (TypeError, ValueError) as exc:
|
|
93
|
+
raise click.ClickException(str(exc))
|
|
94
|
+
|
|
95
|
+
click.echo(format_violations(violations, format=output_format), nl=False)
|
|
96
|
+
|
|
97
|
+
if _should_fail(violations, threshold=effective.fail_on):
|
|
98
|
+
sys.exit(1)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _merge_overrides(
|
|
102
|
+
config: Config,
|
|
103
|
+
*,
|
|
104
|
+
database_url: str | None,
|
|
105
|
+
schemas_csv: str | None,
|
|
106
|
+
fail_on: str | None,
|
|
107
|
+
) -> Config:
|
|
108
|
+
if schemas_csv:
|
|
109
|
+
schemas = [s.strip() for s in schemas_csv.split(",") if s.strip()]
|
|
110
|
+
if not schemas:
|
|
111
|
+
raise click.ClickException(
|
|
112
|
+
f"--schemas {schemas_csv!r} produced an empty schema list. "
|
|
113
|
+
"Check for trailing commas or whitespace-only values."
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
schemas = config.schemas
|
|
117
|
+
effective_fail_on: Severity = (
|
|
118
|
+
cast(Severity, fail_on) if fail_on is not None else config.fail_on
|
|
119
|
+
)
|
|
120
|
+
return Config(
|
|
121
|
+
database_url=database_url or config.database_url,
|
|
122
|
+
schemas=schemas,
|
|
123
|
+
disable=list(config.disable),
|
|
124
|
+
fail_on=effective_fail_on,
|
|
125
|
+
rule_options=dict(config.rule_options),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _run_rules(schema: Schema, *, config: Config) -> list[Violation]:
|
|
130
|
+
registry = default_registry()
|
|
131
|
+
rules = registry.enabled(disabled_ids=config.disable)
|
|
132
|
+
out: list[Violation] = []
|
|
133
|
+
for rule in rules:
|
|
134
|
+
out.extend(rule.check(schema, config.rule_options.get(rule.id, {})))
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _should_fail(violations: list[Violation], *, threshold: Severity) -> bool:
|
|
139
|
+
return any(is_at_or_above(v.severity, threshold) for v in violations)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Load `pgrls.toml`, interpolate environment variables, return a typed Config."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import tomllib
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
Severity = Literal["error", "warning", "info"]
|
|
12
|
+
_VALID_FAIL_ON: tuple[Severity, ...] = ("error", "warning", "info")
|
|
13
|
+
_ENV_PATTERN = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigError(Exception):
|
|
17
|
+
"""Raised when the user's config file is invalid or references missing env vars."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Config:
|
|
22
|
+
"""Loaded configuration.
|
|
23
|
+
|
|
24
|
+
`frozen=True` prevents field reassignment but does NOT freeze the list and
|
|
25
|
+
dict fields. Callers must treat `schemas`, `disable`, and `rule_options` as
|
|
26
|
+
read-only — do not mutate them in place.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
database_url: str | None = None
|
|
30
|
+
schemas: list[str] = field(default_factory=lambda: ["public"])
|
|
31
|
+
disable: list[str] = field(default_factory=list)
|
|
32
|
+
fail_on: Severity = "warning"
|
|
33
|
+
rule_options: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_config(path: Path | str | None) -> Config:
|
|
37
|
+
"""Load config from `path`, or `./pgrls.toml` if `path` is None and the file exists.
|
|
38
|
+
|
|
39
|
+
Returns a default Config when no file is found.
|
|
40
|
+
"""
|
|
41
|
+
resolved = _resolve_path(path)
|
|
42
|
+
if resolved is None:
|
|
43
|
+
return Config()
|
|
44
|
+
|
|
45
|
+
raw = _read_toml(resolved)
|
|
46
|
+
return _build_config(raw)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _resolve_path(path: Path | str | None) -> Path | None:
|
|
50
|
+
if path is not None:
|
|
51
|
+
p = Path(path)
|
|
52
|
+
if not p.is_file():
|
|
53
|
+
raise ConfigError(f"Config file not found: {p}")
|
|
54
|
+
return p
|
|
55
|
+
default = Path.cwd() / "pgrls.toml"
|
|
56
|
+
return default if default.is_file() else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _read_toml(path: Path) -> dict[str, Any]:
|
|
60
|
+
try:
|
|
61
|
+
with path.open("rb") as fh:
|
|
62
|
+
return tomllib.load(fh)
|
|
63
|
+
except tomllib.TOMLDecodeError as exc:
|
|
64
|
+
raise ConfigError(f"Invalid TOML in {path}: {exc}") from exc
|
|
65
|
+
except OSError as exc:
|
|
66
|
+
raise ConfigError(f"Cannot read config {path}: {exc}") from exc
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _build_config(raw: dict[str, Any]) -> Config:
|
|
70
|
+
database = raw.get("database", {})
|
|
71
|
+
if not isinstance(database, dict):
|
|
72
|
+
raise ConfigError("[database] must be a table")
|
|
73
|
+
lint = raw.get("lint", {})
|
|
74
|
+
if not isinstance(lint, dict):
|
|
75
|
+
raise ConfigError("[lint] must be a table")
|
|
76
|
+
|
|
77
|
+
url_raw = database.get("url")
|
|
78
|
+
if url_raw is None:
|
|
79
|
+
database_url = None
|
|
80
|
+
elif isinstance(url_raw, str):
|
|
81
|
+
database_url = _interpolate_env(url_raw)
|
|
82
|
+
else:
|
|
83
|
+
raise ConfigError(
|
|
84
|
+
f"[database].url must be a string, got {type(url_raw).__name__}"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
schemas = database.get("schemas", ["public"])
|
|
88
|
+
if not isinstance(schemas, list) or not all(isinstance(s, str) for s in schemas):
|
|
89
|
+
raise ConfigError("[database].schemas must be a list of strings")
|
|
90
|
+
|
|
91
|
+
disable = lint.get("disable", [])
|
|
92
|
+
if not isinstance(disable, list) or not all(isinstance(s, str) for s in disable):
|
|
93
|
+
raise ConfigError("[lint].disable must be a list of rule-id strings")
|
|
94
|
+
|
|
95
|
+
fail_on = lint.get("fail_on", "warning")
|
|
96
|
+
if fail_on not in _VALID_FAIL_ON:
|
|
97
|
+
raise ConfigError(
|
|
98
|
+
f"[lint].fail_on must be one of {_VALID_FAIL_ON}, got {fail_on!r}"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
rules_raw = lint.get("rules", {})
|
|
102
|
+
if not isinstance(rules_raw, dict):
|
|
103
|
+
raise ConfigError("[lint.rules] must be a table")
|
|
104
|
+
rule_options: dict[str, dict[str, Any]] = {}
|
|
105
|
+
for rule_id, opts in rules_raw.items():
|
|
106
|
+
if not isinstance(opts, dict):
|
|
107
|
+
raise ConfigError(f"[lint.rules.{rule_id}] must be a table")
|
|
108
|
+
rule_options[rule_id] = dict(opts)
|
|
109
|
+
|
|
110
|
+
return Config(
|
|
111
|
+
database_url=database_url,
|
|
112
|
+
schemas=list(schemas),
|
|
113
|
+
disable=list(disable),
|
|
114
|
+
fail_on=fail_on,
|
|
115
|
+
rule_options=rule_options,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _interpolate_env(value: str) -> str:
|
|
120
|
+
"""Replace `$VAR` and `${VAR}` with environment values. Missing vars raise."""
|
|
121
|
+
|
|
122
|
+
def replace(match: re.Match[str]) -> str:
|
|
123
|
+
name = match.group(1) or match.group(2)
|
|
124
|
+
if name not in os.environ:
|
|
125
|
+
raise ConfigError(f"Environment variable {name!r} is not set")
|
|
126
|
+
return os.environ[name]
|
|
127
|
+
|
|
128
|
+
return _ENV_PATTERN.sub(replace, value)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Output formatters. Currently only `text` ships in v0.0.1.
|
|
2
|
+
|
|
3
|
+
JSON, SARIF, and Markdown formats are planned for a future release. Adding a
|
|
4
|
+
format = creating a sibling module and wiring it into `_FORMATTERS` here.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Callable
|
|
9
|
+
|
|
10
|
+
from pgrls.formatters.text import format_text
|
|
11
|
+
from pgrls.violations import Violation
|
|
12
|
+
|
|
13
|
+
_FORMATTERS: dict[str, Callable[[list[Violation]], str]] = {
|
|
14
|
+
"text": format_text,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
SUPPORTED_FORMATS: tuple[str, ...] = tuple(_FORMATTERS.keys())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def format_violations(violations: list[Violation], *, format: str) -> str:
|
|
21
|
+
if format not in _FORMATTERS:
|
|
22
|
+
raise ValueError(
|
|
23
|
+
f"Unknown output format {format!r}. "
|
|
24
|
+
f"Supported: {', '.join(SUPPORTED_FORMATS)}"
|
|
25
|
+
)
|
|
26
|
+
return _FORMATTERS[format](violations)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Human-readable text output."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import Counter
|
|
5
|
+
|
|
6
|
+
from pgrls.violations import Severity, Violation
|
|
7
|
+
|
|
8
|
+
_SEVERITY_LABEL: dict[Severity, str] = {
|
|
9
|
+
"error": "ERROR",
|
|
10
|
+
"warning": "WARN ",
|
|
11
|
+
"info": "INFO ",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def format_text(violations: list[Violation]) -> str:
|
|
16
|
+
if not violations:
|
|
17
|
+
return "pgrls: no issues found.\n"
|
|
18
|
+
|
|
19
|
+
lines: list[str] = []
|
|
20
|
+
for v in violations:
|
|
21
|
+
loc = v.location or "<schema>"
|
|
22
|
+
lines.append(
|
|
23
|
+
f" {_SEVERITY_LABEL[v.severity]} {v.rule_id} {loc}\n"
|
|
24
|
+
f" {v.message}"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
counts: Counter[Severity] = Counter(v.severity for v in violations)
|
|
28
|
+
parts: list[str] = []
|
|
29
|
+
for sev in ("error", "warning", "info"):
|
|
30
|
+
n = counts.get(sev, 0) # type: ignore[arg-type]
|
|
31
|
+
if n:
|
|
32
|
+
parts.append(f"{n} {sev}{'s' if n != 1 else ''}")
|
|
33
|
+
summary = ", ".join(parts) or "0 issues"
|
|
34
|
+
|
|
35
|
+
body = "\n\n".join(lines)
|
|
36
|
+
return f"{body}\n\npgrls: {summary}.\n"
|