auth 3.8.0__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.8.0 → auth-3.9.0}/PKG-INFO +1 -1
  2. {auth-3.8.0 → auth-3.9.0}/auth/audit.py +1 -1
  3. {auth-3.8.0 → auth-3.9.0}/auth/config.py +1 -0
  4. auth-3.9.0/auth/http_hardening.py +54 -0
  5. {auth-3.8.0 → auth-3.9.0}/auth/main.py +7 -5
  6. {auth-3.8.0 → auth-3.9.0}/auth/routes/public.py +62 -20
  7. {auth-3.8.0 → auth-3.9.0}/auth/routes/tenant.py +60 -1
  8. {auth-3.8.0 → auth-3.9.0}/auth/sanitizer.py +4 -0
  9. {auth-3.8.0 → auth-3.9.0}/auth/services/queries.py +9 -1
  10. {auth-3.8.0 → auth-3.9.0}/auth/services/tenant.py +16 -12
  11. {auth-3.8.0 → auth-3.9.0}/auth/static_docs/api_reference.md +37 -19
  12. {auth-3.8.0 → auth-3.9.0}/auth/static_docs/claude_guide.md +3 -1
  13. {auth-3.8.0 → auth-3.9.0}/auth/static_docs/landing.md +1 -0
  14. {auth-3.8.0 → auth-3.9.0}/auth/validation.py +26 -0
  15. {auth-3.8.0 → auth-3.9.0}/auth/workflow_checker.py +5 -1
  16. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/PKG-INFO +1 -1
  17. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/SOURCES.txt +3 -0
  18. {auth-3.8.0 → auth-3.9.0}/pyproject.toml +1 -1
  19. {auth-3.8.0 → auth-3.9.0}/tests/test_degraded_response_is_a_contract.py +3 -8
  20. auth-3.9.0/tests/test_pentest_v1_inputs.py +224 -0
  21. auth-3.9.0/tests/test_pentest_v1_readyz_listings.py +180 -0
  22. {auth-3.8.0 → auth-3.9.0}/LICENSE +0 -0
  23. {auth-3.8.0 → auth-3.9.0}/README.md +0 -0
  24. {auth-3.8.0 → auth-3.9.0}/auth/__init__.py +0 -0
  25. {auth-3.8.0 → auth-3.9.0}/auth/admin.py +0 -0
  26. {auth-3.8.0 → auth-3.9.0}/auth/api_keys.py +0 -0
  27. {auth-3.8.0 → auth-3.9.0}/auth/circuit_breaker.py +0 -0
  28. {auth-3.8.0 → auth-3.9.0}/auth/client/__init__.py +0 -0
  29. {auth-3.8.0 → auth-3.9.0}/auth/client/_transport.py +0 -0
  30. {auth-3.8.0 → auth-3.9.0}/auth/client/base.py +0 -0
  31. {auth-3.8.0 → auth-3.9.0}/auth/client/keys.py +0 -0
  32. {auth-3.8.0 → auth-3.9.0}/auth/client/rbac.py +0 -0
  33. {auth-3.8.0 → auth-3.9.0}/auth/client/workflow.py +0 -0
  34. {auth-3.8.0 → auth-3.9.0}/auth/cmd/__init__.py +0 -0
  35. {auth-3.8.0 → auth-3.9.0}/auth/cmd/server.py +0 -0
  36. {auth-3.8.0 → auth-3.9.0}/auth/core/REST/__init__.py +0 -0
  37. {auth-3.8.0 → auth-3.9.0}/auth/core/REST/client.py +0 -0
  38. {auth-3.8.0 → auth-3.9.0}/auth/core/__init__.py +0 -0
  39. {auth-3.8.0 → auth-3.9.0}/auth/core/models/__init__.py +0 -0
  40. {auth-3.8.0 → auth-3.9.0}/auth/database.py +0 -0
  41. {auth-3.8.0 → auth-3.9.0}/auth/decorators.py +0 -0
  42. {auth-3.8.0 → auth-3.9.0}/auth/docs_page.py +0 -0
  43. {auth-3.8.0 → auth-3.9.0}/auth/encryption.py +0 -0
  44. {auth-3.8.0 → auth-3.9.0}/auth/key_expiry.py +0 -0
  45. {auth-3.8.0 → auth-3.9.0}/auth/keycheck.py +0 -0
  46. {auth-3.8.0 → auth-3.9.0}/auth/logging_config.py +0 -0
  47. {auth-3.8.0 → auth-3.9.0}/auth/migrate.py +0 -0
  48. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01KYTMDEYFVH43HKR0MQWW1EMP_add_auth_api_key.sql +0 -0
  49. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01KYTQN79R1ZBNDPA3ND9AAA73_drop_alembic_version.sql +0 -0
  50. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01KYTRKMWNBDDZPN1H0AXRTT5G_add_auth_tenant_settings.sql +0 -0
  51. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01KYTX0MKVZ775P62CJ87631Z1_grandfather_strict_users.sql +0 -0
  52. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01KZJWHG32K9X1AFBPPB4YJC6A_partition_audit_log.sql +0 -0
  53. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y4SMRCS9PW29AA0TFCVXKR_add_creator_fp_and_rotate_key.sql +0 -0
  54. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y4YA6RY6DZWT235CDV9H5W_enable_row_level_security.sql +0 -0
  55. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y8WEM8SYB1SG8QD35S3T6M_add_encryption_canary.sql +0 -0
  56. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y9AYF2B7WM3AHMGX14AWWJ_rls_on_new_audit_partitions.sql +0 -0
  57. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y9FNKBJ513W0XVCYFYPDR9_drop_stale_public_tables.sql +0 -0
  58. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Y9WFEY32ZWDP161SHR1B2M_add_apply_tenant_rls_function.sql +0 -0
  59. {auth-3.8.0 → auth-3.9.0}/auth/migrations/01M2Z040JTSGF3V0AQMP583BDA_create_audit_log_partitioned_if_absent.sql +0 -0
  60. {auth-3.8.0 → auth-3.9.0}/auth/migrations/__init__.py +0 -0
  61. {auth-3.8.0 → auth-3.9.0}/auth/models/sql.py +0 -0
  62. {auth-3.8.0 → auth-3.9.0}/auth/response_format.py +0 -0
  63. {auth-3.8.0 → auth-3.9.0}/auth/rls.py +0 -0
  64. {auth-3.8.0 → auth-3.9.0}/auth/routes/__init__.py +0 -0
  65. {auth-3.8.0 → auth-3.9.0}/auth/routes/_common.py +0 -0
  66. {auth-3.8.0 → auth-3.9.0}/auth/routes/apikeys.py +0 -0
  67. {auth-3.8.0 → auth-3.9.0}/auth/routes/membership.py +0 -0
  68. {auth-3.8.0 → auth-3.9.0}/auth/routes/namespace.py +0 -0
  69. {auth-3.8.0 → auth-3.9.0}/auth/routes/permissions.py +0 -0
  70. {auth-3.8.0 → auth-3.9.0}/auth/routes/roles.py +0 -0
  71. {auth-3.8.0 → auth-3.9.0}/auth/routes/workflow.py +0 -0
  72. {auth-3.8.0 → auth-3.9.0}/auth/schema_check.py +0 -0
  73. {auth-3.8.0 → auth-3.9.0}/auth/schema_reconcile.py +0 -0
  74. {auth-3.8.0 → auth-3.9.0}/auth/server.py +0 -0
  75. {auth-3.8.0 → auth-3.9.0}/auth/services/base.py +0 -0
  76. {auth-3.8.0 → auth-3.9.0}/auth/services/keys.py +0 -0
  77. {auth-3.8.0 → auth-3.9.0}/auth/services/purge.py +0 -0
  78. {auth-3.8.0 → auth-3.9.0}/auth/services/rbac.py +0 -0
  79. {auth-3.8.0 → auth-3.9.0}/auth/services/recovery.py +0 -0
  80. {auth-3.8.0 → auth-3.9.0}/auth/services/rotation.py +0 -0
  81. {auth-3.8.0 → auth-3.9.0}/auth/services/service.py +0 -0
  82. {auth-3.8.0 → auth-3.9.0}/auth/static_docs/__init__.py +0 -0
  83. {auth-3.8.0 → auth-3.9.0}/auth/static_docs/page.html +0 -0
  84. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/dependency_links.txt +0 -0
  85. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/entry_points.txt +0 -0
  86. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/requires.txt +0 -0
  87. {auth-3.8.0 → auth-3.9.0}/auth.egg-info/top_level.txt +0 -0
  88. {auth-3.8.0 → auth-3.9.0}/setup.cfg +0 -0
  89. {auth-3.8.0 → auth-3.9.0}/tests/test_admin_cli.py +0 -0
  90. {auth-3.8.0 → auth-3.9.0}/tests/test_api_keys.py +0 -0
  91. {auth-3.8.0 → auth-3.9.0}/tests/test_api_keys_encryption.py +0 -0
  92. {auth-3.8.0 → auth-3.9.0}/tests/test_apikey_audit_outcome.py +0 -0
  93. {auth-3.8.0 → auth-3.9.0}/tests/test_apikey_cap_expiry.py +0 -0
  94. {auth-3.8.0 → auth-3.9.0}/tests/test_apikey_expiry.py +0 -0
  95. {auth-3.8.0 → auth-3.9.0}/tests/test_audit_integrity.py +0 -0
  96. {auth-3.8.0 → auth-3.9.0}/tests/test_client.py +0 -0
  97. {auth-3.8.0 → auth-3.9.0}/tests/test_client_exceptions_do_not_render_payload.py +0 -0
  98. {auth-3.8.0 → auth-3.9.0}/tests/test_client_rest.py +0 -0
  99. {auth-3.8.0 → auth-3.9.0}/tests/test_cmd_server.py +0 -0
  100. {auth-3.8.0 → auth-3.9.0}/tests/test_config.py +0 -0
  101. {auth-3.8.0 → auth-3.9.0}/tests/test_correctness_hardening.py +0 -0
  102. {auth-3.8.0 → auth-3.9.0}/tests/test_database_pool_settings.py +0 -0
  103. {auth-3.8.0 → auth-3.9.0}/tests/test_database_sslmode.py +0 -0
  104. {auth-3.8.0 → auth-3.9.0}/tests/test_deploy_lock.py +0 -0
  105. {auth-3.8.0 → auth-3.9.0}/tests/test_docs_page.py +0 -0
  106. {auth-3.8.0 → auth-3.9.0}/tests/test_encryption.py +0 -0
  107. {auth-3.8.0 → auth-3.9.0}/tests/test_encryption_integration.py +0 -0
  108. {auth-3.8.0 → auth-3.9.0}/tests/test_flask.py +0 -0
  109. {auth-3.8.0 → auth-3.9.0}/tests/test_gunicorn_config_invariants.py +0 -0
  110. {auth-3.8.0 → auth-3.9.0}/tests/test_import_footprint.py +0 -0
  111. {auth-3.8.0 → auth-3.9.0}/tests/test_key_rotation.py +0 -0
  112. {auth-3.8.0 → auth-3.9.0}/tests/test_log_redaction.py +0 -0
  113. {auth-3.8.0 → auth-3.9.0}/tests/test_migrate_cli.py +0 -0
  114. {auth-3.8.0 → auth-3.9.0}/tests/test_namespace_purge.py +0 -0
  115. {auth-3.8.0 → auth-3.9.0}/tests/test_no_bundled_libpq.py +0 -0
  116. {auth-3.8.0 → auth-3.9.0}/tests/test_phase_a_hardening.py +0 -0
  117. {auth-3.8.0 → auth-3.9.0}/tests/test_provision_script_no_dsn_leak.py +0 -0
  118. {auth-3.8.0 → auth-3.9.0}/tests/test_reencryption.py +0 -0
  119. {auth-3.8.0 → auth-3.9.0}/tests/test_rotate_key_preserves_strict.py +0 -0
  120. {auth-3.8.0 → auth-3.9.0}/tests/test_routes_errors.py +0 -0
  121. {auth-3.8.0 → auth-3.9.0}/tests/test_schema_check.py +0 -0
  122. {auth-3.8.0 → auth-3.9.0}/tests/test_self_service_audit.py +0 -0
  123. {auth-3.8.0 → auth-3.9.0}/tests/test_served_docs_host.py +0 -0
  124. {auth-3.8.0 → auth-3.9.0}/tests/test_server.py +0 -0
  125. {auth-3.8.0 → auth-3.9.0}/tests/test_service_lifecycle.py +0 -0
  126. {auth-3.8.0 → auth-3.9.0}/tests/test_settings_do_not_echo_secrets.py +0 -0
  127. {auth-3.8.0 → auth-3.9.0}/tests/test_strict_default.py +0 -0
  128. {auth-3.8.0 → 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.8.0
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
@@ -105,7 +105,7 @@ def _fit(value: Optional[str], column: str) -> Optional[str]:
105
105
  """Clamp a value to its audit column width (no-op for None)."""
106
106
  if value is None:
107
107
  return None
108
- return str(value)[: _AUDIT_MAXLEN[column]]
108
+ return str(value).replace("\x00", "")[: _AUDIT_MAXLEN[column]]
109
109
 
110
110
 
111
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):
@@ -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={
@@ -2,11 +2,15 @@
2
2
  from functools import wraps
3
3
 
4
4
  import bleach # type: ignore[import-untyped]
5
+ from flask import abort
5
6
 
6
7
 
7
8
  def sanitize_input(func):
8
9
  @wraps(func)
9
10
  def wrapper(*args, **kwargs):
11
+ values = list(args) + list(kwargs.values())
12
+ if any(isinstance(value, str) and "\x00" in value for value in values):
13
+ abort(400, description="Path parameters must not contain NUL characters.")
10
14
  sanitized_args = [bleach.clean(arg) if isinstance(arg, str) else arg for arg in args]
11
15
  sanitized_kwargs = {key: bleach.clean(value) if isinstance(value, str) else value for key, value in kwargs.items()}
12
16
  return func(*sanitized_args, **sanitized_kwargs)
@@ -109,7 +109,15 @@ class QueryMixin(TenantMixin):
109
109
  if membership.is_active:
110
110
  # Return membership format (user, role) for members endpoint
111
111
  members.append({"user": membership.user, "role": group.role})
112
- return members
112
+ return self._annotate_key_backed(members)
113
+
114
+ def _annotate_key_backed(self, entries: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
115
+ if not entries or not self.strict_users_enabled():
116
+ return entries
117
+ backed = self.key_backed_users([entry["user"] for entry in entries])
118
+ for entry in entries:
119
+ entry["key_backed"] = entry["user"] in backed
120
+ return entries
113
121
 
114
122
  def which_roles_can(self, name: str) -> List[Dict[str, Any]]:
115
123
  """Get roles that have a specific permission"""
@@ -2,7 +2,7 @@
2
2
 
3
3
  import json
4
4
  from datetime import datetime
5
- from typing import Any, Dict, List, Optional, Tuple, cast
5
+ from typing import Any, Dict, List, Optional, Set, Tuple, cast
6
6
 
7
7
  from sqlalchemy import desc, or_
8
8
 
@@ -144,18 +144,12 @@ class TenantMixin(ServiceBase):
144
144
  ]
145
145
  return entries, total
146
146
 
147
- def user_is_key_backed(self, user: str) -> bool:
148
- """True when the user holds ≥1 active, unexpired API key here."""
149
- row: Any = (
150
- self.db.query(AuthApiKey.id)
147
+ def _live_key_query(self, encrypted_users: List[Any]):
148
+ return (
149
+ self.db.query(AuthApiKey._user)
151
150
  .filter(
152
151
  AuthApiKey.creator == self.client,
153
- AuthApiKey._user == self._get_encrypted_user(user),
154
- # Core column rather than the mapped attribute. SQLAlchemy 2.1's
155
- # stubs resolve a legacy `x = Column(...)` attribute to Never, so
156
- # the bare `AuthApiKey.is_active` poisons the whole chain and every
157
- # statement after it reads as unreachable. __table__.c types as a
158
- # KeyedColumnElement and emits byte-identical SQL, verified.
152
+ AuthApiKey._user.in_(encrypted_users),
159
153
  _api_key_table.c.is_active.is_(True),
160
154
  )
161
155
  .filter(
@@ -164,10 +158,20 @@ class TenantMixin(ServiceBase):
164
158
  _api_key_table.c.expires_at > _utcnow(),
165
159
  )
166
160
  )
167
- .first()
168
161
  )
162
+
163
+ def user_is_key_backed(self, user: str) -> bool:
164
+ """True when the user holds ≥1 active, unexpired API key here."""
165
+ row: Any = self._live_key_query([self._get_encrypted_user(user)]).first()
169
166
  return row is not None
170
167
 
168
+ def key_backed_users(self, users: List[str]) -> Set[str]:
169
+ by_ciphertext = {self._get_encrypted_user(user): user for user in set(users)}
170
+ if not by_ciphertext:
171
+ return set()
172
+ rows = self._live_key_query(list(by_ciphertext)).distinct().all()
173
+ return {by_ciphertext[row[0]] for row in rows if row[0] in by_ciphertext}
174
+
171
175
  def _strict_blocks(self, user: str) -> bool:
172
176
  """Strict mode on AND the user has no live key → decision is negative."""
173
177
  return self.strict_users_enabled() and not self.user_is_key_backed(user)
@@ -18,7 +18,7 @@ roles/permissions tables — see section 8 for where it fits and where it doesn'
18
18
 
19
19
  Every request needs a **client key** — any valid UUID4 — sent as a bearer token:
20
20
 
21
- Authorization: Bearer 3f6b1c9e-6f1a-4a5e-9c2e-2b7a5d0e1f34
21
+ Authorization: Bearer <your-client-key>
22
22
 
23
23
  The key is **not** checked against a stored secret. Any well-formed UUID4 is
24
24
  accepted and opens its own isolated namespace: roles, users and permissions
@@ -31,8 +31,11 @@ created under one key are invisible to every other key. Practical consequences:
31
31
  - Anyone holding your key has full read/write access to your namespace. Treat it
32
32
  like a password: keep it out of source control, logs and URLs.
33
33
 
34
- Bad keys fail fast: a missing or non-`Bearer` header gives **401**, a token that
35
- is not a UUID4 gives **400**.
34
+ Bad keys fail fast: a missing header, a scheme other than `Bearer`, or anything
35
+ but single spaces between scheme and key gives **401**; a token that is not a
36
+ UUID4 gives **400**. The scheme is case-insensitive (RFC 9110 §11.1), so
37
+ `bearer <key>` is the same request as `Bearer <key>`. The example keys these
38
+ docs used to print are refused with 400: generate your own.
36
39
 
37
40
  ## 2. Quickstart — the order matters
38
41
 
@@ -101,11 +104,14 @@ wrapper. There is no way to guess which — use the table in section 4.
101
104
  wrapped {{"success": true, "code": 200, "message": "...",
102
105
  "data": ..., "timestamp": "2026-07-20T03:11:34.288114"}}
103
106
 
104
- **Most errors are HTML, not JSON.** A bad header (401), a key that is not a
105
- UUID4 (400), an invalid name (400) and an unknown route (404) answer with Flask's
106
- error pages, `Content-Type: text/html`. Parsing them as JSON will throw, so
107
- branch on the status code first. The strict-mode 409 and the per-user API-key
108
- errors (the 400 at the 25-key limit, the 404 for an unknown key) are JSON.
107
+ **Errors from the application are JSON.** Since 3.9.0 every error auth itself
108
+ raises under `/api/` — a bad header (401), a key that is not a UUID4 (400), an
109
+ invalid name (400), an unknown route (404), a wrong method (405) — answers
110
+ `{{"success": false, "code": N, "message": "...", "details": {{}}, "timestamp": "..."}}`.
111
+ A 401 carries `WWW-Authenticate: Bearer` and a 405 keeps `Allow`. Names echoed in
112
+ a message are HTML-escaped (`&lt;`). The proxy in front of auth can still answer
113
+ with an HTML page (413 body too large, 429 rate limited, 502/504, a duplicated
114
+ `Authorization` header), so branch on the status code before parsing.
109
115
 
110
116
  **`has_permission` is also the membership answer.** The membership check reuses
111
117
  the permission payload, so `GET /api/membership/<user>/<role>` replies with
@@ -176,7 +182,10 @@ nothing changed for them at upgrade — and the audited per-tenant opt-out
176
182
  platforms that authenticate their own callers. Gated decisions:
177
183
  has_permission, the membership check, user_permissions (answers `count: 0` +
178
184
  reason), workflow can_run. NOT gated: user_roles, members and every other
179
- listing. Membership adds for key-less subjects answer **409**
185
+ listing. Listings are configuration, not decisions: under strict_users each
186
+ entry of `members`, `which_users_can` and `workflow/users` carries
187
+ `key_backed`, so filter on it (or call `has_permission`) before treating a
188
+ listing as "who may". Membership adds for key-less subjects answer **409**
180
189
  `{{"result": false, "reason": "user_not_key_backed"}}` — a refused grant must
181
190
  not look like success; check `result` on writes regardless. Create the key
182
191
  first, then grant roles: key creation committing before the grant is a
@@ -193,7 +202,14 @@ recommended backend flow: issue keys to your users, derive the user from
193
202
 
194
203
  ## 4. Endpoints
195
204
 
196
- All paths need the `Authorization` header except `/ping` and `/health`.
205
+ All `/api/` paths need the `Authorization` header except `POST /api/keys/recover`
206
+ (the rotate key in the body authenticates it). `/ping`, `/health`, `/readyz` and
207
+ the documentation pages need none. `/readyz` answers `{{"status": "ready",
208
+ "audit_runway": "ok"}}` publicly (`audit_runway` is `ok`, `attention` or
209
+ `unchecked`); pool and partition detail are shown only on the host itself.
210
+ Every `/api/` response carries `Cache-Control: no-store`, because bodies can hold
211
+ a key shown only once. CORS answers `Access-Control-Allow-Origin: *` and never
212
+ allows credentials.
197
213
  `<user>`, `<role>`/`<group>` and `<name>` go in the path, never in a body. The
198
214
  only endpoints that read a JSON body are the per-user API-key ones (create's
199
215
  optional `label`; validate's `api_key` — secrets never belong in URLs, which
@@ -215,7 +231,7 @@ get logged).
215
231
  | DELETE | `/api/membership/<user>/<role>` | bare `{{"result": true}}` |
216
232
  | GET | `/api/membership/<user>/<role>` | wrapped, `data` = `{{"has_permission": true}}` |
217
233
  | GET | `/api/user_roles/<user>` | bare `{{"result": [{{"user": "alice", "role": "engineers"}}]}}` |
218
- | GET | `/api/members/<role>` | bare `{{"result": [{{"user": "alice", "role": "engineers"}}]}}` |
234
+ | GET | `/api/members/<role>` | bare `{{"result": [{{"user": "alice", "role": "engineers"}}]}}`; under strict_users each entry adds `"key_backed": true\|false` |
219
235
 
220
236
  ### Permissions (permission on role)
221
237
 
@@ -233,7 +249,7 @@ get logged).
233
249
  | GET | `/api/has_permission/<user>/<name>` | wrapped, `data` = `{{"has_permission": true}}` |
234
250
  | GET | `/api/user_permissions/<user>` | wrapped, `data` = `{{"count": 1, "permissions": [{{"name": "deploy"}}]}}` |
235
251
  | GET | `/api/which_roles_can/<name>` | bare `{{"result": [{{"role": "engineers"}}]}}` |
236
- | GET | `/api/which_users_can/<name>` | bare `{{"result": [{{"user": "alice", "role": "engineers"}}]}}` |
252
+ | GET | `/api/which_users_can/<name>` | bare `{{"result": [{{"user": "alice", "role": "engineers"}}]}}`; under strict_users each entry adds `"key_backed": true\|false` |
237
253
 
238
254
  `/api/has_permission/<user>/<name>` is the endpoint you want for an access
239
255
  check: it is true when the user belongs to any role holding that permission.
@@ -245,7 +261,7 @@ Thin aliases over the permission model — a workflow name is just a permission.
245
261
  | Method | Path | Returns |
246
262
  |---|---|---|
247
263
  | GET | `/api/workflow/user/<user>/can_run/<workflow>` | wrapped, `data` = `{{"has_permission": true}}` |
248
- | GET | `/api/workflow/users/<workflow>` | wrapped, `data` = `{{"count": 2, "members": [{{"user": "alice", "role": "engineers"}}]}}` |
264
+ | GET | `/api/workflow/users/<workflow>` | wrapped, `data` = `{{"count": 2, "members": [{{"user": "alice", "role": "engineers"}}]}}`; under strict_users each entry adds `"key_backed": true\|false` |
249
265
 
250
266
  ### API keys (tenant key rotation)
251
267
 
@@ -256,9 +272,9 @@ only copy — persist it. See section 3 for the full semantics and threat model.
256
272
 
257
273
  | Method | Path | Returns |
258
274
  |---|---|---|
259
- | POST | `/api/keys/rotate` | wrapped, `data` = `{{"new_key": "<uuid4>", "migrated": {{"roles": 1, "memberships": 1, "permissions": 1, "api_keys": 0, "settings": 0}}}}` |
275
+ | POST | `/api/keys/rotate` | no body (empty, `{{}}` or `null`; any field is a 400 and nothing moves); wrapped, `data` = `{{"new_key": "<uuid4>", "migrated": {{"roles": 1, "memberships": 1, "permissions": 1, "api_keys": 0, "settings": 0}}}}` |
260
276
  | POST | `/api/keys/get_rotate_key` | wrapped, `data` = `{{"rotate_key": "rrk_..."}}`; `409` with `reason: rotate_key_already_issued` if already issued |
261
- | POST | `/api/keys/recover` | **no Authorization header**; body `{{"rotate_key": "rrk_...", "new_client_key": "<uuid4>"}}`; wrapped, `data` = `{{"client_key": "<uuid4>", "rotate_key": "rrk_..."}}` |
277
+ | POST | `/api/keys/recover` | **no Authorization header**; body `{{"rotate_key": "rrk_...", "new_client_key": "<uuid4>"}}` (`new_client_key` optional; any other field is a 400); wrapped, `data` = `{{"client_key": "<uuid4>", "rotate_key": "rrk_..."}}` |
262
278
 
263
279
  ### Per-user API keys
264
280
 
@@ -293,7 +309,7 @@ off is the audited opt-out for platforms that authenticate their own users.
293
309
  | Method | Path | Returns |
294
310
  |---|---|---|
295
311
  | GET | `/api/settings` | wrapped, `data` = `{{"strict_users": false}}` (defaults when never set) |
296
- | PUT | `/api/settings` | body `{{"strict_users": true}}` → wrapped, `data` = `{{"strict_users": true}}` (idempotent, audited) |
312
+ | PUT | `/api/settings` | body `{{"strict_users": true}}` (any other field is a 400) → wrapped, `data` = `{{"strict_users": true}}` (idempotent, audited) |
297
313
 
298
314
  ### Deleting a namespace
299
315
 
@@ -312,7 +328,7 @@ purge would delete, or compute it yourself:
312
328
 
313
329
  | Method | Path | Returns |
314
330
  |---|---|---|
315
- | GET | `/api/namespace` | wrapped, `data` = `{{"fingerprint": "3f6b1c9e6f1a", "roles": 4, "permissions": 9, "memberships": 12, "api_keys": 3, "settings": true, "recovery_key": true}}` |
331
+ | GET | `/api/namespace` | wrapped, `data` = `{{"fingerprint": "9b2e4c7a1d05", "roles": 4, "permissions": 9, "memberships": 12, "api_keys": 3, "settings": true, "recovery_key": true}}` |
316
332
  | 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
333
 
318
334
  ### Audit (self-service diagnosis)
@@ -330,7 +346,7 @@ false`. Neither the secret nor its hash is ever recorded.
330
346
 
331
347
  | Method | Path | Returns |
332
348
  |---|---|---|
333
- | GET | `/api/audit` | query `?limit=50&offset=0&action=ADD_PERMISSION` → wrapped, `data` = `{{"total": N, "limit": 50, "offset": 0, "entries": [{{"id", "timestamp", "action", "resource", "details", "success", "user", "ip_address", "user_agent"}}]}}` (newest first; `limit` ≤ 500; `action` filters by action name) |
349
+ | GET | `/api/audit` | query `?limit=50&offset=0&action=ADD_PERMISSION` → wrapped, `data` = `{{"total": N, "limit": 50, "offset": 0, "entries": [{{"id", "timestamp", "action", "resource", "details", "success", "user", "ip_address", "user_agent"}}]}}` (newest first; `limit` 1–500; `offset` 0–9223372036854775807; `action` filters by action name, 1–50 letters or underscores, else 400) |
334
350
 
335
351
  ### Service
336
352
 
@@ -368,9 +384,11 @@ containing `/` changes which route matches and yields 404.
368
384
 
369
385
  `pip install auth` ships a client with retries and connection pooling:
370
386
 
387
+ import os
388
+
371
389
  from auth import Client
372
390
 
373
- with Client(api_key="3f6b1c9e-6f1a-4a5e-9c2e-2b7a5d0e1f34",
391
+ with Client(api_key=os.environ["AUTH_CLIENT_KEY"],
374
392
  service_url="https://auth.rodmena.com") as c:
375
393
  c.create_role("engineers")
376
394
  c.add_permission("engineers", "deploy")
@@ -14,9 +14,11 @@ here and at `/docs`.
14
14
 
15
15
  `pip install auth`, then:
16
16
 
17
+ import os
18
+
17
19
  from auth import Client # alias of EnhancedAuthClient: pooling, retries, circuit breaker
18
20
 
19
- KEY = "3f6b1c9e-6f1a-4a5e-9c2e-2b7a5d0e1f34" # your app's secret UUID4, from config/secrets
21
+ KEY = os.environ["AUTH_CLIENT_KEY"] # your app's own secret UUID4, from your secret store
20
22
  with Client(api_key=KEY, service_url="https://auth.rodmena.com") as auth:
21
23
  auth.create_role("engineers")
22
24
  auth.add_permission("engineers", "deploy")
@@ -15,6 +15,7 @@ created implicitly, but a role must exist before you add members or permissions
15
15
  to it.
16
16
 
17
17
  KEY=$(python3 -c "import uuid; print(uuid.uuid4())")
18
+ echo "$KEY" # store it now: a lost key is a lost namespace
18
19
  BASE=https://auth.rodmena.com
19
20
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/role/engineers
20
21
  curl -X POST -H "Authorization: Bearer $KEY" $BASE/api/permission/engineers/deploy
@@ -149,3 +149,29 @@ def validate_user_role_combination(user: str, role: str) -> tuple[bool, str]:
149
149
  )
150
150
 
151
151
  return True, ""
152
+
153
+
154
+ BEARER_HEADER_PATTERN = re.compile(r"([A-Za-z]+) +([^ ]+)")
155
+ AUDIT_ACTION_PATTERN = re.compile(r"[A-Za-z_]{1,50}")
156
+ AUDIT_OFFSET_MAX = 9223372036854775807
157
+ PUBLISHED_EXAMPLE_KEYS = frozenset(
158
+ {
159
+ "3f6b1c9e-6f1a-4a5e-9c2e-2b7a5d0e1f34",
160
+ "550e8400-e29b-41d4-a716-446655440000",
161
+ }
162
+ )
163
+
164
+
165
+ def parse_bearer(header: str) -> Optional[str]:
166
+ match = BEARER_HEADER_PATTERN.fullmatch(header.strip(" \t"))
167
+ if match is None or match.group(1).lower() != "bearer":
168
+ return None
169
+ return match.group(2)
170
+
171
+
172
+ def validate_audit_action(action: str) -> bool:
173
+ return AUDIT_ACTION_PATTERN.fullmatch(action) is not None
174
+
175
+
176
+ def is_published_example_key(client_key: str) -> bool:
177
+ return client_key.lower() in PUBLISHED_EXAMPLE_KEYS