auth 3.5.2__tar.gz → 3.6.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 (115) hide show
  1. {auth-3.5.2 → auth-3.6.0}/PKG-INFO +4 -4
  2. {auth-3.5.2 → auth-3.6.0}/README.md +3 -3
  3. {auth-3.5.2 → auth-3.6.0}/auth/keycheck.py +20 -3
  4. auth-3.6.0/auth/migrate.py +61 -0
  5. auth-3.6.0/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +41 -0
  6. auth-3.6.0/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +21 -0
  7. auth-3.6.0/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +26 -0
  8. auth-3.6.0/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +85 -0
  9. auth-3.6.0/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +279 -0
  10. auth-3.6.0/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +108 -0
  11. auth-3.6.0/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +180 -0
  12. auth-3.6.0/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +40 -0
  13. auth-3.6.0/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +108 -0
  14. auth-3.6.0/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +104 -0
  15. auth-3.6.0/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +166 -0
  16. auth-3.6.0/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +117 -0
  17. auth-3.6.0/auth/migrations/__init__.py +0 -0
  18. {auth-3.5.2 → auth-3.6.0}/auth/static_docs/api_reference.md +33 -10
  19. {auth-3.5.2 → auth-3.6.0}/auth/static_docs/claude_guide.md +5 -4
  20. {auth-3.5.2 → auth-3.6.0}/auth/static_docs/landing.md +2 -2
  21. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/PKG-INFO +4 -4
  22. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/SOURCES.txt +16 -0
  23. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/entry_points.txt +1 -0
  24. {auth-3.5.2 → auth-3.6.0}/pyproject.toml +3 -1
  25. auth-3.6.0/tests/test_migrate_cli.py +104 -0
  26. auth-3.6.0/tests/test_served_docs_host.py +49 -0
  27. {auth-3.5.2 → auth-3.6.0}/LICENSE +0 -0
  28. {auth-3.5.2 → auth-3.6.0}/auth/__init__.py +0 -0
  29. {auth-3.5.2 → auth-3.6.0}/auth/api_keys.py +0 -0
  30. {auth-3.5.2 → auth-3.6.0}/auth/audit.py +0 -0
  31. {auth-3.5.2 → auth-3.6.0}/auth/circuit_breaker.py +0 -0
  32. {auth-3.5.2 → auth-3.6.0}/auth/client/__init__.py +0 -0
  33. {auth-3.5.2 → auth-3.6.0}/auth/client/_transport.py +0 -0
  34. {auth-3.5.2 → auth-3.6.0}/auth/client/base.py +0 -0
  35. {auth-3.5.2 → auth-3.6.0}/auth/client/keys.py +0 -0
  36. {auth-3.5.2 → auth-3.6.0}/auth/client/rbac.py +0 -0
  37. {auth-3.5.2 → auth-3.6.0}/auth/client/workflow.py +0 -0
  38. {auth-3.5.2 → auth-3.6.0}/auth/cmd/__init__.py +0 -0
  39. {auth-3.5.2 → auth-3.6.0}/auth/cmd/server.py +0 -0
  40. {auth-3.5.2 → auth-3.6.0}/auth/config.py +0 -0
  41. {auth-3.5.2 → auth-3.6.0}/auth/core/REST/__init__.py +0 -0
  42. {auth-3.5.2 → auth-3.6.0}/auth/core/REST/client.py +0 -0
  43. {auth-3.5.2 → auth-3.6.0}/auth/core/__init__.py +0 -0
  44. {auth-3.5.2 → auth-3.6.0}/auth/core/models/__init__.py +0 -0
  45. {auth-3.5.2 → auth-3.6.0}/auth/database.py +0 -0
  46. {auth-3.5.2 → auth-3.6.0}/auth/decorators.py +0 -0
  47. {auth-3.5.2 → auth-3.6.0}/auth/docs_page.py +0 -0
  48. {auth-3.5.2 → auth-3.6.0}/auth/encryption.py +0 -0
  49. {auth-3.5.2 → auth-3.6.0}/auth/logging_config.py +0 -0
  50. {auth-3.5.2 → auth-3.6.0}/auth/main.py +0 -0
  51. {auth-3.5.2 → auth-3.6.0}/auth/models/sql.py +0 -0
  52. {auth-3.5.2 → auth-3.6.0}/auth/response_format.py +0 -0
  53. {auth-3.5.2 → auth-3.6.0}/auth/rls.py +0 -0
  54. {auth-3.5.2 → auth-3.6.0}/auth/routes/__init__.py +0 -0
  55. {auth-3.5.2 → auth-3.6.0}/auth/routes/_common.py +0 -0
  56. {auth-3.5.2 → auth-3.6.0}/auth/routes/apikeys.py +0 -0
  57. {auth-3.5.2 → auth-3.6.0}/auth/routes/membership.py +0 -0
  58. {auth-3.5.2 → auth-3.6.0}/auth/routes/permissions.py +0 -0
  59. {auth-3.5.2 → auth-3.6.0}/auth/routes/public.py +0 -0
  60. {auth-3.5.2 → auth-3.6.0}/auth/routes/roles.py +0 -0
  61. {auth-3.5.2 → auth-3.6.0}/auth/routes/tenant.py +0 -0
  62. {auth-3.5.2 → auth-3.6.0}/auth/routes/workflow.py +0 -0
  63. {auth-3.5.2 → auth-3.6.0}/auth/sanitizer.py +0 -0
  64. {auth-3.5.2 → auth-3.6.0}/auth/schema_check.py +0 -0
  65. {auth-3.5.2 → auth-3.6.0}/auth/schema_reconcile.py +0 -0
  66. {auth-3.5.2 → auth-3.6.0}/auth/server.py +0 -0
  67. {auth-3.5.2 → auth-3.6.0}/auth/services/base.py +0 -0
  68. {auth-3.5.2 → auth-3.6.0}/auth/services/keys.py +0 -0
  69. {auth-3.5.2 → auth-3.6.0}/auth/services/queries.py +0 -0
  70. {auth-3.5.2 → auth-3.6.0}/auth/services/rbac.py +0 -0
  71. {auth-3.5.2 → auth-3.6.0}/auth/services/recovery.py +0 -0
  72. {auth-3.5.2 → auth-3.6.0}/auth/services/rotation.py +0 -0
  73. {auth-3.5.2 → auth-3.6.0}/auth/services/service.py +0 -0
  74. {auth-3.5.2 → auth-3.6.0}/auth/services/tenant.py +0 -0
  75. {auth-3.5.2 → auth-3.6.0}/auth/static_docs/__init__.py +0 -0
  76. {auth-3.5.2 → auth-3.6.0}/auth/static_docs/page.html +0 -0
  77. {auth-3.5.2 → auth-3.6.0}/auth/validation.py +0 -0
  78. {auth-3.5.2 → auth-3.6.0}/auth/workflow_checker.py +0 -0
  79. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/dependency_links.txt +0 -0
  80. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/requires.txt +0 -0
  81. {auth-3.5.2 → auth-3.6.0}/auth.egg-info/top_level.txt +0 -0
  82. {auth-3.5.2 → auth-3.6.0}/setup.cfg +0 -0
  83. {auth-3.5.2 → auth-3.6.0}/tests/test_api_keys.py +0 -0
  84. {auth-3.5.2 → auth-3.6.0}/tests/test_api_keys_encryption.py +0 -0
  85. {auth-3.5.2 → auth-3.6.0}/tests/test_audit_integrity.py +0 -0
  86. {auth-3.5.2 → auth-3.6.0}/tests/test_client.py +0 -0
  87. {auth-3.5.2 → auth-3.6.0}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
  88. {auth-3.5.2 → auth-3.6.0}/tests/test_client_rest.py +0 -0
  89. {auth-3.5.2 → auth-3.6.0}/tests/test_cmd_server.py +0 -0
  90. {auth-3.5.2 → auth-3.6.0}/tests/test_config.py +0 -0
  91. {auth-3.5.2 → auth-3.6.0}/tests/test_correctness_hardening.py +0 -0
  92. {auth-3.5.2 → auth-3.6.0}/tests/test_database_pool_settings.py +0 -0
  93. {auth-3.5.2 → auth-3.6.0}/tests/test_database_sslmode.py +0 -0
  94. {auth-3.5.2 → auth-3.6.0}/tests/test_degraded_response_is_a_contract.py +0 -0
  95. {auth-3.5.2 → auth-3.6.0}/tests/test_deploy_lock.py +0 -0
  96. {auth-3.5.2 → auth-3.6.0}/tests/test_docs_page.py +0 -0
  97. {auth-3.5.2 → auth-3.6.0}/tests/test_encryption.py +0 -0
  98. {auth-3.5.2 → auth-3.6.0}/tests/test_encryption_integration.py +0 -0
  99. {auth-3.5.2 → auth-3.6.0}/tests/test_flask.py +0 -0
  100. {auth-3.5.2 → auth-3.6.0}/tests/test_gunicorn_config_invariants.py +0 -0
  101. {auth-3.5.2 → auth-3.6.0}/tests/test_import_footprint.py +0 -0
  102. {auth-3.5.2 → auth-3.6.0}/tests/test_key_rotation.py +0 -0
  103. {auth-3.5.2 → auth-3.6.0}/tests/test_log_redaction.py +0 -0
  104. {auth-3.5.2 → auth-3.6.0}/tests/test_no_bundled_libpq.py +0 -0
  105. {auth-3.5.2 → auth-3.6.0}/tests/test_phase_a_hardening.py +0 -0
  106. {auth-3.5.2 → auth-3.6.0}/tests/test_provision_script_no_dsn_leak.py +0 -0
  107. {auth-3.5.2 → auth-3.6.0}/tests/test_reencryption.py +0 -0
  108. {auth-3.5.2 → auth-3.6.0}/tests/test_routes_errors.py +0 -0
  109. {auth-3.5.2 → auth-3.6.0}/tests/test_schema_check.py +0 -0
  110. {auth-3.5.2 → auth-3.6.0}/tests/test_self_service_audit.py +0 -0
  111. {auth-3.5.2 → auth-3.6.0}/tests/test_server.py +0 -0
  112. {auth-3.5.2 → auth-3.6.0}/tests/test_service_lifecycle.py +0 -0
  113. {auth-3.5.2 → auth-3.6.0}/tests/test_settings_do_not_echo_secrets.py +0 -0
  114. {auth-3.5.2 → auth-3.6.0}/tests/test_strict_default.py +0 -0
  115. {auth-3.5.2 → auth-3.6.0}/tests/test_strict_users.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auth
3
- Version: 3.5.2
3
+ Version: 3.6.0
4
4
  Summary: Authorization for humans
5
5
  Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
6
6
  License-Expression: MIT
@@ -82,7 +82,7 @@ before you add members or permissions to it.
82
82
 
83
83
  ```bash
84
84
  KEY=$(python3 -c "import uuid; print(uuid.uuid4())")
85
- BASE=https://auth.rodmena.app
85
+ BASE=https://auth.rodmena.com
86
86
 
87
87
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/role/engineers
88
88
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/permission/engineers/deploy
@@ -117,7 +117,7 @@ With the Python client (`pip install auth`):
117
117
  ```python
118
118
  from auth import Client
119
119
 
120
- with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
120
+ with Client(api_key=KEY, service_url="https://auth.rodmena.com") as c:
121
121
  c.create_role("engineers")
122
122
  c.add_permission("engineers", "deploy")
123
123
  c.create_api_key("alice") # strict default since 3.0.0
@@ -163,7 +163,7 @@ with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
163
163
 
164
164
  | Doc | What's in it |
165
165
  |---|---|
166
- | **Live API reference** — [`/docs`](https://auth.rodmena.app/docs) · [`/llms.txt`](https://auth.rodmena.app/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
166
+ | **Live API reference** — [`/docs`](https://auth.rodmena.com/docs) · [`/llms.txt`](https://auth.rodmena.com/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
167
167
  | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Design, components, request lifecycle, data model, permission-check and key-rotation flows, diagrams. |
168
168
  | [SECURITY.md](SECURITY.md) | Security model (tenant isolation, encryption, audit, rotation), threat notes, reporting. |
169
169
  | [MIGRATIONS.md](MIGRATIONS.md) | Schema creation vs migrations, upgrade/rollback runbook. |
@@ -20,7 +20,7 @@ before you add members or permissions to it.
20
20
 
21
21
  ```bash
22
22
  KEY=$(python3 -c "import uuid; print(uuid.uuid4())")
23
- BASE=https://auth.rodmena.app
23
+ BASE=https://auth.rodmena.com
24
24
 
25
25
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/role/engineers
26
26
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/permission/engineers/deploy
@@ -55,7 +55,7 @@ With the Python client (`pip install auth`):
55
55
  ```python
56
56
  from auth import Client
57
57
 
58
- with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
58
+ with Client(api_key=KEY, service_url="https://auth.rodmena.com") as c:
59
59
  c.create_role("engineers")
60
60
  c.add_permission("engineers", "deploy")
61
61
  c.create_api_key("alice") # strict default since 3.0.0
@@ -101,7 +101,7 @@ with Client(api_key=KEY, service_url="https://auth.rodmena.app") as c:
101
101
 
102
102
  | Doc | What's in it |
103
103
  |---|---|
104
- | **Live API reference** — [`/docs`](https://auth.rodmena.app/docs) · [`/llms.txt`](https://auth.rodmena.app/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
104
+ | **Live API reference** — [`/docs`](https://auth.rodmena.com/docs) · [`/llms.txt`](https://auth.rodmena.com/llms.txt) | Every endpoint and exact response shape, served by the app (agent-friendly). |
105
105
  | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Design, components, request lifecycle, data model, permission-check and key-rotation flows, diagrams. |
106
106
  | [SECURITY.md](SECURITY.md) | Security model (tenant isolation, encryption, audit, rotation), threat notes, reporting. |
107
107
  | [MIGRATIONS.md](MIGRATIONS.md) | Schema creation vs migrations, upgrade/rollback runbook. |
@@ -164,6 +164,18 @@ def verify_encryption_key(db) -> str:
164
164
  return _set(OK, "encryption key verified against the deployment canary")
165
165
 
166
166
 
167
+ RLS_SCHEMA = "auth_rbac"
168
+
169
+
170
+ def _schema_hint(schema: str) -> str:
171
+ if schema == RLS_SCHEMA:
172
+ return ""
173
+ return (
174
+ f" (AUTH_DATABASE_SCHEMA is {schema!r}; auth's migrations and row level"
175
+ f" security are defined in schema {RLS_SCHEMA!r})"
176
+ )
177
+
178
+
167
179
  def verify_row_level_security(db) -> str:
168
180
  """Confirm RLS is actually in force, not merely enabled.
169
181
 
@@ -198,7 +210,10 @@ def verify_row_level_security(db) -> str:
198
210
  return _set(UNVERIFIED, f"could not read RLS state: {exc.__class__.__name__}")
199
211
 
200
212
  if not rows:
201
- return _set(UNVERIFIED, "no tenant tables found to check RLS on")
213
+ return _set(
214
+ UNVERIFIED,
215
+ "no tenant tables found to check RLS on" + _schema_hint(schema),
216
+ )
202
217
 
203
218
  # A table that is absent is not a table that is safe. The junction tables
204
219
  # are created by the ORM rather than by a migration, so on a fresh database
@@ -210,7 +225,8 @@ def verify_row_level_security(db) -> str:
210
225
  return _set(
211
226
  MISMATCH,
212
227
  "expected tenant tables are absent, so nothing protects them: "
213
- + ", ".join(missing),
228
+ + ", ".join(missing)
229
+ + _schema_hint(schema),
214
230
  )
215
231
 
216
232
  unprotected = [
@@ -221,7 +237,8 @@ def verify_row_level_security(db) -> str:
221
237
  MISMATCH,
222
238
  "row level security is not in force on: "
223
239
  + ", ".join(sorted(unprotected))
224
- + " - tenant isolation would rest on query convention alone",
240
+ + " - tenant isolation would rest on query convention alone"
241
+ + _schema_hint(schema),
225
242
  )
226
243
  return _set(OK, f"row level security forced on {len(rows)} tables")
227
244
 
@@ -0,0 +1,61 @@
1
+ import importlib.util
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import List, Mapping, Optional
7
+
8
+ COMMANDS = ("apply", "status", "verify", "head", "list")
9
+ URL_VARIABLES = ("MG_DATABASE_URL", "AUTH_DATABASE_URL", "AUTH_POSTGRESQL_URL")
10
+ DRIVER_PREFIXES = ("postgresql+psycopg://", "postgres+psycopg://")
11
+ USAGE = (
12
+ "usage: auth-migrate {apply,status,verify,head,list} [migretti options]\n"
13
+ "Runs the migrations shipped with this auth release against the database "
14
+ "named by the first of MG_DATABASE_URL, AUTH_DATABASE_URL or "
15
+ "AUTH_POSTGRESQL_URL that is set."
16
+ )
17
+
18
+
19
+ def migrations_root() -> Path:
20
+ return Path(__file__).resolve().parent
21
+
22
+
23
+ def database_url(environ: Mapping[str, str]) -> Optional[str]:
24
+ for name in URL_VARIABLES:
25
+ value = environ.get(name, "").strip()
26
+ if not value:
27
+ continue
28
+ for prefix in DRIVER_PREFIXES:
29
+ if value.startswith(prefix):
30
+ return "postgresql://" + value[len(prefix) :]
31
+ return value
32
+ return None
33
+
34
+
35
+ def _refuse(message: str) -> int:
36
+ print(f"auth-migrate: {message}", file=sys.stderr)
37
+ return 2
38
+
39
+
40
+ def main(argv: Optional[List[str]] = None) -> int:
41
+ args = list(sys.argv[1:] if argv is None else argv)
42
+ if not args or args[0] not in COMMANDS:
43
+ print(USAGE, file=sys.stderr)
44
+ return 2
45
+ if importlib.util.find_spec("migretti") is None:
46
+ return _refuse('migretti is not installed; install "auth[migrations]"')
47
+ url = database_url(os.environ)
48
+ if url is None:
49
+ return _refuse("set MG_DATABASE_URL, AUTH_DATABASE_URL or AUTH_POSTGRESQL_URL")
50
+ if not url.startswith(("postgresql://", "postgres://")):
51
+ return _refuse("the shipped migrations target PostgreSQL only")
52
+ environment = dict(os.environ, MG_DATABASE_URL=url)
53
+ return subprocess.call(
54
+ [sys.executable, "-m", "migretti", *args],
55
+ cwd=migrations_root(),
56
+ env=environment,
57
+ )
58
+
59
+
60
+ if __name__ == "__main__":
61
+ sys.exit(main())
@@ -0,0 +1,41 @@
1
+ -- migration: add_auth_api_key
2
+ -- id: 01KYTMDEYFVH43HKR0MQWW1EMP
3
+ --
4
+ -- Per-user API-key registry (SPEC 0004, issuedb #9). Mirrors the SQLAlchemy
5
+ -- model auth.models.sql.AuthApiKey exactly — the app's boot-time
6
+ -- create_all(checkfirst=True) may legally create this table first on a fresh
7
+ -- install, so every statement is IF NOT EXISTS and the two DDL paths converge
8
+ -- in either order. Schema is the production/CI deployment schema (auth_rbac,
9
+ -- AUTH_DATABASE_SCHEMA); schemaless SQLite/dev installs are covered by
10
+ -- create_all and never run migretti.
11
+
12
+ -- migrate: up
13
+ CREATE SCHEMA IF NOT EXISTS auth_rbac;
14
+
15
+ CREATE TABLE IF NOT EXISTS auth_rbac.auth_api_key (
16
+ id SERIAL PRIMARY KEY,
17
+ key_id VARCHAR(36) NOT NULL,
18
+ creator VARCHAR(64) NOT NULL,
19
+ "user" TEXT NOT NULL,
20
+ key_hash VARCHAR(64) NOT NULL,
21
+ key_prefix VARCHAR(16) NOT NULL,
22
+ label TEXT,
23
+ is_active BOOLEAN DEFAULT TRUE,
24
+ date_created TIMESTAMP DEFAULT now(),
25
+ modified TIMESTAMP DEFAULT now(),
26
+ revoked_at TIMESTAMP,
27
+ expires_at TIMESTAMP,
28
+ last_used_at TIMESTAMP,
29
+ CONSTRAINT uq_auth_api_key_key_hash UNIQUE (key_hash),
30
+ CONSTRAINT uq_auth_api_key_key_id UNIQUE (key_id)
31
+ );
32
+
33
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_api_key_id
34
+ ON auth_rbac.auth_api_key (id);
35
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_api_key_creator
36
+ ON auth_rbac.auth_api_key (creator);
37
+ CREATE INDEX IF NOT EXISTS ix_auth_api_key_creator_user
38
+ ON auth_rbac.auth_api_key (creator, "user");
39
+
40
+ -- migrate: down
41
+ DROP TABLE IF EXISTS auth_rbac.auth_api_key;
@@ -0,0 +1,21 @@
1
+ -- migration: drop_alembic_version
2
+ -- id: 01KYTQN79R1ZBNDPA3ND9AAA73
3
+ --
4
+ -- Alembic is fully purged (issuedb #14, SPEC 0009): migretti owns all
5
+ -- tracking, so the legacy alembic_version table goes. Its single recorded
6
+ -- revision was 0001_widen_text (varchar->TEXT widening, applied 2026-07);
7
+ -- the revision source now lives in git history only. The down section
8
+ -- faithfully restores the table and its one row. On databases that never ran
9
+ -- Alembic (fresh installs, CI) the up is a no-op.
10
+
11
+ -- migrate: up
12
+ DROP TABLE IF EXISTS auth_rbac.alembic_version;
13
+
14
+ -- migrate: down
15
+ CREATE TABLE IF NOT EXISTS auth_rbac.alembic_version (
16
+ version_num VARCHAR(32) NOT NULL,
17
+ CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num)
18
+ );
19
+ INSERT INTO auth_rbac.alembic_version (version_num)
20
+ VALUES ('0001_widen_text')
21
+ ON CONFLICT DO NOTHING;
@@ -0,0 +1,26 @@
1
+ -- migration: add_auth_tenant_settings
2
+ -- id: 01KYTRKMWNBDDZPN1H0AXRTT5G
3
+ --
4
+ -- Per-tenant settings (SPEC 0010, issuedb #15) — one row per creator, absence
5
+ -- means defaults. strict_users gates SPEC 0008 strict user identity (opt-in
6
+ -- in 2.5.0; default flip is 3.0.0, gated on client confirmations). Mirrors
7
+ -- auth.models.sql.AuthTenantSettings; IF NOT EXISTS so create_all(checkfirst)
8
+ -- and mg apply converge in either order.
9
+
10
+ -- migrate: up
11
+ CREATE SCHEMA IF NOT EXISTS auth_rbac;
12
+
13
+ CREATE TABLE IF NOT EXISTS auth_rbac.auth_tenant_settings (
14
+ id SERIAL PRIMARY KEY,
15
+ creator VARCHAR(64) NOT NULL,
16
+ strict_users BOOLEAN NOT NULL DEFAULT FALSE,
17
+ date_created TIMESTAMP DEFAULT now(),
18
+ modified TIMESTAMP DEFAULT now(),
19
+ CONSTRAINT uq_auth_tenant_settings_creator UNIQUE (creator)
20
+ );
21
+
22
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_tenant_settings_id
23
+ ON auth_rbac.auth_tenant_settings (id);
24
+
25
+ -- migrate: down
26
+ DROP TABLE IF EXISTS auth_rbac.auth_tenant_settings;
@@ -0,0 +1,85 @@
1
+ -- migration: grandfather_strict_users
2
+ -- id: 01KYTX0MKVZ775P62CJ87631Z1
3
+ --
4
+ -- 3.0.0 flip protection (SPEC 0012, issuedb #18): every creator existing on
5
+ -- this database gets an explicit strict_users=false row, so the 3.0.0
6
+ -- no-row-means-strict default reaches ONLY tenants created afterwards. A
7
+ -- marker row ('__meta:grandfathered-3.0__', reserved) records that the pass
8
+ -- ran; the identical marker-guarded pass in auth.database.create_tables()
9
+ -- composes idempotently with this migration in either order.
10
+ --
11
+ -- The three base RBAC tables are created here IF NOT EXISTS (exact
12
+ -- create_all parity, like add_auth_api_key did for its table): on a fresh
13
+ -- database migrations must be self-sufficient — production already has
14
+ -- them, so these are no-ops there.
15
+ --
16
+ -- down removes the marker only: the grandfather rows are deliberate,
17
+ -- auditable tenant state and are kept on rollback.
18
+
19
+ -- migrate: up
20
+ CREATE SCHEMA IF NOT EXISTS auth_rbac;
21
+
22
+ CREATE TABLE IF NOT EXISTS auth_rbac.auth_group (
23
+ id SERIAL PRIMARY KEY,
24
+ creator VARCHAR(64) NOT NULL,
25
+ role TEXT NOT NULL,
26
+ description TEXT,
27
+ is_active BOOLEAN DEFAULT TRUE,
28
+ date_created TIMESTAMP DEFAULT now(),
29
+ modified TIMESTAMP DEFAULT now(),
30
+ CONSTRAINT uq_auth_group_creator_role UNIQUE (creator, role)
31
+ );
32
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_id ON auth_rbac.auth_group (id);
33
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_creator ON auth_rbac.auth_group (creator);
34
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_group_role ON auth_rbac.auth_group (role);
35
+
36
+ CREATE TABLE IF NOT EXISTS auth_rbac.auth_membership (
37
+ id SERIAL PRIMARY KEY,
38
+ "user" TEXT NOT NULL,
39
+ creator VARCHAR(64) NOT NULL,
40
+ is_active BOOLEAN DEFAULT TRUE,
41
+ date_created TIMESTAMP DEFAULT now(),
42
+ modified TIMESTAMP DEFAULT now(),
43
+ CONSTRAINT uq_auth_membership_creator_user UNIQUE (creator, "user")
44
+ );
45
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_id ON auth_rbac.auth_membership (id);
46
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_creator ON auth_rbac.auth_membership (creator);
47
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_membership_user ON auth_rbac.auth_membership ("user");
48
+
49
+ CREATE TABLE IF NOT EXISTS auth_rbac.auth_permission (
50
+ id SERIAL PRIMARY KEY,
51
+ name TEXT NOT NULL,
52
+ creator VARCHAR(64) NOT NULL,
53
+ is_active BOOLEAN DEFAULT TRUE,
54
+ date_created TIMESTAMP DEFAULT now(),
55
+ modified TIMESTAMP DEFAULT now(),
56
+ CONSTRAINT uq_auth_permission_creator_name UNIQUE (creator, name)
57
+ );
58
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_id ON auth_rbac.auth_permission (id);
59
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_creator ON auth_rbac.auth_permission (creator);
60
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_auth_permission_name ON auth_rbac.auth_permission (name);
61
+
62
+ INSERT INTO auth_rbac.auth_tenant_settings (creator, strict_users)
63
+ SELECT c.creator, FALSE
64
+ FROM (
65
+ SELECT creator FROM auth_rbac.auth_group
66
+ UNION SELECT creator FROM auth_rbac.auth_membership
67
+ UNION SELECT creator FROM auth_rbac.auth_permission
68
+ UNION SELECT creator FROM auth_rbac.auth_api_key
69
+ ) c
70
+ WHERE NOT EXISTS (
71
+ SELECT 1 FROM auth_rbac.auth_tenant_settings
72
+ WHERE creator = '__meta:grandfathered-3.0__'
73
+ )
74
+ AND c.creator NOT IN (SELECT creator FROM auth_rbac.auth_tenant_settings);
75
+
76
+ INSERT INTO auth_rbac.auth_tenant_settings (creator, strict_users)
77
+ SELECT '__meta:grandfathered-3.0__', FALSE
78
+ WHERE NOT EXISTS (
79
+ SELECT 1 FROM auth_rbac.auth_tenant_settings
80
+ WHERE creator = '__meta:grandfathered-3.0__'
81
+ );
82
+
83
+ -- migrate: down
84
+ DELETE FROM auth_rbac.auth_tenant_settings
85
+ WHERE creator = '__meta:grandfathered-3.0__';
@@ -0,0 +1,279 @@
1
+ -- migration: partition_audit_log
2
+ -- id: 01KZJWHG32K9X1AFBPPB4YJC6A
3
+ --
4
+ -- audit_log was the whole growth problem: 175k rows / 52 MB, ~79% of the entire
5
+ -- database, growing ~4.8k rows/day on average and ~10.7k/day in the most recent
6
+ -- month, with no retention or partitioning of any kind. Pruning it by DELETE
7
+ -- would bloat the heap and demand a VACUUM FULL (an exclusive lock on the audit
8
+ -- trail); pruning it by DROP PARTITION is O(1) and takes no lock on live data.
9
+ --
10
+ -- This converts auth_rbac.audit_log to a RANGE partitioned table on "timestamp",
11
+ -- one partition per month, preserving every row, the sequence position and the
12
+ -- query indexes.
13
+ --
14
+ -- Shape follows the DATABASE, not auth/audit.py: the model declares
15
+ -- user = Column(String(64)) but production carries TEXT (the pre-2.x varchar→TEXT
16
+ -- reconciliation noted in the 3.0.1 release). Matching the live column keeps
17
+ -- create_all(checkfirst=True) and mg apply convergent, which MIGRATIONS.md requires.
18
+ --
19
+ -- PRIMARY KEY becomes (id, "timestamp") because PostgreSQL requires the partition
20
+ -- key to be part of every unique constraint. id remains unique in practice — it is
21
+ -- still fed by the single audit_log_id_seq sequence.
22
+ --
23
+ -- RETENTION IS NOT AUTOMATED HERE ON PURPOSE. Dropping audit history is a
24
+ -- compliance decision, not a housekeeping default. This migration ships the
25
+ -- mechanism (drop_audit_log_partitions_before) and leaves the policy to an
26
+ -- operator who has decided how long auth history must be kept.
27
+
28
+ -- migrate: up
29
+
30
+ CREATE SCHEMA IF NOT EXISTS auth_rbac;
31
+
32
+ -- ---------------------------------------------------------------- provisioning
33
+ -- Create one monthly partition if it does not already exist. Idempotent, so it
34
+ -- is safe from cron, from a migration, or by hand.
35
+ CREATE OR REPLACE FUNCTION auth_rbac.provision_audit_log_partition(p_month date)
36
+ RETURNS text
37
+ LANGUAGE plpgsql
38
+ AS $$
39
+ DECLARE
40
+ v_start date := date_trunc('month', p_month)::date;
41
+ v_end date := (date_trunc('month', p_month) + interval '1 month')::date;
42
+ v_name text := format('audit_log_%s', to_char(v_start, 'YYYY_MM'));
43
+ BEGIN
44
+ IF EXISTS (
45
+ SELECT 1 FROM pg_class c
46
+ JOIN pg_namespace n ON n.oid = c.relnamespace
47
+ WHERE n.nspname = 'auth_rbac' AND c.relname = v_name
48
+ ) THEN
49
+ RETURN format('auth_rbac.%s already exists', v_name);
50
+ END IF;
51
+
52
+ EXECUTE format(
53
+ 'CREATE TABLE auth_rbac.%I PARTITION OF auth_rbac.audit_log '
54
+ 'FOR VALUES FROM (%L) TO (%L)', v_name, v_start, v_end);
55
+ RETURN format('created auth_rbac.%s [%s, %s)', v_name, v_start, v_end);
56
+ END;
57
+ $$;
58
+
59
+ COMMENT ON FUNCTION auth_rbac.provision_audit_log_partition(date) IS
60
+ 'Create the monthly audit_log partition covering p_month, if absent. Idempotent.';
61
+
62
+ -- ------------------------------------------------------------------- retention
63
+ -- Drop whole partitions strictly older than the cutoff. Returns what it dropped
64
+ -- so the caller can log it. Never touches the DEFAULT partition.
65
+ CREATE OR REPLACE FUNCTION auth_rbac.drop_audit_log_partitions_before(p_cutoff date)
66
+ RETURNS SETOF text
67
+ LANGUAGE plpgsql
68
+ AS $$
69
+ DECLARE
70
+ r record;
71
+ v_upper timestamp;
72
+ BEGIN
73
+ FOR r IN
74
+ SELECT c.relname,
75
+ pg_get_expr(c.relpartbound, c.oid) AS bound
76
+ FROM pg_class c
77
+ JOIN pg_inherits i ON i.inhrelid = c.oid
78
+ JOIN pg_class p ON p.oid = i.inhparent
79
+ JOIN pg_namespace n ON n.oid = p.relnamespace
80
+ WHERE n.nspname = 'auth_rbac'
81
+ AND p.relname = 'audit_log'
82
+ AND pg_get_expr(c.relpartbound, c.oid) NOT LIKE '%DEFAULT%'
83
+ LOOP
84
+ -- The bound reads: FOR VALUES FROM ('2026-07-01 00:00:00') TO ('2026-08-01 00:00:00')
85
+ -- Capture the WHOLE quoted upper bound. An earlier version matched only
86
+ -- [0-9-]+ and so stopped at the space before the time, yielding NULL —
87
+ -- the IF was then NULL, nothing was dropped, and the function still
88
+ -- reported success. A retention job that silently retains everything is
89
+ -- worse than none, so a parse failure now raises instead of skipping.
90
+ v_upper := substring(r.bound from 'TO \(''([^'']+)''\)')::timestamp;
91
+ IF v_upper IS NULL THEN
92
+ RAISE EXCEPTION 'cannot parse partition bound for auth_rbac.%: %', r.relname, r.bound;
93
+ END IF;
94
+
95
+ IF v_upper <= p_cutoff::timestamp THEN
96
+ EXECUTE format('DROP TABLE auth_rbac.%I', r.relname);
97
+ RETURN NEXT format('dropped auth_rbac.%s %s', r.relname, r.bound);
98
+ END IF;
99
+ END LOOP;
100
+ END;
101
+ $$;
102
+
103
+ COMMENT ON FUNCTION auth_rbac.drop_audit_log_partitions_before(date) IS
104
+ 'Drop audit_log partitions entirely older than p_cutoff. Invoke deliberately: '
105
+ 'audit retention is a compliance decision, not a scheduled default.';
106
+
107
+ -- --------------------------------------------------------------- the conversion
108
+ DO $$
109
+ DECLARE
110
+ v_is_partitioned boolean;
111
+ v_month date;
112
+ v_max date;
113
+ v_owner text;
114
+ r record;
115
+ BEGIN
116
+ SELECT c.relkind = 'p', pg_get_userbyid(c.relowner)
117
+ INTO v_is_partitioned, v_owner
118
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
119
+ WHERE n.nspname = 'auth_rbac' AND c.relname = 'audit_log';
120
+
121
+ IF v_is_partitioned IS NULL THEN
122
+ RAISE NOTICE 'auth_rbac.audit_log absent; nothing to convert';
123
+ RETURN;
124
+ END IF;
125
+ IF v_is_partitioned THEN
126
+ RAISE NOTICE 'auth_rbac.audit_log already partitioned; nothing to do';
127
+ RETURN;
128
+ END IF;
129
+
130
+ -- 1. the new partitioned parent, shaped exactly like the live table
131
+ CREATE TABLE auth_rbac.audit_log__partitioned (
132
+ id integer NOT NULL DEFAULT nextval('auth_rbac.audit_log_id_seq'),
133
+ "timestamp" timestamp without time zone NOT NULL,
134
+ client_id text NOT NULL,
135
+ "user" text,
136
+ action character varying(50) NOT NULL,
137
+ resource text,
138
+ details text,
139
+ ip_address character varying(45),
140
+ user_agent text,
141
+ success integer,
142
+ PRIMARY KEY (id, "timestamp")
143
+ ) PARTITION BY RANGE ("timestamp");
144
+
145
+ -- 2. a DEFAULT partition: a trap, not a home. Rows landing here mean the
146
+ -- provisioner fell behind; monitor it rather than rely on it.
147
+ CREATE TABLE auth_rbac.audit_log_default
148
+ PARTITION OF auth_rbac.audit_log__partitioned DEFAULT;
149
+
150
+ -- 3. monthly partitions covering all existing data plus 12 months ahead
151
+ SELECT COALESCE(date_trunc('month', min("timestamp"))::date, date_trunc('month', now())::date)
152
+ INTO v_month FROM auth_rbac.audit_log;
153
+ v_max := (date_trunc('month', now()) + interval '12 months')::date;
154
+ WHILE v_month <= v_max LOOP
155
+ EXECUTE format(
156
+ 'CREATE TABLE auth_rbac.%I PARTITION OF auth_rbac.audit_log__partitioned '
157
+ 'FOR VALUES FROM (%L) TO (%L)',
158
+ 'audit_log_' || to_char(v_month, 'YYYY_MM'),
159
+ v_month,
160
+ (v_month + interval '1 month')::date);
161
+ v_month := (v_month + interval '1 month')::date;
162
+ END LOOP;
163
+
164
+ -- 4. move the data
165
+ INSERT INTO auth_rbac.audit_log__partitioned
166
+ (id, "timestamp", client_id, "user", action, resource, details, ip_address, user_agent, success)
167
+ SELECT id, "timestamp", client_id, "user", action, resource, details, ip_address, user_agent, success
168
+ FROM auth_rbac.audit_log;
169
+
170
+ -- 5. detach the sequence before dropping its old owner, or the DROP cascades
171
+ -- to the sequence and the id counter restarts at 1.
172
+ ALTER SEQUENCE auth_rbac.audit_log_id_seq OWNED BY NONE;
173
+
174
+ DROP TABLE auth_rbac.audit_log;
175
+ ALTER TABLE auth_rbac.audit_log__partitioned RENAME TO audit_log;
176
+
177
+ -- 6. restore the ORIGINAL owner. The migration runner is a DDL-capable role
178
+ -- (pgadmin in production) which is not necessarily the table owner, and
179
+ -- PostgreSQL refuses "ALTER SEQUENCE ... OWNED BY" when the sequence and
180
+ -- its table have different owners. ALTER TABLE ... OWNER TO does not
181
+ -- cascade to partitions, so each one is set explicitly.
182
+ EXECUTE format('ALTER TABLE auth_rbac.audit_log OWNER TO %I', v_owner);
183
+ FOR r IN
184
+ SELECT c.relname
185
+ FROM pg_inherits i
186
+ JOIN pg_class c ON c.oid = i.inhrelid
187
+ WHERE i.inhparent = 'auth_rbac.audit_log'::regclass
188
+ LOOP
189
+ EXECUTE format('ALTER TABLE auth_rbac.%I OWNER TO %I', r.relname, v_owner);
190
+ END LOOP;
191
+
192
+ ALTER SEQUENCE auth_rbac.audit_log_id_seq OWNED BY auth_rbac.audit_log.id;
193
+ END;
194
+ $$;
195
+
196
+ -- 6. indexes, recreated on the parent so every partition inherits them.
197
+ -- ix_..._id mirrors the model's index=True on the primary key column.
198
+ -- IF NOT EXISTS guards the index NAME, not the table, so these must sit behind
199
+ -- the same absent-table guard the conversion block uses: to_regclass returns
200
+ -- NULL instead of raising. On a fresh database auth_rbac.audit_log has not
201
+ -- been created yet (SQLAlchemy create_all does that at app boot), and an
202
+ -- unguarded CREATE INDEX errors there rather than no-opping.
203
+ DO $guard$
204
+ BEGIN
205
+ IF to_regclass('auth_rbac.audit_log') IS NULL THEN
206
+ RAISE NOTICE 'auth_rbac.audit_log absent; skipping index creation';
207
+ RETURN;
208
+ END IF;
209
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_id
210
+ ON auth_rbac.audit_log (id);
211
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_client_id
212
+ ON auth_rbac.audit_log (client_id);
213
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_user
214
+ ON auth_rbac.audit_log ("user");
215
+ -- new: retention and time-range queries scan by timestamp; the old table had
216
+ -- no index on it at all.
217
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_timestamp
218
+ ON auth_rbac.audit_log ("timestamp");
219
+ END;
220
+ $guard$;
221
+
222
+ -- migrate: down
223
+ -- Collapse back to a single unpartitioned table, preserving rows and the sequence.
224
+ DO $$
225
+ DECLARE
226
+ v_is_partitioned boolean;
227
+ v_owner text;
228
+ BEGIN
229
+ SELECT c.relkind = 'p', pg_get_userbyid(c.relowner)
230
+ INTO v_is_partitioned, v_owner
231
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
232
+ WHERE n.nspname = 'auth_rbac' AND c.relname = 'audit_log';
233
+
234
+ IF v_is_partitioned IS NOT TRUE THEN
235
+ RAISE NOTICE 'auth_rbac.audit_log is not partitioned; nothing to revert';
236
+ RETURN;
237
+ END IF;
238
+
239
+ CREATE TABLE auth_rbac.audit_log__plain (
240
+ id integer NOT NULL DEFAULT nextval('auth_rbac.audit_log_id_seq'),
241
+ "timestamp" timestamp without time zone NOT NULL,
242
+ client_id text NOT NULL,
243
+ "user" text,
244
+ action character varying(50) NOT NULL,
245
+ resource text,
246
+ details text,
247
+ ip_address character varying(45),
248
+ user_agent text,
249
+ success integer,
250
+ PRIMARY KEY (id)
251
+ );
252
+
253
+ INSERT INTO auth_rbac.audit_log__plain
254
+ (id, "timestamp", client_id, "user", action, resource, details, ip_address, user_agent, success)
255
+ SELECT id, "timestamp", client_id, "user", action, resource, details, ip_address, user_agent, success
256
+ FROM auth_rbac.audit_log;
257
+
258
+ ALTER SEQUENCE auth_rbac.audit_log_id_seq OWNED BY NONE;
259
+ DROP TABLE auth_rbac.audit_log;
260
+ ALTER TABLE auth_rbac.audit_log__plain RENAME TO audit_log;
261
+ EXECUTE format('ALTER TABLE auth_rbac.audit_log OWNER TO %I', v_owner);
262
+ ALTER SEQUENCE auth_rbac.audit_log_id_seq OWNED BY auth_rbac.audit_log.id;
263
+ END;
264
+ $$;
265
+
266
+ DO $guard$
267
+ BEGIN
268
+ IF to_regclass('auth_rbac.audit_log') IS NULL THEN
269
+ RAISE NOTICE 'auth_rbac.audit_log absent; skipping index creation';
270
+ RETURN;
271
+ END IF;
272
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_id ON auth_rbac.audit_log (id);
273
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_client_id ON auth_rbac.audit_log (client_id);
274
+ CREATE INDEX IF NOT EXISTS ix_auth_rbac_audit_log_user ON auth_rbac.audit_log ("user");
275
+ END;
276
+ $guard$;
277
+
278
+ DROP FUNCTION IF EXISTS auth_rbac.drop_audit_log_partitions_before(date);
279
+ DROP FUNCTION IF EXISTS auth_rbac.provision_audit_log_partition(date);