rn-forge-web 0.3.0.dev0__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.
Potentially problematic release.
This version of rn-forge-web might be problematic. Click here for more details.
- rn_forge/web/__init__.py +367 -0
- rn_forge/web/asgi.py +147 -0
- rn_forge/web/auth.py +115 -0
- rn_forge/web/concurrency.py +251 -0
- rn_forge/web/conformance/__init__.py +33 -0
- rn_forge/web/conformance/cases.py +1890 -0
- rn_forge/web/conformance/types.py +134 -0
- rn_forge/web/deprecation.py +37 -0
- rn_forge/web/exceptions.py +386 -0
- rn_forge/web/health.py +239 -0
- rn_forge/web/idempotency.py +296 -0
- rn_forge/web/merge_patch.py +98 -0
- rn_forge/web/models.py +24 -0
- rn_forge/web/openapi.py +176 -0
- rn_forge/web/operations.py +54 -0
- rn_forge/web/pagination.py +253 -0
- rn_forge/web/problem.py +593 -0
- rn_forge/web/py.typed +0 -0
- rn_forge/web/read_mask.py +121 -0
- rn_forge/web/security.py +97 -0
- rn_forge/web/soft_delete.py +31 -0
- rn_forge/web/tracing.py +53 -0
- rn_forge/web/transfer.py +408 -0
- rn_forge_web-0.3.0.dev0.dist-info/METADATA +139 -0
- rn_forge_web-0.3.0.dev0.dist-info/RECORD +27 -0
- rn_forge_web-0.3.0.dev0.dist-info/WHEEL +4 -0
- rn_forge_web-0.3.0.dev0.dist-info/licenses/LICENSE +21 -0
rn_forge/web/__init__.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Framework-agnostic HTTP primitives and wire contracts."""
|
|
2
|
+
|
|
3
|
+
from rn_forge.web.asgi import (
|
|
4
|
+
ASGIApp,
|
|
5
|
+
BodySizeLimitMiddleware,
|
|
6
|
+
Message,
|
|
7
|
+
Receive,
|
|
8
|
+
Scope,
|
|
9
|
+
Send,
|
|
10
|
+
)
|
|
11
|
+
from rn_forge.web.auth import (
|
|
12
|
+
AUTH_FAILED_DETAIL,
|
|
13
|
+
CSRF_FAILED_DETAIL,
|
|
14
|
+
BearerErrorCode,
|
|
15
|
+
Credentials,
|
|
16
|
+
challenge_header,
|
|
17
|
+
parse_authorization,
|
|
18
|
+
)
|
|
19
|
+
from rn_forge.web.concurrency import (
|
|
20
|
+
ANY_ETAG,
|
|
21
|
+
EntityVersionETagCodec,
|
|
22
|
+
ETagCodec,
|
|
23
|
+
VersionETagCodec,
|
|
24
|
+
check_item_precondition,
|
|
25
|
+
check_precondition,
|
|
26
|
+
is_not_modified,
|
|
27
|
+
)
|
|
28
|
+
from rn_forge.web.conformance import (
|
|
29
|
+
CASES,
|
|
30
|
+
REDACTED,
|
|
31
|
+
VARIABLE_MEMBERS,
|
|
32
|
+
ConformanceArea,
|
|
33
|
+
ConformanceCapability,
|
|
34
|
+
ConformanceCase,
|
|
35
|
+
RequestSpec,
|
|
36
|
+
case_by_id,
|
|
37
|
+
cases_for,
|
|
38
|
+
cases_provided_by,
|
|
39
|
+
redact,
|
|
40
|
+
)
|
|
41
|
+
from rn_forge.web.deprecation import (
|
|
42
|
+
deprecation_headers,
|
|
43
|
+
)
|
|
44
|
+
from rn_forge.web.exceptions import (
|
|
45
|
+
AuthenticationFailed,
|
|
46
|
+
ContentTooLarge,
|
|
47
|
+
CsrfFailed,
|
|
48
|
+
DomainConflict,
|
|
49
|
+
IdempotencyKeyInFlight,
|
|
50
|
+
IdempotencyKeyRequired,
|
|
51
|
+
IdempotencyKeyReuse,
|
|
52
|
+
InvalidBatchGet,
|
|
53
|
+
InvalidCursor,
|
|
54
|
+
InvalidMergePatch,
|
|
55
|
+
InvalidOrderBy,
|
|
56
|
+
InvalidReadMask,
|
|
57
|
+
ItemsDenied,
|
|
58
|
+
MalformedPrecondition,
|
|
59
|
+
PermissionDenied,
|
|
60
|
+
PreconditionRequired,
|
|
61
|
+
RemoteProblem,
|
|
62
|
+
ResourceDeleted,
|
|
63
|
+
ResourceNotDeleted,
|
|
64
|
+
RowsInvalid,
|
|
65
|
+
ServiceUnavailable,
|
|
66
|
+
SessionRequired,
|
|
67
|
+
TooManyRequests,
|
|
68
|
+
UnsupportedMediaType,
|
|
69
|
+
VersionConflict,
|
|
70
|
+
WebError,
|
|
71
|
+
)
|
|
72
|
+
from rn_forge.web.health import (
|
|
73
|
+
LEGACY_LIVENESS_PATH,
|
|
74
|
+
LIVENESS_PATH,
|
|
75
|
+
READINESS_PATH,
|
|
76
|
+
Check,
|
|
77
|
+
CheckResult,
|
|
78
|
+
CheckStatus,
|
|
79
|
+
HealthReport,
|
|
80
|
+
liveness_body,
|
|
81
|
+
run_checks,
|
|
82
|
+
run_checks_sync,
|
|
83
|
+
)
|
|
84
|
+
from rn_forge.web.idempotency import (
|
|
85
|
+
IDEMPOTENCY_KEY_HEADER,
|
|
86
|
+
SAFE_METHODS,
|
|
87
|
+
AsyncIdempotencyStore,
|
|
88
|
+
IdempotencyStore,
|
|
89
|
+
InMemoryAsyncIdempotencyStore,
|
|
90
|
+
InMemoryIdempotencyStore,
|
|
91
|
+
StoredResponse,
|
|
92
|
+
check_idempotency_key,
|
|
93
|
+
request_hash,
|
|
94
|
+
run_idempotent,
|
|
95
|
+
run_idempotent_async,
|
|
96
|
+
)
|
|
97
|
+
from rn_forge.web.merge_patch import (
|
|
98
|
+
MERGE_PATCH_MEDIA_TYPE,
|
|
99
|
+
JsonValue,
|
|
100
|
+
apply_merge_patch,
|
|
101
|
+
merge_representation,
|
|
102
|
+
require_patch_object,
|
|
103
|
+
)
|
|
104
|
+
from rn_forge.web.models import WireModel
|
|
105
|
+
from rn_forge.web.openapi import (
|
|
106
|
+
API_CATALOG_PATH,
|
|
107
|
+
DOCS_PATH,
|
|
108
|
+
LINKSET_MEDIA_TYPE,
|
|
109
|
+
OPENAPI_PATH,
|
|
110
|
+
api_catalog_body,
|
|
111
|
+
operation_id,
|
|
112
|
+
)
|
|
113
|
+
from rn_forge.web.operations import Operation
|
|
114
|
+
from rn_forge.web.pagination import (
|
|
115
|
+
DEFAULT_PAGE_SIZE_PARAM,
|
|
116
|
+
DEFAULT_PAGE_TOKEN_PARAM,
|
|
117
|
+
ORDER_BY_PARAM,
|
|
118
|
+
Cursor,
|
|
119
|
+
OrderField,
|
|
120
|
+
Page,
|
|
121
|
+
SortValue,
|
|
122
|
+
check_cursor_order,
|
|
123
|
+
clamp_page_size,
|
|
124
|
+
decode_cursor,
|
|
125
|
+
encode_cursor,
|
|
126
|
+
format_order_by,
|
|
127
|
+
next_link_header,
|
|
128
|
+
parse_order_by,
|
|
129
|
+
)
|
|
130
|
+
from rn_forge.web.problem import (
|
|
131
|
+
BAD_GATEWAY,
|
|
132
|
+
BAD_REQUEST,
|
|
133
|
+
BLANK_TYPE,
|
|
134
|
+
CONFLICT,
|
|
135
|
+
CONTENT_TOO_LARGE,
|
|
136
|
+
CSRF_FAILED,
|
|
137
|
+
FORBIDDEN,
|
|
138
|
+
GENERIC_SERVER_DETAIL,
|
|
139
|
+
INTERNAL_ERROR,
|
|
140
|
+
NOT_FOUND,
|
|
141
|
+
NULL_FIELD_DETAIL,
|
|
142
|
+
PRECONDITION_FAILED,
|
|
143
|
+
PRECONDITION_REQUIRED,
|
|
144
|
+
PROBLEM_MEDIA_TYPE,
|
|
145
|
+
REQUIRED_FIELD_DETAIL,
|
|
146
|
+
SERVICE_UNAVAILABLE,
|
|
147
|
+
TOO_MANY_REQUESTS,
|
|
148
|
+
UNAUTHORIZED,
|
|
149
|
+
UNSUPPORTED_MEDIA_TYPE,
|
|
150
|
+
VALIDATION_ERROR,
|
|
151
|
+
HasProblemExtensions,
|
|
152
|
+
HasResponseHeaders,
|
|
153
|
+
ProblemDetail,
|
|
154
|
+
ProblemRegistry,
|
|
155
|
+
ProblemResponse,
|
|
156
|
+
ProblemType,
|
|
157
|
+
default_registry,
|
|
158
|
+
field_error,
|
|
159
|
+
problem_from_body,
|
|
160
|
+
render_problem,
|
|
161
|
+
unmapped_exceptions,
|
|
162
|
+
)
|
|
163
|
+
from rn_forge.web.read_mask import (
|
|
164
|
+
READ_MASK_PARAM,
|
|
165
|
+
FieldTree,
|
|
166
|
+
ReadMask,
|
|
167
|
+
parse_read_mask,
|
|
168
|
+
)
|
|
169
|
+
from rn_forge.web.soft_delete import (
|
|
170
|
+
SHOW_DELETED_PARAM,
|
|
171
|
+
require_live,
|
|
172
|
+
)
|
|
173
|
+
from rn_forge.web.tracing import (
|
|
174
|
+
EXPOSED_HEADERS,
|
|
175
|
+
TRACE_ID_KEY,
|
|
176
|
+
current_span_id,
|
|
177
|
+
current_trace_id,
|
|
178
|
+
)
|
|
179
|
+
from rn_forge.web.transfer import (
|
|
180
|
+
DUPLICATE_ID_DETAIL,
|
|
181
|
+
NON_EMPTY_IDS_DETAIL,
|
|
182
|
+
NON_EMPTY_LIST_DETAIL,
|
|
183
|
+
TABULAR_FORMATS,
|
|
184
|
+
BatchUpdateItem,
|
|
185
|
+
ImportCounts,
|
|
186
|
+
RowError,
|
|
187
|
+
TabularFormat,
|
|
188
|
+
batch_get_ids,
|
|
189
|
+
content_disposition,
|
|
190
|
+
export_cap_problem,
|
|
191
|
+
import_report_body,
|
|
192
|
+
negotiate_tabular_format,
|
|
193
|
+
parse_batch_update,
|
|
194
|
+
parse_flag,
|
|
195
|
+
row_cap_problem,
|
|
196
|
+
row_errors_problem,
|
|
197
|
+
unreadable_file_detail,
|
|
198
|
+
unsupported_file_detail,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
__all__ = [
|
|
202
|
+
"ANY_ETAG",
|
|
203
|
+
"API_CATALOG_PATH",
|
|
204
|
+
"AUTH_FAILED_DETAIL",
|
|
205
|
+
"BAD_GATEWAY",
|
|
206
|
+
"BAD_REQUEST",
|
|
207
|
+
"BLANK_TYPE",
|
|
208
|
+
"CASES",
|
|
209
|
+
"CONFLICT",
|
|
210
|
+
"CONTENT_TOO_LARGE",
|
|
211
|
+
"CSRF_FAILED",
|
|
212
|
+
"CSRF_FAILED_DETAIL",
|
|
213
|
+
"DEFAULT_PAGE_SIZE_PARAM",
|
|
214
|
+
"DEFAULT_PAGE_TOKEN_PARAM",
|
|
215
|
+
"DOCS_PATH",
|
|
216
|
+
"DUPLICATE_ID_DETAIL",
|
|
217
|
+
"EXPOSED_HEADERS",
|
|
218
|
+
"FORBIDDEN",
|
|
219
|
+
"GENERIC_SERVER_DETAIL",
|
|
220
|
+
"IDEMPOTENCY_KEY_HEADER",
|
|
221
|
+
"INTERNAL_ERROR",
|
|
222
|
+
"LEGACY_LIVENESS_PATH",
|
|
223
|
+
"LINKSET_MEDIA_TYPE",
|
|
224
|
+
"LIVENESS_PATH",
|
|
225
|
+
"MERGE_PATCH_MEDIA_TYPE",
|
|
226
|
+
"NON_EMPTY_IDS_DETAIL",
|
|
227
|
+
"NON_EMPTY_LIST_DETAIL",
|
|
228
|
+
"NOT_FOUND",
|
|
229
|
+
"NULL_FIELD_DETAIL",
|
|
230
|
+
"OPENAPI_PATH",
|
|
231
|
+
"ORDER_BY_PARAM",
|
|
232
|
+
"PRECONDITION_FAILED",
|
|
233
|
+
"PRECONDITION_REQUIRED",
|
|
234
|
+
"PROBLEM_MEDIA_TYPE",
|
|
235
|
+
"READINESS_PATH",
|
|
236
|
+
"READ_MASK_PARAM",
|
|
237
|
+
"REDACTED",
|
|
238
|
+
"REQUIRED_FIELD_DETAIL",
|
|
239
|
+
"SAFE_METHODS",
|
|
240
|
+
"SERVICE_UNAVAILABLE",
|
|
241
|
+
"SHOW_DELETED_PARAM",
|
|
242
|
+
"TABULAR_FORMATS",
|
|
243
|
+
"TOO_MANY_REQUESTS",
|
|
244
|
+
"TRACE_ID_KEY",
|
|
245
|
+
"UNAUTHORIZED",
|
|
246
|
+
"UNSUPPORTED_MEDIA_TYPE",
|
|
247
|
+
"VALIDATION_ERROR",
|
|
248
|
+
"VARIABLE_MEMBERS",
|
|
249
|
+
"ASGIApp",
|
|
250
|
+
"AsyncIdempotencyStore",
|
|
251
|
+
"AuthenticationFailed",
|
|
252
|
+
"BatchUpdateItem",
|
|
253
|
+
"BearerErrorCode",
|
|
254
|
+
"BodySizeLimitMiddleware",
|
|
255
|
+
"Check",
|
|
256
|
+
"CheckResult",
|
|
257
|
+
"CheckStatus",
|
|
258
|
+
"ConformanceArea",
|
|
259
|
+
"ConformanceCapability",
|
|
260
|
+
"ConformanceCase",
|
|
261
|
+
"ContentTooLarge",
|
|
262
|
+
"Credentials",
|
|
263
|
+
"CsrfFailed",
|
|
264
|
+
"Cursor",
|
|
265
|
+
"DomainConflict",
|
|
266
|
+
"ETagCodec",
|
|
267
|
+
"EntityVersionETagCodec",
|
|
268
|
+
"FieldTree",
|
|
269
|
+
"HasProblemExtensions",
|
|
270
|
+
"HasResponseHeaders",
|
|
271
|
+
"HealthReport",
|
|
272
|
+
"IdempotencyKeyInFlight",
|
|
273
|
+
"IdempotencyKeyRequired",
|
|
274
|
+
"IdempotencyKeyReuse",
|
|
275
|
+
"IdempotencyStore",
|
|
276
|
+
"ImportCounts",
|
|
277
|
+
"InMemoryAsyncIdempotencyStore",
|
|
278
|
+
"InMemoryIdempotencyStore",
|
|
279
|
+
"InvalidBatchGet",
|
|
280
|
+
"InvalidCursor",
|
|
281
|
+
"InvalidMergePatch",
|
|
282
|
+
"InvalidOrderBy",
|
|
283
|
+
"InvalidReadMask",
|
|
284
|
+
"ItemsDenied",
|
|
285
|
+
"JsonValue",
|
|
286
|
+
"MalformedPrecondition",
|
|
287
|
+
"Message",
|
|
288
|
+
"Operation",
|
|
289
|
+
"OrderField",
|
|
290
|
+
"Page",
|
|
291
|
+
"PermissionDenied",
|
|
292
|
+
"PreconditionRequired",
|
|
293
|
+
"ProblemDetail",
|
|
294
|
+
"ProblemRegistry",
|
|
295
|
+
"ProblemResponse",
|
|
296
|
+
"ProblemType",
|
|
297
|
+
"ReadMask",
|
|
298
|
+
"Receive",
|
|
299
|
+
"RemoteProblem",
|
|
300
|
+
"RequestSpec",
|
|
301
|
+
"ResourceDeleted",
|
|
302
|
+
"ResourceNotDeleted",
|
|
303
|
+
"RowError",
|
|
304
|
+
"RowsInvalid",
|
|
305
|
+
"Scope",
|
|
306
|
+
"Send",
|
|
307
|
+
"ServiceUnavailable",
|
|
308
|
+
"SessionRequired",
|
|
309
|
+
"SortValue",
|
|
310
|
+
"StoredResponse",
|
|
311
|
+
"TabularFormat",
|
|
312
|
+
"TooManyRequests",
|
|
313
|
+
"UnsupportedMediaType",
|
|
314
|
+
"VersionConflict",
|
|
315
|
+
"VersionETagCodec",
|
|
316
|
+
"WebError",
|
|
317
|
+
"WireModel",
|
|
318
|
+
"api_catalog_body",
|
|
319
|
+
"apply_merge_patch",
|
|
320
|
+
"batch_get_ids",
|
|
321
|
+
"case_by_id",
|
|
322
|
+
"cases_for",
|
|
323
|
+
"cases_provided_by",
|
|
324
|
+
"challenge_header",
|
|
325
|
+
"check_cursor_order",
|
|
326
|
+
"check_idempotency_key",
|
|
327
|
+
"check_item_precondition",
|
|
328
|
+
"check_precondition",
|
|
329
|
+
"clamp_page_size",
|
|
330
|
+
"content_disposition",
|
|
331
|
+
"current_span_id",
|
|
332
|
+
"current_trace_id",
|
|
333
|
+
"decode_cursor",
|
|
334
|
+
"default_registry",
|
|
335
|
+
"deprecation_headers",
|
|
336
|
+
"encode_cursor",
|
|
337
|
+
"export_cap_problem",
|
|
338
|
+
"field_error",
|
|
339
|
+
"format_order_by",
|
|
340
|
+
"import_report_body",
|
|
341
|
+
"is_not_modified",
|
|
342
|
+
"liveness_body",
|
|
343
|
+
"merge_representation",
|
|
344
|
+
"negotiate_tabular_format",
|
|
345
|
+
"next_link_header",
|
|
346
|
+
"operation_id",
|
|
347
|
+
"parse_authorization",
|
|
348
|
+
"parse_batch_update",
|
|
349
|
+
"parse_flag",
|
|
350
|
+
"parse_order_by",
|
|
351
|
+
"parse_read_mask",
|
|
352
|
+
"problem_from_body",
|
|
353
|
+
"redact",
|
|
354
|
+
"render_problem",
|
|
355
|
+
"request_hash",
|
|
356
|
+
"require_live",
|
|
357
|
+
"require_patch_object",
|
|
358
|
+
"row_cap_problem",
|
|
359
|
+
"row_errors_problem",
|
|
360
|
+
"run_checks",
|
|
361
|
+
"run_checks_sync",
|
|
362
|
+
"run_idempotent",
|
|
363
|
+
"run_idempotent_async",
|
|
364
|
+
"unmapped_exceptions",
|
|
365
|
+
"unreadable_file_detail",
|
|
366
|
+
"unsupported_file_detail",
|
|
367
|
+
]
|
rn_forge/web/asgi.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Framework-independent ASGI middleware and type aliases.
|
|
2
|
+
|
|
3
|
+
The middleware wraps any ASGI application — FastAPI, Starlette, or Django
|
|
4
|
+
served over ASGI.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Awaitable, Callable, MutableMapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from rn_forge.web.exceptions import ContentTooLarge
|
|
14
|
+
from rn_forge.web.problem import BLANK_TYPE, CONTENT_TOO_LARGE, PROBLEM_MEDIA_TYPE
|
|
15
|
+
from rn_forge.web.tracing import TRACE_ID_KEY, current_trace_id
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"ASGIApp",
|
|
19
|
+
"BodySizeLimitMiddleware",
|
|
20
|
+
"Message",
|
|
21
|
+
"Receive",
|
|
22
|
+
"Scope",
|
|
23
|
+
"Send",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
type Scope = MutableMapping[str, Any]
|
|
27
|
+
"""The ASGI connection scope."""
|
|
28
|
+
|
|
29
|
+
type Message = MutableMapping[str, Any]
|
|
30
|
+
"""One ASGI event, in either direction."""
|
|
31
|
+
|
|
32
|
+
type Receive = Callable[[], Awaitable[Message]]
|
|
33
|
+
"""The ASGI receive callable."""
|
|
34
|
+
|
|
35
|
+
type Send = Callable[[Message], Awaitable[None]]
|
|
36
|
+
"""The ASGI send callable."""
|
|
37
|
+
|
|
38
|
+
type ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
39
|
+
"""An ASGI application or middleware."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _get_header(headers: object, name: str) -> str | None:
|
|
43
|
+
"""Return the first value of *name* from a raw ASGI header list.
|
|
44
|
+
|
|
45
|
+
ASGI headers are a list of ``(bytes, bytes)`` pairs and field names are
|
|
46
|
+
case-insensitive, so both sides are lowercased before comparison.
|
|
47
|
+
"""
|
|
48
|
+
if not isinstance(headers, list):
|
|
49
|
+
return None
|
|
50
|
+
wanted = name.lower().encode("latin-1")
|
|
51
|
+
for entry in headers: # pyright: ignore[reportUnknownVariableType]
|
|
52
|
+
if not isinstance(entry, (tuple, list)) or len(entry) != 2: # pyright: ignore[reportUnknownArgumentType]
|
|
53
|
+
continue
|
|
54
|
+
key, value = entry # pyright: ignore[reportUnknownVariableType]
|
|
55
|
+
if (
|
|
56
|
+
isinstance(key, bytes)
|
|
57
|
+
and key.lower() == wanted
|
|
58
|
+
and isinstance(value, bytes)
|
|
59
|
+
):
|
|
60
|
+
return value.decode("latin-1")
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class BodySizeLimitMiddleware:
|
|
65
|
+
"""Reject a request body over *max_bytes* with RFC 9110 §15.5.14's 413.
|
|
66
|
+
|
|
67
|
+
Rejects a declared ``Content-Length`` over the limit before the downstream
|
|
68
|
+
application runs at all. A streamed body with no (or an understated)
|
|
69
|
+
``Content-Length`` is checked as it arrives; :class:`ContentTooLarge` is
|
|
70
|
+
raised out of the wrapped ``receive`` so the downstream application's read
|
|
71
|
+
aborts, and this middleware sends the 413 itself — unless the downstream
|
|
72
|
+
application already started its own response, in which case nothing more
|
|
73
|
+
can be done and the partial response stands.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
app: The downstream ASGI application.
|
|
77
|
+
max_bytes: The largest body this middleware admits.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, app: ASGIApp, max_bytes: int) -> None:
|
|
81
|
+
self.app = app
|
|
82
|
+
self.max_bytes = max_bytes
|
|
83
|
+
|
|
84
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
85
|
+
"""Run the middleware for one connection."""
|
|
86
|
+
if scope.get("type") != "http":
|
|
87
|
+
await self.app(scope, receive, send)
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
declared = _get_header(scope.get("headers"), "content-length")
|
|
91
|
+
if (
|
|
92
|
+
declared is not None
|
|
93
|
+
and declared.isdigit()
|
|
94
|
+
and int(declared) > self.max_bytes
|
|
95
|
+
):
|
|
96
|
+
await _send_413(send, str(scope.get("path", "")))
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
started = False
|
|
100
|
+
|
|
101
|
+
async def send_wrapper(message: Message) -> None:
|
|
102
|
+
nonlocal started
|
|
103
|
+
if message.get("type") == "http.response.start":
|
|
104
|
+
started = True
|
|
105
|
+
await send(message)
|
|
106
|
+
|
|
107
|
+
received = 0
|
|
108
|
+
|
|
109
|
+
async def receive_wrapper() -> Message:
|
|
110
|
+
nonlocal received
|
|
111
|
+
message = await receive()
|
|
112
|
+
received += len(message.get("body", b""))
|
|
113
|
+
if received > self.max_bytes:
|
|
114
|
+
raise ContentTooLarge("Request body exceeds the configured limit")
|
|
115
|
+
return message
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
await self.app(scope, receive_wrapper, send_wrapper)
|
|
119
|
+
except ContentTooLarge:
|
|
120
|
+
if started:
|
|
121
|
+
raise
|
|
122
|
+
await _send_413(send, str(scope.get("path", "")))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
async def _send_413(send: Send, path: str) -> None:
|
|
126
|
+
"""Send a minimal, framework-free 413 problem response."""
|
|
127
|
+
body = json.dumps(
|
|
128
|
+
{
|
|
129
|
+
"type": BLANK_TYPE,
|
|
130
|
+
"title": CONTENT_TOO_LARGE.title,
|
|
131
|
+
"status": CONTENT_TOO_LARGE.status,
|
|
132
|
+
"detail": "Request body exceeds the configured limit",
|
|
133
|
+
"instance": path,
|
|
134
|
+
TRACE_ID_KEY: current_trace_id(),
|
|
135
|
+
}
|
|
136
|
+
).encode()
|
|
137
|
+
await send(
|
|
138
|
+
{
|
|
139
|
+
"type": "http.response.start",
|
|
140
|
+
"status": CONTENT_TOO_LARGE.status,
|
|
141
|
+
"headers": [
|
|
142
|
+
(b"content-type", PROBLEM_MEDIA_TYPE.encode()),
|
|
143
|
+
(b"content-length", str(len(body)).encode()),
|
|
144
|
+
],
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
await send({"type": "http.response.body", "body": body})
|
rn_forge/web/auth.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Framework-independent authentication wire contract.
|
|
2
|
+
|
|
3
|
+
Raw credentials, the ``Authorization`` header and the ``WWW-Authenticate``
|
|
4
|
+
challenge. Verification details must not be exposed in a 401 response.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Final, Literal
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AUTH_FAILED_DETAIL",
|
|
15
|
+
"CSRF_FAILED_DETAIL",
|
|
16
|
+
"BearerErrorCode",
|
|
17
|
+
"Credentials",
|
|
18
|
+
"challenge_header",
|
|
19
|
+
"parse_authorization",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
AUTH_FAILED_DETAIL: Final = "Authentication failed."
|
|
23
|
+
"""The non-sensitive detail returned for authentication failures."""
|
|
24
|
+
|
|
25
|
+
CSRF_FAILED_DETAIL: Final = "CSRF verification failed."
|
|
26
|
+
"""The detail returned for a CSRF rejection; it never names the check that failed."""
|
|
27
|
+
|
|
28
|
+
type BearerErrorCode = Literal["invalid_request", "invalid_token", "insufficient_scope"]
|
|
29
|
+
"""The ``error`` codes RFC 6750 §3 defines for a Bearer challenge."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Credentials:
|
|
34
|
+
"""Raw credentials lifted off the request, before verification.
|
|
35
|
+
|
|
36
|
+
``scheme`` is the HTTP auth scheme as sent (``Bearer``, ``Basic``, ...) and
|
|
37
|
+
``token`` its parameter, verbatim. This is what a framework binding hands
|
|
38
|
+
an authenticator; nothing here interprets it.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
scheme: str
|
|
42
|
+
token: str
|
|
43
|
+
extras: Mapping[str, Any] = field(default_factory=dict[str, Any])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def challenge_header(
|
|
47
|
+
*,
|
|
48
|
+
scheme: str = "Bearer",
|
|
49
|
+
realm: str | None = None,
|
|
50
|
+
error: BearerErrorCode | None = None,
|
|
51
|
+
error_description: str | None = None,
|
|
52
|
+
scope: str | None = None,
|
|
53
|
+
) -> str:
|
|
54
|
+
"""Build a ``WWW-Authenticate`` challenge.
|
|
55
|
+
|
|
56
|
+
Parameters follow RFC 6750 for Bearer and RFC 7617 for Basic. ``None``
|
|
57
|
+
values are omitted.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
scheme: ``Bearer`` or ``Basic``.
|
|
61
|
+
realm: The protection space.
|
|
62
|
+
error: One of RFC 6750's three codes. Bearer only.
|
|
63
|
+
error_description: Non-sensitive human-readable text.
|
|
64
|
+
scope: The scope required, for ``insufficient_scope``.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
A complete challenge header value.
|
|
68
|
+
|
|
69
|
+
Example::
|
|
70
|
+
|
|
71
|
+
challenge_header(realm="example")
|
|
72
|
+
# 'Bearer realm="example"'
|
|
73
|
+
challenge_header(realm="example", error="insufficient_scope", scope="read")
|
|
74
|
+
# 'Bearer realm="example", error="insufficient_scope", scope="read"'
|
|
75
|
+
"""
|
|
76
|
+
params: list[tuple[str, str]] = []
|
|
77
|
+
if realm is not None:
|
|
78
|
+
params.append(("realm", realm))
|
|
79
|
+
if error is not None:
|
|
80
|
+
params.append(("error", error))
|
|
81
|
+
if error_description is not None:
|
|
82
|
+
params.append(("error_description", error_description))
|
|
83
|
+
if scope is not None:
|
|
84
|
+
params.append(("scope", scope))
|
|
85
|
+
if not params:
|
|
86
|
+
return scheme
|
|
87
|
+
rendered = ", ".join(f'{k}="{_quote(v)}"' for k, v in params)
|
|
88
|
+
return f"{scheme} {rendered}"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_authorization(header: str | None, scheme: str) -> Credentials | None:
|
|
92
|
+
"""Return the *scheme* credentials in an ``Authorization`` header value.
|
|
93
|
+
|
|
94
|
+
The scheme is matched case-insensitively (RFC 9110 §11.1) and the token
|
|
95
|
+
is returned verbatim apart from surrounding whitespace — it may be empty.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
header: The ``Authorization`` header value, or ``None`` when absent.
|
|
99
|
+
scheme: The expected scheme, e.g. ``"Bearer"``.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
``Credentials(scheme, token)``, or ``None`` when *header* is absent or
|
|
103
|
+
names another scheme.
|
|
104
|
+
"""
|
|
105
|
+
if not header:
|
|
106
|
+
return None
|
|
107
|
+
sent, _, token = header.partition(" ")
|
|
108
|
+
if sent.lower() != scheme.lower():
|
|
109
|
+
return None
|
|
110
|
+
return Credentials(scheme, token.strip())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _quote(value: str) -> str:
|
|
114
|
+
"""Escape a quoted-string parameter value (RFC 9110 §5.6.4)."""
|
|
115
|
+
return value.replace("\\", "\\\\").replace('"', '\\"')
|