pboot-kernel 1.10.0.1__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.
@@ -0,0 +1,254 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncGenerator, AsyncIterable, Awaitable, Callable, Mapping, MutableMapping
4
+ from contextlib import aclosing
5
+ from typing import Any, TypeVar
6
+
7
+ import anyio
8
+
9
+ from kernel._utils import create_collapsing_task_group
10
+ from kernel.requests import ClientDisconnect, Request
11
+ from kernel.responses import Response
12
+ from kernel.types import ASGIApp, Message, Receive, Scope, Send
13
+
14
+ RequestResponseEndpoint = Callable[[Request], Awaitable[Response]]
15
+ DispatchFunction = Callable[[Request, RequestResponseEndpoint], Awaitable[Response]]
16
+ BodyStreamGenerator = AsyncGenerator[bytes | MutableMapping[str, Any], None]
17
+ AsyncContentStream = AsyncIterable[str | bytes | memoryview | MutableMapping[str, Any]]
18
+ T = TypeVar("T")
19
+
20
+
21
+ class _CachedRequest(Request):
22
+ """
23
+ If the user calls Request.body() from their dispatch function
24
+ we cache the entire request body in memory and pass that to downstream middlewares,
25
+ but if they call Request.stream() then all we do is send an
26
+ empty body so that downstream things don't hang forever.
27
+ """
28
+
29
+ def __init__(self, scope: Scope, receive: Receive, send: Send):
30
+ super().__init__(scope, receive, send)
31
+ self._wrapped_rcv_disconnected = False
32
+ self._wrapped_rcv_consumed = False
33
+
34
+ async def wrapped_receive(self) -> Message:
35
+ # wrapped_rcv state 1: disconnected
36
+ if self._wrapped_rcv_disconnected:
37
+ # we've already sent a disconnect to the downstream app
38
+ # we don't need to wait to get another one
39
+ # (although most ASGI servers will just keep sending it)
40
+ return {"type": "http.disconnect"}
41
+ # wrapped_rcv state 1: consumed but not yet disconnected
42
+ if self._wrapped_rcv_consumed:
43
+ # since the downstream app has consumed us all that is left
44
+ # is to send it a disconnect
45
+ if self._is_disconnected:
46
+ # the middleware has already seen the disconnect
47
+ # since we know the client is disconnected no need to wait
48
+ # for the message
49
+ self._wrapped_rcv_disconnected = True
50
+ return {"type": "http.disconnect"}
51
+ # we don't know yet if the client is disconnected or not
52
+ # so we'll wait until we get that message
53
+ msg = await self.receive()
54
+ if msg["type"] != "http.disconnect": # pragma: no cover
55
+ # at this point a disconnect is all that we should be receiving
56
+ # if we get something else, things went wrong somewhere
57
+ raise RuntimeError(f"Unexpected message received: {msg['type']}")
58
+ self._wrapped_rcv_disconnected = True
59
+ return msg
60
+
61
+ # wrapped_rcv state 3: not yet consumed
62
+ if getattr(self, "_body", None) is not None:
63
+ # body() was called, we return it even if the client disconnected
64
+ self._wrapped_rcv_consumed = True
65
+ return {
66
+ "type": "http.request",
67
+ "body": self._body,
68
+ "more_body": False,
69
+ }
70
+ elif self._stream_consumed:
71
+ # stream() was called to completion
72
+ # return an empty body so that downstream apps don't hang
73
+ # waiting for a disconnect
74
+ self._wrapped_rcv_consumed = True
75
+ return {
76
+ "type": "http.request",
77
+ "body": b"",
78
+ "more_body": False,
79
+ }
80
+ else:
81
+ # body() was never called and stream() wasn't consumed
82
+ try:
83
+ async with aclosing(self.stream()) as stream:
84
+ chunk = await stream.__anext__()
85
+ self._wrapped_rcv_consumed = self._stream_consumed
86
+ return {
87
+ "type": "http.request",
88
+ "body": chunk,
89
+ "more_body": not self._stream_consumed,
90
+ }
91
+ except ClientDisconnect:
92
+ self._wrapped_rcv_disconnected = True
93
+ return {"type": "http.disconnect"}
94
+
95
+
96
+ class BaseHTTPMiddleware:
97
+ def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
98
+ self.app = app
99
+ self.dispatch_func = self.dispatch if dispatch is None else dispatch
100
+
101
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
102
+ if scope["type"] != "http":
103
+ await self.app(scope, receive, send)
104
+ return
105
+
106
+ request = _CachedRequest(scope, receive, send)
107
+ wrapped_receive = request.wrapped_receive
108
+ response_sent = anyio.Event()
109
+ app_exc: Exception | None = None
110
+ exception_already_raised = False
111
+
112
+ async def call_next(request: Request) -> Response:
113
+ async def receive_or_disconnect() -> Message:
114
+ if response_sent.is_set():
115
+ return {"type": "http.disconnect"}
116
+
117
+ async with anyio.create_task_group() as task_group:
118
+
119
+ async def wrap(func: Callable[[], Awaitable[T]]) -> T:
120
+ result = await func()
121
+ task_group.cancel_scope.cancel()
122
+ return result
123
+
124
+ task_group.start_soon(wrap, response_sent.wait)
125
+ message = await wrap(wrapped_receive)
126
+
127
+ if response_sent.is_set():
128
+ return {"type": "http.disconnect"}
129
+
130
+ return message
131
+
132
+ async def send_no_error(message: Message) -> None:
133
+ try:
134
+ await send_stream.send(message)
135
+ except anyio.BrokenResourceError:
136
+ # recv_stream has been closed, i.e. response_sent has been set.
137
+ return
138
+
139
+ if message["type"] == "http.response.pathsend" or (
140
+ message["type"] == "http.response.body" and not message.get("more_body", False)
141
+ ):
142
+ await response_sent.wait()
143
+
144
+ async def coro() -> None:
145
+ nonlocal app_exc
146
+
147
+ with send_stream:
148
+ try:
149
+ await self.app(scope, receive_or_disconnect, send_no_error)
150
+ except Exception as exc:
151
+ app_exc = exc
152
+
153
+ task_group.start_soon(coro)
154
+
155
+ try:
156
+ info = None
157
+ while True:
158
+ message = await recv_stream.receive()
159
+ if message["type"] == "http.response.debug":
160
+ info = message["info"]
161
+ continue
162
+ elif message["type"] == "http.response.early_hint":
163
+ await send(message)
164
+ continue
165
+ break
166
+ except anyio.EndOfStream:
167
+ if app_exc is not None:
168
+ nonlocal exception_already_raised
169
+ exception_already_raised = True
170
+ # Prevent `anyio.EndOfStream` from polluting app exception context.
171
+ # If both cause and context are None then the context is suppressed
172
+ # and `anyio.EndOfStream` is not present in the exception traceback.
173
+ # If exception cause is not None then it is propagated with
174
+ # reraising here.
175
+ # If exception has no cause but has context set then the context is
176
+ # propagated as a cause with the reraise. This is necessary in order
177
+ # to prevent `anyio.EndOfStream` from polluting the exception
178
+ # context.
179
+ raise app_exc from app_exc.__cause__ or app_exc.__context__
180
+ raise RuntimeError("No response returned.")
181
+
182
+ assert message["type"] == "http.response.start"
183
+
184
+ async def body_stream() -> BodyStreamGenerator:
185
+ async for message in recv_stream:
186
+ if message["type"] == "http.response.pathsend":
187
+ yield message
188
+ break
189
+ assert message["type"] == "http.response.body", f"Unexpected message: {message}"
190
+ body = message.get("body", b"")
191
+ if body:
192
+ yield body
193
+ if not message.get("more_body", False):
194
+ break
195
+
196
+ response = _StreamingResponse(status_code=message["status"], content=body_stream(), info=info)
197
+ response.raw_headers = message.get("headers", [])
198
+ return response
199
+
200
+ send_stream, recv_stream = anyio.create_memory_object_stream[Message]()
201
+ with recv_stream, send_stream:
202
+ async with create_collapsing_task_group() as task_group:
203
+ response = await self.dispatch_func(request, call_next)
204
+ await response(scope, wrapped_receive, send)
205
+ response_sent.set()
206
+ recv_stream.close()
207
+ if app_exc is not None and not exception_already_raised:
208
+ raise app_exc
209
+
210
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
211
+ raise NotImplementedError() # pragma: no cover
212
+
213
+
214
+ class _StreamingResponse(Response):
215
+ def __init__(
216
+ self,
217
+ content: AsyncContentStream,
218
+ status_code: int = 200,
219
+ headers: Mapping[str, str] | None = None,
220
+ media_type: str | None = None,
221
+ info: Mapping[str, Any] | None = None,
222
+ ) -> None:
223
+ self.info = info
224
+ self.body_iterator = content
225
+ self.status_code = status_code
226
+ self.media_type = media_type
227
+ self.init_headers(headers)
228
+ self.background = None
229
+
230
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
231
+ if self.info is not None:
232
+ await send({"type": "http.response.debug", "info": self.info})
233
+ await send(
234
+ {
235
+ "type": "http.response.start",
236
+ "status": self.status_code,
237
+ "headers": self.raw_headers,
238
+ }
239
+ )
240
+
241
+ should_close_body = True
242
+ async for chunk in self.body_iterator:
243
+ if isinstance(chunk, dict):
244
+ # We got an ASGI message which is not response body (eg: pathsend)
245
+ should_close_body = False
246
+ await send(chunk)
247
+ continue
248
+ await send({"type": "http.response.body", "body": chunk, "more_body": True})
249
+
250
+ if should_close_body:
251
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
252
+
253
+ if self.background:
254
+ await self.background()
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import cast
4
+
5
+ from kernel.datastructures import Headers
6
+ from kernel.exceptions import HTTPException
7
+ from kernel.responses import PlainTextResponse
8
+ from kernel.types import ASGIApp, Message, Receive, Scope, Send
9
+
10
+ MAX_BODY_SIZE_SCOPE_KEY = "starlette.max_body_size"
11
+ _BODY_LIMIT_RESPONDER_SCOPE_KEY = "starlette._body_limit_responder"
12
+
13
+
14
+ class _Missing:
15
+ __slots__ = ()
16
+
17
+
18
+ _MISSING = _Missing()
19
+
20
+
21
+ class _RequestBodyTooLarge(HTTPException):
22
+ def __init__(self) -> None:
23
+ super().__init__(status_code=413, detail="Content Too Large")
24
+
25
+
26
+ class _RequestBodyLimitResponseSent(Exception):
27
+ pass
28
+
29
+
30
+ class RequestBodyLimitMiddleware:
31
+ """Limit the total size of an HTTP request body."""
32
+
33
+ def __init__(self, app: ASGIApp, max_body_size: int) -> None:
34
+ self.app = app
35
+ self.max_body_size = max_body_size
36
+
37
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
38
+ if scope["type"] != "http":
39
+ return await self.app(scope, receive, send)
40
+
41
+ responder = RequestBodyLimitResponder(self.app, self.max_body_size)
42
+ await responder(scope, receive, send)
43
+
44
+
45
+ class RequestBodyLimitResponder:
46
+ def __init__(self, app: ASGIApp, max_body_size: int) -> None:
47
+ self.app = app
48
+ self.max_body_size = max_body_size
49
+ self._scope: Scope | None = None
50
+ self._receive: Receive | None = None
51
+ self._send: Send | None = None
52
+ self.content_length: int | None = None
53
+ self.total_size = 0
54
+ self.response_started = False
55
+
56
+ @property
57
+ def scope(self) -> Scope:
58
+ assert self._scope is not None
59
+ return self._scope
60
+
61
+ @property
62
+ def receive(self) -> Receive:
63
+ assert self._receive is not None
64
+ return self._receive
65
+
66
+ @property
67
+ def send(self) -> Send:
68
+ assert self._send is not None
69
+ return self._send
70
+
71
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
72
+ previous_scope_limit = cast(int | _Missing, scope.get(MAX_BODY_SIZE_SCOPE_KEY, _MISSING))
73
+ scope[MAX_BODY_SIZE_SCOPE_KEY] = self.max_body_size
74
+
75
+ active_responder = cast(RequestBodyLimitResponder | None, scope.get(_BODY_LIMIT_RESPONDER_SCOPE_KEY))
76
+ if active_responder is not None:
77
+ active_responder.max_body_size = self.max_body_size
78
+ if active_responder.total_size > active_responder.max_body_size:
79
+ raise _RequestBodyTooLarge
80
+ return await self.app(scope, receive, send)
81
+
82
+ self._scope = scope
83
+ self._receive = receive
84
+ self._send = send
85
+ self.content_length = _get_content_length(scope)
86
+ scope[_BODY_LIMIT_RESPONDER_SCOPE_KEY] = self
87
+
88
+ try:
89
+ await self.app(scope, self.receive_with_limit, self.send_with_limit)
90
+ except _RequestBodyTooLarge:
91
+ if self.response_started:
92
+ raise
93
+ response = PlainTextResponse("Content Too Large", status_code=413)
94
+ await response(scope, receive, send)
95
+ except _RequestBodyLimitResponseSent:
96
+ pass
97
+ finally:
98
+ scope.pop(_BODY_LIMIT_RESPONDER_SCOPE_KEY, None)
99
+ if isinstance(previous_scope_limit, _Missing):
100
+ scope.pop(MAX_BODY_SIZE_SCOPE_KEY, None)
101
+ else:
102
+ scope[MAX_BODY_SIZE_SCOPE_KEY] = previous_scope_limit
103
+
104
+ async def receive_with_limit(self) -> Message:
105
+ if self.content_length is not None and self.content_length > self.max_body_size:
106
+ raise _RequestBodyTooLarge
107
+
108
+ message = await self.receive()
109
+ if message["type"] == "http.request":
110
+ self.total_size += len(message.get("body", b""))
111
+ if self.total_size > self.max_body_size:
112
+ raise _RequestBodyTooLarge
113
+ return message
114
+
115
+ async def send_with_limit(self, message: Message) -> None:
116
+ if message["type"] == "http.response.start":
117
+ self.response_started = True
118
+ if self.content_length is not None and self.content_length > self.max_body_size:
119
+ response = PlainTextResponse("Content Too Large", status_code=413)
120
+ await response(self.scope, self.receive, self.send)
121
+ raise _RequestBodyLimitResponseSent
122
+ await self.send(message)
123
+
124
+
125
+ def _get_content_length(scope: Scope) -> int | None:
126
+ content_length = Headers(scope=scope).get("content-length")
127
+ if content_length is None:
128
+ return None
129
+ try:
130
+ return int(content_length)
131
+ except ValueError:
132
+ return None
@@ -0,0 +1,177 @@
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import re
5
+ from collections.abc import Collection
6
+
7
+ from kernel.datastructures import Headers, MutableHeaders
8
+ from kernel.responses import PlainTextResponse, Response
9
+ from kernel.types import ASGIApp, Message, Receive, Scope, Send
10
+
11
+ ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "QUERY")
12
+ SAFELISTED_HEADERS = {"Accept", "Accept-Language", "Content-Language", "Content-Type"}
13
+
14
+
15
+ class CORSMiddleware:
16
+ def __init__(
17
+ self,
18
+ app: ASGIApp,
19
+ allow_origins: Collection[str] = (),
20
+ allow_methods: Collection[str] = ("GET",),
21
+ allow_headers: Collection[str] = (),
22
+ allow_credentials: bool = False,
23
+ allow_origin_regex: str | None = None,
24
+ allow_private_network: bool = False,
25
+ expose_headers: Collection[str] = (),
26
+ max_age: int = 600,
27
+ ) -> None:
28
+ if "*" in allow_methods:
29
+ allow_methods = ALL_METHODS
30
+
31
+ compiled_allow_origin_regex = None
32
+ if allow_origin_regex is not None:
33
+ compiled_allow_origin_regex = re.compile(allow_origin_regex)
34
+
35
+ allow_all_origins = "*" in allow_origins
36
+ allow_all_headers = "*" in allow_headers
37
+ preflight_explicit_allow_origin = not allow_all_origins or allow_credentials
38
+
39
+ simple_headers: dict[str, str] = {}
40
+ if allow_all_origins:
41
+ simple_headers["Access-Control-Allow-Origin"] = "*"
42
+ if allow_credentials:
43
+ simple_headers["Access-Control-Allow-Credentials"] = "true"
44
+ if expose_headers:
45
+ simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers)
46
+
47
+ preflight_headers: dict[str, str] = {
48
+ "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network" # noqa: E501 # fmt: skip
49
+ }
50
+ if not preflight_explicit_allow_origin:
51
+ preflight_headers["Access-Control-Allow-Origin"] = "*"
52
+ preflight_headers.update(
53
+ {
54
+ "Access-Control-Allow-Methods": ", ".join(allow_methods),
55
+ "Access-Control-Max-Age": str(max_age),
56
+ }
57
+ )
58
+ allow_headers = sorted(SAFELISTED_HEADERS | set(allow_headers))
59
+ if allow_headers and not allow_all_headers:
60
+ preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers)
61
+ if allow_credentials:
62
+ preflight_headers["Access-Control-Allow-Credentials"] = "true"
63
+
64
+ self.app = app
65
+ self.allow_origins = allow_origins
66
+ self.allow_methods = allow_methods
67
+ self.allow_headers = [h.lower() for h in allow_headers]
68
+ self.allow_all_origins = allow_all_origins
69
+ self.allow_all_headers = allow_all_headers
70
+ self.allow_credentials = allow_credentials
71
+ self.preflight_explicit_allow_origin = preflight_explicit_allow_origin
72
+ self.allow_origin_regex = compiled_allow_origin_regex
73
+ self.allow_private_network = allow_private_network
74
+ self.simple_headers = simple_headers
75
+ self.preflight_headers = preflight_headers
76
+
77
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
78
+ if scope["type"] != "http": # pragma: no cover
79
+ await self.app(scope, receive, send)
80
+ return
81
+
82
+ method = scope["method"]
83
+ headers = Headers(scope=scope)
84
+ origin = headers.get("origin")
85
+
86
+ if origin is not None and method == "OPTIONS" and "access-control-request-method" in headers:
87
+ response = self.preflight_response(request_headers=headers)
88
+ await response(scope, receive, send)
89
+ return
90
+
91
+ await self.simple_response(scope, receive, send, request_headers=headers)
92
+
93
+ def is_allowed_origin(self, origin: str) -> bool:
94
+ if self.allow_all_origins:
95
+ return True
96
+
97
+ if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(origin):
98
+ return True
99
+
100
+ return origin in self.allow_origins
101
+
102
+ def preflight_response(self, request_headers: Headers) -> Response:
103
+ requested_origin = request_headers["origin"]
104
+ requested_method = request_headers["access-control-request-method"]
105
+ requested_headers = request_headers.get("access-control-request-headers")
106
+ requested_private_network = request_headers.get("access-control-request-private-network")
107
+
108
+ headers = dict(self.preflight_headers)
109
+ failures: list[str] = []
110
+
111
+ if self.is_allowed_origin(origin=requested_origin):
112
+ if self.preflight_explicit_allow_origin:
113
+ # The "else" case is already accounted for in self.preflight_headers
114
+ # and the value would be "*".
115
+ headers["Access-Control-Allow-Origin"] = requested_origin
116
+ else:
117
+ failures.append("origin")
118
+
119
+ if requested_method not in self.allow_methods:
120
+ failures.append("method")
121
+
122
+ # If we allow all headers, then we have to mirror back any requested
123
+ # headers in the response.
124
+ if self.allow_all_headers and requested_headers is not None:
125
+ headers["Access-Control-Allow-Headers"] = requested_headers
126
+ elif requested_headers is not None:
127
+ for header in [h.lower() for h in requested_headers.split(",")]:
128
+ if header.strip() not in self.allow_headers:
129
+ failures.append("headers")
130
+ break
131
+
132
+ if requested_private_network is not None:
133
+ if self.allow_private_network:
134
+ headers["Access-Control-Allow-Private-Network"] = "true"
135
+ else:
136
+ failures.append("private-network")
137
+
138
+ # We don't strictly need to use 400 responses here, since its up to
139
+ # the browser to enforce the CORS policy, but its more informative
140
+ # if we do.
141
+ if failures:
142
+ failure_text = "Disallowed CORS " + ", ".join(failures)
143
+ return PlainTextResponse(failure_text, status_code=400, headers=headers)
144
+
145
+ return PlainTextResponse("OK", status_code=200, headers=headers)
146
+
147
+ async def simple_response(self, scope: Scope, receive: Receive, send: Send, request_headers: Headers) -> None:
148
+ send = functools.partial(self.send, send=send, request_headers=request_headers)
149
+ await self.app(scope, receive, send)
150
+
151
+ async def send(self, message: Message, send: Send, request_headers: Headers) -> None:
152
+ if message["type"] != "http.response.start":
153
+ await send(message)
154
+ return
155
+
156
+ message.setdefault("headers", [])
157
+ headers = MutableHeaders(scope=message)
158
+ origin = request_headers.get("Origin")
159
+ if origin is not None:
160
+ headers.update(self.simple_headers)
161
+
162
+ # If credentials are allowed, then we must respond with the specific origin instead of '*'.
163
+ if origin is not None and self.allow_all_origins and self.allow_credentials:
164
+ self.allow_explicit_origin(headers, origin)
165
+
166
+ # If we only allow specific origins, then we have to mirror back the Origin header in the response.
167
+ elif origin is not None and not self.allow_all_origins and self.is_allowed_origin(origin=origin):
168
+ self.allow_explicit_origin(headers, origin)
169
+ else:
170
+ headers["Vary"] = ", ".join([*headers.getlist("Vary"), "Origin"])
171
+
172
+ await send(message)
173
+
174
+ @staticmethod
175
+ def allow_explicit_origin(headers: MutableHeaders, origin: str) -> None:
176
+ headers["Access-Control-Allow-Origin"] = origin
177
+ headers["Vary"] = ", ".join([*headers.getlist("Vary"), "Origin"])