auth 3.7.2__tar.gz → 3.9.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 (128) hide show
  1. {auth-3.7.2 → auth-3.9.0}/PKG-INFO +1 -1
  2. auth-3.9.0/auth/admin.py +254 -0
  3. {auth-3.7.2 → auth-3.9.0}/auth/audit.py +3 -1
  4. {auth-3.7.2 → auth-3.9.0}/auth/config.py +1 -0
  5. auth-3.9.0/auth/http_hardening.py +54 -0
  6. {auth-3.7.2 → auth-3.9.0}/auth/main.py +7 -5
  7. {auth-3.7.2 → auth-3.9.0}/auth/routes/__init__.py +2 -0
  8. auth-3.9.0/auth/routes/namespace.py +37 -0
  9. {auth-3.7.2 → auth-3.9.0}/auth/routes/public.py +62 -20
  10. {auth-3.7.2 → auth-3.9.0}/auth/routes/tenant.py +60 -1
  11. {auth-3.7.2 → auth-3.9.0}/auth/sanitizer.py +4 -0
  12. auth-3.9.0/auth/services/purge.py +94 -0
  13. {auth-3.7.2 → auth-3.9.0}/auth/services/queries.py +9 -1
  14. {auth-3.7.2 → auth-3.9.0}/auth/services/service.py +5 -2
  15. {auth-3.7.2 → auth-3.9.0}/auth/services/tenant.py +16 -12
  16. {auth-3.7.2 → auth-3.9.0}/auth/static_docs/api_reference.md +71 -18
  17. {auth-3.7.2 → auth-3.9.0}/auth/static_docs/claude_guide.md +3 -1
  18. {auth-3.7.2 → auth-3.9.0}/auth/static_docs/landing.md +1 -0
  19. {auth-3.7.2 → auth-3.9.0}/auth/validation.py +26 -0
  20. {auth-3.7.2 → auth-3.9.0}/auth/workflow_checker.py +5 -1
  21. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/PKG-INFO +1 -1
  22. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/SOURCES.txt +8 -0
  23. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/entry_points.txt +1 -0
  24. {auth-3.7.2 → auth-3.9.0}/pyproject.toml +2 -1
  25. auth-3.9.0/tests/test_admin_cli.py +167 -0
  26. {auth-3.7.2 → auth-3.9.0}/tests/test_degraded_response_is_a_contract.py +3 -8
  27. auth-3.9.0/tests/test_namespace_purge.py +179 -0
  28. auth-3.9.0/tests/test_pentest_v1_inputs.py +224 -0
  29. auth-3.9.0/tests/test_pentest_v1_readyz_listings.py +180 -0
  30. {auth-3.7.2 → auth-3.9.0}/LICENSE +0 -0
  31. {auth-3.7.2 → auth-3.9.0}/README.md +0 -0
  32. {auth-3.7.2 → auth-3.9.0}/auth/__init__.py +0 -0
  33. {auth-3.7.2 → auth-3.9.0}/auth/api_keys.py +0 -0
  34. {auth-3.7.2 → auth-3.9.0}/auth/circuit_breaker.py +0 -0
  35. {auth-3.7.2 → auth-3.9.0}/auth/client/__init__.py +0 -0
  36. {auth-3.7.2 → auth-3.9.0}/auth/client/_transport.py +0 -0
  37. {auth-3.7.2 → auth-3.9.0}/auth/client/base.py +0 -0
  38. {auth-3.7.2 → auth-3.9.0}/auth/client/keys.py +0 -0
  39. {auth-3.7.2 → auth-3.9.0}/auth/client/rbac.py +0 -0
  40. {auth-3.7.2 → auth-3.9.0}/auth/client/workflow.py +0 -0
  41. {auth-3.7.2 → auth-3.9.0}/auth/cmd/__init__.py +0 -0
  42. {auth-3.7.2 → auth-3.9.0}/auth/cmd/server.py +0 -0
  43. {auth-3.7.2 → auth-3.9.0}/auth/core/REST/__init__.py +0 -0
  44. {auth-3.7.2 → auth-3.9.0}/auth/core/REST/client.py +0 -0
  45. {auth-3.7.2 → auth-3.9.0}/auth/core/__init__.py +0 -0
  46. {auth-3.7.2 → auth-3.9.0}/auth/core/models/__init__.py +0 -0
  47. {auth-3.7.2 → auth-3.9.0}/auth/database.py +0 -0
  48. {auth-3.7.2 → auth-3.9.0}/auth/decorators.py +0 -0
  49. {auth-3.7.2 → auth-3.9.0}/auth/docs_page.py +0 -0
  50. {auth-3.7.2 → auth-3.9.0}/auth/encryption.py +0 -0
  51. {auth-3.7.2 → auth-3.9.0}/auth/key_expiry.py +0 -0
  52. {auth-3.7.2 → auth-3.9.0}/auth/keycheck.py +0 -0
  53. {auth-3.7.2 → auth-3.9.0}/auth/logging_config.py +0 -0
  54. {auth-3.7.2 → auth-3.9.0}/auth/migrate.py +0 -0
  55. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +0 -0
  56. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +0 -0
  57. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +0 -0
  58. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +0 -0
  59. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +0 -0
  60. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +0 -0
  61. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +0 -0
  62. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +0 -0
  63. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +0 -0
  64. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +0 -0
  65. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +0 -0
  66. {auth-3.7.2 → auth-3.9.0}/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +0 -0
  67. {auth-3.7.2 → auth-3.9.0}/auth/migrations/__init__.py +0 -0
  68. {auth-3.7.2 → auth-3.9.0}/auth/models/sql.py +0 -0
  69. {auth-3.7.2 → auth-3.9.0}/auth/response_format.py +0 -0
  70. {auth-3.7.2 → auth-3.9.0}/auth/rls.py +0 -0
  71. {auth-3.7.2 → auth-3.9.0}/auth/routes/_common.py +0 -0
  72. {auth-3.7.2 → auth-3.9.0}/auth/routes/apikeys.py +0 -0
  73. {auth-3.7.2 → auth-3.9.0}/auth/routes/membership.py +0 -0
  74. {auth-3.7.2 → auth-3.9.0}/auth/routes/permissions.py +0 -0
  75. {auth-3.7.2 → auth-3.9.0}/auth/routes/roles.py +0 -0
  76. {auth-3.7.2 → auth-3.9.0}/auth/routes/workflow.py +0 -0
  77. {auth-3.7.2 → auth-3.9.0}/auth/schema_check.py +0 -0
  78. {auth-3.7.2 → auth-3.9.0}/auth/schema_reconcile.py +0 -0
  79. {auth-3.7.2 → auth-3.9.0}/auth/server.py +0 -0
  80. {auth-3.7.2 → auth-3.9.0}/auth/services/base.py +0 -0
  81. {auth-3.7.2 → auth-3.9.0}/auth/services/keys.py +0 -0
  82. {auth-3.7.2 → auth-3.9.0}/auth/services/rbac.py +0 -0
  83. {auth-3.7.2 → auth-3.9.0}/auth/services/recovery.py +0 -0
  84. {auth-3.7.2 → auth-3.9.0}/auth/services/rotation.py +0 -0
  85. {auth-3.7.2 → auth-3.9.0}/auth/static_docs/__init__.py +0 -0
  86. {auth-3.7.2 → auth-3.9.0}/auth/static_docs/page.html +0 -0
  87. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/dependency_links.txt +0 -0
  88. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/requires.txt +0 -0
  89. {auth-3.7.2 → auth-3.9.0}/auth.egg-info/top_level.txt +0 -0
  90. {auth-3.7.2 → auth-3.9.0}/setup.cfg +0 -0
  91. {auth-3.7.2 → auth-3.9.0}/tests/test_api_keys.py +0 -0
  92. {auth-3.7.2 → auth-3.9.0}/tests/test_api_keys_encryption.py +0 -0
  93. {auth-3.7.2 → auth-3.9.0}/tests/test_apikey_audit_outcome.py +0 -0
  94. {auth-3.7.2 → auth-3.9.0}/tests/test_apikey_cap_expiry.py +0 -0
  95. {auth-3.7.2 → auth-3.9.0}/tests/test_apikey_expiry.py +0 -0
  96. {auth-3.7.2 → auth-3.9.0}/tests/test_audit_integrity.py +0 -0
  97. {auth-3.7.2 → auth-3.9.0}/tests/test_client.py +0 -0
  98. {auth-3.7.2 → auth-3.9.0}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
  99. {auth-3.7.2 → auth-3.9.0}/tests/test_client_rest.py +0 -0
  100. {auth-3.7.2 → auth-3.9.0}/tests/test_cmd_server.py +0 -0
  101. {auth-3.7.2 → auth-3.9.0}/tests/test_config.py +0 -0
  102. {auth-3.7.2 → auth-3.9.0}/tests/test_correctness_hardening.py +0 -0
  103. {auth-3.7.2 → auth-3.9.0}/tests/test_database_pool_settings.py +0 -0
  104. {auth-3.7.2 → auth-3.9.0}/tests/test_database_sslmode.py +0 -0
  105. {auth-3.7.2 → auth-3.9.0}/tests/test_deploy_lock.py +0 -0
  106. {auth-3.7.2 → auth-3.9.0}/tests/test_docs_page.py +0 -0
  107. {auth-3.7.2 → auth-3.9.0}/tests/test_encryption.py +0 -0
  108. {auth-3.7.2 → auth-3.9.0}/tests/test_encryption_integration.py +0 -0
  109. {auth-3.7.2 → auth-3.9.0}/tests/test_flask.py +0 -0
  110. {auth-3.7.2 → auth-3.9.0}/tests/test_gunicorn_config_invariants.py +0 -0
  111. {auth-3.7.2 → auth-3.9.0}/tests/test_import_footprint.py +0 -0
  112. {auth-3.7.2 → auth-3.9.0}/tests/test_key_rotation.py +0 -0
  113. {auth-3.7.2 → auth-3.9.0}/tests/test_log_redaction.py +0 -0
  114. {auth-3.7.2 → auth-3.9.0}/tests/test_migrate_cli.py +0 -0
  115. {auth-3.7.2 → auth-3.9.0}/tests/test_no_bundled_libpq.py +0 -0
  116. {auth-3.7.2 → auth-3.9.0}/tests/test_phase_a_hardening.py +0 -0
  117. {auth-3.7.2 → auth-3.9.0}/tests/test_provision_script_no_dsn_leak.py +0 -0
  118. {auth-3.7.2 → auth-3.9.0}/tests/test_reencryption.py +0 -0
  119. {auth-3.7.2 → auth-3.9.0}/tests/test_rotate_key_preserves_strict.py +0 -0
  120. {auth-3.7.2 → auth-3.9.0}/tests/test_routes_errors.py +0 -0
  121. {auth-3.7.2 → auth-3.9.0}/tests/test_schema_check.py +0 -0
  122. {auth-3.7.2 → auth-3.9.0}/tests/test_self_service_audit.py +0 -0
  123. {auth-3.7.2 → auth-3.9.0}/tests/test_served_docs_host.py +0 -0
  124. {auth-3.7.2 → auth-3.9.0}/tests/test_server.py +0 -0
  125. {auth-3.7.2 → auth-3.9.0}/tests/test_service_lifecycle.py +0 -0
  126. {auth-3.7.2 → auth-3.9.0}/tests/test_settings_do_not_echo_secrets.py +0 -0
  127. {auth-3.7.2 → auth-3.9.0}/tests/test_strict_default.py +0 -0
  128. {auth-3.7.2 → auth-3.9.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.9.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):
@@ -103,7 +105,7 @@ def _fit(value: Optional[str], column: str) -> Optional[str]:
103
105
  """Clamp a value to its audit column width (no-op for None)."""
104
106
  if value is None:
105
107
  return None
106
- return str(value)[: _AUDIT_MAXLEN[column]]
108
+ return str(value).replace("\x00", "")[: _AUDIT_MAXLEN[column]]
107
109
 
108
110
 
109
111
  def client_fingerprint(token: Optional[str]) -> str:
@@ -57,6 +57,7 @@ class Settings(BaseSettings):
57
57
  # Security settings
58
58
  allow_cors: bool = True
59
59
  cors_origins: str = "*"
60
+ readyz_detail_cidrs: str = "127.0.0.1/32,::1/128"
60
61
  enable_audit_logging: bool = True
61
62
  # Pepper used to fingerprint the client key before it is written to audit
62
63
  # rows or logs. Falls back to jwt_secret_key when empty so the fingerprint
@@ -0,0 +1,54 @@
1
+ import base64
2
+ import hashlib
3
+ import re
4
+
5
+ from flask import request
6
+ from werkzeug.exceptions import HTTPException
7
+
8
+ from auth.docs_page import _HTML
9
+ from auth.response_format import APIResponse
10
+
11
+ API_PREFIX = "/api/"
12
+ STYLE_BLOCK = re.compile(r"<style>(.*?)</style>", re.DOTALL)
13
+
14
+
15
+ def _style_hash(rendered_page: str) -> str:
16
+ match = STYLE_BLOCK.search(rendered_page)
17
+ style_text = match.group(1) if match else ""
18
+ digest = hashlib.sha256(style_text.encode("utf-8")).digest()
19
+ return "sha256-" + base64.b64encode(digest).decode("ascii")
20
+
21
+
22
+ CONTENT_SECURITY_POLICY = (
23
+ "default-src 'none'; "
24
+ f"style-src '{_style_hash(_HTML.format(body=''))}'; "
25
+ "frame-ancestors 'none'; base-uri 'none'; form-action 'none'"
26
+ )
27
+
28
+
29
+ def _api_error(error: HTTPException):
30
+ code = error.code or 500
31
+ response, status = APIResponse.error(error.description or error.name, code)
32
+ for name, value in error.get_headers():
33
+ if name.lower() != "content-type":
34
+ response.headers[name] = value
35
+ if code == 401:
36
+ response.headers["WWW-Authenticate"] = "Bearer"
37
+ return response, status
38
+
39
+
40
+ def _set_headers(response):
41
+ response.headers["Content-Security-Policy"] = CONTENT_SECURITY_POLICY
42
+ if request.path.startswith(API_PREFIX):
43
+ response.headers["Cache-Control"] = "no-store"
44
+ return response
45
+
46
+
47
+ def register(app):
48
+ @app.errorhandler(HTTPException)
49
+ def _http_error(error: HTTPException):
50
+ if request.path.startswith(API_PREFIX):
51
+ return _api_error(error)
52
+ return error
53
+
54
+ app.after_request(_set_headers)
@@ -39,12 +39,12 @@ def _init_rate_limiter(app, settings):
39
39
  return
40
40
 
41
41
  from auth.audit import client_fingerprint
42
+ from auth.validation import parse_bearer
42
43
 
43
44
  def _key():
44
- header = request.headers.get("Authorization", "")
45
- parts = header.split()
46
- if len(parts) == 2 and parts[0].lower() == "bearer":
47
- return client_fingerprint(parts[1])
45
+ token = parse_bearer(request.headers.get("Authorization", ""))
46
+ if token is not None:
47
+ return client_fingerprint(token)
48
48
  return get_remote_address()
49
49
 
50
50
  limiter = Limiter(
@@ -94,7 +94,7 @@ def create_app():
94
94
  if settings.allow_cors:
95
95
  raw_origins = settings.cors_origins or "*"
96
96
  if raw_origins == "*":
97
- CORS(app)
97
+ CORS(app, send_wildcard=True)
98
98
  else:
99
99
  CORS(app, origins=[origin.strip() for origin in raw_origins.split(",")])
100
100
 
@@ -124,11 +124,13 @@ def create_app():
124
124
  verify_encryption_key(_db)
125
125
 
126
126
  # Import and register routes
127
+ from auth import http_hardening
127
128
  from auth.docs_page import register_docs_routes
128
129
  from auth.routes import register_routes
129
130
 
130
131
  register_routes(app)
131
132
  register_docs_routes(app)
133
+ http_hardening.register(app)
132
134
 
133
135
  @app.errorhandler(Exception)
134
136
  def _unhandled_exception(e):
@@ -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")
@@ -1,14 +1,19 @@
1
1
  """Public, unauthenticated routes plus the /api/* authentication gate."""
2
2
 
3
+ import ipaddress
3
4
  import logging
4
5
  import threading
6
+ from datetime import datetime, timezone
5
7
 
6
8
  from flask import abort, g, jsonify, request
7
9
  from sqlalchemy import text
8
10
 
9
11
  from auth import keycheck
12
+ from auth.config import get_settings
10
13
  from auth.database import engine
11
14
  from auth.validation import (
15
+ is_published_example_key,
16
+ parse_bearer,
12
17
  validate_client_key,
13
18
  )
14
19
 
@@ -57,6 +62,48 @@ def _pool_depth():
57
62
  return None
58
63
 
59
64
 
65
+ def _detail_allowed() -> bool:
66
+ try:
67
+ peer = ipaddress.ip_address(request.remote_addr or "")
68
+ networks = [
69
+ ipaddress.ip_network(cidr.strip(), strict=False)
70
+ for cidr in get_settings().readyz_detail_cidrs.split(",")
71
+ if cidr.strip()
72
+ ]
73
+ except ValueError:
74
+ return False
75
+ return any(peer in network for network in networks)
76
+
77
+
78
+ AUDIT_RUNWAY_MIN_MONTHS = 2
79
+
80
+
81
+ def _audit_runway() -> str:
82
+ state = _audit_partitions()
83
+ if not state.get("checked"):
84
+ return "unchecked"
85
+ if state.get("stranded"):
86
+ return "attention"
87
+ newest = state.get("newest") or ""
88
+ try:
89
+ year, month = (int(part) for part in newest.rsplit("_", 2)[-2:])
90
+ except ValueError:
91
+ return "attention"
92
+ today = datetime.now(timezone.utc)
93
+ months_ahead = (year - today.year) * 12 + (month - today.month)
94
+ return "attention" if months_ahead < AUDIT_RUNWAY_MIN_MONTHS else "ok"
95
+
96
+
97
+ def _readyz_body(status: str, pool_depth, reason=None) -> dict:
98
+ body: dict = {"status": status, "audit_runway": _audit_runway()}
99
+ if reason is not None:
100
+ body["reason"] = reason
101
+ if _detail_allowed():
102
+ body["pool"] = pool_depth
103
+ body["audit_partitions"] = _audit_partitions()
104
+ return body
105
+
106
+
60
107
  def register(app):
61
108
  """Register the public routes on ``app``."""
62
109
 
@@ -89,16 +136,23 @@ def register(app):
89
136
  if not auth_header:
90
137
  abort(401, description="Authorization header is missing.")
91
138
 
92
- parts = auth_header.split()
93
- if len(parts) != 2 or parts[0].lower() != "bearer":
139
+ client_key = parse_bearer(auth_header)
140
+ if client_key is None:
94
141
  abort(
95
142
  401,
96
143
  description="Invalid Authorization header format. Must be 'Bearer <token>'.",
97
144
  )
98
145
 
99
- client_key = parts[1]
100
146
  if not validate_client_key(client_key):
101
147
  abort(400, description="Invalid client key. Must be a valid UUID4.")
148
+ if is_published_example_key(client_key):
149
+ abort(
150
+ 400,
151
+ description=(
152
+ "This client key is the example published in the documentation. "
153
+ "Generate your own UUID4 and keep it secret."
154
+ ),
155
+ )
102
156
 
103
157
  # Canonicalize to lowercase: a UUID4 is case-insensitive, but the raw
104
158
  # string is used verbatim as the tenant identifier AND the encryption KDF
@@ -162,12 +216,9 @@ def register(app):
162
216
  # A probe is already in flight — almost certainly stalled. Report
163
217
  # the previous verdict rather than adding another backend to the
164
218
  # queue we are trying to measure.
165
- body = {
166
- "status": _last_commit_verdict[0],
167
- "reason": "commit probe already in flight",
168
- "pool": pool_depth,
169
- "audit_partitions": _audit_partitions(),
170
- }
219
+ body = _readyz_body(
220
+ _last_commit_verdict[0], pool_depth, "commit probe already in flight"
221
+ )
171
222
  return jsonify(body), (200 if _last_commit_verdict[0] == "ready" else 503)
172
223
  try:
173
224
  with engine.begin() as conn:
@@ -181,16 +232,7 @@ def register(app):
181
232
  except Exception:
182
233
  logger.exception("readiness check failed: commit path unavailable")
183
234
  _last_commit_verdict[0] = "unready"
184
- return jsonify({
185
- "status": "unready",
186
- "reason": "commit path",
187
- "pool": pool_depth,
188
- "audit_partitions": _audit_partitions(),
189
- }), 503
235
+ return jsonify(_readyz_body("unready", pool_depth, "commit path")), 503
190
236
  finally:
191
237
  _COMMIT_PROBE_LOCK.release()
192
- return jsonify({
193
- "status": "ready",
194
- "pool": pool_depth,
195
- "audit_partitions": _audit_partitions(),
196
- })
238
+ return jsonify(_readyz_body("ready", pool_depth))
@@ -26,9 +26,41 @@ from auth.services.recovery import (
26
26
  TargetNamespaceNotEmpty,
27
27
  recover_namespace,
28
28
  )
29
+ from auth.validation import (
30
+ AUDIT_OFFSET_MAX,
31
+ is_published_example_key,
32
+ validate_audit_action,
33
+ )
29
34
 
30
35
  logger = logging.getLogger(__name__)
31
36
 
37
+ SETTINGS_FIELDS = frozenset({"strict_users"})
38
+ RECOVER_FIELDS = frozenset({"rotate_key", "new_client_key"})
39
+
40
+
41
+ def _unknown_fields(body, allowed):
42
+ return sorted(str(name) for name in set(body) - allowed)
43
+
44
+
45
+ ROTATE_NO_BODY = (
46
+ "rotate takes no body. The server mints the new key and returns it in data.new_key."
47
+ )
48
+
49
+
50
+ def _rotate_body_refusal():
51
+ raw = request.get_data(cache=True).strip()
52
+ if raw in (b"", b"null"):
53
+ return None
54
+ body = request.get_json(silent=True, force=True)
55
+ if body == {}:
56
+ return None
57
+ if isinstance(body, dict):
58
+ return APIResponse.bad_request(
59
+ f"Unknown field(s) {', '.join(_unknown_fields(body, frozenset()))}; "
60
+ + ROTATE_NO_BODY
61
+ )
62
+ return APIResponse.bad_request(ROTATE_NO_BODY)
63
+
32
64
 
33
65
  def register(app):
34
66
  """Register the tenant routes on ``app``."""
@@ -50,6 +82,9 @@ def register(app):
50
82
  the decorator — seeing only ``g.client_key`` — cannot capture. Neither
51
83
  raw key is ever written to the audit trail.
52
84
  """
85
+ refusal = _rotate_body_refusal()
86
+ if refusal is not None:
87
+ return refusal
53
88
  old_key = g.client_key
54
89
  new_key = str(uuid.uuid4())
55
90
  audit_on = get_settings().enable_audit_logging
@@ -119,6 +154,12 @@ def register(app):
119
154
  return APIResponse.bad_request(
120
155
  'JSON body required: {"strict_users": true|false}'
121
156
  )
157
+ unknown = _unknown_fields(body, SETTINGS_FIELDS)
158
+ if unknown:
159
+ return APIResponse.bad_request(
160
+ f"Unknown field(s) {', '.join(unknown)}; "
161
+ "settings accepts only strict_users."
162
+ )
122
163
 
123
164
  auth_service = _get_auth_service(db)
124
165
  result = auth_service.set_strict_users(body["strict_users"])
@@ -187,10 +228,21 @@ def register(app):
187
228
  body = request.get_json(silent=True, force=True)
188
229
  if not isinstance(body, dict) or not isinstance(body.get("rotate_key"), str):
189
230
  return APIResponse.bad_request('JSON body required: {"rotate_key": "rrk_..."}')
231
+ unknown = _unknown_fields(body, RECOVER_FIELDS)
232
+ if unknown:
233
+ return APIResponse.bad_request(
234
+ f"Unknown field(s) {', '.join(unknown)}; "
235
+ "recover accepts only rotate_key and new_client_key."
236
+ )
190
237
 
191
238
  new_key = body.get("new_client_key") or str(uuid.uuid4())
192
239
  if not isinstance(new_key, str) or not validate_client_key(new_key):
193
240
  return APIResponse.bad_request("new_client_key must be a valid UUID4")
241
+ if is_published_example_key(new_key):
242
+ return APIResponse.bad_request(
243
+ "new_client_key is the example published in the documentation; "
244
+ "generate your own UUID4"
245
+ )
194
246
 
195
247
  try:
196
248
  result = recover_namespace(db, body["rotate_key"], new_key)
@@ -252,12 +304,19 @@ def register(app):
252
304
  return APIResponse.bad_request("limit must be between 1 and 500")
253
305
  if offset < 0:
254
306
  return APIResponse.bad_request("offset must be >= 0")
307
+ if offset > AUDIT_OFFSET_MAX:
308
+ return APIResponse.bad_request(f"offset must be <= {AUDIT_OFFSET_MAX}")
309
+ action = request.args.get("action") or None
310
+ if action is not None and not validate_audit_action(action):
311
+ return APIResponse.bad_request(
312
+ "action must be 1-50 letters or underscores, e.g. CREATE_ROLE"
313
+ )
255
314
 
256
315
  auth_service = _get_auth_service(db)
257
316
  entries, total = auth_service.get_audit(
258
317
  limit=limit,
259
318
  offset=offset,
260
- action=request.args.get("action"),
319
+ action=action,
261
320
  )
262
321
  return APIResponse.success(
263
322
  data={