auth 3.7.2__tar.gz → 3.8.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 (125) hide show
  1. {auth-3.7.2 → auth-3.8.0}/PKG-INFO +1 -1
  2. auth-3.8.0/auth/admin.py +254 -0
  3. {auth-3.7.2 → auth-3.8.0}/auth/audit.py +2 -0
  4. {auth-3.7.2 → auth-3.8.0}/auth/routes/__init__.py +2 -0
  5. auth-3.8.0/auth/routes/namespace.py +37 -0
  6. auth-3.8.0/auth/services/purge.py +94 -0
  7. {auth-3.7.2 → auth-3.8.0}/auth/services/service.py +5 -2
  8. {auth-3.7.2 → auth-3.8.0}/auth/static_docs/api_reference.md +35 -0
  9. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/PKG-INFO +1 -1
  10. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/SOURCES.txt +5 -0
  11. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/entry_points.txt +1 -0
  12. {auth-3.7.2 → auth-3.8.0}/pyproject.toml +2 -1
  13. auth-3.8.0/tests/test_admin_cli.py +167 -0
  14. auth-3.8.0/tests/test_namespace_purge.py +179 -0
  15. {auth-3.7.2 → auth-3.8.0}/LICENSE +0 -0
  16. {auth-3.7.2 → auth-3.8.0}/README.md +0 -0
  17. {auth-3.7.2 → auth-3.8.0}/auth/__init__.py +0 -0
  18. {auth-3.7.2 → auth-3.8.0}/auth/api_keys.py +0 -0
  19. {auth-3.7.2 → auth-3.8.0}/auth/circuit_breaker.py +0 -0
  20. {auth-3.7.2 → auth-3.8.0}/auth/client/__init__.py +0 -0
  21. {auth-3.7.2 → auth-3.8.0}/auth/client/_transport.py +0 -0
  22. {auth-3.7.2 → auth-3.8.0}/auth/client/base.py +0 -0
  23. {auth-3.7.2 → auth-3.8.0}/auth/client/keys.py +0 -0
  24. {auth-3.7.2 → auth-3.8.0}/auth/client/rbac.py +0 -0
  25. {auth-3.7.2 → auth-3.8.0}/auth/client/workflow.py +0 -0
  26. {auth-3.7.2 → auth-3.8.0}/auth/cmd/__init__.py +0 -0
  27. {auth-3.7.2 → auth-3.8.0}/auth/cmd/server.py +0 -0
  28. {auth-3.7.2 → auth-3.8.0}/auth/config.py +0 -0
  29. {auth-3.7.2 → auth-3.8.0}/auth/core/REST/__init__.py +0 -0
  30. {auth-3.7.2 → auth-3.8.0}/auth/core/REST/client.py +0 -0
  31. {auth-3.7.2 → auth-3.8.0}/auth/core/__init__.py +0 -0
  32. {auth-3.7.2 → auth-3.8.0}/auth/core/models/__init__.py +0 -0
  33. {auth-3.7.2 → auth-3.8.0}/auth/database.py +0 -0
  34. {auth-3.7.2 → auth-3.8.0}/auth/decorators.py +0 -0
  35. {auth-3.7.2 → auth-3.8.0}/auth/docs_page.py +0 -0
  36. {auth-3.7.2 → auth-3.8.0}/auth/encryption.py +0 -0
  37. {auth-3.7.2 → auth-3.8.0}/auth/key_expiry.py +0 -0
  38. {auth-3.7.2 → auth-3.8.0}/auth/keycheck.py +0 -0
  39. {auth-3.7.2 → auth-3.8.0}/auth/logging_config.py +0 -0
  40. {auth-3.7.2 → auth-3.8.0}/auth/main.py +0 -0
  41. {auth-3.7.2 → auth-3.8.0}/auth/migrate.py +0 -0
  42. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +0 -0
  43. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +0 -0
  44. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +0 -0
  45. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +0 -0
  46. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +0 -0
  47. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +0 -0
  48. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +0 -0
  49. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +0 -0
  50. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +0 -0
  51. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +0 -0
  52. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +0 -0
  53. {auth-3.7.2 → auth-3.8.0}/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +0 -0
  54. {auth-3.7.2 → auth-3.8.0}/auth/migrations/__init__.py +0 -0
  55. {auth-3.7.2 → auth-3.8.0}/auth/models/sql.py +0 -0
  56. {auth-3.7.2 → auth-3.8.0}/auth/response_format.py +0 -0
  57. {auth-3.7.2 → auth-3.8.0}/auth/rls.py +0 -0
  58. {auth-3.7.2 → auth-3.8.0}/auth/routes/_common.py +0 -0
  59. {auth-3.7.2 → auth-3.8.0}/auth/routes/apikeys.py +0 -0
  60. {auth-3.7.2 → auth-3.8.0}/auth/routes/membership.py +0 -0
  61. {auth-3.7.2 → auth-3.8.0}/auth/routes/permissions.py +0 -0
  62. {auth-3.7.2 → auth-3.8.0}/auth/routes/public.py +0 -0
  63. {auth-3.7.2 → auth-3.8.0}/auth/routes/roles.py +0 -0
  64. {auth-3.7.2 → auth-3.8.0}/auth/routes/tenant.py +0 -0
  65. {auth-3.7.2 → auth-3.8.0}/auth/routes/workflow.py +0 -0
  66. {auth-3.7.2 → auth-3.8.0}/auth/sanitizer.py +0 -0
  67. {auth-3.7.2 → auth-3.8.0}/auth/schema_check.py +0 -0
  68. {auth-3.7.2 → auth-3.8.0}/auth/schema_reconcile.py +0 -0
  69. {auth-3.7.2 → auth-3.8.0}/auth/server.py +0 -0
  70. {auth-3.7.2 → auth-3.8.0}/auth/services/base.py +0 -0
  71. {auth-3.7.2 → auth-3.8.0}/auth/services/keys.py +0 -0
  72. {auth-3.7.2 → auth-3.8.0}/auth/services/queries.py +0 -0
  73. {auth-3.7.2 → auth-3.8.0}/auth/services/rbac.py +0 -0
  74. {auth-3.7.2 → auth-3.8.0}/auth/services/recovery.py +0 -0
  75. {auth-3.7.2 → auth-3.8.0}/auth/services/rotation.py +0 -0
  76. {auth-3.7.2 → auth-3.8.0}/auth/services/tenant.py +0 -0
  77. {auth-3.7.2 → auth-3.8.0}/auth/static_docs/__init__.py +0 -0
  78. {auth-3.7.2 → auth-3.8.0}/auth/static_docs/claude_guide.md +0 -0
  79. {auth-3.7.2 → auth-3.8.0}/auth/static_docs/landing.md +0 -0
  80. {auth-3.7.2 → auth-3.8.0}/auth/static_docs/page.html +0 -0
  81. {auth-3.7.2 → auth-3.8.0}/auth/validation.py +0 -0
  82. {auth-3.7.2 → auth-3.8.0}/auth/workflow_checker.py +0 -0
  83. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/dependency_links.txt +0 -0
  84. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/requires.txt +0 -0
  85. {auth-3.7.2 → auth-3.8.0}/auth.egg-info/top_level.txt +0 -0
  86. {auth-3.7.2 → auth-3.8.0}/setup.cfg +0 -0
  87. {auth-3.7.2 → auth-3.8.0}/tests/test_api_keys.py +0 -0
  88. {auth-3.7.2 → auth-3.8.0}/tests/test_api_keys_encryption.py +0 -0
  89. {auth-3.7.2 → auth-3.8.0}/tests/test_apikey_audit_outcome.py +0 -0
  90. {auth-3.7.2 → auth-3.8.0}/tests/test_apikey_cap_expiry.py +0 -0
  91. {auth-3.7.2 → auth-3.8.0}/tests/test_apikey_expiry.py +0 -0
  92. {auth-3.7.2 → auth-3.8.0}/tests/test_audit_integrity.py +0 -0
  93. {auth-3.7.2 → auth-3.8.0}/tests/test_client.py +0 -0
  94. {auth-3.7.2 → auth-3.8.0}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
  95. {auth-3.7.2 → auth-3.8.0}/tests/test_client_rest.py +0 -0
  96. {auth-3.7.2 → auth-3.8.0}/tests/test_cmd_server.py +0 -0
  97. {auth-3.7.2 → auth-3.8.0}/tests/test_config.py +0 -0
  98. {auth-3.7.2 → auth-3.8.0}/tests/test_correctness_hardening.py +0 -0
  99. {auth-3.7.2 → auth-3.8.0}/tests/test_database_pool_settings.py +0 -0
  100. {auth-3.7.2 → auth-3.8.0}/tests/test_database_sslmode.py +0 -0
  101. {auth-3.7.2 → auth-3.8.0}/tests/test_degraded_response_is_a_contract.py +0 -0
  102. {auth-3.7.2 → auth-3.8.0}/tests/test_deploy_lock.py +0 -0
  103. {auth-3.7.2 → auth-3.8.0}/tests/test_docs_page.py +0 -0
  104. {auth-3.7.2 → auth-3.8.0}/tests/test_encryption.py +0 -0
  105. {auth-3.7.2 → auth-3.8.0}/tests/test_encryption_integration.py +0 -0
  106. {auth-3.7.2 → auth-3.8.0}/tests/test_flask.py +0 -0
  107. {auth-3.7.2 → auth-3.8.0}/tests/test_gunicorn_config_invariants.py +0 -0
  108. {auth-3.7.2 → auth-3.8.0}/tests/test_import_footprint.py +0 -0
  109. {auth-3.7.2 → auth-3.8.0}/tests/test_key_rotation.py +0 -0
  110. {auth-3.7.2 → auth-3.8.0}/tests/test_log_redaction.py +0 -0
  111. {auth-3.7.2 → auth-3.8.0}/tests/test_migrate_cli.py +0 -0
  112. {auth-3.7.2 → auth-3.8.0}/tests/test_no_bundled_libpq.py +0 -0
  113. {auth-3.7.2 → auth-3.8.0}/tests/test_phase_a_hardening.py +0 -0
  114. {auth-3.7.2 → auth-3.8.0}/tests/test_provision_script_no_dsn_leak.py +0 -0
  115. {auth-3.7.2 → auth-3.8.0}/tests/test_reencryption.py +0 -0
  116. {auth-3.7.2 → auth-3.8.0}/tests/test_rotate_key_preserves_strict.py +0 -0
  117. {auth-3.7.2 → auth-3.8.0}/tests/test_routes_errors.py +0 -0
  118. {auth-3.7.2 → auth-3.8.0}/tests/test_schema_check.py +0 -0
  119. {auth-3.7.2 → auth-3.8.0}/tests/test_self_service_audit.py +0 -0
  120. {auth-3.7.2 → auth-3.8.0}/tests/test_served_docs_host.py +0 -0
  121. {auth-3.7.2 → auth-3.8.0}/tests/test_server.py +0 -0
  122. {auth-3.7.2 → auth-3.8.0}/tests/test_service_lifecycle.py +0 -0
  123. {auth-3.7.2 → auth-3.8.0}/tests/test_settings_do_not_echo_secrets.py +0 -0
  124. {auth-3.7.2 → auth-3.8.0}/tests/test_strict_default.py +0 -0
  125. {auth-3.7.2 → auth-3.8.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.7.2
3
+ Version: 3.8.0
4
4
  Summary: Authorization for humans
5
5
  Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
6
6
  License-Expression: MIT
@@ -0,0 +1,254 @@
1
+ import argparse
2
+ import os
3
+ import sys
4
+ from datetime import datetime
5
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, cast
6
+
7
+ from sqlalchemy import Table, create_engine, func, select
8
+ from sqlalchemy.engine import Engine
9
+ from sqlalchemy.orm import Session
10
+
11
+ from auth.audit import AuditAction, AuditLog, client_fingerprint, record_audit
12
+ from auth.models.sql import (
13
+ AuthApiKey,
14
+ AuthGroup,
15
+ AuthMembership,
16
+ AuthPermission,
17
+ AuthTenantSettings,
18
+ )
19
+ from auth.rls import tenant_fingerprint
20
+
21
+ ADMIN_URL_VARIABLE = "AUTH_ADMIN_DATABASE_URL"
22
+ DRIVER_PREFIXES = ("postgresql+psycopg://", "postgres+psycopg://")
23
+ MIN_PREFIX = 12
24
+ LIST_PREFIX = 16
25
+ ROLE_NAMES_WIDTH = 60
26
+ AUDIT_CHUNK = 500
27
+
28
+ _KINDS = (
29
+ ("roles", cast(Table, AuthGroup.__table__)),
30
+ ("permissions", cast(Table, AuthPermission.__table__)),
31
+ ("memberships", cast(Table, AuthMembership.__table__)),
32
+ ("api_keys", cast(Table, AuthApiKey.__table__)),
33
+ ("settings", cast(Table, AuthTenantSettings.__table__)),
34
+ )
35
+
36
+
37
+ class AdminError(Exception):
38
+ pass
39
+
40
+
41
+ def admin_url(environ: Mapping[str, str]) -> Optional[str]:
42
+ value = environ.get(ADMIN_URL_VARIABLE, "").strip()
43
+ if not value:
44
+ return None
45
+ for prefix in DRIVER_PREFIXES:
46
+ if value.startswith(prefix):
47
+ return "postgresql+psycopg://" + value[len(prefix) :]
48
+ if value.startswith(("postgresql://", "postgres://")):
49
+ return "postgresql+psycopg://" + value.split("://", 1)[1]
50
+ raise AdminError(f"{ADMIN_URL_VARIABLE} must name a PostgreSQL database")
51
+
52
+
53
+ def _namespaces(conn) -> Dict[str, Dict[str, Any]]:
54
+ found: Dict[str, Dict[str, Any]] = {}
55
+ for kind, table in _KINDS:
56
+ rows = conn.execute(
57
+ select(
58
+ table.c.creator,
59
+ func.count(),
60
+ func.min(table.c.date_created),
61
+ func.max(table.c.date_created),
62
+ ).group_by(table.c.creator)
63
+ )
64
+ for creator, count, first, last in rows:
65
+ entry = found.setdefault(
66
+ creator,
67
+ {kind_name: 0 for kind_name, _ in _KINDS}
68
+ | {"first": first, "last": last, "role_names": []},
69
+ )
70
+ entry[kind] = int(count)
71
+ if first is not None and (entry["first"] is None or first < entry["first"]):
72
+ entry["first"] = first
73
+ if last is not None and (entry["last"] is None or last > entry["last"]):
74
+ entry["last"] = last
75
+ groups = cast(Table, AuthGroup.__table__)
76
+ for creator, role in conn.execute(
77
+ select(groups.c.creator, groups.c.role)
78
+ .where(groups.c.is_active.is_(True))
79
+ .order_by(groups.c.role)
80
+ ):
81
+ if creator in found:
82
+ found[creator]["role_names"].append(role)
83
+ return found
84
+
85
+
86
+ def _last_audit(conn, creators: Sequence[str]) -> Dict[str, Optional[datetime]]:
87
+ audit = cast(Table, AuditLog.__table__)
88
+ by_ref = {client_fingerprint(c): c for c in creators}
89
+ refs = list(by_ref)
90
+ last: Dict[str, Optional[datetime]] = dict.fromkeys(creators)
91
+ for start in range(0, len(refs), AUDIT_CHUNK):
92
+ chunk = refs[start : start + AUDIT_CHUNK]
93
+ for ref, when in conn.execute(
94
+ select(audit.c.client_id, func.max(audit.c.timestamp))
95
+ .where(audit.c.client_id.in_(chunk))
96
+ .group_by(audit.c.client_id)
97
+ ):
98
+ last[by_ref[ref]] = when
99
+ return last
100
+
101
+
102
+ def list_namespaces(
103
+ admin_engine: Engine,
104
+ created_from: Optional[datetime] = None,
105
+ created_to: Optional[datetime] = None,
106
+ role: Optional[str] = None,
107
+ ) -> List[Dict[str, Any]]:
108
+ with admin_engine.connect() as conn:
109
+ found = _namespaces(conn)
110
+ last_audit = _last_audit(conn, list(found))
111
+ result = []
112
+ for creator, entry in found.items():
113
+ if created_from and (entry["first"] is None or entry["first"] < created_from):
114
+ continue
115
+ if created_to and (entry["first"] is None or entry["first"] > created_to):
116
+ continue
117
+ if role and role not in entry["role_names"]:
118
+ continue
119
+ result.append(
120
+ {
121
+ "fingerprint": tenant_fingerprint(creator)[:LIST_PREFIX],
122
+ **{kind: entry[kind] for kind, _ in _KINDS},
123
+ "first_created": entry["first"],
124
+ "last_created": entry["last"],
125
+ "last_audit": last_audit[creator],
126
+ "role_names": entry["role_names"],
127
+ }
128
+ )
129
+ result.sort(key=lambda r: (r["first_created"] or datetime.min, r["fingerprint"]))
130
+ return result
131
+
132
+
133
+ def resolve_namespace(admin_engine: Engine, prefix: str) -> str:
134
+ prefix = prefix.lower()
135
+ if len(prefix) < MIN_PREFIX or any(c not in "0123456789abcdef" for c in prefix):
136
+ raise AdminError(f"--fp needs at least {MIN_PREFIX} hex characters")
137
+ with admin_engine.connect() as conn:
138
+ creators: Set[str] = set()
139
+ for _, table in _KINDS:
140
+ creators.update(c for (c,) in conn.execute(select(table.c.creator).distinct()))
141
+ matches = [c for c in creators if tenant_fingerprint(c).startswith(prefix)]
142
+ if not matches:
143
+ raise AdminError("no namespace has that fingerprint")
144
+ if len(matches) > 1:
145
+ raise AdminError(f"{len(matches)} namespaces share that prefix; give more characters")
146
+ return str(matches[0])
147
+
148
+
149
+ def purge_resolved(session: Session, creator: str) -> Dict[str, Any]:
150
+ from auth.services.service import AuthorizationService
151
+
152
+ service = AuthorizationService(
153
+ session, creator, validate_client=False, manage_transaction=False
154
+ )
155
+ deleted = service.purge_namespace()
156
+ record_audit(
157
+ session,
158
+ client_id=client_fingerprint(creator),
159
+ user=None,
160
+ action=AuditAction.PURGE_NAMESPACE,
161
+ resource="namespace",
162
+ details={**{k: v for k, v in deleted.items() if k != "fingerprint"}, "via": "auth-admin"},
163
+ user_agent="auth-admin",
164
+ success=True,
165
+ )
166
+ session.commit()
167
+ return deleted
168
+
169
+
170
+ def _when(value: Optional[datetime]) -> str:
171
+ return value.strftime("%Y-%m-%dT%H:%M:%SZ") if value else "-"
172
+
173
+
174
+ def _print_list(rows: List[Dict[str, Any]]) -> None:
175
+ print(
176
+ f"{'fingerprint':16} roles perms members keys settings "
177
+ f"{'first_created':20} {'last_created':20} {'last_audit':20} role_names"
178
+ )
179
+ for r in rows:
180
+ names = ",".join(r["role_names"])
181
+ if len(names) > ROLE_NAMES_WIDTH:
182
+ names = names[: ROLE_NAMES_WIDTH - 3] + "..."
183
+ print(
184
+ f"{r['fingerprint']:16} {r['roles']:5} {r['permissions']:5} {r['memberships']:7} "
185
+ f"{r['api_keys']:4} {'yes' if r['settings'] else 'no':8} {_when(r['first_created']):20} "
186
+ f"{_when(r['last_created']):20} {_when(r['last_audit']):20} {names}"
187
+ )
188
+ print(f"{len(rows)} namespace(s)")
189
+
190
+
191
+ def _parse_time(value: str) -> datetime:
192
+ from auth.key_expiry import parse_expiry
193
+
194
+ return parse_expiry(value)
195
+
196
+
197
+ def _parser() -> argparse.ArgumentParser:
198
+ parser = argparse.ArgumentParser(prog="auth-admin")
199
+ groups = parser.add_subparsers(dest="group", required=True)
200
+ namespaces = groups.add_parser("namespaces").add_subparsers(dest="command", required=True)
201
+ listing = namespaces.add_parser("list")
202
+ listing.add_argument("--created-from", type=_parse_time)
203
+ listing.add_argument("--created-to", type=_parse_time)
204
+ listing.add_argument("--role")
205
+ purge = namespaces.add_parser("purge")
206
+ purge.add_argument("--fp", required=True)
207
+ purge.add_argument("--confirm", required=True)
208
+ return parser
209
+
210
+
211
+ def run(argv: Sequence[str], admin_engine: Engine, session_factory) -> int:
212
+ args = _parser().parse_args(list(argv))
213
+ try:
214
+ if args.command == "list":
215
+ _print_list(
216
+ list_namespaces(admin_engine, args.created_from, args.created_to, args.role)
217
+ )
218
+ return 0
219
+ if args.confirm.lower() != args.fp.lower():
220
+ raise AdminError("--confirm must repeat --fp exactly; nothing was purged")
221
+ creator = resolve_namespace(admin_engine, args.fp)
222
+ session = session_factory()
223
+ try:
224
+ deleted = purge_resolved(session, creator)
225
+ finally:
226
+ session.close()
227
+ except AdminError as error:
228
+ print(f"auth-admin: {error}", file=sys.stderr)
229
+ return 2
230
+ counts = " ".join(f"{k}={v}" for k, v in deleted.items() if k != "fingerprint")
231
+ print(f"purged {tenant_fingerprint(creator)[:LIST_PREFIX]}: {counts}")
232
+ return 0
233
+
234
+
235
+ def main(argv: Optional[Sequence[str]] = None) -> int:
236
+ try:
237
+ url = admin_url(os.environ)
238
+ except AdminError as error:
239
+ print(f"auth-admin: {error}", file=sys.stderr)
240
+ return 2
241
+ if url is None:
242
+ print(f"auth-admin: set {ADMIN_URL_VARIABLE}", file=sys.stderr)
243
+ return 2
244
+ from auth.database import SessionLocal
245
+
246
+ admin_engine = create_engine(url, pool_pre_ping=True)
247
+ try:
248
+ return run(sys.argv[1:] if argv is None else argv, admin_engine, SessionLocal)
249
+ finally:
250
+ admin_engine.dispose()
251
+
252
+
253
+ if __name__ == "__main__":
254
+ sys.exit(main())
@@ -49,6 +49,8 @@ class AuditAction(Enum):
49
49
  GET_AUDIT = "GET_AUDIT"
50
50
  GET_ROTATE_KEY = "GET_ROTATE_KEY"
51
51
  RECOVER_KEY = "RECOVER_KEY"
52
+ GET_NAMESPACE = "GET_NAMESPACE"
53
+ PURGE_NAMESPACE = "PURGE_NAMESPACE"
52
54
 
53
55
 
54
56
  class AuditLog(Base):
@@ -9,6 +9,7 @@ resolves exactly as it did before the split.
9
9
  from auth.routes import (
10
10
  apikeys,
11
11
  membership,
12
+ namespace,
12
13
  permissions,
13
14
  public,
14
15
  roles,
@@ -33,6 +34,7 @@ _ROUTE_MODULES = (
33
34
  workflow,
34
35
  apikeys,
35
36
  tenant,
37
+ namespace,
36
38
  )
37
39
 
38
40
 
@@ -0,0 +1,37 @@
1
+ from flask import request
2
+
3
+ from auth.audit import AuditAction
4
+ from auth.decorators import audit_log, record_outcome
5
+ from auth.response_format import APIResponse
6
+ from auth.routes._common import _get_auth_service, with_db_session
7
+
8
+
9
+ def register(app):
10
+ @app.route("/api/namespace", methods=["GET"])
11
+ @with_db_session
12
+ @audit_log(AuditAction.GET_NAMESPACE, resource_extractor=lambda kwargs: "namespace")
13
+ def get_namespace(db):
14
+ summary = _get_auth_service(db).namespace_summary()
15
+ return APIResponse.success(data=summary, message="Namespace summary")
16
+
17
+ @app.route("/api/namespace", methods=["DELETE"])
18
+ @with_db_session
19
+ @audit_log(AuditAction.PURGE_NAMESPACE, resource_extractor=lambda kwargs: "namespace")
20
+ def purge_namespace(db):
21
+ body = request.get_json(silent=True)
22
+ if not isinstance(body, dict) or set(body) != {"confirm"}:
23
+ record_outcome(refused=True, reason="confirm_required")
24
+ return APIResponse.bad_request(
25
+ 'Send {"confirm": "<fingerprint>"}. GET /api/namespace shows the fingerprint.'
26
+ )
27
+ auth_service = _get_auth_service(db)
28
+ fingerprint = auth_service.namespace_summary()["fingerprint"]
29
+ if body["confirm"] != fingerprint:
30
+ record_outcome(refused=True, reason="confirm_mismatch")
31
+ return APIResponse.bad_request(
32
+ "confirm does not match this namespace's fingerprint. "
33
+ "GET /api/namespace shows it. Nothing was deleted."
34
+ )
35
+ deleted = auth_service.purge_namespace()
36
+ record_outcome(**{k: v for k, v in deleted.items() if k != "fingerprint"})
37
+ return APIResponse.success(data=deleted, message="Namespace purged")
@@ -0,0 +1,94 @@
1
+ from typing import Any, Dict, cast
2
+
3
+ from sqlalchemy import Table, delete, func, or_, select
4
+ from sqlalchemy.engine import CursorResult
5
+
6
+ from auth.models.sql import (
7
+ AuthApiKey,
8
+ AuthGroup,
9
+ AuthMembership,
10
+ AuthPermission,
11
+ AuthTenantSettings,
12
+ membership_groups,
13
+ permission_groups,
14
+ )
15
+ from auth.rls import tenant_fingerprint
16
+ from auth.services.rotation import RotationMixin
17
+
18
+ FINGERPRINT_LENGTH = 12
19
+
20
+ _groups = cast(Table, AuthGroup.__table__)
21
+ _memberships = cast(Table, AuthMembership.__table__)
22
+ _permissions = cast(Table, AuthPermission.__table__)
23
+ _api_keys = cast(Table, AuthApiKey.__table__)
24
+ _settings = cast(Table, AuthTenantSettings.__table__)
25
+
26
+
27
+ def namespace_fingerprint(client_key: str) -> str:
28
+ return tenant_fingerprint(client_key.lower())[:FINGERPRINT_LENGTH]
29
+
30
+
31
+ class PurgeMixin(RotationMixin):
32
+ def _delete(self, statement) -> int:
33
+ return int(cast(CursorResult, self.db.execute(statement)).rowcount or 0)
34
+
35
+ def _count(self, table: Table) -> int:
36
+ return int(
37
+ self.db.execute(
38
+ select(func.count()).select_from(table).where(table.c.creator == self.client)
39
+ ).scalar()
40
+ or 0
41
+ )
42
+
43
+ def namespace_summary(self) -> Dict[str, Any]:
44
+ settings_row = self.db.execute(
45
+ select(_settings.c.rotate_key_hash).where(_settings.c.creator == self.client)
46
+ ).first()
47
+ return {
48
+ "fingerprint": namespace_fingerprint(self.client),
49
+ "roles": self._count(_groups),
50
+ "permissions": self._count(_permissions),
51
+ "memberships": self._count(_memberships),
52
+ "api_keys": self._count(_api_keys),
53
+ "settings": settings_row is not None,
54
+ "recovery_key": bool(settings_row and settings_row[0]),
55
+ }
56
+
57
+ def purge_namespace(self) -> Dict[str, Any]:
58
+ self._lock_tenant()
59
+ group_ids = select(_groups.c.id).where(_groups.c.creator == self.client)
60
+ member_ids = select(_memberships.c.id).where(_memberships.c.creator == self.client)
61
+ permission_ids = select(_permissions.c.id).where(_permissions.c.creator == self.client)
62
+ summary = self.namespace_summary()
63
+ role_links = self._delete(
64
+ delete(membership_groups).where(
65
+ or_(
66
+ membership_groups.c.membership_id.in_(member_ids),
67
+ membership_groups.c.group_id.in_(group_ids),
68
+ )
69
+ )
70
+ )
71
+ permission_links = self._delete(
72
+ delete(permission_groups).where(
73
+ or_(
74
+ permission_groups.c.permission_id.in_(permission_ids),
75
+ permission_groups.c.group_id.in_(group_ids),
76
+ )
77
+ )
78
+ )
79
+ deleted: Dict[str, Any] = {"fingerprint": summary["fingerprint"]}
80
+ for name, table in (
81
+ ("memberships", _memberships),
82
+ ("permissions", _permissions),
83
+ ("roles", _groups),
84
+ ("api_keys", _api_keys),
85
+ ):
86
+ deleted[name] = self._delete(delete(table).where(table.c.creator == self.client))
87
+ deleted["settings"] = bool(
88
+ self._delete(delete(_settings).where(_settings.c.creator == self.client))
89
+ )
90
+ deleted["recovery_key"] = summary["recovery_key"]
91
+ deleted["role_links"] = role_links + permission_links
92
+ self._strict_cache = None
93
+ self._commit()
94
+ return deleted
@@ -4,7 +4,8 @@ SQLAlchemy-based authorization service
4
4
  The implementation is split across a linear chain of mixins — see
5
5
  :mod:`auth.services.base`, :mod:`auth.services.tenant`,
6
6
  :mod:`auth.services.queries`, :mod:`auth.services.rbac`,
7
- :mod:`auth.services.keys` and :mod:`auth.services.rotation`. This module stays
7
+ :mod:`auth.services.keys`, :mod:`auth.services.rotation` and
8
+ :mod:`auth.services.purge`. This module stays
8
9
  the public import path: ``from auth.services.service import
9
10
  AuthorizationService`` resolves exactly as it did before the split.
10
11
  """
@@ -38,13 +39,14 @@ from auth.services.keys import (
38
39
  API_KEYS_PER_USER_CAP,
39
40
  ApiKeyMixin,
40
41
  )
42
+ from auth.services.purge import PurgeMixin
41
43
  from auth.services.queries import QueryMixin
42
44
  from auth.services.rbac import RbacMixin
43
45
  from auth.services.rotation import RotationMixin
44
46
  from auth.services.tenant import TenantMixin
45
47
 
46
48
 
47
- class AuthorizationService(RotationMixin):
49
+ class AuthorizationService(PurgeMixin):
48
50
  """Authorization service using SQLAlchemy"""
49
51
 
50
52
 
@@ -58,6 +60,7 @@ __all__ = [
58
60
  "AuthPermission",
59
61
  "AuthTenantSettings",
60
62
  "AuthorizationService",
63
+ "PurgeMixin",
61
64
  "QueryMixin",
62
65
  "RbacMixin",
63
66
  "RotationMixin",
@@ -295,6 +295,26 @@ off is the audited opt-out for platforms that authenticate their own users.
295
295
  | GET | `/api/settings` | wrapped, `data` = `{{"strict_users": false}}` (defaults when never set) |
296
296
  | PUT | `/api/settings` | body `{{"strict_users": true}}` → wrapped, `data` = `{{"strict_users": true}}` (idempotent, audited) |
297
297
 
298
+ ### Deleting a namespace
299
+
300
+ `DELETE /api/namespace` erases everything in your namespace in one
301
+ transaction: roles, permissions, memberships, per-user API keys, settings and
302
+ the recovery key. Use it when a customer leaves, or at the end of a test run.
303
+ It cannot be undone. Your audit trail stays, including an entry for the purge
304
+ with the counts it deleted. Former per-user keys then validate as
305
+ `unknown_key`, the old recovery key no longer recovers, and the same client key
306
+ opens an empty namespace with the server's default settings.
307
+
308
+ To confirm, send the namespace fingerprint, the first 12 hex characters of the
309
+ SHA-256 of your client key. `GET /api/namespace` returns it with the counts a
310
+ purge would delete, or compute it yourself:
311
+ `python -c "import hashlib,sys; print(hashlib.sha256(sys.argv[1].lower().encode()).hexdigest()[:12])" "$KEY"`.
312
+
313
+ | Method | Path | Returns |
314
+ |---|---|---|
315
+ | GET | `/api/namespace` | wrapped, `data` = `{{"fingerprint": "3f6b1c9e6f1a", "roles": 4, "permissions": 9, "memberships": 12, "api_keys": 3, "settings": true, "recovery_key": true}}` |
316
+ | DELETE | `/api/namespace` | body `{{"confirm": "<fingerprint>"}}` → wrapped, `data` = `{{"fingerprint": "...", "memberships": 12, "permissions": 9, "roles": 4, "api_keys": 3, "settings": true, "recovery_key": true, "role_links": 21}}`. 400 and nothing deleted when the body is missing, has other fields, or names another fingerprint |
317
+
298
318
  ### Audit (self-service diagnosis)
299
319
 
300
320
  Read-only access to YOUR namespace's own audit trail — who granted/revoked what,
@@ -437,3 +457,18 @@ it. Wait for `GET /readyz` to answer 200. If it answers 503 naming
437
457
  `AUTH_DATABASE_SCHEMA`, set it to `auth_rbac`; if it names tables without row
438
458
  level security, the migrations were not applied. One worker uses about
439
459
  120–150 MB.
460
+
461
+ Operators of an instance can list and purge namespaces whose key nobody holds
462
+ any more with `auth-admin`. It reads across namespaces through
463
+ `AUTH_ADMIN_DATABASE_URL`, which must be a PostgreSQL role allowed to bypass
464
+ row level security, and it performs the purge through the normal application
465
+ connection (`AUTH_DATABASE_URL`), bound to that one namespace:
466
+
467
+ auth-admin namespaces list [--created-from ISO] [--created-to ISO] [--role NAME]
468
+ auth-admin namespaces purge --fp <12+ hex of the fingerprint> --confirm <the same>
469
+
470
+ `list` prints the fingerprint, row counts, active role names, creation times
471
+ and the time of the namespace's last audit entry. It never prints a client
472
+ key, a user name or a decrypted value. `purge` refuses a prefix that matches no
473
+ namespace or more than one, and records a `PURGE_NAMESPACE` audit entry with
474
+ `"via": "auth-admin"`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auth
3
- Version: 3.7.2
3
+ Version: 3.8.0
4
4
  Summary: Authorization for humans
5
5
  Author-email: Farshid Ashouri <farsheed.ashouri@gmail.com>
6
6
  License-Expression: MIT
@@ -2,6 +2,7 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  auth/__init__.py
5
+ auth/admin.py
5
6
  auth/api_keys.py
6
7
  auth/audit.py
7
8
  auth/circuit_breaker.py
@@ -59,6 +60,7 @@ auth/routes/__init__.py
59
60
  auth/routes/_common.py
60
61
  auth/routes/apikeys.py
61
62
  auth/routes/membership.py
63
+ auth/routes/namespace.py
62
64
  auth/routes/permissions.py
63
65
  auth/routes/public.py
64
66
  auth/routes/roles.py
@@ -66,6 +68,7 @@ auth/routes/tenant.py
66
68
  auth/routes/workflow.py
67
69
  auth/services/base.py
68
70
  auth/services/keys.py
71
+ auth/services/purge.py
69
72
  auth/services/queries.py
70
73
  auth/services/rbac.py
71
74
  auth/services/recovery.py
@@ -77,6 +80,7 @@ auth/static_docs/api_reference.md
77
80
  auth/static_docs/claude_guide.md
78
81
  auth/static_docs/landing.md
79
82
  auth/static_docs/page.html
83
+ tests/test_admin_cli.py
80
84
  tests/test_api_keys.py
81
85
  tests/test_api_keys_encryption.py
82
86
  tests/test_apikey_audit_outcome.py
@@ -102,6 +106,7 @@ tests/test_import_footprint.py
102
106
  tests/test_key_rotation.py
103
107
  tests/test_log_redaction.py
104
108
  tests/test_migrate_cli.py
109
+ tests/test_namespace_purge.py
105
110
  tests/test_no_bundled_libpq.py
106
111
  tests/test_phase_a_hardening.py
107
112
  tests/test_provision_script_no_dsn_leak.py
@@ -1,3 +1,4 @@
1
1
  [console_scripts]
2
+ auth-admin = auth.admin:main
2
3
  auth-migrate = auth.migrate:main
3
4
  auth-server = auth.server:main
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "auth"
7
- version = "3.7.2"
7
+ version = "3.8.0"
8
8
  description = "Authorization for humans"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -90,6 +90,7 @@ dev = [
90
90
  [project.scripts]
91
91
  auth-server = "auth.server:main"
92
92
  auth-migrate = "auth.migrate:main"
93
+ auth-admin = "auth.admin:main"
93
94
 
94
95
  [tool.uv]
95
96
  constraint-dependencies = [