pgrls 0.0.1__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
pgrls/cli.py ADDED
@@ -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)
pgrls/config.py ADDED
@@ -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"
pgrls/introspect.py ADDED
@@ -0,0 +1,123 @@
1
+ """Read RLS-relevant state from `pg_catalog` into a normalized Schema."""
2
+ from __future__ import annotations
3
+
4
+ from collections import defaultdict
5
+ from typing import cast
6
+
7
+ import psycopg
8
+ from psycopg.rows import dict_row
9
+
10
+ from pgrls.model import Policy, Schema, Table
11
+
12
+ _POLICY_CMD_MAP: dict[str, str] = {
13
+ "*": "ALL",
14
+ "r": "SELECT",
15
+ "a": "INSERT",
16
+ "w": "UPDATE",
17
+ "d": "DELETE",
18
+ }
19
+
20
+
21
+ _SCHEMA_EXISTS_SQL = """
22
+ SELECT nspname
23
+ FROM pg_catalog.pg_namespace
24
+ WHERE nspname = ANY(%s)
25
+ """
26
+
27
+ _TABLES_SQL = """
28
+ SELECT
29
+ n.nspname AS schema_name,
30
+ c.relname AS table_name,
31
+ c.relrowsecurity AS rls_enabled,
32
+ c.relforcerowsecurity AS force_rls,
33
+ c.oid AS table_oid
34
+ FROM pg_catalog.pg_class c
35
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
36
+ WHERE c.relkind = 'r'
37
+ AND n.nspname = ANY(%s)
38
+ ORDER BY n.nspname, c.relname
39
+ """
40
+
41
+ _POLICIES_SQL = """
42
+ SELECT
43
+ p.polrelid AS table_oid,
44
+ p.polname AS policy_name,
45
+ p.polcmd AS cmd,
46
+ p.polpermissive AS permissive,
47
+ COALESCE(
48
+ (
49
+ SELECT array_agg(
50
+ CASE WHEN ro.oid = 0 THEN 'PUBLIC' ELSE r.rolname END
51
+ ORDER BY CASE WHEN ro.oid = 0 THEN 0 ELSE 1 END, r.rolname
52
+ )
53
+ FROM (SELECT unnest(p.polroles) AS oid) ro
54
+ LEFT JOIN pg_catalog.pg_roles r ON r.oid = ro.oid
55
+ ),
56
+ ARRAY[]::TEXT[]
57
+ ) AS roles,
58
+ pg_catalog.pg_get_expr(p.polqual, p.polrelid) AS using_sql,
59
+ pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid) AS with_check_sql
60
+ FROM pg_catalog.pg_policy p
61
+ WHERE p.polrelid = ANY(%s)
62
+ ORDER BY p.polrelid, p.polname
63
+ """
64
+
65
+
66
+ def introspect(conn: psycopg.Connection, schemas: list[str]) -> Schema:
67
+ """Build a Schema from `pg_catalog` for the given schema list.
68
+
69
+ Raises ValueError if any requested schema does not exist on the connection.
70
+ """
71
+ if not schemas:
72
+ return Schema(tables=())
73
+
74
+ with conn.cursor(row_factory=dict_row) as cur:
75
+ cur.execute(_SCHEMA_EXISTS_SQL, (schemas,))
76
+ existing = {row["nspname"] for row in cur.fetchall()}
77
+ missing = [s for s in schemas if s not in existing]
78
+ if missing:
79
+ raise ValueError(
80
+ f"Schemas not found in database: {', '.join(missing)}"
81
+ )
82
+
83
+ cur.execute(_TABLES_SQL, (schemas,))
84
+ table_rows = cur.fetchall()
85
+ if not table_rows:
86
+ return Schema(tables=())
87
+
88
+ oids = [row["table_oid"] for row in table_rows]
89
+ cur.execute(_POLICIES_SQL, (oids,))
90
+ policy_rows = cur.fetchall()
91
+
92
+ by_oid: dict[int, list[Policy]] = defaultdict(list)
93
+ for row in policy_rows:
94
+ cmd_letter = cast(str, row["cmd"])
95
+ command = _POLICY_CMD_MAP.get(cmd_letter)
96
+ if command is None:
97
+ raise RuntimeError(
98
+ f"Unknown pg_policy.polcmd value {cmd_letter!r} for "
99
+ f"policy {row['policy_name']!r}"
100
+ )
101
+ by_oid[row["table_oid"]].append(
102
+ Policy(
103
+ name=row["policy_name"],
104
+ command=command, # type: ignore[arg-type]
105
+ permissive=row["permissive"],
106
+ roles=tuple(row["roles"]),
107
+ using_sql=row["using_sql"],
108
+ with_check_sql=row["with_check_sql"],
109
+ )
110
+ )
111
+
112
+ tables = [
113
+ Table(
114
+ schema=row["schema_name"],
115
+ name=row["table_name"],
116
+ rls_enabled=row["rls_enabled"],
117
+ force_rls=row["force_rls"],
118
+ policies=tuple(by_oid.get(row["table_oid"], [])),
119
+ )
120
+ for row in table_rows
121
+ ]
122
+
123
+ return Schema(tables=tuple(tables))
pgrls/model.py ADDED
@@ -0,0 +1,75 @@
1
+ """Normalized representation of a Postgres schema's RLS state.
2
+
3
+ Snapshot format is versioned: structural changes bump major, additive bump minor.
4
+ Currently version 1.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any, Literal
10
+
11
+ PolicyCommand = Literal["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]
12
+ Snapshot = dict[str, Any]
13
+
14
+ SNAPSHOT_VERSION = 1
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Policy:
19
+ name: str
20
+ command: Literal["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]
21
+ permissive: bool
22
+ roles: tuple[str, ...]
23
+ using_sql: str | None
24
+ with_check_sql: str | None
25
+
26
+ @property
27
+ def is_permissive(self) -> bool:
28
+ return self.permissive
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Table:
33
+ schema: str
34
+ name: str
35
+ rls_enabled: bool
36
+ force_rls: bool
37
+ policies: tuple[Policy, ...]
38
+
39
+ @property
40
+ def qualified_name(self) -> str:
41
+ return f"{self.schema}.{self.name}"
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Schema:
46
+ tables: tuple[Table, ...] = ()
47
+
48
+ def to_snapshot(self) -> Snapshot:
49
+ return {
50
+ "version": SNAPSHOT_VERSION,
51
+ "tables": [
52
+ {
53
+ "schema": t.schema,
54
+ "name": t.name,
55
+ "rls_enabled": t.rls_enabled,
56
+ "force_rls": t.force_rls,
57
+ }
58
+ for t in self.tables
59
+ ],
60
+ "policies": [
61
+ {
62
+ "id": f"{t.schema}.{t.name}.{p.name}",
63
+ "table_schema": t.schema,
64
+ "table_name": t.name,
65
+ "policy_name": p.name,
66
+ "command": p.command,
67
+ "permissive": p.permissive,
68
+ "roles": list(p.roles),
69
+ "using_sql": p.using_sql,
70
+ "with_check_sql": p.with_check_sql,
71
+ }
72
+ for t in self.tables
73
+ for p in t.policies
74
+ ],
75
+ }
@@ -0,0 +1,64 @@
1
+ """Rule protocol and registry.
2
+
3
+ Rule discovery happens here. SEC001 is registered lazily on first call to
4
+ all_rules() or default_registry(). When more rules land, add their imports
5
+ to _build_default_registry() below.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Protocol, runtime_checkable
10
+
11
+ from pgrls.model import Schema
12
+ from pgrls.violations import Severity, Violation
13
+
14
+
15
+ @runtime_checkable
16
+ class Rule(Protocol):
17
+ id: str
18
+ severity: Severity
19
+ title: str
20
+
21
+ def check(self, schema: Schema, options: dict[str, Any]) -> list[Violation]: ...
22
+
23
+
24
+ class RuleRegistry:
25
+ def __init__(self) -> None:
26
+ self._rules: dict[str, Rule] = {}
27
+
28
+ def register(self, rule: Rule) -> None:
29
+ if not isinstance(rule, Rule):
30
+ raise TypeError(
31
+ f"Expected a Rule, got {type(rule).__name__!r}. "
32
+ "Ensure the class defines id, severity, title, and check()."
33
+ )
34
+ if rule.id in self._rules:
35
+ raise ValueError(f"Rule {rule.id!r} is already registered")
36
+ self._rules[rule.id] = rule
37
+
38
+ def enabled(self, disabled_ids: list[str]) -> list[Rule]:
39
+ skip = set(disabled_ids)
40
+ return [r for rid, r in self._rules.items() if rid not in skip]
41
+
42
+
43
+ _DEFAULT_REGISTRY: RuleRegistry | None = None
44
+
45
+
46
+ def _build_default_registry() -> RuleRegistry:
47
+ from pgrls.rules.sec001 import SEC001
48
+
49
+ registry = RuleRegistry()
50
+ registry.register(SEC001())
51
+ return registry
52
+
53
+
54
+ def default_registry() -> RuleRegistry:
55
+ """Return the registry of all built-in rules."""
56
+ global _DEFAULT_REGISTRY
57
+ if _DEFAULT_REGISTRY is None:
58
+ _DEFAULT_REGISTRY = _build_default_registry()
59
+ return _DEFAULT_REGISTRY
60
+
61
+
62
+ def all_rules() -> list[Rule]:
63
+ """Return every rule shipped with pgrls."""
64
+ return default_registry().enabled(disabled_ids=[])
pgrls/rules/sec001.py ADDED
@@ -0,0 +1,50 @@
1
+ """SEC001 — RLS not enabled on a table in a configured schema.
2
+
3
+ DESIGN.md §4 detection: `pg_class.relrowsecurity = false` in the configured
4
+ schemas, minus the per-rule `allowlist`. Allowlist entries can be unqualified
5
+ (`countries`) or schema-qualified (`tenant.things`).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from pgrls.model import Schema, Table
12
+ from pgrls.violations import Severity, Violation
13
+
14
+
15
+ class SEC001:
16
+ id: str = "SEC001"
17
+ severity: Severity = "error"
18
+ title: str = "RLS not enabled on table"
19
+
20
+ def check(self, schema: Schema, options: dict[str, Any]) -> list[Violation]:
21
+ allowlist = self._parse_allowlist(options)
22
+ return [
23
+ self._violation(t)
24
+ for t in schema.tables
25
+ if not t.rls_enabled and not self._is_allowlisted(t, allowlist)
26
+ ]
27
+
28
+ def _parse_allowlist(self, options: dict[str, Any]) -> set[str]:
29
+ raw = options.get("allowlist", [])
30
+ if not isinstance(raw, list) or not all(isinstance(s, str) for s in raw):
31
+ raise TypeError(
32
+ "SEC001 option 'allowlist' must be a list of strings"
33
+ )
34
+ return set(raw)
35
+
36
+ def _is_allowlisted(self, table: Table, allowlist: set[str]) -> bool:
37
+ return table.name in allowlist or table.qualified_name in allowlist
38
+
39
+ def _violation(self, table: Table) -> Violation:
40
+ return Violation(
41
+ rule_id=self.id,
42
+ severity=self.severity,
43
+ title=self.title,
44
+ message=(
45
+ f"Table {table.qualified_name} does not have row-level "
46
+ "security enabled. Add ENABLE ROW LEVEL SECURITY or include the "
47
+ "table in [lint.rules.SEC001].allowlist if it is a public reference table."
48
+ ),
49
+ location=table.qualified_name,
50
+ )
pgrls/violations.py ADDED
@@ -0,0 +1,22 @@
1
+ """Violation and Severity types reported by rules."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+
7
+ Severity = Literal["error", "warning", "info"]
8
+ SEVERITY_ORDER: dict[Severity, int] = {"error": 0, "warning": 1, "info": 2}
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Violation:
13
+ rule_id: str
14
+ severity: Severity
15
+ title: str
16
+ message: str
17
+ location: str | None # qualified table name or policy id; None for schema-wide
18
+
19
+
20
+ def is_at_or_above(severity: Severity, threshold: Severity) -> bool:
21
+ """True when `severity` is at least as severe as `threshold` (lower = more severe)."""
22
+ return SEVERITY_ORDER[severity] <= SEVERITY_ORDER[threshold]
@@ -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`.
@@ -0,0 +1,15 @@
1
+ pgrls/__init__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
2
+ pgrls/cli.py,sha256=i6F-w6Zrx6wCyZ7_LKW1dHqQHGAEqLkT1TzxTH_ClEw,4108
3
+ pgrls/config.py,sha256=CcTj_pUJQWXgNYgeoUIeSItrJbJoq6-OGHpNFFJbyU0,4311
4
+ pgrls/introspect.py,sha256=4Eb5KApa5vNd9E0fUHIseI10hAGHHxBDtl-xSL1O-_Y,3609
5
+ pgrls/model.py,sha256=fZYnsoxsDQ9ksxU-wthsgHsEHf5MJBHBsgUcF7YsZPI,1986
6
+ pgrls/violations.py,sha256=OrhPwRaVrzX-2ZrkMTLtUjeeR37KZ5gH9NfCuC5TgvY,701
7
+ pgrls/formatters/__init__.py,sha256=E_pGEsY3ls3OOAu-ezCGmpyYSjYKPy68GFVulo0H2Ww,817
8
+ pgrls/formatters/text.py,sha256=s79BaqmPoOpL79ZY1nKpwM-t2CUju8kShBtB1rxdi9w,1009
9
+ pgrls/rules/__init__.py,sha256=G9Ot3NcfQPQ6LhJ4Uz0LrCbG7W1c0VhegFT94IIT7QE,1845
10
+ pgrls/rules/sec001.py,sha256=8xMQX2-AWrWQ3mtg55c-ELQMEXE5pDznA3vBk8eicp4,1838
11
+ pgrls-0.0.1.dist-info/METADATA,sha256=x9FwKC6x2ZdgmHweNaVY0fF1t0B7FGdmwLHEudhbtQY,4359
12
+ pgrls-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
13
+ pgrls-0.0.1.dist-info/entry_points.txt,sha256=Oi4ZOJzM_HKHpLsDXfNzyTe5WYKCKgfp8NwUKaHD-U0,41
14
+ pgrls-0.0.1.dist-info/licenses/LICENSE,sha256=NDDFyeHqZE9SUlZgh3q2-bWvjNTaesPuUIIgiO8ivKA,1071
15
+ pgrls-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pgrls = pgrls.cli:main
@@ -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.