phlo-postgres 0.15.3__tar.gz → 0.16.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.
Files changed (36) hide show
  1. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/PKG-INFO +3 -3
  2. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/pyproject.toml +4 -4
  3. phlo_postgres-0.16.0/src/phlo_postgres/governance.py +298 -0
  4. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/plugin.py +14 -0
  5. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/security_readiness.py +10 -4
  6. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/PKG-INFO +3 -3
  7. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/SOURCES.txt +1 -0
  8. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/requires.txt +1 -1
  9. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/README.md +0 -0
  10. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/setup.cfg +0 -0
  11. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/__init__.py +0 -0
  12. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/authorization.py +0 -0
  13. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/checkpoints.py +0 -0
  14. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/cli.py +0 -0
  15. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/cli_plugin.py +0 -0
  16. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/continuity.py +0 -0
  17. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/dataset_state_store.py +0 -0
  18. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/exporter_service.yaml +0 -0
  19. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/publish_target.py +0 -0
  20. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/resource.py +0 -0
  21. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/service.yaml +0 -0
  22. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/settings.py +0 -0
  23. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/settings_store.py +0 -0
  24. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres/volume_setup.yaml +0 -0
  25. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/dependency_links.txt +0 -0
  26. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/entry_points.txt +0 -0
  27. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/src/phlo_postgres.egg-info/top_level.txt +0 -0
  28. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_authorization.py +0 -0
  29. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_checkpoints.py +0 -0
  30. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_continuity.py +0 -0
  31. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_dataset_state_store.py +0 -0
  32. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_integration_postgres.py +0 -0
  33. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_postgres_cli.py +0 -0
  34. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_postgres_plugin.py +0 -0
  35. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_resource.py +0 -0
  36. {phlo_postgres-0.15.3 → phlo_postgres-0.16.0}/tests/test_settings_store.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phlo-postgres
3
- Version: 0.15.3
3
+ Version: 0.16.0
4
4
  Summary: Postgres service plugin for Phlo
5
5
  Author-email: Phlo Team <team@phlo.dev>
6
6
  License: MIT
7
- Requires-Python: >=3.11
7
+ Requires-Python: >=3.12
8
8
  Description-Content-Type: text/plain
9
- Requires-Dist: phlo<0.17,>=0.16.1
9
+ Requires-Dist: phlo<0.18,>=0.17.0
10
10
  Requires-Dist: psycopg2-binary>=2.9.11
11
11
  Provides-Extra: dev
12
12
  Requires-Dist: pytest>=7.0; extra == "dev"
@@ -7,13 +7,13 @@ requires = [
7
7
 
8
8
  [project]
9
9
  dependencies = [
10
- "phlo>=0.16.1,<0.17",
10
+ "phlo>=0.17.0,<0.18",
11
11
  "psycopg2-binary>=2.9.11",
12
12
  ]
13
13
  description = "Postgres service plugin for Phlo"
14
14
  name = "phlo-postgres"
15
- requires-python = ">=3.11"
16
- version = "0.15.3"
15
+ requires-python = ">=3.12"
16
+ version = "0.16.0"
17
17
 
18
18
  [[project.authors]]
19
19
  email = "team@phlo.dev"
@@ -45,7 +45,7 @@ text = "Postgres service plugin for Phlo."
45
45
 
46
46
  [tool.ruff]
47
47
  line-length = 100
48
- target-version = "py311"
48
+ target-version = "py312"
49
49
 
50
50
  [tool.setuptools]
51
51
  include-package-data = true
@@ -0,0 +1,298 @@
1
+ """PostgreSQL governance backend for access control via SQL grants.
2
+
3
+ Implements the GovernanceBackend protocol over ``PostgresResource``:
4
+ apply/revoke emit GRANT/REVOKE/ALTER DEFAULT PRIVILEGES, and
5
+ ``list_policies`` returns managed grants as typed rows the core
6
+ ``PostgresCompiler`` diffs for plan and verify.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import Any
13
+
14
+ from phlo.capabilities.interfaces import AccessPolicy
15
+ from phlo.logging import get_logger
16
+ from phlo_postgres.resource import PostgresResource
17
+
18
+ logger = get_logger(__name__)
19
+
20
+ _ALLOWED_PRIVILEGES = frozenset(
21
+ {"SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "USAGE", "MAINTAIN"}
22
+ )
23
+ _PREDEFINED_ROLES = frozenset({"pg_read_all_data", "pg_write_all_data"})
24
+ _IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
25
+ _RESOURCE_RE = re.compile(
26
+ r"^[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*$"
27
+ r"|^[a-zA-Z_][a-zA-Z0-9_]*\.\*$"
28
+ r"|^\*$"
29
+ )
30
+ _MANAGED_ROLE_RE = "phlo\\_%"
31
+
32
+
33
+ def _quote_identifier(identifier: str) -> str:
34
+ """Quote one validated SQL identifier."""
35
+ if not _IDENTIFIER_RE.match(identifier):
36
+ raise ValueError(f"Invalid identifier: {identifier!r}")
37
+ return '"' + identifier.replace('"', '""') + '"'
38
+
39
+
40
+ def _split_resource(pattern: str) -> tuple[str, str | None]:
41
+ """Split a resource pattern into (schema, table-or-None-for-wildcards)."""
42
+ if not _RESOURCE_RE.match(pattern):
43
+ raise ValueError(f"Invalid resource pattern: {pattern!r}")
44
+ if pattern == "*":
45
+ return "*", None
46
+ if pattern.endswith(".*"):
47
+ return pattern[:-2], None
48
+ schema, _, table = pattern.partition(".")
49
+ return schema, table
50
+
51
+
52
+ class PostgresGovernanceBackend:
53
+ """GovernanceBackend implementation using PostgreSQL GRANT/REVOKE."""
54
+
55
+ def __init__(self, postgres: PostgresResource | None = None) -> None:
56
+ """Initialize with an optional Postgres resource."""
57
+ self._pg = postgres or PostgresResource()
58
+
59
+ def probe(self) -> bool:
60
+ """Return whether postgres answers a trivial read (readiness evidence)."""
61
+ try:
62
+ row = self._pg.query_one("SELECT 1")
63
+ except Exception:
64
+ return False
65
+ return bool(row)
66
+
67
+ def list_policies(self, *, table_name: str | None = None) -> list[dict[str, Any]]:
68
+ """List managed grants as typed rows.
69
+
70
+ Row kinds: ``table_grant`` (one row per concrete table grant),
71
+ ``schema_usage`` (USAGE on a schema), ``all_tables`` (one row per
72
+ managed role/schema/privilege carrying ``complete`` — whether the
73
+ role holds the privilege on every current table in the schema),
74
+ ``default_privileges`` (default ACLs for future tables), and
75
+ ``role_membership`` (predefined ``pg_*_all_data`` memberships).
76
+ """
77
+ rows: list[dict[str, Any]] = []
78
+ table_filter = ""
79
+ params: tuple[Any, ...] = ()
80
+ if table_name is not None:
81
+ _split_resource(table_name)
82
+ table_filter = "AND (g.table_schema || '.' || g.table_name) = %s"
83
+ params = (table_name,)
84
+ grant_rows = self._pg.query(
85
+ f"""
86
+ SELECT g.grantee, g.table_schema, g.table_name, g.privilege_type
87
+ FROM information_schema.role_table_grants g
88
+ WHERE g.grantee LIKE %s ESCAPE '\\' {table_filter}
89
+ ORDER BY g.grantee, g.table_schema, g.table_name, g.privilege_type
90
+ """,
91
+ (_MANAGED_ROLE_RE, *params),
92
+ )
93
+ for grantee, schema, table, privilege in grant_rows:
94
+ rows.append(
95
+ {
96
+ "kind": "table_grant",
97
+ "grantee": grantee,
98
+ "schema": schema,
99
+ "table": table,
100
+ "privilege": privilege,
101
+ }
102
+ )
103
+
104
+ coverage_rows = self._pg.query(
105
+ """
106
+ SELECT g.grantee, g.table_schema, g.privilege_type,
107
+ bool_and(
108
+ has_table_privilege(
109
+ g.grantee,
110
+ quote_ident(t.table_schema) || '.' || quote_ident(t.table_name),
111
+ g.privilege_type
112
+ )
113
+ ) AS complete
114
+ FROM (
115
+ SELECT DISTINCT grantee, table_schema, privilege_type
116
+ FROM information_schema.role_table_grants
117
+ WHERE grantee LIKE %s ESCAPE '\\'
118
+ ) g
119
+ JOIN information_schema.tables t ON t.table_schema = g.table_schema
120
+ GROUP BY g.grantee, g.table_schema, g.privilege_type
121
+ """,
122
+ (_MANAGED_ROLE_RE,),
123
+ )
124
+ for grantee, schema, privilege, complete in coverage_rows:
125
+ rows.append(
126
+ {
127
+ "kind": "all_tables",
128
+ "grantee": grantee,
129
+ "schema": schema,
130
+ "table": "",
131
+ "privilege": privilege,
132
+ "complete": bool(complete),
133
+ }
134
+ )
135
+
136
+ usage_rows = self._pg.query(
137
+ """
138
+ SELECT grantee.rolname, n.nspname, acl.privilege_type
139
+ FROM pg_namespace n
140
+ CROSS JOIN LATERAL aclexplode(n.nspacl) acl
141
+ JOIN pg_roles grantee ON grantee.oid = acl.grantee
142
+ WHERE acl.privilege_type = 'USAGE' AND grantee.rolname LIKE %s ESCAPE '\\'
143
+ """,
144
+ (_MANAGED_ROLE_RE,),
145
+ )
146
+ for grantee, schema, privilege in usage_rows:
147
+ rows.append(
148
+ {
149
+ "kind": "schema_usage",
150
+ "grantee": grantee,
151
+ "schema": schema,
152
+ "table": "",
153
+ "privilege": privilege,
154
+ }
155
+ )
156
+
157
+ default_rows = self._pg.query(
158
+ """
159
+ SELECT grantee.rolname, n.nspname, acl.privilege_type
160
+ FROM pg_default_acl d
161
+ JOIN pg_namespace n ON n.oid = d.defaclnamespace
162
+ CROSS JOIN LATERAL aclexplode(d.defaclacl) acl
163
+ JOIN pg_roles grantee ON grantee.oid = acl.grantee
164
+ WHERE d.defaclobjtype = 'r' AND grantee.rolname LIKE %s ESCAPE '\\'
165
+ """,
166
+ (_MANAGED_ROLE_RE,),
167
+ )
168
+ for grantee, schema, privilege in default_rows:
169
+ rows.append(
170
+ {
171
+ "kind": "default_privileges",
172
+ "grantee": grantee,
173
+ "schema": schema,
174
+ "table": "",
175
+ "privilege": privilege,
176
+ }
177
+ )
178
+
179
+ membership_rows = self._pg.query(
180
+ """
181
+ SELECT member.rolname, parent.rolname
182
+ FROM pg_auth_members m
183
+ JOIN pg_roles member ON member.oid = m.member
184
+ JOIN pg_roles parent ON parent.oid = m.roleid
185
+ WHERE member.rolname LIKE %s ESCAPE '\\'
186
+ AND parent.rolname IN ('pg_read_all_data', 'pg_write_all_data')
187
+ """,
188
+ (_MANAGED_ROLE_RE,),
189
+ )
190
+ for grantee, parent_role in membership_rows:
191
+ rows.append(
192
+ {
193
+ "kind": "role_membership",
194
+ "grantee": grantee,
195
+ "schema": "",
196
+ "table": "",
197
+ "privilege": parent_role,
198
+ }
199
+ )
200
+ return rows
201
+
202
+ def apply_policy(self, *, policy: AccessPolicy) -> None:
203
+ """Apply one canonical grant as PostgreSQL statements.
204
+
205
+ The policy id encodes the artifact scope (the core compiler names
206
+ artifacts ``<role>__<resource>__<priv>`` with ``__DEFAULT`` for
207
+ default privileges); the resource pattern selects the statement
208
+ shape: ``*`` grants a predefined role, ``schema.*`` grants USAGE or
209
+ ALL TABLES plus default privileges, ``schema.table`` grants on one
210
+ table.
211
+ """
212
+ role = policy.principal
213
+ _quote_identifier(role)
214
+ scope_hint = str(policy.policy_id or "")
215
+ for privilege in [p.strip() for p in policy.action.split(",") if p.strip()]:
216
+ self._apply_privilege(privilege, policy.table_pattern, role, scope_hint)
217
+ logger.info(
218
+ "postgres_governance_apply_policy",
219
+ principal=role,
220
+ resource=policy.table_pattern,
221
+ action=policy.action,
222
+ )
223
+
224
+ def _apply_privilege(self, privilege: str, pattern: str, role: str, scope_hint: str) -> None:
225
+ schema, table = _split_resource(pattern)
226
+ role_ref = _quote_identifier(role)
227
+ if pattern == "*":
228
+ if privilege not in _PREDEFINED_ROLES:
229
+ raise ValueError(f"Unsupported predefined role: {privilege!r}")
230
+ self._pg.execute(f"GRANT {privilege} TO {role_ref}")
231
+ return
232
+ if privilege not in _ALLOWED_PRIVILEGES:
233
+ raise ValueError(f"Unsupported privilege: {privilege!r}")
234
+ schema_ref = _quote_identifier(schema)
235
+ if table is None:
236
+ if privilege == "USAGE" or scope_hint.endswith("__USAGE"):
237
+ self._pg.execute(f"GRANT USAGE ON SCHEMA {schema_ref} TO {role_ref}")
238
+ return
239
+ if scope_hint.endswith("__DEFAULT"):
240
+ self._pg.execute(
241
+ f"ALTER DEFAULT PRIVILEGES IN SCHEMA {schema_ref} "
242
+ f"GRANT {privilege} ON TABLES TO {role_ref}"
243
+ )
244
+ return
245
+ self._pg.execute(
246
+ f"GRANT {privilege} ON ALL TABLES IN SCHEMA {schema_ref} TO {role_ref}"
247
+ )
248
+ return
249
+ table_ref = f"{schema_ref}.{_quote_identifier(table)}"
250
+ self._pg.execute(f"GRANT {privilege} ON TABLE {table_ref} TO {role_ref}")
251
+
252
+ def revoke_policy(self, *, policy_id: str) -> None:
253
+ """Revoke a grant. policy_id: ``SCOPE:PRIVILEGE:RESOURCE:ROLE``."""
254
+ parts = policy_id.split(":")
255
+ if len(parts) != 4:
256
+ raise ValueError(f"policy_id must be 'SCOPE:PRIVILEGE:RESOURCE:ROLE', got: {policy_id}")
257
+ scope, privilege, pattern, role = parts
258
+ role_ref = _quote_identifier(role)
259
+ schema, table = _split_resource(pattern)
260
+ if pattern == "*":
261
+ if privilege not in _PREDEFINED_ROLES:
262
+ raise ValueError(f"Unsupported predefined role: {privilege!r}")
263
+ self._pg.execute(f"REVOKE {privilege} FROM {role_ref}")
264
+ return
265
+ if privilege not in _ALLOWED_PRIVILEGES:
266
+ raise ValueError(f"Unsupported privilege: {privilege!r}")
267
+ schema_ref = _quote_identifier(schema)
268
+ if scope == "schema_usage" or privilege == "USAGE":
269
+ self._pg.execute(f"REVOKE USAGE ON SCHEMA {schema_ref} FROM {role_ref}")
270
+ return
271
+ if scope == "default_privileges":
272
+ self._pg.execute(
273
+ f"ALTER DEFAULT PRIVILEGES IN SCHEMA {schema_ref} "
274
+ f"REVOKE {privilege} ON TABLES FROM {role_ref}"
275
+ )
276
+ return
277
+ if table is None:
278
+ self._pg.execute(
279
+ f"REVOKE {privilege} ON ALL TABLES IN SCHEMA {schema_ref} FROM {role_ref}"
280
+ )
281
+ return
282
+ self._pg.execute(
283
+ f"REVOKE {privilege} ON TABLE {schema_ref}.{_quote_identifier(table)} FROM {role_ref}"
284
+ )
285
+ logger.info("postgres_governance_revoke_policy", policy_id=policy_id)
286
+
287
+ def check_access(self, *, principal: str, table_name: str, action: str) -> bool:
288
+ """Return whether principal holds the privilege on the table."""
289
+ _quote_identifier(principal)
290
+ _split_resource(table_name)
291
+ privilege = action.split(",")[0].strip().upper()
292
+ if privilege not in _ALLOWED_PRIVILEGES:
293
+ raise ValueError(f"Unsupported privilege: {privilege!r}")
294
+ row = self._pg.query_one(
295
+ "SELECT has_table_privilege(%s, %s, %s)",
296
+ (principal, table_name, privilege),
297
+ )
298
+ return bool(row and row[0])
@@ -28,7 +28,9 @@ from phlo.capabilities import (
28
28
  SlingConnectionSpec,
29
29
  BackendReadinessSpec,
30
30
  BackupContributorSpec,
31
+ CapabilitySupport,
31
32
  DatasetStateStoreSpec,
33
+ GovernanceBackendSpec,
32
34
  )
33
35
  from phlo.plugins import (
34
36
  PackageYamlServicePlugin,
@@ -135,6 +137,18 @@ class PostgresResourceProvider(ResourceProviderPlugin):
135
137
 
136
138
  return [BackupContributorSpec(name="postgres", provider=PostgresBackupContributor())]
137
139
 
140
+ def get_governance_backends(self) -> list[GovernanceBackendSpec]:
141
+ """Expose the postgres governance backend for SQL grants."""
142
+ from phlo_postgres.governance import PostgresGovernanceBackend
143
+
144
+ return [
145
+ GovernanceBackendSpec(
146
+ name="postgres",
147
+ provider=PostgresGovernanceBackend(),
148
+ support=CapabilitySupport(),
149
+ )
150
+ ]
151
+
138
152
  """Resource provider plugin that exposes PostgreSQL capabilities.
139
153
 
140
154
  This plugin registers the PostgresResource and PostgresPublishTarget with
@@ -1,9 +1,10 @@
1
1
  """Provider-owned postgres security readiness (read-only).
2
2
 
3
- Inspects only locally inspectable facts (configuration present, non-default).
4
- Authoritative grant/audit observation requires a live backend and is reported
5
- ``unavailable`` until that evidence is obtainable; ``unavailable`` and
6
- ``failed`` both block production readiness.
3
+ Inspects locally inspectable facts (configuration present, non-default),
4
+ then observes managed-grant convergence against the canonical RBAC model
5
+ through the postgres governance backend when that path is wired. When no
6
+ live observation is possible the result stays ``unavailable``;
7
+ ``unavailable`` and ``failed`` both block production readiness.
7
8
  """
8
9
 
9
10
  from __future__ import annotations
@@ -13,6 +14,8 @@ import os
13
14
  from phlo.security.backend_readiness import (
14
15
  BackendReadinessResult,
15
16
  BackendReadinessState,
17
+ observe_policy_convergence,
18
+ stamp,
16
19
  )
17
20
 
18
21
  REQUIRED_REFERENCES = ["POSTGRES_USER", "POSTGRES_PASSWORD"]
@@ -34,6 +37,9 @@ class PostgresReadinessProvider:
34
37
  + ", ".join(sorted(missing)),
35
38
  evidence_source="declared configuration",
36
39
  )
40
+ observed = observe_policy_convergence("postgres")
41
+ if observed is not None:
42
+ return stamp(observed)
37
43
  return BackendReadinessResult(
38
44
  backend="postgres",
39
45
  state=BackendReadinessState.UNAVAILABLE,
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phlo-postgres
3
- Version: 0.15.3
3
+ Version: 0.16.0
4
4
  Summary: Postgres service plugin for Phlo
5
5
  Author-email: Phlo Team <team@phlo.dev>
6
6
  License: MIT
7
- Requires-Python: >=3.11
7
+ Requires-Python: >=3.12
8
8
  Description-Content-Type: text/plain
9
- Requires-Dist: phlo<0.17,>=0.16.1
9
+ Requires-Dist: phlo<0.18,>=0.17.0
10
10
  Requires-Dist: psycopg2-binary>=2.9.11
11
11
  Provides-Extra: dev
12
12
  Requires-Dist: pytest>=7.0; extra == "dev"
@@ -8,6 +8,7 @@ src/phlo_postgres/cli_plugin.py
8
8
  src/phlo_postgres/continuity.py
9
9
  src/phlo_postgres/dataset_state_store.py
10
10
  src/phlo_postgres/exporter_service.yaml
11
+ src/phlo_postgres/governance.py
11
12
  src/phlo_postgres/plugin.py
12
13
  src/phlo_postgres/publish_target.py
13
14
  src/phlo_postgres/resource.py
@@ -1,4 +1,4 @@
1
- phlo<0.17,>=0.16.1
1
+ phlo<0.18,>=0.17.0
2
2
  psycopg2-binary>=2.9.11
3
3
 
4
4
  [dev]
File without changes
File without changes