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/problem.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
"""RFC 9457 problem details and exception-to-problem mapping.
|
|
2
|
+
|
|
3
|
+
No RFC 9457 library is adopted: ``fastapi-problem`` 0.12.1 (checked 2026-09-23) emits no ``instance``,
|
|
4
|
+
sets its own ``type`` and ``title`` instead of ``about:blank`` and the status phrase, and has no
|
|
5
|
+
exception-to-status registry.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Iterable, Mapping
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from http import HTTPStatus
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
from typing import Any, Final, Protocol, Self, cast, runtime_checkable
|
|
16
|
+
|
|
17
|
+
from pydantic import ConfigDict, model_validator
|
|
18
|
+
from rn_forge.web.auth import AUTH_FAILED_DETAIL, CSRF_FAILED_DETAIL, challenge_header
|
|
19
|
+
from rn_forge.web.exceptions import (
|
|
20
|
+
AuthenticationFailed,
|
|
21
|
+
ContentTooLarge,
|
|
22
|
+
CsrfFailed,
|
|
23
|
+
DomainConflict,
|
|
24
|
+
IdempotencyKeyInFlight,
|
|
25
|
+
IdempotencyKeyRequired,
|
|
26
|
+
IdempotencyKeyReuse,
|
|
27
|
+
InvalidBatchGet,
|
|
28
|
+
InvalidCursor,
|
|
29
|
+
InvalidMergePatch,
|
|
30
|
+
InvalidOrderBy,
|
|
31
|
+
InvalidReadMask,
|
|
32
|
+
ItemsDenied,
|
|
33
|
+
MalformedPrecondition,
|
|
34
|
+
PermissionDenied,
|
|
35
|
+
PreconditionRequired,
|
|
36
|
+
RemoteProblem,
|
|
37
|
+
RowsInvalid,
|
|
38
|
+
ServiceUnavailable,
|
|
39
|
+
TooManyRequests,
|
|
40
|
+
UnsupportedMediaType,
|
|
41
|
+
VersionConflict,
|
|
42
|
+
)
|
|
43
|
+
from rn_forge.web.models import WireModel
|
|
44
|
+
from rn_forge.web.tracing import TRACE_ID_KEY, current_trace_id
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"BAD_GATEWAY",
|
|
48
|
+
"BAD_REQUEST",
|
|
49
|
+
"BLANK_TYPE",
|
|
50
|
+
"CONFLICT",
|
|
51
|
+
"CONTENT_TOO_LARGE",
|
|
52
|
+
"CSRF_FAILED",
|
|
53
|
+
"FORBIDDEN",
|
|
54
|
+
"GENERIC_SERVER_DETAIL",
|
|
55
|
+
"INTERNAL_ERROR",
|
|
56
|
+
"NOT_FOUND",
|
|
57
|
+
"NULL_FIELD_DETAIL",
|
|
58
|
+
"PRECONDITION_FAILED",
|
|
59
|
+
"PRECONDITION_REQUIRED",
|
|
60
|
+
"PROBLEM_MEDIA_TYPE",
|
|
61
|
+
"REQUIRED_FIELD_DETAIL",
|
|
62
|
+
"SERVICE_UNAVAILABLE",
|
|
63
|
+
"TOO_MANY_REQUESTS",
|
|
64
|
+
"UNAUTHORIZED",
|
|
65
|
+
"UNSUPPORTED_MEDIA_TYPE",
|
|
66
|
+
"VALIDATION_ERROR",
|
|
67
|
+
"HasProblemExtensions",
|
|
68
|
+
"HasResponseHeaders",
|
|
69
|
+
"ProblemDetail",
|
|
70
|
+
"ProblemRegistry",
|
|
71
|
+
"ProblemResponse",
|
|
72
|
+
"ProblemType",
|
|
73
|
+
"default_registry",
|
|
74
|
+
"field_error",
|
|
75
|
+
"problem_from_body",
|
|
76
|
+
"render_problem",
|
|
77
|
+
"unmapped_exceptions",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
PROBLEM_MEDIA_TYPE: Final = "application/problem+json"
|
|
81
|
+
"""The ``Content-Type`` every error response in this kit carries."""
|
|
82
|
+
|
|
83
|
+
GENERIC_SERVER_DETAIL: Final = "An unexpected error occurred."
|
|
84
|
+
"""What a 5xx ``detail`` says when the caller did not supply one. See :meth:`ProblemRegistry.build`."""
|
|
85
|
+
|
|
86
|
+
BLANK_TYPE: Final = "about:blank"
|
|
87
|
+
"""RFC 9457's prescribed ``type`` when there is no type URI to give."""
|
|
88
|
+
|
|
89
|
+
_CORE_MEMBERS: Final = frozenset({"type", "title", "status", "detail", "instance"})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@runtime_checkable
|
|
93
|
+
class HasProblemExtensions(Protocol):
|
|
94
|
+
"""An exception that contributes extension members to its own problem body.
|
|
95
|
+
|
|
96
|
+
:meth:`ProblemRegistry.build` merges the result beneath an explicit
|
|
97
|
+
``extensions=`` argument and only for a row below 500 — a 5xx body says
|
|
98
|
+
nothing about the cause, so nothing an exception carries reaches the wire
|
|
99
|
+
for one. An application that wants some of ``AppException.error_data`` on
|
|
100
|
+
the wire implements this and chooses the members; ``error_data`` itself is
|
|
101
|
+
never published automatically, since it routinely carries credentials and
|
|
102
|
+
internal identifiers.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def problem_extensions(self) -> Mapping[str, Any]: ...
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@runtime_checkable
|
|
109
|
+
class HasResponseHeaders(Protocol):
|
|
110
|
+
"""An exception that contributes response headers to its own problem response.
|
|
111
|
+
|
|
112
|
+
:func:`render_problem` merges the result beneath an explicit ``headers=``
|
|
113
|
+
argument, so a caller's header always wins a collision.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def response_headers(self) -> Mapping[str, str]: ...
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class ProblemDetail(WireModel):
|
|
120
|
+
"""An RFC 9457 problem.
|
|
121
|
+
|
|
122
|
+
Extension members are **flattened at the top level on the wire** (RFC 9457
|
|
123
|
+
§3.2): the model allows extra members, and ``ProblemDetail(...,
|
|
124
|
+
extensions={...})`` merges a mapping in as extras. Core members win a
|
|
125
|
+
collision with an extension of the same name.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
model_config = ConfigDict(frozen=True, extra="allow")
|
|
129
|
+
|
|
130
|
+
type: str
|
|
131
|
+
title: str
|
|
132
|
+
status: int
|
|
133
|
+
detail: str
|
|
134
|
+
instance: str
|
|
135
|
+
|
|
136
|
+
@model_validator(mode="before")
|
|
137
|
+
@classmethod
|
|
138
|
+
def _merge_extensions(cls, data: Any) -> Any:
|
|
139
|
+
if isinstance(data, dict) and "extensions" in data:
|
|
140
|
+
merged = dict(cast("dict[str, Any]", data))
|
|
141
|
+
extensions = cast("Mapping[str, Any] | None", merged.pop("extensions"))
|
|
142
|
+
return {**(extensions or {}), **merged}
|
|
143
|
+
return cast(Any, data)
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def extensions(self) -> dict[str, Any]:
|
|
147
|
+
"""The extension members, as a fresh mapping."""
|
|
148
|
+
return dict(self.model_extra or {})
|
|
149
|
+
|
|
150
|
+
def as_body(self) -> dict[str, Any]:
|
|
151
|
+
"""Return the wire body, extensions merged at the top level."""
|
|
152
|
+
return self.model_dump()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass(frozen=True)
|
|
156
|
+
class ProblemType:
|
|
157
|
+
"""A registry row: the slug, status and title a class of failure maps to."""
|
|
158
|
+
|
|
159
|
+
slug: str
|
|
160
|
+
status: int
|
|
161
|
+
title: str
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# Standard problem rows. `default_registry()` binds each to an exception class;
|
|
165
|
+
# they remain public so applications can customize those bindings.
|
|
166
|
+
NOT_FOUND: Final = ProblemType("not-found", 404, "Not Found")
|
|
167
|
+
VALIDATION_ERROR: Final = ProblemType("validation-error", 422, "Validation Error")
|
|
168
|
+
INTERNAL_ERROR: Final = ProblemType("internal-error", 500, "Internal Server Error")
|
|
169
|
+
CONFLICT: Final = ProblemType("conflict", 409, "Conflict")
|
|
170
|
+
PRECONDITION_FAILED: Final = ProblemType(
|
|
171
|
+
"precondition-failed", 412, "Precondition Failed"
|
|
172
|
+
)
|
|
173
|
+
PRECONDITION_REQUIRED: Final = ProblemType(
|
|
174
|
+
"precondition-required", 428, "Precondition Required"
|
|
175
|
+
)
|
|
176
|
+
UNAUTHORIZED: Final = ProblemType("unauthorized", 401, "Unauthorized")
|
|
177
|
+
FORBIDDEN: Final = ProblemType("forbidden", 403, "Forbidden")
|
|
178
|
+
CSRF_FAILED: Final = ProblemType("csrf-failed", 403, "CSRF Failed")
|
|
179
|
+
BAD_REQUEST: Final = ProblemType("bad-request", 400, "Bad Request")
|
|
180
|
+
BAD_GATEWAY: Final = ProblemType("bad-gateway", 502, "Bad Gateway")
|
|
181
|
+
CONTENT_TOO_LARGE: Final = ProblemType("content-too-large", 413, "Content Too Large")
|
|
182
|
+
UNSUPPORTED_MEDIA_TYPE: Final = ProblemType(
|
|
183
|
+
"unsupported-media-type", 415, "Unsupported Media Type"
|
|
184
|
+
)
|
|
185
|
+
TOO_MANY_REQUESTS: Final = ProblemType("too-many-requests", 429, "Too Many Requests")
|
|
186
|
+
SERVICE_UNAVAILABLE: Final = ProblemType(
|
|
187
|
+
"service-unavailable", 503, "Service Unavailable"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class ProblemRegistry:
|
|
192
|
+
"""Maps exception classes to problem types, resolving by MRO.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
type_base: Prefix for the ``type`` URI. When empty (the default), the
|
|
196
|
+
``type`` is ``about:blank``, which is what RFC 9457 prescribes when
|
|
197
|
+
there is no type URI to give — a library must not invent a URI
|
|
198
|
+
namespace. When set, ``type`` becomes ``type_base + slug``.
|
|
199
|
+
fallback: The row an unregistered exception resolves to.
|
|
200
|
+
|
|
201
|
+
Example::
|
|
202
|
+
|
|
203
|
+
registry = ProblemRegistry(type_base="https://errors.example.com/")
|
|
204
|
+
registry.register(OrderLocked, ProblemType("order-locked", 409, "Order Locked"))
|
|
205
|
+
body = registry.build(exc, instance="/orders/17").as_body()
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
def __init__(
|
|
209
|
+
self,
|
|
210
|
+
*,
|
|
211
|
+
type_base: str = "",
|
|
212
|
+
fallback: ProblemType = INTERNAL_ERROR,
|
|
213
|
+
) -> None:
|
|
214
|
+
self._type_base = type_base
|
|
215
|
+
self._fallback = fallback
|
|
216
|
+
self._rows: dict[type[BaseException], ProblemType] = {}
|
|
217
|
+
|
|
218
|
+
def register(self, exc_type: type[BaseException], problem: ProblemType) -> Self:
|
|
219
|
+
"""Register *problem* for *exc_type*, returning ``self`` for chaining."""
|
|
220
|
+
self._rows[exc_type] = problem
|
|
221
|
+
return self
|
|
222
|
+
|
|
223
|
+
@property
|
|
224
|
+
def fallback(self) -> ProblemType:
|
|
225
|
+
"""The row an unregistered exception resolves to."""
|
|
226
|
+
return self._fallback
|
|
227
|
+
|
|
228
|
+
def rows(self) -> Mapping[type[BaseException], ProblemType]:
|
|
229
|
+
"""Return a read-only view of the registered rows, in registration order.
|
|
230
|
+
|
|
231
|
+
A framework adapter needs the registered exception *types* — Starlette
|
|
232
|
+
dispatches a handler per class — and an OpenAPI document needs the
|
|
233
|
+
statuses they map to.
|
|
234
|
+
"""
|
|
235
|
+
return MappingProxyType(self._rows)
|
|
236
|
+
|
|
237
|
+
def problem_for(self, exc: BaseException) -> ProblemType:
|
|
238
|
+
"""Return the row for *exc*, walking its MRO before falling back.
|
|
239
|
+
|
|
240
|
+
The MRO walk is what makes an adapter subclass resolve to its base
|
|
241
|
+
class's row without anyone remembering to register it.
|
|
242
|
+
"""
|
|
243
|
+
for cls in type(exc).__mro__:
|
|
244
|
+
row = self._rows.get(cls)
|
|
245
|
+
if row is not None:
|
|
246
|
+
return row
|
|
247
|
+
return self._fallback
|
|
248
|
+
|
|
249
|
+
def problem_for_status(self, status: int) -> ProblemType:
|
|
250
|
+
"""Return the row for a bare HTTP status that carries no exception type.
|
|
251
|
+
|
|
252
|
+
A framework raises HTTP errors no application registered — a routing
|
|
253
|
+
404, a 405. The row is the **first registered row with that status**, so
|
|
254
|
+
a framework 404 and a ``LookupError`` produce the same body. With no such
|
|
255
|
+
row it is derived from the IANA reason phrase (405 →
|
|
256
|
+
``method-not-allowed`` / ``Method Not Allowed``); a status with no
|
|
257
|
+
reason phrase resolves to the fallback.
|
|
258
|
+
|
|
259
|
+
"""
|
|
260
|
+
for row in self._rows.values():
|
|
261
|
+
if row.status == status:
|
|
262
|
+
return row
|
|
263
|
+
try:
|
|
264
|
+
phrase = HTTPStatus(status).phrase
|
|
265
|
+
except ValueError:
|
|
266
|
+
return self._fallback
|
|
267
|
+
return ProblemType(
|
|
268
|
+
"-".join(re.findall(r"[a-z0-9]+", phrase.lower())), status, phrase
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
def type_uri(self, problem: ProblemType) -> str:
|
|
272
|
+
"""Return the ``type`` member for *problem*."""
|
|
273
|
+
return f"{self._type_base}{problem.slug}" if self._type_base else BLANK_TYPE
|
|
274
|
+
|
|
275
|
+
def build(
|
|
276
|
+
self,
|
|
277
|
+
exc: BaseException,
|
|
278
|
+
*,
|
|
279
|
+
instance: str,
|
|
280
|
+
detail: str | None = None,
|
|
281
|
+
extensions: Mapping[str, Any] | None = None,
|
|
282
|
+
problem: ProblemType | None = None,
|
|
283
|
+
) -> ProblemDetail:
|
|
284
|
+
"""Build the problem body for *exc*.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
exc: The exception to describe.
|
|
288
|
+
instance: A URI reference identifying this occurrence — in practice
|
|
289
|
+
the request path.
|
|
290
|
+
detail: Overrides the derived detail. Supply it to say something
|
|
291
|
+
more useful than ``str(exc)``.
|
|
292
|
+
extensions: Extra members, flattened onto the wire body. Wins over
|
|
293
|
+
a same-named member *exc* contributes via
|
|
294
|
+
:class:`HasProblemExtensions`.
|
|
295
|
+
problem: The row to build from instead of resolving one from *exc*
|
|
296
|
+
— for a framework HTTP error, :meth:`problem_for_status`'s.
|
|
297
|
+
|
|
298
|
+
Returns:
|
|
299
|
+
The problem. When the status is 5xx and *detail* was not supplied,
|
|
300
|
+
the detail is :data:`GENERIC_SERVER_DETAIL` rather than
|
|
301
|
+
``str(exc)`` — this is the one piece of policy in the module, and
|
|
302
|
+
it is the default because getting it wrong leaks internals.
|
|
303
|
+
|
|
304
|
+
When *exc* implements :class:`HasProblemExtensions` and the
|
|
305
|
+
resolved row's status is below 500, its ``problem_extensions()``
|
|
306
|
+
are merged beneath *extensions*. Nothing is merged for a 5xx row —
|
|
307
|
+
a 5xx body says nothing about the cause, and that rule is not
|
|
308
|
+
reachable around.
|
|
309
|
+
|
|
310
|
+
``title`` is *row*'s title only when :attr:`type_uri` resolves to a
|
|
311
|
+
real URI (a ``type_base`` is configured, so the title describes
|
|
312
|
+
it). With ``about:blank``, RFC 9457 §4.2.1 prescribes the HTTP
|
|
313
|
+
status phrase instead.
|
|
314
|
+
"""
|
|
315
|
+
row = problem if problem is not None else self.problem_for(exc)
|
|
316
|
+
if detail is not None:
|
|
317
|
+
resolved = detail
|
|
318
|
+
elif row.status >= 500:
|
|
319
|
+
resolved = GENERIC_SERVER_DETAIL
|
|
320
|
+
else:
|
|
321
|
+
resolved = _message_of(exc) or row.title
|
|
322
|
+
merged: dict[str, Any] = {}
|
|
323
|
+
if row.status < 500 and isinstance(exc, HasProblemExtensions):
|
|
324
|
+
merged.update(exc.problem_extensions())
|
|
325
|
+
merged.update(extensions or {})
|
|
326
|
+
return ProblemDetail.model_validate(
|
|
327
|
+
{
|
|
328
|
+
"type": self.type_uri(row),
|
|
329
|
+
"title": row.title if self._type_base else _status_phrase(row.status),
|
|
330
|
+
"status": row.status,
|
|
331
|
+
"detail": resolved,
|
|
332
|
+
"instance": instance,
|
|
333
|
+
"extensions": merged,
|
|
334
|
+
}
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _status_phrase(status: int) -> str:
|
|
339
|
+
"""Return the IANA reason phrase for *status*, or the status as a string.
|
|
340
|
+
|
|
341
|
+
A status outside :class:`http.HTTPStatus` has no phrase; that is only
|
|
342
|
+
reachable through an application-defined :class:`ProblemType` carrying a
|
|
343
|
+
non-standard status.
|
|
344
|
+
"""
|
|
345
|
+
try:
|
|
346
|
+
return HTTPStatus(status).phrase
|
|
347
|
+
except ValueError:
|
|
348
|
+
return str(status)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _message_of(exc: BaseException) -> str:
|
|
352
|
+
"""Return the human-readable message of *exc*, and nothing else.
|
|
353
|
+
|
|
354
|
+
``AppException.__str__`` renders ``"<error_code> | <message> | <error_data>"``,
|
|
355
|
+
which is a useful log line and a terrible ``detail`` member — it would put
|
|
356
|
+
the exception's whole context dict on the wire, including whatever a caller
|
|
357
|
+
attached to it. So read ``.message`` when there is one.
|
|
358
|
+
"""
|
|
359
|
+
message = getattr(exc, "message", None)
|
|
360
|
+
return message if isinstance(message, str) else str(exc)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
@dataclass(frozen=True)
|
|
364
|
+
class ProblemResponse:
|
|
365
|
+
"""A rendered problem response, ready for a framework to send.
|
|
366
|
+
|
|
367
|
+
The body is :attr:`problem`'s wire form and the ``Content-Type`` is
|
|
368
|
+
always :data:`PROBLEM_MEDIA_TYPE`.
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
problem: ProblemDetail
|
|
372
|
+
headers: Mapping[str, str]
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def status(self) -> int:
|
|
376
|
+
"""The HTTP status."""
|
|
377
|
+
return self.problem.status
|
|
378
|
+
|
|
379
|
+
@property
|
|
380
|
+
def body(self) -> dict[str, Any]:
|
|
381
|
+
"""The JSON body, extensions flattened (:meth:`ProblemDetail.as_body`)."""
|
|
382
|
+
return self.problem.as_body()
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def render_problem(
|
|
386
|
+
registry: ProblemRegistry,
|
|
387
|
+
exc: BaseException,
|
|
388
|
+
*,
|
|
389
|
+
instance: str,
|
|
390
|
+
problem: ProblemType | None = None,
|
|
391
|
+
detail: str | None = None,
|
|
392
|
+
extensions: Mapping[str, Any] | None = None,
|
|
393
|
+
headers: Mapping[str, str] | None = None,
|
|
394
|
+
realm: str | None = None,
|
|
395
|
+
) -> ProblemResponse:
|
|
396
|
+
"""Render *exc* as a complete problem response: body and headers.
|
|
397
|
+
|
|
398
|
+
On top of :meth:`ProblemRegistry.build`:
|
|
399
|
+
|
|
400
|
+
- the current span's trace id is the ``traceId`` extension (``null``
|
|
401
|
+
when no span is recording);
|
|
402
|
+
- a 401 carries :data:`~rn_forge.web.auth.AUTH_FAILED_DETAIL` as its
|
|
403
|
+
detail, whatever *detail* says, and a ``WWW-Authenticate`` challenge
|
|
404
|
+
unless *headers* already carries one or *exc* is an
|
|
405
|
+
:class:`~rn_forge.web.exceptions.AuthenticationFailed` whose
|
|
406
|
+
``challenge`` is false;
|
|
407
|
+
- a ``csrf-failed`` problem carries
|
|
408
|
+
:data:`~rn_forge.web.auth.CSRF_FAILED_DETAIL` as its detail, whatever
|
|
409
|
+
*detail* says;
|
|
410
|
+
- when *exc* implements :class:`HasResponseHeaders`, its headers are
|
|
411
|
+
merged beneath *headers*, so an explicit *headers* entry wins.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
registry: The rows to render with.
|
|
415
|
+
exc: The exception being rendered.
|
|
416
|
+
instance: The ``instance`` member — in practice the request path.
|
|
417
|
+
problem: The row to use instead of resolving one from *exc*.
|
|
418
|
+
detail: Overrides the derived detail.
|
|
419
|
+
extensions: Extra members, flattened onto the body.
|
|
420
|
+
headers: Response headers to carry, e.g. a framework-built challenge.
|
|
421
|
+
realm: The ``realm`` of the challenge added to a 401.
|
|
422
|
+
|
|
423
|
+
Returns:
|
|
424
|
+
The response. Logging a 5xx is the caller's job.
|
|
425
|
+
"""
|
|
426
|
+
row = problem if problem is not None else registry.problem_for(exc)
|
|
427
|
+
body = registry.build(
|
|
428
|
+
exc,
|
|
429
|
+
instance=instance,
|
|
430
|
+
detail=_fixed_detail(row) or detail,
|
|
431
|
+
problem=row,
|
|
432
|
+
extensions={TRACE_ID_KEY: current_trace_id(), **(extensions or {})},
|
|
433
|
+
)
|
|
434
|
+
out: dict[str, str] = {}
|
|
435
|
+
if isinstance(exc, HasResponseHeaders):
|
|
436
|
+
out.update(exc.response_headers())
|
|
437
|
+
out.update(headers or {})
|
|
438
|
+
if (
|
|
439
|
+
row.status == 401
|
|
440
|
+
and getattr(exc, "challenge", True)
|
|
441
|
+
and not any(name.lower() == "www-authenticate" for name in out)
|
|
442
|
+
):
|
|
443
|
+
out["WWW-Authenticate"] = challenge_header(realm=realm)
|
|
444
|
+
return ProblemResponse(problem=body, headers=out)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _fixed_detail(row: ProblemType) -> str | None:
|
|
448
|
+
"""Return the detail a row must render whatever the caller supplied."""
|
|
449
|
+
if row.status == 401:
|
|
450
|
+
return AUTH_FAILED_DETAIL
|
|
451
|
+
return CSRF_FAILED_DETAIL if row == CSRF_FAILED else None
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def default_registry(*, type_base: str = "") -> ProblemRegistry:
|
|
455
|
+
"""Return a **fresh** registry carrying this package's exceptions.
|
|
456
|
+
|
|
457
|
+
A factory, never a shared module-level singleton: a consumer that mutated a
|
|
458
|
+
shared registry would change every other consumer's error bodies.
|
|
459
|
+
|
|
460
|
+
Args:
|
|
461
|
+
type_base: Forwarded to :class:`ProblemRegistry`.
|
|
462
|
+
"""
|
|
463
|
+
return (
|
|
464
|
+
ProblemRegistry(type_base=type_base)
|
|
465
|
+
.register(DomainConflict, CONFLICT)
|
|
466
|
+
.register(VersionConflict, PRECONDITION_FAILED)
|
|
467
|
+
.register(PreconditionRequired, PRECONDITION_REQUIRED)
|
|
468
|
+
.register(MalformedPrecondition, BAD_REQUEST)
|
|
469
|
+
.register(InvalidBatchGet, BAD_REQUEST)
|
|
470
|
+
.register(InvalidCursor, BAD_REQUEST)
|
|
471
|
+
.register(InvalidOrderBy, BAD_REQUEST)
|
|
472
|
+
.register(InvalidReadMask, BAD_REQUEST)
|
|
473
|
+
.register(IdempotencyKeyRequired, BAD_REQUEST)
|
|
474
|
+
.register(IdempotencyKeyReuse, VALIDATION_ERROR)
|
|
475
|
+
.register(IdempotencyKeyInFlight, CONFLICT)
|
|
476
|
+
.register(AuthenticationFailed, UNAUTHORIZED)
|
|
477
|
+
.register(PermissionDenied, FORBIDDEN)
|
|
478
|
+
.register(CsrfFailed, CSRF_FAILED)
|
|
479
|
+
.register(ItemsDenied, FORBIDDEN)
|
|
480
|
+
.register(RemoteProblem, BAD_GATEWAY)
|
|
481
|
+
.register(ContentTooLarge, CONTENT_TOO_LARGE)
|
|
482
|
+
.register(TooManyRequests, TOO_MANY_REQUESTS)
|
|
483
|
+
.register(UnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE)
|
|
484
|
+
.register(InvalidMergePatch, VALIDATION_ERROR)
|
|
485
|
+
.register(RowsInvalid, VALIDATION_ERROR)
|
|
486
|
+
.register(ServiceUnavailable, SERVICE_UNAVAILABLE)
|
|
487
|
+
.register(LookupError, NOT_FOUND)
|
|
488
|
+
.register(ValueError, VALIDATION_ERROR)
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def unmapped_exceptions(
|
|
493
|
+
registry: ProblemRegistry, *bases: type[BaseException]
|
|
494
|
+
) -> list[type[BaseException]]:
|
|
495
|
+
"""Return every subclass of *bases* that resolves to *registry*'s fallback.
|
|
496
|
+
|
|
497
|
+
Recursively walks ``__subclasses__()`` from each base. An application
|
|
498
|
+
calls this from a test or a readiness check to prove its exception table
|
|
499
|
+
is total — a domain error that resolves to the fallback becomes a 500 with
|
|
500
|
+
nothing to catch it.
|
|
501
|
+
|
|
502
|
+
Args:
|
|
503
|
+
registry: The registry to check resolution against.
|
|
504
|
+
bases: The exception base classes to walk subclasses of.
|
|
505
|
+
|
|
506
|
+
Returns:
|
|
507
|
+
The unmapped subclasses, sorted by qualified name.
|
|
508
|
+
"""
|
|
509
|
+
seen: set[type[BaseException]] = set()
|
|
510
|
+
for base in bases:
|
|
511
|
+
_collect_subclasses(base, seen)
|
|
512
|
+
rows = registry.rows()
|
|
513
|
+
unmapped = [
|
|
514
|
+
cls
|
|
515
|
+
for cls in seen
|
|
516
|
+
if _resolve(cls, rows, registry.fallback) is registry.fallback
|
|
517
|
+
]
|
|
518
|
+
return sorted(unmapped, key=lambda cls: f"{cls.__module__}.{cls.__qualname__}")
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _resolve(
|
|
522
|
+
cls: type[BaseException],
|
|
523
|
+
rows: Mapping[type[BaseException], ProblemType],
|
|
524
|
+
fallback: ProblemType,
|
|
525
|
+
) -> ProblemType:
|
|
526
|
+
"""Walk *cls*'s MRO for a registered row, mirroring :meth:`ProblemRegistry.problem_for`."""
|
|
527
|
+
for candidate in cls.__mro__:
|
|
528
|
+
row = rows.get(candidate)
|
|
529
|
+
if row is not None:
|
|
530
|
+
return row
|
|
531
|
+
return fallback
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _collect_subclasses(
|
|
535
|
+
cls: type[BaseException], out: set[type[BaseException]]
|
|
536
|
+
) -> None:
|
|
537
|
+
"""Depth-first collection of every strict subclass of *cls*."""
|
|
538
|
+
for sub in cls.__subclasses__():
|
|
539
|
+
out.add(sub)
|
|
540
|
+
_collect_subclasses(sub, out)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
REQUIRED_FIELD_DETAIL: Final = "This field is required."
|
|
544
|
+
"""The ``detail`` of a validation error for a missing field, on every stack."""
|
|
545
|
+
|
|
546
|
+
NULL_FIELD_DETAIL: Final = "This field may not be null."
|
|
547
|
+
"""The ``detail`` of a validation error for a ``null`` on a non-nullable field, on every stack."""
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def field_error(path: Iterable[object], detail: str) -> dict[str, str]:
|
|
551
|
+
"""Return one validation-error entry: ``{"pointer": ..., "detail": ...}``.
|
|
552
|
+
|
|
553
|
+
The shape is RFC 9457 §3's validation example; a framework binding builds
|
|
554
|
+
one per field message and puts the list under the ``errors`` extension.
|
|
555
|
+
|
|
556
|
+
Args:
|
|
557
|
+
path: The field's location, outermost first. Segments are escaped
|
|
558
|
+
per RFC 6901 §3; an empty path is the document root (``""``).
|
|
559
|
+
detail: The human-readable message for that field.
|
|
560
|
+
|
|
561
|
+
Example::
|
|
562
|
+
|
|
563
|
+
field_error(("items", 1, "qty"), "must be > 0")
|
|
564
|
+
# {"pointer": "/items/1/qty", "detail": "must be > 0"}
|
|
565
|
+
"""
|
|
566
|
+
escaped = [str(p).replace("~", "~0").replace("/", "~1") for p in path]
|
|
567
|
+
return {"pointer": "/" + "/".join(escaped) if escaped else "", "detail": detail}
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def problem_from_body(status: int, body: Mapping[str, Any]) -> ProblemDetail:
|
|
571
|
+
"""Parse an upstream ``application/problem+json`` body back into a problem.
|
|
572
|
+
|
|
573
|
+
Missing ``type`` defaults to ``about:blank``, missing ``status`` falls back
|
|
574
|
+
to *status*, and unknown members become extensions.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
status: The HTTP status of the response the body came from.
|
|
578
|
+
body: The decoded JSON object.
|
|
579
|
+
|
|
580
|
+
Returns:
|
|
581
|
+
The parsed problem.
|
|
582
|
+
"""
|
|
583
|
+
parsed_status = body.get("status")
|
|
584
|
+
return ProblemDetail.model_validate(
|
|
585
|
+
{
|
|
586
|
+
"type": str(body.get("type") or BLANK_TYPE),
|
|
587
|
+
"title": str(body.get("title") or ""),
|
|
588
|
+
"status": parsed_status if isinstance(parsed_status, int) else status,
|
|
589
|
+
"detail": str(body.get("detail") or ""),
|
|
590
|
+
"instance": str(body.get("instance") or ""),
|
|
591
|
+
"extensions": {k: v for k, v in body.items() if k not in _CORE_MEMBERS},
|
|
592
|
+
}
|
|
593
|
+
)
|
rn_forge/web/py.typed
ADDED
|
File without changes
|