swiftpy-framework 0.1.0__py3-none-any.whl

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 (211) hide show
  1. swiftpy/.gitignore +0 -0
  2. swiftpy/__init__.py +572 -0
  3. swiftpy/admin/__init__.py +50 -0
  4. swiftpy/admin/auth.py +522 -0
  5. swiftpy/admin/registry.py +567 -0
  6. swiftpy/admin/views.py +1583 -0
  7. swiftpy/ai/__init__.py +199 -0
  8. swiftpy/ai/_deterministic.py +40 -0
  9. swiftpy/ai/_fake.py +604 -0
  10. swiftpy/ai/agents/__init__.py +30 -0
  11. swiftpy/ai/agents/base_agent.py +506 -0
  12. swiftpy/ai/agents/memory.py +864 -0
  13. swiftpy/ai/client.py +1011 -0
  14. swiftpy/ai/conversation.py +171 -0
  15. swiftpy/ai/embeddings.py +321 -0
  16. swiftpy/ai/exceptions.py +75 -0
  17. swiftpy/ai/history_strategies.py +157 -0
  18. swiftpy/ai/middleware.py +918 -0
  19. swiftpy/ai/observability/__init__.py +28 -0
  20. swiftpy/ai/observability/drivers.py +763 -0
  21. swiftpy/ai/observability/observer.py +364 -0
  22. swiftpy/ai/pool.py +102 -0
  23. swiftpy/ai/pricing.py +101 -0
  24. swiftpy/ai/prompts/__init__.py +6 -0
  25. swiftpy/ai/prompts/loader.py +343 -0
  26. swiftpy/ai/providers/__init__.py +22 -0
  27. swiftpy/ai/providers/anthropic_provider.py +353 -0
  28. swiftpy/ai/providers/base.py +273 -0
  29. swiftpy/ai/providers/openai_provider.py +275 -0
  30. swiftpy/ai/rag/__init__.py +53 -0
  31. swiftpy/ai/rag/context_formatter.py +263 -0
  32. swiftpy/ai/rag/pipeline_builder.py +544 -0
  33. swiftpy/ai/rag/reranker.py +484 -0
  34. swiftpy/ai/rag/result.py +78 -0
  35. swiftpy/ai/rag/retriever.py +315 -0
  36. swiftpy/ai/redis_store.py +227 -0
  37. swiftpy/ai/streaming.py +115 -0
  38. swiftpy/ai/tools/__init__.py +22 -0
  39. swiftpy/ai/tools/base_tool.py +489 -0
  40. swiftpy/ai/tools/first_party.py +384 -0
  41. swiftpy/ai/tools/tool_loop.py +417 -0
  42. swiftpy/ai/vectorstore/__init__.py +46 -0
  43. swiftpy/ai/vectorstore/base.py +542 -0
  44. swiftpy/ai/vectorstore/chroma_adapter.py +435 -0
  45. swiftpy/ai/vectorstore/in_memory_adapter.py +321 -0
  46. swiftpy/ai/vectorstore/lancedb_adapter.py +370 -0
  47. swiftpy/ai/vectorstore/pgvector_adapter.py +496 -0
  48. swiftpy/ai/vectorstore/pinecone_adapter.py +445 -0
  49. swiftpy/ai/vectorstore/qdrant_adapter.py +418 -0
  50. swiftpy/auth/__init__.py +50 -0
  51. swiftpy/auth/api_key_guard.py +544 -0
  52. swiftpy/auth/auth_manager.py +259 -0
  53. swiftpy/auth/exceptions.py +71 -0
  54. swiftpy/auth/jwt_guard.py +230 -0
  55. swiftpy/auth/jwt_issuer.py +658 -0
  56. swiftpy/auth/token_blacklist.py +300 -0
  57. swiftpy/cache/__init__.py +14 -0
  58. swiftpy/cache/cache.py +251 -0
  59. swiftpy/cache/driver.py +216 -0
  60. swiftpy/cache/drivers/memory.py +199 -0
  61. swiftpy/cache/drivers/redis.py +421 -0
  62. swiftpy/console/__init__.py +0 -0
  63. swiftpy/console/cli.py +68 -0
  64. swiftpy/console/commands/__init__.py +0 -0
  65. swiftpy/console/commands/cache.py +164 -0
  66. swiftpy/console/commands/make.py +935 -0
  67. swiftpy/console/commands/migrate.py +280 -0
  68. swiftpy/console/commands/new.py +1806 -0
  69. swiftpy/console/commands/queue.py +306 -0
  70. swiftpy/console/commands/seed.py +252 -0
  71. swiftpy/console/commands/start.py +171 -0
  72. swiftpy/console/commands/storage.py +104 -0
  73. swiftpy/console/loader.py +21 -0
  74. swiftpy/console/stubs/__init__.py +26 -0
  75. swiftpy/console/stubs/controller.stub +14 -0
  76. swiftpy/console/stubs/event.stub +14 -0
  77. swiftpy/console/stubs/job.stub +22 -0
  78. swiftpy/console/stubs/listener.stub +14 -0
  79. swiftpy/console/stubs/mail.stub +20 -0
  80. swiftpy/console/stubs/middleware.stub +16 -0
  81. swiftpy/console/stubs/migration.alter.stub +17 -0
  82. swiftpy/console/stubs/migration.api_keys.stub +22 -0
  83. swiftpy/console/stubs/migration.blank.stub +11 -0
  84. swiftpy/console/stubs/migration.create.stub +15 -0
  85. swiftpy/console/stubs/migration.stub +11 -0
  86. swiftpy/console/stubs/migration.update.stub +17 -0
  87. swiftpy/console/stubs/model.stub +17 -0
  88. swiftpy/console/stubs/provider.stub +18 -0
  89. swiftpy/console/stubs/repository.stub +10 -0
  90. swiftpy/console/stubs/request.stub +16 -0
  91. swiftpy/console/stubs/resource.stub +21 -0
  92. swiftpy/console/stubs/schema.stub +12 -0
  93. swiftpy/console/stubs/seeder.stub +14 -0
  94. swiftpy/console/stubs/service.stub +10 -0
  95. swiftpy/core/__init__.py +0 -0
  96. swiftpy/core/application.py +1306 -0
  97. swiftpy/core/bootstrap.py +30 -0
  98. swiftpy/core/config.py +432 -0
  99. swiftpy/core/container.py +596 -0
  100. swiftpy/core/container_exceptions.py +18 -0
  101. swiftpy/core/context.py +148 -0
  102. swiftpy/core/exceptions.py +352 -0
  103. swiftpy/core/providers/base.py +35 -0
  104. swiftpy/database/__init__.py +41 -0
  105. swiftpy/database/exceptions.py +42 -0
  106. swiftpy/database/identifiers.py +105 -0
  107. swiftpy/database/migrations/__init__.py +36 -0
  108. swiftpy/database/migrations/blueprint.py +431 -0
  109. swiftpy/database/migrations/lock.py +104 -0
  110. swiftpy/database/migrations/migration.py +22 -0
  111. swiftpy/database/migrations/migrator.py +507 -0
  112. swiftpy/database/migrations/schema.py +435 -0
  113. swiftpy/database/orm/__init__.py +33 -0
  114. swiftpy/database/orm/fields.py +92 -0
  115. swiftpy/database/orm/model.py +2034 -0
  116. swiftpy/database/orm/registry.py +33 -0
  117. swiftpy/database/orm/relationships.py +836 -0
  118. swiftpy/database/pagination/__init__.py +16 -0
  119. swiftpy/database/pagination/contracts.py +60 -0
  120. swiftpy/database/pagination/paginator.py +112 -0
  121. swiftpy/database/pagination/simple_paginator.py +97 -0
  122. swiftpy/database/pool.py +218 -0
  123. swiftpy/database/query_builder.py +1803 -0
  124. swiftpy/database/seeder.py +39 -0
  125. swiftpy/database/transaction.py +276 -0
  126. swiftpy/events/__init__.py +10 -0
  127. swiftpy/events/dispatcher.py +308 -0
  128. swiftpy/events/redis_bus.py +552 -0
  129. swiftpy/filesystem/__init__.py +227 -0
  130. swiftpy/filesystem/disk.py +378 -0
  131. swiftpy/filesystem/drivers/__init__.py +11 -0
  132. swiftpy/filesystem/drivers/base.py +156 -0
  133. swiftpy/filesystem/drivers/local.py +559 -0
  134. swiftpy/filesystem/drivers/s3.py +655 -0
  135. swiftpy/filesystem/events.py +37 -0
  136. swiftpy/filesystem/exceptions.py +127 -0
  137. swiftpy/filesystem/manager.py +138 -0
  138. swiftpy/filesystem/metadata.py +22 -0
  139. swiftpy/filesystem/paths.py +99 -0
  140. swiftpy/filesystem/service_provider.py +17 -0
  141. swiftpy/filesystem/uploads/__init__.py +13 -0
  142. swiftpy/filesystem/uploads/handlers.py +362 -0
  143. swiftpy/filesystem/uploads/uploaded_file.py +222 -0
  144. swiftpy/filesystem/uploads/validators.py +186 -0
  145. swiftpy/filesystem/visibility.py +22 -0
  146. swiftpy/helpers/__init__.py +42 -0
  147. swiftpy/helpers/helper.py +180 -0
  148. swiftpy/http/exceptions.py +41 -0
  149. swiftpy/http/middleware.py +307 -0
  150. swiftpy/http/request.py +375 -0
  151. swiftpy/http/response.py +442 -0
  152. swiftpy/http/router.py +1050 -0
  153. swiftpy/mail/__init__.py +58 -0
  154. swiftpy/mail/attachments.py +255 -0
  155. swiftpy/mail/config.py +71 -0
  156. swiftpy/mail/envelope.py +183 -0
  157. swiftpy/mail/exceptions.py +90 -0
  158. swiftpy/mail/facade.py +312 -0
  159. swiftpy/mail/mailable.py +53 -0
  160. swiftpy/mail/manager.py +240 -0
  161. swiftpy/mail/message.py +186 -0
  162. swiftpy/mail/models.py +19 -0
  163. swiftpy/mail/queue/__init__.py +5 -0
  164. swiftpy/mail/queue/job.py +279 -0
  165. swiftpy/mail/service_provider.py +19 -0
  166. swiftpy/mail/templates/__init__.py +5 -0
  167. swiftpy/mail/templates/renderer.py +173 -0
  168. swiftpy/mail/transports/__init__.py +21 -0
  169. swiftpy/mail/transports/api/__init__.py +13 -0
  170. swiftpy/mail/transports/api/base.py +194 -0
  171. swiftpy/mail/transports/api/mailgun.py +158 -0
  172. swiftpy/mail/transports/api/resend.py +156 -0
  173. swiftpy/mail/transports/api/sendgrid.py +172 -0
  174. swiftpy/mail/transports/base.py +24 -0
  175. swiftpy/mail/transports/console.py +91 -0
  176. swiftpy/mail/transports/sendmail.py +128 -0
  177. swiftpy/mail/transports/smtp.py +466 -0
  178. swiftpy/queue/__init__.py +13 -0
  179. swiftpy/queue/dispatcher.py +813 -0
  180. swiftpy/queue/job.py +541 -0
  181. swiftpy/queue/worker.py +556 -0
  182. swiftpy/support/__init__.py +12 -0
  183. swiftpy/support/keys.py +108 -0
  184. swiftpy/support/redis_config.py +223 -0
  185. swiftpy/support/strings.py +114 -0
  186. swiftpy/testing/__init__.py +20 -0
  187. swiftpy/testing/fakes/__init__.py +11 -0
  188. swiftpy/testing/fakes/ai_fake.py +21 -0
  189. swiftpy/testing/fakes/vectorstore_fake.py +194 -0
  190. swiftpy/testing/fixtures.py +124 -0
  191. swiftpy/testing/http_client.py +730 -0
  192. swiftpy/testing/test_case.py +126 -0
  193. swiftpy/validation/__init__.py +97 -0
  194. swiftpy/validation/exceptions.py +26 -0
  195. swiftpy/validation/form_request.py +302 -0
  196. swiftpy/validation/protocols.py +33 -0
  197. swiftpy/validation/rules/__init__.py +89 -0
  198. swiftpy/validation/rules/builtin.py +391 -0
  199. swiftpy/validation/rules/exists.py +86 -0
  200. swiftpy/validation/rules/registry.py +290 -0
  201. swiftpy/validation/rules/required.py +55 -0
  202. swiftpy/validation/rules/unique.py +138 -0
  203. swiftpy/validation/validator.py +612 -0
  204. swiftpy/websockets/__init__.py +19 -0
  205. swiftpy/websockets/connection.py +317 -0
  206. swiftpy/websockets/manager.py +271 -0
  207. swiftpy_framework-0.1.0.dist-info/METADATA +603 -0
  208. swiftpy_framework-0.1.0.dist-info/RECORD +211 -0
  209. swiftpy_framework-0.1.0.dist-info/WHEEL +4 -0
  210. swiftpy_framework-0.1.0.dist-info/entry_points.txt +2 -0
  211. swiftpy_framework-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,544 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import hmac
6
+ import logging
7
+ import secrets
8
+ from collections.abc import Awaitable, Callable
9
+ from datetime import UTC, datetime
10
+ from typing import Any
11
+ from weakref import WeakKeyDictionary
12
+
13
+ import bcrypt
14
+
15
+ from swiftpy.auth.exceptions import (
16
+ AuthenticationError,
17
+ AuthenticationServiceUnavailableError,
18
+ InvalidApiKeyError,
19
+ )
20
+ from swiftpy.core.config import Config, ConfigurationError
21
+ from swiftpy.core.container import get_container
22
+ from swiftpy.core.context import Context
23
+ from swiftpy.database.identifiers import validate_identifier
24
+ from swiftpy.database.pool import DatabasePool
25
+ from swiftpy.database.transaction import get_active_connection
26
+ from swiftpy.http.middleware import Handler, Middleware
27
+ from swiftpy.http.request import Request
28
+ from swiftpy.http.response import Response, json_response, unauthorized
29
+
30
+ logger = logging.getLogger("swiftpy.auth.api_key")
31
+
32
+ _EPHEMERAL_PEPPERS: WeakKeyDictionary[Config, bytes] = WeakKeyDictionary()
33
+ _DUMMY_HASH: str = "0" * 64
34
+ MIN_PEPPER_BYTES: int = 32
35
+
36
+
37
+ def _prepare_bcrypt_secret(raw_key_or_secret: str) -> bytes:
38
+ """Encode API secret for bcrypt, SHA-256 pre-hashing secrets over bcrypt's 72-byte cap."""
39
+ raw_bytes = raw_key_or_secret.encode("utf-8")
40
+ if len(raw_bytes) > 72:
41
+ return hashlib.sha256(raw_bytes).hexdigest().encode("ascii")
42
+ return raw_bytes
43
+
44
+
45
+ def _validate_pepper_bytes(pepper: str | bytes, *, source: str = "AUTH_KEY_PEPPER") -> bytes:
46
+ """Validate that a server pepper is at least MIN_PEPPER_BYTES (32 bytes) in UTF-8."""
47
+ pepper_bytes = pepper.encode("utf-8") if isinstance(pepper, str) else bytes(pepper)
48
+ if len(pepper_bytes) < MIN_PEPPER_BYTES:
49
+ raise ConfigurationError(
50
+ f"{source} must be at least {MIN_PEPPER_BYTES} bytes (got {len(pepper_bytes)} bytes)."
51
+ )
52
+ return pepper_bytes
53
+
54
+
55
+ def get_server_pepper(config: Config | None = None) -> bytes:
56
+ """
57
+ Retrieve the server pepper used for HMAC-SHA256 API key hashing (Decision D-2).
58
+
59
+ In production (debug=False), fails fast if AUTH_KEY_PEPPER is missing or <32 bytes.
60
+ In debug/development mode, binds an isolated ephemeral pepper onto the resolved Config.
61
+ """
62
+ if config is None:
63
+ cfg: Config | None = None
64
+ try:
65
+ container = get_container()
66
+ if container.has(Config):
67
+ cfg = container.resolve(Config)
68
+ except RuntimeError:
69
+ pass
70
+ if cfg is None:
71
+ try:
72
+ cfg = Config.get_instance()
73
+ except (RuntimeError, ValueError):
74
+ cfg = Config()
75
+ else:
76
+ cfg = config
77
+
78
+ raw_pepper = (
79
+ cfg.get("auth.guards.api_key.pepper")
80
+ or cfg.get("auth.api_key.pepper")
81
+ or cfg.get("auth_key_pepper")
82
+ or cfg.get("api_key_pepper")
83
+ )
84
+ if raw_pepper is not None and str(raw_pepper).strip():
85
+ return _validate_pepper_bytes(
86
+ raw_pepper if isinstance(raw_pepper, bytes) else str(raw_pepper),
87
+ source="AUTH_KEY_PEPPER",
88
+ )
89
+
90
+ app_env = str(cfg.get("app.env") or cfg.get("env") or "development").lower()
91
+ debug_val = cfg.get("app.debug") if cfg.get("app.debug") is not None else cfg.get("debug")
92
+ if debug_val is not None:
93
+ is_debug = bool(debug_val)
94
+ else:
95
+ is_debug = app_env not in ("production", "prod")
96
+
97
+ if is_debug:
98
+ existing = _EPHEMERAL_PEPPERS.get(cfg)
99
+ if existing is None:
100
+ existing = secrets.token_bytes(32)
101
+ _EPHEMERAL_PEPPERS[cfg] = existing
102
+ logger.warning(
103
+ "SECURITY WARNING: No AUTH_KEY_PEPPER configured. Generated an ephemeral "
104
+ "server pepper for debug/development. Set AUTH_KEY_PEPPER in your environment."
105
+ )
106
+ return existing
107
+
108
+ raise ConfigurationError(
109
+ "AUTH_KEY_PEPPER is not configured. A server pepper of at least 32 bytes is required in production."
110
+ )
111
+
112
+
113
+ def generate_api_key(prefix: str = "sk_live_") -> tuple[str, str, str]:
114
+ """
115
+ Generate a new API key pair adhering to the prefix.secret format (Decision D-2).
116
+
117
+ Returns:
118
+ tuple[str, str, str]: (full_key, key_prefix, secret)
119
+ """
120
+ clean_prefix = prefix.rstrip(".")
121
+ random_suffix = secrets.token_hex(4)
122
+ full_prefix = (
123
+ f"{clean_prefix}{random_suffix}"
124
+ if clean_prefix.endswith("_")
125
+ else f"{clean_prefix}_{random_suffix}"
126
+ )
127
+ secret = secrets.token_urlsafe(32)
128
+ full_key = f"{full_prefix}.{secret}"
129
+ return full_key, full_prefix, secret
130
+
131
+
132
+ def hash_api_key(
133
+ raw_key_or_secret: str,
134
+ pepper: str | bytes | None = None,
135
+ rounds: int | None = None,
136
+ *,
137
+ config: Config | None = None,
138
+ ) -> str:
139
+ """
140
+ Hash an API key secret using HMAC-SHA256 with the server pepper (Decision D-2).
141
+ Defaults to get_server_pepper(config) when pepper is omitted; uses legacy bcrypt
142
+ only when rounds is explicitly requested without a pepper.
143
+ """
144
+ if pepper is not None or rounds is None:
145
+ p_bytes = (
146
+ _validate_pepper_bytes(pepper, source="Server pepper")
147
+ if pepper is not None
148
+ else get_server_pepper(config)
149
+ )
150
+ return hmac.new(
151
+ p_bytes, raw_key_or_secret.encode("utf-8"), hashlib.sha256
152
+ ).hexdigest()
153
+
154
+ # Legacy bcrypt opt-in (only when rounds is explicitly provided without pepper)
155
+ salt = bcrypt.gensalt(rounds=rounds)
156
+ return bcrypt.hashpw(_prepare_bcrypt_secret(raw_key_or_secret), salt).decode("utf-8")
157
+
158
+
159
+ def verify_api_key_hash(
160
+ raw_key_or_secret: str,
161
+ hashed: str,
162
+ pepper: str | bytes | None = None,
163
+ ) -> bool:
164
+ """
165
+ Verify an API key secret against its stored hash in constant time.
166
+ Supports peppered HMAC-SHA256 (64 hex characters) and legacy bcrypt ($2...).
167
+ """
168
+ if hashed.startswith("$2"):
169
+ try:
170
+ return bcrypt.checkpw(
171
+ _prepare_bcrypt_secret(raw_key_or_secret), hashed.encode("utf-8")
172
+ )
173
+ except (ValueError, TypeError):
174
+ return False
175
+
176
+ if pepper is not None:
177
+ p_bytes = _validate_pepper_bytes(pepper, source="Server pepper")
178
+ computed = hmac.new(
179
+ p_bytes, raw_key_or_secret.encode("utf-8"), hashlib.sha256
180
+ ).hexdigest()
181
+ return hmac.compare_digest(computed, hashed)
182
+
183
+ return False
184
+
185
+
186
+ async def _verify_api_key_hash_async(
187
+ raw_key_or_secret: str,
188
+ hashed: str,
189
+ pepper: str | bytes | None = None,
190
+ ) -> bool:
191
+ """
192
+ Non-blocking wrapper for API key hash verification.
193
+ Offloads CPU-heavy bcrypt verification to the default executor so the event loop is never blocked.
194
+ """
195
+ if hashed.startswith("$2"):
196
+ loop = asyncio.get_running_loop()
197
+ return await loop.run_in_executor(
198
+ None, verify_api_key_hash, raw_key_or_secret, hashed, pepper
199
+ )
200
+ return verify_api_key_hash(raw_key_or_secret, hashed, pepper=pepper)
201
+
202
+
203
+ async def require_api_key(
204
+ request: Request | None = None,
205
+ *,
206
+ header_name: str = "x-api-key",
207
+ table: str = "api_keys",
208
+ prefix_column: str = "key_prefix",
209
+ hash_column: str = "key_hash",
210
+ pepper: str | bytes | None = None,
211
+ pool: DatabasePool | None = None,
212
+ key_validator: Callable[[str], Awaitable[Any]] | None = None,
213
+ ) -> dict[str, Any]:
214
+ """
215
+ Parse an API key from request headers or WebSocket credentials and validate it against the database (Decision D-2).
216
+
217
+ Enforces:
218
+ 1. Strict '<prefix>.<secret>' key format (legacy unsegmented keys are rejected upfront)
219
+ 2. Prefix-indexed O(1) single-row lookup ('SELECT * FROM table WHERE key_prefix = $1 LIMIT 1')
220
+ 3. Constant-time HMAC-SHA256 verification with server pepper (or executor-offloaded bcrypt)
221
+ 4. Active transaction connection reuse via get_active_connection()
222
+ 5. Validation of active, revoked, and timezone-aware expires_at constraints
223
+ 6. Stripping of sensitive hash/secret fields before attaching to request.state and Context
224
+ 7. Support for WebSockets via Sec-WebSocket-Protocol or URL query parameters (with documented
225
+ log-leak risk for query strings).
226
+ """
227
+ # 1. Resolve request from argument or task Context
228
+ req = request or Context.get("request")
229
+ if req is None or not isinstance(req, Request):
230
+ raise RuntimeError(
231
+ "No active HTTP Request found. Pass 'request' explicitly or call within request pipeline."
232
+ )
233
+
234
+ # 2. Extract API key from headers or WebSocket handshake and check for duplicate headers
235
+ raw_key: str | None = None
236
+
237
+ header_name_bytes = header_name.lower().encode("latin1")
238
+ matching_custom_headers = [
239
+ v.decode("latin1")
240
+ for k, v in req.scope.get("headers", [])
241
+ if k.lower() == header_name_bytes
242
+ ]
243
+ if len(matching_custom_headers) > 1:
244
+ raise InvalidApiKeyError(f"Multiple '{header_name}' headers provided")
245
+ if matching_custom_headers:
246
+ raw_key = matching_custom_headers[0].strip()
247
+
248
+ if not raw_key:
249
+ raw_auth_headers = [
250
+ v.decode("latin1")
251
+ for k, v in req.scope.get("headers", [])
252
+ if k.lower() == b"authorization"
253
+ ]
254
+ if len(raw_auth_headers) > 1:
255
+ raise InvalidApiKeyError("Multiple Authorization headers provided")
256
+ if raw_auth_headers:
257
+ parts = raw_auth_headers[0].strip().split(" ", 1)
258
+ if len(parts) == 2 and parts[0].lower() in {"apikey", "bearer"}:
259
+ raw_key = parts[1].strip()
260
+
261
+ if not raw_key and req.scope.get("type") == "websocket":
262
+ # Check Sec-WebSocket-Protocol (subprotocols)
263
+ subprotocols = req.scope.get("subprotocols", [])
264
+ if not subprotocols and "sec-websocket-protocol" in req.headers:
265
+ subprotocols = [p.strip() for p in req.headers["sec-websocket-protocol"].split(",") if p.strip()]
266
+
267
+ for i, proto in enumerate(subprotocols):
268
+ proto_clean = proto.strip()
269
+ if proto_clean.lower() in ("apikey", "api_key") and i + 1 < len(subprotocols):
270
+ raw_key = subprotocols[i + 1].strip()
271
+ break
272
+ if proto_clean.lower().startswith("apikey."):
273
+ raw_key = proto_clean[7:].strip()
274
+ break
275
+ if "." in proto_clean and proto_clean.count(".") != 2:
276
+ # Potential prefix.secret API key
277
+ raw_key = proto_clean
278
+ break
279
+
280
+ # Check query parameters as fallback (with log-leak warning)
281
+ if not raw_key:
282
+ raw_key = (
283
+ req.query_params.get("api_key")
284
+ or req.query_params.get("key")
285
+ or req.query_params.get(header_name.lower())
286
+ or req.query_params.get(header_name.lower().replace("-", "_"))
287
+ )
288
+ if raw_key:
289
+ logger.debug(
290
+ "WebSocket authenticated via query parameter API key. Note: Query parameter keys "
291
+ "carry log-leak risks as query strings are frequently logged in server and proxy logs."
292
+ )
293
+
294
+ if not raw_key:
295
+ raise InvalidApiKeyError(f"Missing API key header '{header_name}'")
296
+
297
+ # 3. Custom validator callback (if provided)
298
+ if key_validator is not None:
299
+ user_or_record = await key_validator(raw_key)
300
+ if not user_or_record:
301
+ raise InvalidApiKeyError("Invalid API key")
302
+
303
+ record_dict = (
304
+ dict(user_or_record)
305
+ if isinstance(user_or_record, dict)
306
+ else {"user": user_or_record}
307
+ )
308
+ record_dict.pop(hash_column, None)
309
+ record_dict.pop("key_hash", None)
310
+ record_dict.pop("secret", None)
311
+ record_dict.pop("password", None)
312
+ record_dict.pop("password_hash", None)
313
+ req.state["user"] = record_dict
314
+ req.state["auth_guard"] = "api_key"
315
+ Context.set("__swiftpy_current_user__", record_dict)
316
+ return record_dict
317
+
318
+ # 4. Validate table and column identifiers to prevent SQL injection
319
+ table = validate_identifier(table, param_name="table")
320
+ valid_prefix_col = validate_identifier(prefix_column, param_name="prefix_column")
321
+ hash_column = validate_identifier(hash_column, param_name="column")
322
+
323
+ # 5. Enforce '<prefix>.<secret>' format (Decision D-2); reject legacy unsegmented keys upfront
324
+ if "." not in raw_key:
325
+ raise InvalidApiKeyError(
326
+ "Invalid API key format. Expected '<prefix>.<secret>'."
327
+ )
328
+
329
+ prefix, secret = raw_key.split(".", 1)
330
+ if not prefix or not secret:
331
+ raise InvalidApiKeyError(
332
+ "Invalid API key format. Expected '<prefix>.<secret>'."
333
+ )
334
+
335
+ # 6. Resolve active transaction connection or DatabasePool
336
+ active_conn = get_active_connection()
337
+ active_pool = pool
338
+ if active_conn is None and active_pool is None:
339
+ try:
340
+ container = get_container()
341
+ if container.has(DatabasePool):
342
+ active_pool = container.resolve(DatabasePool)
343
+ except RuntimeError:
344
+ pass
345
+
346
+ if active_conn is None and active_pool is None:
347
+ raise RuntimeError(
348
+ "DatabasePool is required to validate API keys against the database."
349
+ )
350
+
351
+ active_pepper = (
352
+ _validate_pepper_bytes(pepper, source="Server pepper")
353
+ if pepper is not None
354
+ else get_server_pepper()
355
+ )
356
+
357
+ # 7. Single-row O(1) indexed lookup by key_prefix
358
+ query = f'SELECT * FROM "{table}" WHERE "{valid_prefix_col}" = $1 LIMIT 1'
359
+ try:
360
+ if active_conn is not None:
361
+ row = await active_conn.fetchrow(query, prefix)
362
+ else:
363
+ assert active_pool is not None
364
+ db = active_pool.get_pool()
365
+ async with db.acquire() as conn:
366
+ row = await conn.fetchrow(query, prefix)
367
+ except Exception as exc:
368
+ logger.exception(
369
+ "Authentication service unavailable: database error during API key check"
370
+ )
371
+ raise AuthenticationServiceUnavailableError(
372
+ "Authentication service unavailable"
373
+ ) from exc
374
+
375
+ if row is None:
376
+ # Constant-time dummy comparison to prevent prefix-timing side channels
377
+ dummy_computed = hmac.new(
378
+ active_pepper, b"dummy_constant_time_comparison", hashlib.sha256
379
+ ).hexdigest()
380
+ hmac.compare_digest(dummy_computed, _DUMMY_HASH)
381
+ raise InvalidApiKeyError("Invalid API key")
382
+
383
+ row_dict = dict(row)
384
+ stored_hash: str = str(row_dict.get(hash_column) or "")
385
+
386
+ if not stored_hash or not await _verify_api_key_hash_async(
387
+ secret, stored_hash, pepper=active_pepper
388
+ ):
389
+ raise InvalidApiKeyError("Invalid API key")
390
+
391
+ # Check active status
392
+ if row_dict.get("is_active") is False or row_dict.get("active") is False:
393
+ raise InvalidApiKeyError("API key is inactive")
394
+
395
+ # Check revocation
396
+ if row_dict.get("revoked") is True:
397
+ raise InvalidApiKeyError("API key has been revoked")
398
+
399
+ # Check expiration with strict type validation (P2-A5)
400
+ now = datetime.now(UTC)
401
+ expires_at = row_dict.get("expires_at")
402
+ if expires_at is not None:
403
+ if isinstance(expires_at, str):
404
+ try:
405
+ expires_at = datetime.fromisoformat(expires_at)
406
+ except ValueError as exc:
407
+ raise InvalidApiKeyError("Invalid API key") from exc
408
+ elif not isinstance(expires_at, datetime):
409
+ raise InvalidApiKeyError("Invalid API key")
410
+
411
+ if expires_at.tzinfo is None:
412
+ expires_at = expires_at.replace(tzinfo=UTC)
413
+ if now >= expires_at:
414
+ raise InvalidApiKeyError("API key has expired")
415
+
416
+ # 8. Strip sensitive credentials before storing in request state / Context (P2-A2 requirement 4)
417
+ safe_record = dict(row_dict)
418
+ safe_record.pop(hash_column, None)
419
+ safe_record.pop("key_hash", None)
420
+ safe_record.pop("secret", None)
421
+ safe_record.pop("password", None)
422
+ safe_record.pop("password_hash", None)
423
+
424
+ req.state["user"] = safe_record
425
+ req.state["auth_guard"] = "api_key"
426
+ Context.set("__swiftpy_current_user__", safe_record)
427
+
428
+ return safe_record
429
+
430
+
431
+ class ApiKeyGuard(Middleware):
432
+ """
433
+ Middleware adapter for API key authentication (Decision D-2).
434
+ Applies require_api_key() and handles AuthenticationError (401) or
435
+ AuthenticationServiceUnavailableError (503).
436
+ """
437
+
438
+ def __init__(
439
+ self,
440
+ table: str = "api_keys",
441
+ prefix_column: str = "key_prefix",
442
+ hash_column: str = "key_hash",
443
+ header_name: str = "x-api-key",
444
+ pepper: str | bytes | None = None,
445
+ pool: DatabasePool | None = None,
446
+ ) -> None:
447
+ self.table = validate_identifier(table, param_name="table")
448
+ self.prefix_column = validate_identifier(prefix_column, param_name="prefix_column")
449
+ self.hash_column = validate_identifier(hash_column, param_name="column")
450
+ self.header_name = header_name
451
+ if pepper is not None:
452
+ _validate_pepper_bytes(pepper, source="Server pepper")
453
+ self.pepper = pepper
454
+ self.pool = pool
455
+
456
+ @classmethod
457
+ def from_config(
458
+ cls,
459
+ config: Config | None = None,
460
+ pool: DatabasePool | None = None,
461
+ ) -> ApiKeyGuard:
462
+ """Construct an ApiKeyGuard reading settings from Config ('auth.guards.api_key.*')."""
463
+ if config is None:
464
+ try:
465
+ cfg = Config.get_instance()
466
+ except (RuntimeError, ValueError):
467
+ cfg = Config()
468
+ else:
469
+ cfg = config
470
+
471
+ guard_cfg: dict[str, Any] = {}
472
+ guards = cfg.get("auth.guards")
473
+ if isinstance(guards, dict) and isinstance(guards.get("api_key"), dict):
474
+ guard_cfg = guards["api_key"]
475
+ elif isinstance(cfg.get("auth.api_key"), dict):
476
+ guard_cfg = cfg.get("auth.api_key")
477
+
478
+ table = str(
479
+ guard_cfg.get("table")
480
+ or cfg.get("auth.guards.api_key.table")
481
+ or "api_keys"
482
+ )
483
+ prefix_column = str(
484
+ guard_cfg.get("prefix_column")
485
+ or cfg.get("auth.guards.api_key.prefix_column")
486
+ or "key_prefix"
487
+ )
488
+ hash_column = str(
489
+ guard_cfg.get("hash_column")
490
+ or cfg.get("auth.guards.api_key.hash_column")
491
+ or "key_hash"
492
+ )
493
+ header_name = str(
494
+ guard_cfg.get("header")
495
+ or guard_cfg.get("header_name")
496
+ or cfg.get("auth.guards.api_key.header")
497
+ or "x-api-key"
498
+ )
499
+ pepper = guard_cfg.get("pepper") or cfg.get("auth.guards.api_key.pepper")
500
+
501
+ return cls(
502
+ table=table,
503
+ prefix_column=prefix_column,
504
+ hash_column=hash_column,
505
+ header_name=header_name,
506
+ pepper=str(pepper) if pepper is not None else None,
507
+ pool=pool,
508
+ )
509
+
510
+ async def authenticate(self, request: Request | None = None) -> dict[str, Any]:
511
+ """Authenticate the request using this guard's configured table, columns, header, and pepper."""
512
+ return await require_api_key(
513
+ request,
514
+ table=self.table,
515
+ prefix_column=self.prefix_column,
516
+ hash_column=self.hash_column,
517
+ header_name=self.header_name,
518
+ pepper=self.pepper,
519
+ pool=self.pool,
520
+ )
521
+
522
+ async def handle(self, request: Request, next_handler: Handler) -> Response:
523
+ try:
524
+ await self.authenticate(request)
525
+ except AuthenticationError as exc:
526
+ return unauthorized(exc.message, headers=exc.headers)
527
+ except AuthenticationServiceUnavailableError as exc:
528
+ return json_response(
529
+ {"detail": exc.message},
530
+ status_code=exc.status_code,
531
+ headers=exc.headers,
532
+ )
533
+
534
+ return await next_handler(request)
535
+
536
+
537
+ __all__ = [
538
+ "ApiKeyGuard",
539
+ "generate_api_key",
540
+ "get_server_pepper",
541
+ "hash_api_key",
542
+ "require_api_key",
543
+ "verify_api_key_hash",
544
+ ]