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
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The ``readMask`` query parameter: partial responses (AIP-157)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Final, cast
|
|
8
|
+
|
|
9
|
+
from rn_forge.web.exceptions import InvalidReadMask
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"READ_MASK_PARAM",
|
|
13
|
+
"FieldTree",
|
|
14
|
+
"ReadMask",
|
|
15
|
+
"parse_read_mask",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
READ_MASK_PARAM: Final = "readMask"
|
|
19
|
+
"""The name of the query parameter that carries the mask."""
|
|
20
|
+
|
|
21
|
+
type FieldTree = Mapping[str, FieldTree | None]
|
|
22
|
+
"""The declared shape of a representation, by wire field name.
|
|
23
|
+
|
|
24
|
+
A declared object, or a list of declared objects, maps to a subtree. Every
|
|
25
|
+
other field maps to ``None``, including a free-form JSON value.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
type _MaskTree = Mapping[str, _MaskTree | None]
|
|
29
|
+
|
|
30
|
+
_WHOLE: Final = "*"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class ReadMask:
|
|
35
|
+
"""A validated, merged set of field paths.
|
|
36
|
+
|
|
37
|
+
*tree* maps each selected wire field name to a subtree of selected
|
|
38
|
+
sub-fields, or to ``None`` when the whole value is selected.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
tree: _MaskTree
|
|
42
|
+
|
|
43
|
+
def apply(self, body: Mapping[str, Any]) -> dict[str, Any]:
|
|
44
|
+
"""Return a copy of *body* holding only the selected fields.
|
|
45
|
+
|
|
46
|
+
A path through a list applies to every element. A selected field that
|
|
47
|
+
*body* lacks is not added.
|
|
48
|
+
"""
|
|
49
|
+
return _prune(body, self.tree)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_read_mask(raw: str | None, *, fields: FieldTree) -> ReadMask | None:
|
|
53
|
+
"""Parse a ``readMask`` value against the declared fields of a representation.
|
|
54
|
+
|
|
55
|
+
Paths are comma-separated and joined by ``.``; whitespace around a path is
|
|
56
|
+
ignored. Overlapping paths merge, so ``address`` and
|
|
57
|
+
``address.city`` select the whole ``address``.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
raw: The raw query value.
|
|
61
|
+
fields: The declared shape of the representation.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
``None`` when *raw* is absent, blank or ``*``: the whole representation.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
InvalidReadMask: ``*`` is combined with other paths, or a path is empty
|
|
68
|
+
or names no declared field, including one that goes inside a scalar
|
|
69
|
+
or free-form field.
|
|
70
|
+
"""
|
|
71
|
+
if not raw or not raw.strip():
|
|
72
|
+
return None
|
|
73
|
+
paths = [part.strip() for part in raw.split(",")]
|
|
74
|
+
if _WHOLE in paths:
|
|
75
|
+
if len(paths) > 1:
|
|
76
|
+
raise InvalidReadMask("readMask '*' cannot be combined with other paths")
|
|
77
|
+
return None
|
|
78
|
+
tree: dict[str, Any] = {}
|
|
79
|
+
for path in paths:
|
|
80
|
+
_add(tree, path, fields)
|
|
81
|
+
return ReadMask(tree)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _add(tree: dict[str, Any], path: str, fields: FieldTree) -> None:
|
|
85
|
+
"""Merge *path* into *tree*, raising if it names no declared field."""
|
|
86
|
+
node: dict[str, Any] | None = tree
|
|
87
|
+
declared: FieldTree | None = fields
|
|
88
|
+
segments = path.split(".")
|
|
89
|
+
for position, segment in enumerate(segments):
|
|
90
|
+
if declared is None or segment not in declared:
|
|
91
|
+
raise InvalidReadMask(f"Unknown readMask path '{path}'")
|
|
92
|
+
declared = declared[segment]
|
|
93
|
+
if node is None:
|
|
94
|
+
continue
|
|
95
|
+
if position == len(segments) - 1:
|
|
96
|
+
node[segment] = None
|
|
97
|
+
else:
|
|
98
|
+
node = node.setdefault(segment, {})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _prune(body: Mapping[str, Any], tree: _MaskTree) -> dict[str, Any]:
|
|
102
|
+
"""Keep the members of *body* that *tree* selects."""
|
|
103
|
+
kept: dict[str, Any] = {}
|
|
104
|
+
for name, value in body.items():
|
|
105
|
+
if name not in tree:
|
|
106
|
+
continue
|
|
107
|
+
subtree = tree[name]
|
|
108
|
+
if subtree is None:
|
|
109
|
+
kept[name] = value
|
|
110
|
+
elif isinstance(value, Mapping):
|
|
111
|
+
kept[name] = _prune(cast("Mapping[str, Any]", value), subtree)
|
|
112
|
+
elif isinstance(value, list):
|
|
113
|
+
kept[name] = [
|
|
114
|
+
_prune(cast("Mapping[str, Any]", item), subtree)
|
|
115
|
+
if isinstance(item, Mapping)
|
|
116
|
+
else item
|
|
117
|
+
for item in cast("list[Any]", value)
|
|
118
|
+
]
|
|
119
|
+
else:
|
|
120
|
+
kept[name] = value
|
|
121
|
+
return kept
|
rn_forge/web/security.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""OWASP REST Security Cheat Sheet response headers, via the ``secure`` library.
|
|
2
|
+
|
|
3
|
+
**Requires the ``security`` extra.** Not re-exported from the package facade;
|
|
4
|
+
import it directly.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
import secure
|
|
13
|
+
from rn_forge.web.asgi import ASGIApp, Message, Receive, Scope, Send
|
|
14
|
+
|
|
15
|
+
__all__ = ["API_SECURITY_HEADERS", "HSTS_HEADER", "SecurityHeadersMiddleware"]
|
|
16
|
+
|
|
17
|
+
_PRESET: Final = secure.Secure(
|
|
18
|
+
cache=secure.CacheControl().no_store(),
|
|
19
|
+
csp=secure.ContentSecurityPolicy().frame_ancestors("'none'"),
|
|
20
|
+
xcto=secure.XContentTypeOptions(),
|
|
21
|
+
xfo=secure.XFrameOptions().deny(),
|
|
22
|
+
referrer=secure.ReferrerPolicy().no_referrer(),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
API_SECURITY_HEADERS: Final[Mapping[str, str]] = dict(_PRESET.header_items())
|
|
26
|
+
"""The OWASP REST Security Cheat Sheet response headers, HSTS excluded.
|
|
27
|
+
|
|
28
|
+
``Strict-Transport-Security`` is HTTPS-deployment-specific and is each stack's
|
|
29
|
+
own opt-in flag rather than part of this preset.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
_HSTS_PRESET: Final = secure.Secure(
|
|
33
|
+
hsts=secure.StrictTransportSecurity().max_age(31_536_000).include_subdomains()
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
HSTS_HEADER: Final[Mapping[str, str]] = dict(_HSTS_PRESET.header_items())
|
|
37
|
+
"""``Strict-Transport-Security``, a year, including subdomains.
|
|
38
|
+
|
|
39
|
+
Added only when a stack's ``hsts`` flag is set — an HTTP deployment that sent
|
|
40
|
+
it would be telling browsers to refuse a future plaintext connection.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SecurityHeadersMiddleware:
|
|
45
|
+
"""Pure-ASGI middleware stamping :data:`API_SECURITY_HEADERS` on every response.
|
|
46
|
+
|
|
47
|
+
Uses ``setdefault`` semantics: a header name the downstream application
|
|
48
|
+
already set is left alone, so a route's own ``Cache-Control`` wins.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
app: The downstream ASGI application.
|
|
52
|
+
headers: The headers to set. Defaults to :data:`API_SECURITY_HEADERS`.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self, app: ASGIApp, *, headers: Mapping[str, str] = API_SECURITY_HEADERS
|
|
57
|
+
) -> None:
|
|
58
|
+
self.app = app
|
|
59
|
+
self.headers = headers
|
|
60
|
+
|
|
61
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
62
|
+
"""Run the middleware for one connection."""
|
|
63
|
+
if scope.get("type") != "http":
|
|
64
|
+
await self.app(scope, receive, send)
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
async def send_wrapper(message: Message) -> None:
|
|
68
|
+
if message.get("type") == "http.response.start":
|
|
69
|
+
_setdefault_headers(message, self.headers)
|
|
70
|
+
await send(message)
|
|
71
|
+
|
|
72
|
+
await self.app(scope, receive, send_wrapper)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _existing_headers(raw: object) -> list[tuple[bytes, bytes]]:
|
|
76
|
+
"""Return *raw* as a well-formed list of ASGI header pairs, or an empty one."""
|
|
77
|
+
existing: list[tuple[bytes, bytes]] = []
|
|
78
|
+
if not isinstance(raw, list):
|
|
79
|
+
return existing
|
|
80
|
+
for entry in raw: # pyright: ignore[reportUnknownVariableType]
|
|
81
|
+
if not isinstance(entry, (tuple, list)) or len(entry) != 2: # pyright: ignore[reportUnknownArgumentType]
|
|
82
|
+
continue
|
|
83
|
+
key, value = entry # pyright: ignore[reportUnknownVariableType]
|
|
84
|
+
if isinstance(key, bytes) and isinstance(value, bytes):
|
|
85
|
+
existing.append((key, value))
|
|
86
|
+
return existing
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _setdefault_headers(message: Message, headers: Mapping[str, str]) -> None:
|
|
90
|
+
"""Append each header in *headers* to *message*, skipping names already present."""
|
|
91
|
+
existing = _existing_headers(message.get("headers"))
|
|
92
|
+
present = {key.lower() for key, _value in existing}
|
|
93
|
+
for name, value in headers.items():
|
|
94
|
+
wanted = name.lower().encode("latin-1")
|
|
95
|
+
if wanted not in present:
|
|
96
|
+
existing.append((name.encode("latin-1"), value.encode("latin-1")))
|
|
97
|
+
message["headers"] = existing
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Soft delete: the ``showDeleted`` parameter and the live-resource guard (AIP-164)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
from rn_forge.web.exceptions import ResourceDeleted
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"SHOW_DELETED_PARAM",
|
|
12
|
+
"require_live",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
SHOW_DELETED_PARAM: Final = "showDeleted"
|
|
16
|
+
"""The name of the query parameter that includes soft-deleted resources in a list."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def require_live(delete_time: datetime | None, *, label: str, id: object) -> None:
|
|
20
|
+
"""Raise :class:`~rn_forge.web.ResourceDeleted` when the resource is soft-deleted.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
delete_time: The resource's ``delete_time``; ``None`` while it is live.
|
|
24
|
+
label: The resource's display name, such as ``Note``.
|
|
25
|
+
id: The resource identifier.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
ResourceDeleted: *delete_time* is not ``None``.
|
|
29
|
+
"""
|
|
30
|
+
if delete_time is not None:
|
|
31
|
+
raise ResourceDeleted(label, id)
|
rn_forge/web/tracing.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""W3C Trace Context: the current trace and span ids.
|
|
2
|
+
|
|
3
|
+
The current trace is read from OpenTelemetry's active span. This module never
|
|
4
|
+
configures a ``TracerProvider`` or an exporter — those are the application's
|
|
5
|
+
job (or ``opentelemetry-instrument``'s), per OpenTelemetry's own library
|
|
6
|
+
guidance.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
from opentelemetry import trace
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"EXPOSED_HEADERS",
|
|
17
|
+
"TRACE_ID_KEY",
|
|
18
|
+
"current_span_id",
|
|
19
|
+
"current_trace_id",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
TRACE_ID_KEY: Final = "traceId"
|
|
23
|
+
"""The problem-body extension member that carries the current trace id."""
|
|
24
|
+
|
|
25
|
+
EXPOSED_HEADERS: Final[tuple[str, ...]] = (
|
|
26
|
+
"ETag",
|
|
27
|
+
"Link",
|
|
28
|
+
"Location",
|
|
29
|
+
"Retry-After",
|
|
30
|
+
"Deprecation",
|
|
31
|
+
"Sunset",
|
|
32
|
+
"Content-Disposition",
|
|
33
|
+
)
|
|
34
|
+
"""Response headers this kit emits that a browser can read only when a CORS
|
|
35
|
+
policy names them in ``Access-Control-Expose-Headers``.
|
|
36
|
+
|
|
37
|
+
An application's own CORS configuration does not know what the kit emits; a
|
|
38
|
+
CORS binding passes this list so the kit's own concurrency, discovery and
|
|
39
|
+
retry contracts survive a browser client. ``traceresponse`` is not listed
|
|
40
|
+
here: the OpenTelemetry response propagator exposes it itself.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def current_trace_id() -> str | None:
|
|
45
|
+
"""Return the current span's trace id, or ``None`` when no span is recording."""
|
|
46
|
+
ctx = trace.get_current_span().get_span_context()
|
|
47
|
+
return format(ctx.trace_id, "032x") if ctx.is_valid else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def current_span_id() -> str | None:
|
|
51
|
+
"""Return the current span's id, or ``None`` when no span is recording."""
|
|
52
|
+
ctx = trace.get_current_span().get_span_context()
|
|
53
|
+
return format(ctx.span_id, "016x") if ctx.is_valid else None
|