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.

@@ -0,0 +1,134 @@
1
+ """The shapes a conformance case is written in, and the redaction rule."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Final, Literal, cast
8
+
9
+ __all__ = [
10
+ "REDACTED",
11
+ "VARIABLE_MEMBERS",
12
+ "ConformanceArea",
13
+ "ConformanceCapability",
14
+ "ConformanceCase",
15
+ "RequestSpec",
16
+ "redact",
17
+ ]
18
+
19
+ type ConformanceArea = Literal[
20
+ "problem",
21
+ "concurrency",
22
+ "pagination",
23
+ "idempotency",
24
+ "health",
25
+ "auth",
26
+ "casing",
27
+ "tracing",
28
+ "deprecation",
29
+ "discovery",
30
+ "security",
31
+ "cors",
32
+ "transfer",
33
+ "timestamps",
34
+ "operations",
35
+ "patch",
36
+ "read-mask",
37
+ "soft-delete",
38
+ ]
39
+ """Areas covered by the conformance suite."""
40
+
41
+ type ConformanceCapability = Literal["session-routes", "csrf"]
42
+ """An optional binding feature a case needs.
43
+
44
+ ``session-routes`` is a route that authenticates by cookie session only.
45
+ ``csrf`` is the CSRF check on unsafe methods of a session route.
46
+ """
47
+
48
+ REDACTED: Final = "<redacted>"
49
+ """What :func:`redact` substitutes for a member that legitimately varies."""
50
+
51
+ VARIABLE_MEMBERS: Final = frozenset({"instance", "traceId", "timestamp"})
52
+ """Body members that differ per request and must not be compared literally.
53
+
54
+ ``instance`` is the request path plus, in practice, an id the driver chose;
55
+ ``traceId`` is generated per request (or per trace, when a caller's
56
+ ``traceparent`` continues one); ``timestamp`` is the clock. Everything else in
57
+ a response body is part of the contract and is compared exactly.
58
+ """
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class RequestSpec:
63
+ """The request a driver must issue.
64
+
65
+ ``path`` is relative to whatever base the driver mounts the fixture app
66
+ at, and always begins with ``/``. A ``query`` value that is a tuple is a
67
+ repeated parameter, one occurrence per item.
68
+ """
69
+
70
+ method: str
71
+ path: str
72
+ headers: Mapping[str, str] = field(default_factory=dict[str, str])
73
+ query: Mapping[str, str | tuple[str, ...]] = field(
74
+ default_factory=dict[str, str | tuple[str, ...]]
75
+ )
76
+ body: Any = None
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class ConformanceCase:
81
+ """One wire decision, expressed as a request and the response it must get.
82
+
83
+ Header names are compared case-insensitively and values exactly. Bodies are
84
+ compared after :func:`redact`. ``depends_on`` names prerequisite requests
85
+ in execution order. ``requires`` names the optional capabilities a binding
86
+ must provide for the case to apply to it (see
87
+ :func:`~rn_forge.web.conformance.cases_provided_by`).
88
+ """
89
+
90
+ id: str
91
+ area: ConformanceArea
92
+ description: str
93
+ request: RequestSpec
94
+ expect_status: int
95
+ depends_on: tuple[str, ...] = ()
96
+ requires: frozenset[ConformanceCapability] = frozenset()
97
+ expect_headers: Mapping[str, str] = field(default_factory=dict[str, str])
98
+ expect_absent_headers: frozenset[str] = frozenset()
99
+ expect_body: Mapping[str, Any] = field(default_factory=dict[str, Any])
100
+ expect_header_patterns: Mapping[str, str] = field(default_factory=dict[str, str])
101
+ """Header name → regular expression, matched with ``re.fullmatch`` against
102
+ the header value. Header names are compared case-insensitively, as for
103
+ :attr:`expect_headers`. Used where the exact value is not deterministic
104
+ (a generated span id in ``traceresponse``)."""
105
+ expect_text: str | None = None
106
+ """The exact response body, for a case whose body is not JSON (a CSV
107
+ export). When set, :attr:`expect_body` is not compared."""
108
+
109
+
110
+ def redact(body: Mapping[str, Any]) -> dict[str, Any]:
111
+ """Blank the members that legitimately differ per request.
112
+
113
+ Recurses into nested mappings and lists, so a problem body's extensions and
114
+ a page's items are covered too. Idempotent: redacting an already-redacted
115
+ body returns the same thing, which is what makes it safe for a driver to
116
+ apply without knowing whether the table's expectation was already redacted.
117
+ """
118
+ return {k: _redact_value(k, v) for k, v in body.items()}
119
+
120
+
121
+ def _redact_value(key: str, value: Any) -> Any:
122
+ """Redact one member, recursing through containers."""
123
+ if key in VARIABLE_MEMBERS:
124
+ return REDACTED
125
+ if isinstance(value, Mapping):
126
+ return redact(cast("Mapping[str, Any]", value))
127
+ if isinstance(value, list):
128
+ return [
129
+ redact(cast("Mapping[str, Any]", item))
130
+ if isinstance(item, Mapping)
131
+ else item
132
+ for item in cast("list[Any]", value)
133
+ ]
134
+ return value
@@ -0,0 +1,37 @@
1
+ """Response headers marking an endpoint deprecated."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from email.utils import format_datetime
7
+
8
+ __all__ = ["deprecation_headers"]
9
+
10
+
11
+ def deprecation_headers(
12
+ *,
13
+ deprecated_at: datetime,
14
+ sunset: datetime | None = None,
15
+ link: str | None = None,
16
+ ) -> dict[str, str]:
17
+ """Return the headers marking a response's endpoint deprecated.
18
+
19
+ RFC 9745's ``Deprecation`` field carries *deprecated_at* as a
20
+ structured-field date (``@<epoch-seconds>``). RFC 8594's ``Sunset`` field
21
+ carries *sunset* as an HTTP-date, when given. *link* is emitted as
22
+ ``Link: <link>; rel="deprecation"``, RFC 9745's link relation.
23
+
24
+ Args:
25
+ deprecated_at: When the endpoint became deprecated.
26
+ sunset: When the endpoint stops being served. Omitted when unscheduled.
27
+ link: A URI for the deprecation notice.
28
+
29
+ Returns:
30
+ ``Deprecation``, and ``Sunset``/``Link`` when given.
31
+ """
32
+ headers = {"Deprecation": f"@{int(deprecated_at.timestamp())}"}
33
+ if sunset is not None:
34
+ headers["Sunset"] = format_datetime(sunset, usegmt=True)
35
+ if link is not None:
36
+ headers["Link"] = f'<{link}>; rel="deprecation"'
37
+ return headers
@@ -0,0 +1,386 @@
1
+ """Typed exceptions mapped to HTTP problems by the default registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping, Sequence
6
+ from typing import TYPE_CHECKING, Any, ClassVar
7
+
8
+ from rn_forge.commons.exceptions import AppException
9
+
10
+ if TYPE_CHECKING:
11
+ from rn_forge.web.problem import ProblemDetail
12
+ from rn_forge.web.transfer import RowError
13
+
14
+ __all__ = [
15
+ "AuthenticationFailed",
16
+ "ContentTooLarge",
17
+ "CsrfFailed",
18
+ "DomainConflict",
19
+ "IdempotencyKeyInFlight",
20
+ "IdempotencyKeyRequired",
21
+ "IdempotencyKeyReuse",
22
+ "InvalidBatchGet",
23
+ "InvalidCursor",
24
+ "InvalidMergePatch",
25
+ "InvalidOrderBy",
26
+ "InvalidReadMask",
27
+ "ItemsDenied",
28
+ "MalformedPrecondition",
29
+ "PermissionDenied",
30
+ "PreconditionRequired",
31
+ "RemoteProblem",
32
+ "ResourceDeleted",
33
+ "ResourceNotDeleted",
34
+ "RowsInvalid",
35
+ "ServiceUnavailable",
36
+ "SessionRequired",
37
+ "TooManyRequests",
38
+ "UnsupportedMediaType",
39
+ "VersionConflict",
40
+ "WebError",
41
+ ]
42
+
43
+
44
+ _UNSUPPORTED_MEDIA_TYPE_DETAIL = (
45
+ "Use Content-Type: application/merge-patch+json for PATCH"
46
+ )
47
+
48
+
49
+ class WebError(AppException):
50
+ """Base class for every exception this package raises."""
51
+
52
+
53
+ class DomainConflict(WebError):
54
+ """The request conflicts with the current state of the resource (409)."""
55
+
56
+
57
+ class ResourceDeleted(DomainConflict):
58
+ """The resource is soft-deleted and cannot be written (409).
59
+
60
+ Args:
61
+ label: The resource's display name, such as ``Note``.
62
+ id: The resource identifier.
63
+
64
+ The message is ``{label} {id} is deleted``.
65
+ """
66
+
67
+ def __init__(self, label: str, id: object, **error_data: Any) -> None:
68
+ super().__init__("{} {} is deleted", label, id, **error_data)
69
+
70
+
71
+ class ResourceNotDeleted(DomainConflict):
72
+ """The resource is live and cannot be undeleted (409).
73
+
74
+ Args:
75
+ label: The resource's display name, such as ``Note``.
76
+ id: The resource identifier.
77
+
78
+ The message is ``{label} {id} is not deleted``.
79
+ """
80
+
81
+ def __init__(self, label: str, id: object, **error_data: Any) -> None:
82
+ super().__init__("{} {} is not deleted", label, id, **error_data)
83
+
84
+
85
+ class _PointedError(WebError):
86
+ """A :class:`WebError` that may carry ``errors`` entries for the problem body.
87
+
88
+ Args:
89
+ *message_args: Forwarded to ``AppException``.
90
+ errors: Validation-error entries (see :func:`~rn_forge.web.field_error`)
91
+ emitted as the problem's ``errors`` member. ``None`` emits nothing.
92
+ **error_data: Forwarded to ``AppException``.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ *message_args: Any,
98
+ errors: Sequence[Mapping[str, str]] | None = None,
99
+ **error_data: Any,
100
+ ) -> None:
101
+ super().__init__(*message_args, **error_data)
102
+ self.errors = errors
103
+
104
+ def problem_extensions(self) -> Mapping[str, Any]:
105
+ """Return the ``errors`` member when one was given."""
106
+ return {} if self.errors is None else {"errors": list(self.errors)}
107
+
108
+
109
+ class VersionConflict(_PointedError):
110
+ """The client's precondition did not match the current version (412)."""
111
+
112
+
113
+ class PreconditionRequired(_PointedError):
114
+ """The route requires a precondition and the client sent none (428)."""
115
+
116
+
117
+ class MalformedPrecondition(_PointedError):
118
+ """The precondition header was present but could not be parsed (400)."""
119
+
120
+
121
+ class InvalidCursor(WebError):
122
+ """The pagination token was absent from, or malformed in, the request (400)."""
123
+
124
+
125
+ class InvalidBatchGet(WebError):
126
+ """A ``:batchGet`` request's ``ids`` parameter is missing or over the row cap (400)."""
127
+
128
+
129
+ class InvalidOrderBy(WebError):
130
+ """``orderBy`` names a field the endpoint cannot sort by, or is malformed (400)."""
131
+
132
+
133
+ class InvalidReadMask(WebError):
134
+ """``readMask`` combines ``*`` with other paths, or names an undeclared field (400)."""
135
+
136
+
137
+ class ContentTooLarge(WebError):
138
+ """The request body exceeds the configured size limit (413)."""
139
+
140
+
141
+ class UnsupportedMediaType(WebError):
142
+ """The request's media type is not one the route accepts (415).
143
+
144
+ The message defaults to ``Use Content-Type: application/merge-patch+json for PATCH``.
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ *message_args: Any,
150
+ **error_data: Any,
151
+ ) -> None:
152
+ super().__init__(
153
+ *(message_args or (_UNSUPPORTED_MEDIA_TYPE_DETAIL,)), **error_data
154
+ )
155
+
156
+ def response_headers(self) -> dict[str, str]:
157
+ """Return the ``Accept-Patch`` header (RFC 5789 section 2.2)."""
158
+ return {"Accept-Patch": "application/merge-patch+json"}
159
+
160
+
161
+ class InvalidMergePatch(WebError):
162
+ """A merge-patch body is not a JSON object (422).
163
+
164
+ The message defaults to ``A merge patch must be a JSON object.``
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ *message_args: Any,
170
+ **error_data: Any,
171
+ ) -> None:
172
+ super().__init__(
173
+ *(message_args or ("A merge patch must be a JSON object.",)), **error_data
174
+ )
175
+
176
+
177
+ class IdempotencyKeyRequired(WebError):
178
+ """The endpoint requires an ``Idempotency-Key`` and none was sent (400)."""
179
+
180
+
181
+ class IdempotencyKeyReuse(WebError):
182
+ """The idempotency key was replayed with a different request body (422)."""
183
+
184
+
185
+ class IdempotencyKeyInFlight(WebError):
186
+ """The idempotency key was claimed and its original request has not completed (409)."""
187
+
188
+
189
+ class AuthenticationFailed(WebError):
190
+ """No credentials were supplied, or they failed verification (401).
191
+
192
+ The message carries the reason for the binding to log; it must never reach
193
+ the response body, which renders :data:`~rn_forge.web.auth.AUTH_FAILED_DETAIL`.
194
+ The response carries a ``WWW-Authenticate`` challenge unless
195
+ :attr:`challenge` is false.
196
+ """
197
+
198
+ challenge: ClassVar[bool] = True
199
+ """Whether the 401 response carries a ``WWW-Authenticate`` challenge."""
200
+
201
+
202
+ class SessionRequired(AuthenticationFailed):
203
+ """A session-only route was called without a valid session (401).
204
+
205
+ The response carries no ``WWW-Authenticate`` header: a cookie session has
206
+ no registered authentication scheme to challenge with.
207
+ """
208
+
209
+ challenge: ClassVar[bool] = False
210
+
211
+
212
+ class CsrfFailed(WebError):
213
+ """The CSRF token or origin check rejected the request (403).
214
+
215
+ Not a :class:`PermissionDenied`, and rendered as its own problem type. The
216
+ message carries the reason for the
217
+ binding to log; it must never reach the response body, which renders
218
+ :data:`~rn_forge.web.auth.CSRF_FAILED_DETAIL`.
219
+ """
220
+
221
+
222
+ class PermissionDenied(WebError):
223
+ """Credentials verified, but the principal lacks the required access (403)."""
224
+
225
+
226
+ class ItemsDenied(PermissionDenied):
227
+ """Some items of a bulk request are not permitted (403).
228
+
229
+ Renders ``Forbidden`` with one ``errors`` entry per message, whose
230
+ ``pointer`` is ``/<root>/<index>`` (``/<root>/<index>/<field>`` for a
231
+ field-keyed entry).
232
+
233
+ Args:
234
+ errors: Messages by item index, or by item index then field name.
235
+ root: The first pointer segment, such as ``"requests"`` or ``"ids"``.
236
+
237
+ Example::
238
+
239
+ ItemsDenied({"1": ["You may not create this order."]}, root="requests")
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ errors: Mapping[str | int, Sequence[str] | Mapping[str, Sequence[str]]],
245
+ *,
246
+ root: str,
247
+ ) -> None:
248
+ super().__init__("Forbidden")
249
+ self.errors = errors
250
+ self.root = root
251
+
252
+ def problem_extensions(self) -> Mapping[str, Any]:
253
+ """Return the ``errors`` member."""
254
+ from rn_forge.web.problem import field_error # problem imports this module
255
+
256
+ entries: list[dict[str, str]] = []
257
+ for index, item in self.errors.items():
258
+ if isinstance(item, Mapping):
259
+ entries.extend(
260
+ field_error((self.root, index, field), message)
261
+ for field, messages in item.items()
262
+ for message in messages
263
+ )
264
+ else:
265
+ entries.extend(
266
+ field_error((self.root, index), message) for message in item
267
+ )
268
+ return {"errors": entries}
269
+
270
+
271
+ class RowsInvalid(WebError):
272
+ """One or more rows of an import or bulk request are invalid (422).
273
+
274
+ Renders ``One or more rows are invalid.`` with one ``errors`` entry per
275
+ failed cell, whose ``pointer`` is ``/<root>/<row>[/<field>]``.
276
+
277
+ Args:
278
+ errors: The failed cells.
279
+ root: The first pointer segment.
280
+ """
281
+
282
+ def __init__(self, errors: Iterable[RowError], *, root: str = "rows") -> None:
283
+ super().__init__("One or more rows are invalid.")
284
+ self.errors = tuple(errors)
285
+ self.root = root
286
+
287
+ def problem_extensions(self) -> Mapping[str, Any]:
288
+ """Return the ``errors`` member."""
289
+ from rn_forge.web.problem import field_error # problem imports this module
290
+
291
+ return {
292
+ "errors": [
293
+ field_error(
294
+ (self.root, e.row, *([e.field] if e.field else [])), e.message
295
+ )
296
+ for e in self.errors
297
+ ]
298
+ }
299
+
300
+
301
+ class TooManyRequests(WebError):
302
+ """The client has sent too many requests in a given time (429).
303
+
304
+ Args:
305
+ *message_args: Forwarded to ``AppException``.
306
+ retry_after: Seconds the client should wait before retrying, carried
307
+ as a ``Retry-After`` response header. ``None`` sends no header.
308
+ **error_data: Forwarded to ``AppException``.
309
+ """
310
+
311
+ retry_after: int | None
312
+
313
+ def __init__(
314
+ self,
315
+ *message_args: Any,
316
+ retry_after: int | None = None,
317
+ **error_data: Any,
318
+ ) -> None:
319
+ super().__init__(*message_args, **error_data)
320
+ self.retry_after = retry_after
321
+
322
+ def response_headers(self) -> dict[str, str]:
323
+ """Return the ``Retry-After`` header, or nothing when unset."""
324
+ return (
325
+ {} if self.retry_after is None else {"Retry-After": str(self.retry_after)}
326
+ )
327
+
328
+
329
+ class ServiceUnavailable(WebError):
330
+ """The service cannot handle the request right now (503).
331
+
332
+ Args:
333
+ *message_args: Forwarded to ``AppException``.
334
+ retry_after: Seconds the client should wait before retrying, carried
335
+ as a ``Retry-After`` response header. ``None`` sends no header.
336
+ **error_data: Forwarded to ``AppException``.
337
+ """
338
+
339
+ retry_after: int | None
340
+
341
+ def __init__(
342
+ self,
343
+ *message_args: Any,
344
+ retry_after: int | None = None,
345
+ **error_data: Any,
346
+ ) -> None:
347
+ super().__init__(*message_args, **error_data)
348
+ self.retry_after = retry_after
349
+
350
+ def response_headers(self) -> dict[str, str]:
351
+ """Return the ``Retry-After`` header, or nothing when unset."""
352
+ return (
353
+ {} if self.retry_after is None else {"Retry-After": str(self.retry_after)}
354
+ )
355
+
356
+
357
+ class RemoteProblem(WebError):
358
+ """An upstream service returned an ``application/problem+json`` body.
359
+
360
+ Carries the parsed :class:`~rn_forge.web.problem.ProblemDetail` so a gateway
361
+ can re-emit the upstream's slug rather than flattening every upstream
362
+ failure into "internal error".
363
+
364
+ Args:
365
+ problem: The parsed upstream problem.
366
+ *message_args: Forwarded to ``AppException``.
367
+ **error_data: Forwarded to ``AppException``.
368
+ """
369
+
370
+ problem: ProblemDetail
371
+
372
+ def __init__(
373
+ self,
374
+ problem: ProblemDetail,
375
+ *message_args: Any,
376
+ **error_data: Any,
377
+ ) -> None:
378
+ error_data.setdefault("error_code", problem.status)
379
+ super().__init__(
380
+ "Upstream returned a problem: {} ({})",
381
+ problem.title,
382
+ problem.status,
383
+ *message_args,
384
+ **error_data,
385
+ )
386
+ self.problem = problem