sendproof-fastapi 0.1.0a1__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.
- sendproof_fastapi/__init__.py +9 -0
- sendproof_fastapi/bench.py +109 -0
- sendproof_fastapi/capture_send.py +51 -0
- sendproof_fastapi/marker.py +41 -0
- sendproof_fastapi/middleware.py +424 -0
- sendproof_fastapi/py.typed +0 -0
- sendproof_fastapi/routing.py +64 -0
- sendproof_fastapi-0.1.0a1.dist-info/METADATA +118 -0
- sendproof_fastapi-0.1.0a1.dist-info/RECORD +11 -0
- sendproof_fastapi-0.1.0a1.dist-info/WHEEL +4 -0
- sendproof_fastapi-0.1.0a1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Sendproof workbench, rollback previews and observed sends for FastAPI and Starlette."""
|
|
2
|
+
|
|
3
|
+
from sendproof_core import AuthProvider, Identity, OpenApiDocument
|
|
4
|
+
|
|
5
|
+
from .bench import Sendproof
|
|
6
|
+
from .marker import preview
|
|
7
|
+
|
|
8
|
+
__all__ = ["AuthProvider", "Identity", "OpenApiDocument", "Sendproof", "preview"]
|
|
9
|
+
__version__ = "0.1.0a1"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""The public ``Sendproof`` object for FastAPI and Starlette applications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Awaitable, Callable, Iterable
|
|
7
|
+
|
|
8
|
+
from starlette.middleware import Middleware
|
|
9
|
+
from starlette.requests import Request
|
|
10
|
+
|
|
11
|
+
from sendproof_core import AuthProvider, BenchOptions, Identity, OpenApiDocument, PreviewProvider
|
|
12
|
+
from sendproof_core.assets import UiAssets
|
|
13
|
+
from sendproof_core.scope import install_logging_capture
|
|
14
|
+
from sendproof_core.stores.base import DataStore, StoresOnlyProvider, validate_stores
|
|
15
|
+
from sendproof_core.workbench import Workbench
|
|
16
|
+
|
|
17
|
+
from .middleware import SendproofMiddleware
|
|
18
|
+
|
|
19
|
+
IdentityResolver = Callable[[Request], "Identity | None | Awaitable[Identity | None]"]
|
|
20
|
+
Authorizer = Callable[[Request, "Identity | None"], "bool | Awaitable[bool]"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Sendproof:
|
|
24
|
+
"""Adds the Sendproof workbench to a FastAPI (or Starlette) application.
|
|
25
|
+
|
|
26
|
+
The workbench is **off** unless ``environment`` is listed in ``environments``
|
|
27
|
+
(default ``("Development",)``). ``environment`` defaults to ``$SENDPROOF_ENVIRONMENT`` and
|
|
28
|
+
then to ``"Production"``, so installing the package never exposes it by accident.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
app: The application. Create the ``Sendproof`` before the first request is served.
|
|
32
|
+
provider: A data-layer provider such as ``sendproof_sqlalchemy.SQLAlchemyPreview``.
|
|
33
|
+
Without one, and without ``data_stores``, no operation is advertised and previews
|
|
34
|
+
answer 503.
|
|
35
|
+
data_stores: Hooked data stores (``mongo_store``, ``redis_store``, ``dynamodb_store`` from
|
|
36
|
+
``sendproof_core.stores``). MongoDB rolls back in its own transaction, and Redis and
|
|
37
|
+
DynamoDB block a write during a Preview. They also let an app with no SQL ``provider``
|
|
38
|
+
Preview: a SQL database you give no provider for is then not covered. Only hooked
|
|
39
|
+
clients are covered.
|
|
40
|
+
identity: Returns the caller's :class:`~sendproof_core.Identity` for a request, or
|
|
41
|
+
``None``. Used for the capabilities ``identity`` and to own observed-send traces.
|
|
42
|
+
It reads what your authentication already established, such as a session.
|
|
43
|
+
authorize: Optional workbench policy, ``(request, identity) -> bool``. When it returns
|
|
44
|
+
false the workbench, previews and traces answer 401 or 403.
|
|
45
|
+
api_name: Display name. Defaults to the application's ``title``.
|
|
46
|
+
openapi_url: Defaults to the application's ``openapi_url``.
|
|
47
|
+
documents: Extra named OpenAPI documents.
|
|
48
|
+
auth_providers: Sign-in integrations to advertise, for example
|
|
49
|
+
``AuthProvider("Password", "cookie", "/auth/sign-in")``.
|
|
50
|
+
field_modules: Same-origin ES module URLs that register custom field renderers.
|
|
51
|
+
include_sql_parameter_values: Show SQL parameter values. Defaults to Development only.
|
|
52
|
+
trace_ttl: Seconds an observed-send trace is kept (default 300).
|
|
53
|
+
clock: Monotonic clock used by the trace store, injectable for tests.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
__test__ = False # not a pytest test class
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
app: Any,
|
|
61
|
+
*,
|
|
62
|
+
provider: PreviewProvider | None = None,
|
|
63
|
+
data_stores: Iterable[DataStore] = (),
|
|
64
|
+
identity: IdentityResolver | None = None,
|
|
65
|
+
authorize: Authorizer | None = None,
|
|
66
|
+
api_name: str | None = None,
|
|
67
|
+
openapi_url: str | None = None,
|
|
68
|
+
documents: Iterable[OpenApiDocument] = (),
|
|
69
|
+
environment: str | None = None,
|
|
70
|
+
environments: Iterable[str] = ("Development",),
|
|
71
|
+
auth_providers: Iterable[AuthProvider] = (),
|
|
72
|
+
field_modules: Iterable[str] = (),
|
|
73
|
+
include_sql_parameter_values: bool | None = None,
|
|
74
|
+
trace_ttl: float = 300.0,
|
|
75
|
+
clock: Callable[[], float] = time.monotonic,
|
|
76
|
+
assets: UiAssets | None = None,
|
|
77
|
+
) -> None:
|
|
78
|
+
self.stores = validate_stores(data_stores)
|
|
79
|
+
# Without a SQL provider, hooked stores alone can carry a Preview: MongoDB aborts its own
|
|
80
|
+
# transaction and the guarded stores block writes, so no SQL transaction is needed.
|
|
81
|
+
if provider is None and self.stores:
|
|
82
|
+
provider = StoresOnlyProvider()
|
|
83
|
+
self.provider = provider
|
|
84
|
+
self.authorize = authorize
|
|
85
|
+
self.options = BenchOptions(
|
|
86
|
+
api_name=api_name,
|
|
87
|
+
openapi_url=openapi_url,
|
|
88
|
+
documents=list(documents),
|
|
89
|
+
environment=environment,
|
|
90
|
+
environments=tuple(environments),
|
|
91
|
+
auth_providers=list(auth_providers),
|
|
92
|
+
field_modules=list(field_modules),
|
|
93
|
+
include_sql_parameter_values=include_sql_parameter_values,
|
|
94
|
+
trace_ttl=trace_ttl,
|
|
95
|
+
clock=clock,
|
|
96
|
+
identity=identity,
|
|
97
|
+
framework="FastAPI",
|
|
98
|
+
)
|
|
99
|
+
self.workbench = Workbench(self.options, provider, assets)
|
|
100
|
+
if getattr(app, "middleware_stack", None) is not None:
|
|
101
|
+
raise RuntimeError("Create Sendproof before the application starts serving requests.")
|
|
102
|
+
# Appended last so the host's own middleware (sessions, authentication) runs first.
|
|
103
|
+
app.user_middleware.append(Middleware(SendproofMiddleware, bench=self))
|
|
104
|
+
install_logging_capture()
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def enabled(self) -> bool:
|
|
108
|
+
"""Whether the workbench is active in the configured environment."""
|
|
109
|
+
return self.options.enabled
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Buffers an ASGI response so that a preview can wrap it in an envelope."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from sendproof_core import limits
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ResponseTooLarge(Exception):
|
|
11
|
+
"""The inner response exceeded the 1 MiB preview cap."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BufferedResponse:
|
|
15
|
+
"""An ASGI ``send`` callable that keeps the status, headers and a bounded body."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, maximum: int = limits.RESPONSE_BYTES) -> None:
|
|
18
|
+
self.status = 500
|
|
19
|
+
self.headers: list[tuple[str, str]] = []
|
|
20
|
+
self.started = False
|
|
21
|
+
self.complete = False
|
|
22
|
+
self.exceeded = False
|
|
23
|
+
self._maximum = maximum
|
|
24
|
+
self._chunks: list[bytes] = []
|
|
25
|
+
self._size = 0
|
|
26
|
+
|
|
27
|
+
async def __call__(self, message: dict[str, Any]) -> None:
|
|
28
|
+
kind = message["type"]
|
|
29
|
+
if kind == "http.response.start":
|
|
30
|
+
self.started = True
|
|
31
|
+
self.status = message["status"]
|
|
32
|
+
self.headers = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in message.get("headers", [])]
|
|
33
|
+
elif kind == "http.response.body":
|
|
34
|
+
chunk = message.get("body", b"")
|
|
35
|
+
self._size += len(chunk)
|
|
36
|
+
if self._size > self._maximum:
|
|
37
|
+
self.exceeded = True
|
|
38
|
+
raise ResponseTooLarge
|
|
39
|
+
self._chunks.append(chunk)
|
|
40
|
+
self.complete = not message.get("more_body", False)
|
|
41
|
+
elif kind in ("http.response.pathsend", "http.response.zerocopysend"):
|
|
42
|
+
raise RuntimeError("Sendproof previews require a buffered response.")
|
|
43
|
+
|
|
44
|
+
def header(self, name: str) -> str | None:
|
|
45
|
+
"""First header value, case-insensitive."""
|
|
46
|
+
lowered = name.lower()
|
|
47
|
+
return next((v for k, v in self.headers if k.lower() == lowered), None)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def body(self) -> bytes:
|
|
51
|
+
return b"".join(self._chunks)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""The ``@preview`` marker for FastAPI and Starlette path operation functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable, Iterable, TypeVar
|
|
6
|
+
|
|
7
|
+
from sendproof_core.marker import MARKER, apply_marker, is_marked, is_previewable, unavailable_info
|
|
8
|
+
|
|
9
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def preview(
|
|
13
|
+
endpoint: Any = True, *, reason: str | None = None, stores: Iterable[str] | None = None
|
|
14
|
+
) -> Any:
|
|
15
|
+
"""Mark a path operation function as eligible for Sendproof previews, or as ``preview: false``.
|
|
16
|
+
|
|
17
|
+
Apply it directly to the function, below the route decorator::
|
|
18
|
+
|
|
19
|
+
@app.post("/items")
|
|
20
|
+
@preview
|
|
21
|
+
def create_item(item: Item, db: Session = Depends(get_db)): ...
|
|
22
|
+
|
|
23
|
+
Only marked operations are advertised and accepted. The function keeps its signature, so
|
|
24
|
+
FastAPI's dependency injection and OpenAPI generation are unchanged.
|
|
25
|
+
|
|
26
|
+
An operation you know writes to a store a Preview cannot roll back, such as one that clears a
|
|
27
|
+
Redis session, can be marked ``preview: false``. The workbench then shows "Preview unavailable"
|
|
28
|
+
with your reason before anyone tries, a Preview of it is refused (never confirmed) without
|
|
29
|
+
running the handler, and Send still runs it::
|
|
30
|
+
|
|
31
|
+
@app.delete("/sessions/{id}")
|
|
32
|
+
@preview(False, reason="Clears the Redis session", stores=["redis"])
|
|
33
|
+
def delete_session(id: str): ...
|
|
34
|
+
|
|
35
|
+
Without ``reason`` the published reason names the first of ``stores``. The binding never
|
|
36
|
+
infers the mark: without it the operation is advertised and the write guard decides at run time.
|
|
37
|
+
"""
|
|
38
|
+
return apply_marker(endpoint, True, reason=reason, stores=stores)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
__all__ = ["MARKER", "is_marked", "is_previewable", "preview", "unavailable_info"]
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""Pure ASGI middleware that serves the workbench and runs previews and observed sends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any, Awaitable, Callable
|
|
10
|
+
|
|
11
|
+
import anyio
|
|
12
|
+
from starlette.datastructures import Headers
|
|
13
|
+
from starlette.requests import Request
|
|
14
|
+
from starlette.routing import Match
|
|
15
|
+
|
|
16
|
+
from sendproof_core import Identity, PreviewUnavailable, RequestScope, protocol
|
|
17
|
+
from sendproof_core.capture import Capture
|
|
18
|
+
from sendproof_core.provider import run_in_thread
|
|
19
|
+
from sendproof_core.scope import activate, deactivate, request_context
|
|
20
|
+
from sendproof_core.workbench import Response, Workbench, blocked_response, json_response, problem_response, trace_owner
|
|
21
|
+
|
|
22
|
+
from .capture_send import BufferedResponse
|
|
23
|
+
from .marker import is_marked, is_previewable
|
|
24
|
+
from .routing import find_route, preview_operations, route_path, unavailable_operations
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("sendproof_fastapi")
|
|
27
|
+
ASGIApp = Callable[..., Awaitable[None]]
|
|
28
|
+
|
|
29
|
+
#: Scope key of a re-dispatched preview: the route that was checked before the handler runs.
|
|
30
|
+
#: Only this middleware sets it; HTTP clients cannot place keys in the ASGI scope.
|
|
31
|
+
PREVIEW_ROUTE = "sendproof.preview_route"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SendproofMiddleware:
|
|
35
|
+
"""Intercepts ``/sendproof/*`` and Preview/Observed requests; everything else passes through."""
|
|
36
|
+
|
|
37
|
+
__test__ = False
|
|
38
|
+
|
|
39
|
+
def __init__(self, app: ASGIApp, bench: "Any") -> None:
|
|
40
|
+
self.app = app
|
|
41
|
+
self.bench = bench
|
|
42
|
+
|
|
43
|
+
async def __call__(self, scope: dict, receive: Callable, send: Callable) -> None:
|
|
44
|
+
if scope["type"] not in ("http", "websocket"):
|
|
45
|
+
await self.app(scope, receive, send) # lifespan: its background tasks belong to no request
|
|
46
|
+
return
|
|
47
|
+
# Every request is attributed, so a store write that no request accounts for (a thread a
|
|
48
|
+
# Preview handler started without its context) can fail the open Previews.
|
|
49
|
+
with request_context():
|
|
50
|
+
await self._handle(scope, receive, send)
|
|
51
|
+
|
|
52
|
+
async def _handle(self, scope: dict, receive: Callable, send: Callable) -> None:
|
|
53
|
+
bench = self.bench
|
|
54
|
+
if scope["type"] != "http" or not bench.options.enabled:
|
|
55
|
+
await self.app(scope, receive, send)
|
|
56
|
+
return
|
|
57
|
+
if PREVIEW_ROUTE in scope:
|
|
58
|
+
await self._inner_preview(scope, receive, send)
|
|
59
|
+
return
|
|
60
|
+
started = time.perf_counter()
|
|
61
|
+
path = route_path(scope)
|
|
62
|
+
if path == protocol.BENCH_PREFIX or path.startswith(protocol.BENCH_PREFIX + "/"):
|
|
63
|
+
if path == protocol.PREVIEW_PREFIX or path.startswith(protocol.PREVIEW_PREFIX + "/"):
|
|
64
|
+
await self._preview(scope, receive, send, path, started)
|
|
65
|
+
else:
|
|
66
|
+
await self._workbench(scope, receive, send, path)
|
|
67
|
+
return
|
|
68
|
+
headers = Headers(scope=scope)
|
|
69
|
+
if protocol.requests_rollback(headers.getlist):
|
|
70
|
+
await _send(send, problem_response(400, "Use the Sendproof preview URL for rollback requests."))
|
|
71
|
+
return
|
|
72
|
+
if scope["method"] != "HEAD" and protocol.requests_trace(headers.getlist):
|
|
73
|
+
if await self._observed(scope, receive, send, headers, started):
|
|
74
|
+
return
|
|
75
|
+
await self.app(scope, receive, send)
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------ helpers
|
|
78
|
+
async def _identity(self, scope: dict, receive: Callable) -> Identity | None:
|
|
79
|
+
resolver = self.bench.options.identity
|
|
80
|
+
if resolver is None:
|
|
81
|
+
return None
|
|
82
|
+
try:
|
|
83
|
+
result = resolver(Request(scope, receive))
|
|
84
|
+
return await result if inspect.isawaitable(result) else result
|
|
85
|
+
except Exception:
|
|
86
|
+
logger.exception("The Sendproof identity resolver failed; treating the caller as anonymous.")
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
async def _authorized(self, scope: dict, receive: Callable, identity: Identity | None) -> bool:
|
|
90
|
+
hook = self.bench.authorize
|
|
91
|
+
if hook is None:
|
|
92
|
+
return True
|
|
93
|
+
try:
|
|
94
|
+
result = hook(Request(scope, receive), identity)
|
|
95
|
+
return bool(await result if inspect.isawaitable(result) else result)
|
|
96
|
+
except Exception:
|
|
97
|
+
logger.exception("The Sendproof authorization hook failed; denying access.")
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _origin_ok(scope: dict, headers: Headers) -> bool:
|
|
102
|
+
return protocol.is_same_origin(headers.getlist, scope.get("scheme", "http"), headers.get("host", ""))
|
|
103
|
+
|
|
104
|
+
# ---------------------------------------------------------------- workbench
|
|
105
|
+
async def _workbench(self, scope: dict, receive: Callable, send: Callable, path: str) -> None:
|
|
106
|
+
bench: Any = self.bench
|
|
107
|
+
method = scope["method"]
|
|
108
|
+
if method not in ("GET", "HEAD"):
|
|
109
|
+
await _send(send, Response(405, [("allow", "GET, HEAD")]), head=False)
|
|
110
|
+
return
|
|
111
|
+
identity = await self._identity(scope, receive)
|
|
112
|
+
if not await self._authorized(scope, receive, identity):
|
|
113
|
+
await _send(send, problem_response(403 if identity else 401, "Access to the workbench is denied."), head=method == "HEAD")
|
|
114
|
+
return
|
|
115
|
+
root = scope.get("root_path", "")
|
|
116
|
+
workbench: Workbench = bench.workbench
|
|
117
|
+
if path == protocol.BENCH_PREFIX:
|
|
118
|
+
query = scope.get("query_string", b"").decode("latin-1")
|
|
119
|
+
location = f"{root}/sendproof/" + (f"?{query}" if query else "")
|
|
120
|
+
response = Response(307, [("location", location), ("cache-control", "no-store")])
|
|
121
|
+
elif path in ("/sendproof/", "/sendproof/signin.html"):
|
|
122
|
+
response = workbench.asset("index.html")
|
|
123
|
+
elif path == "/sendproof/_api/capabilities":
|
|
124
|
+
app = scope["app"]
|
|
125
|
+
described = []
|
|
126
|
+
for store in bench.stores:
|
|
127
|
+
try:
|
|
128
|
+
described.append(await store.adescribe())
|
|
129
|
+
except Exception:
|
|
130
|
+
logger.warning("Sendproof could not describe a data store.", exc_info=True)
|
|
131
|
+
response = workbench.capabilities(
|
|
132
|
+
root, identity, preview_operations(app.router.routes),
|
|
133
|
+
getattr(app, "openapi_url", None) or "/openapi.json", getattr(app, "title", "API"),
|
|
134
|
+
unavailable_operations(app.router.routes), described,
|
|
135
|
+
)
|
|
136
|
+
elif path.startswith("/sendproof/_api/traces/"):
|
|
137
|
+
headers = Headers(scope=scope)
|
|
138
|
+
owner = trace_owner(identity, root) if self._origin_ok(scope, headers) else None
|
|
139
|
+
response = await run_in_thread(workbench.trace, path.rsplit("/", 1)[1], owner)
|
|
140
|
+
elif path.startswith("/sendproof/_api/"):
|
|
141
|
+
response = Response(404, [("cache-control", "no-store")])
|
|
142
|
+
else:
|
|
143
|
+
response = workbench.asset(path[len("/sendproof/"):])
|
|
144
|
+
await _send(send, response, head=method == "HEAD")
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------------ preview
|
|
147
|
+
async def _preview(self, scope: dict, receive: Callable, send: Callable, path: str, started: float) -> None:
|
|
148
|
+
bench: Any = self.bench
|
|
149
|
+
headers = Headers(scope=scope)
|
|
150
|
+
if not protocol.has_exact_preference(headers.getlist):
|
|
151
|
+
await _send(send, problem_response(400, "A Sendproof preview requires Prefer: tx=rollback."))
|
|
152
|
+
return
|
|
153
|
+
if scope["method"] == "HEAD":
|
|
154
|
+
await _send(send, problem_response(405, "A preview requires a response body."))
|
|
155
|
+
return
|
|
156
|
+
target = path[len(protocol.PREVIEW_PREFIX):]
|
|
157
|
+
if not protocol.is_valid_preview_target(target):
|
|
158
|
+
await _send(send, problem_response(400, "The Sendproof preview target is invalid."))
|
|
159
|
+
return
|
|
160
|
+
if not self._origin_ok(scope, headers):
|
|
161
|
+
await _send(send, problem_response(403, "This preview is forbidden."))
|
|
162
|
+
return
|
|
163
|
+
|
|
164
|
+
prefix = scope["path"][: len(scope["path"]) - len(path)]
|
|
165
|
+
inner = dict(scope)
|
|
166
|
+
inner["path"] = prefix + target
|
|
167
|
+
raw = scope.get("raw_path")
|
|
168
|
+
if raw is not None:
|
|
169
|
+
marker = protocol.PREVIEW_PREFIX.encode()
|
|
170
|
+
index = raw.find(marker)
|
|
171
|
+
inner["raw_path"] = raw[:index] + raw[index + len(marker):] if index >= 0 else inner["path"].encode()
|
|
172
|
+
inner["headers"] = [
|
|
173
|
+
(k, v) for k, v in scope["headers"] if k.lower() != b"accept-encoding"
|
|
174
|
+
] + [(b"cache-control", b"no-cache, no-store")]
|
|
175
|
+
inner.pop("endpoint", None)
|
|
176
|
+
# The host's middleware runs again for the inner request. Give it its own per-request
|
|
177
|
+
# dictionaries so that session or state changes made during the preview never reach the
|
|
178
|
+
# outer response (for example a session cookie written by SessionMiddleware).
|
|
179
|
+
for key in ("state", "session"):
|
|
180
|
+
if isinstance(inner.get(key), dict):
|
|
181
|
+
inner[key] = dict(inner[key])
|
|
182
|
+
|
|
183
|
+
found = find_route(scope["app"].router.routes, inner)
|
|
184
|
+
if found is None or found[1] != Match.FULL:
|
|
185
|
+
await _send(send, problem_response(404 if found is None else 405, "The preview target was not found for this method."))
|
|
186
|
+
return
|
|
187
|
+
if not is_previewable(getattr(found[0], "endpoint", None)):
|
|
188
|
+
await _send(send, problem_response(409, "This operation is unavailable for preview."))
|
|
189
|
+
return
|
|
190
|
+
inner[PREVIEW_ROUTE] = found[0]
|
|
191
|
+
identity = await self._identity(scope, receive)
|
|
192
|
+
if not await self._authorized(scope, receive, identity):
|
|
193
|
+
await _send(send, problem_response(403 if identity else 401, "This preview is forbidden."))
|
|
194
|
+
return
|
|
195
|
+
provider = bench.provider
|
|
196
|
+
if provider is None or not provider.is_available:
|
|
197
|
+
await _send(send, problem_response(503, "Preview requires one available preview provider."))
|
|
198
|
+
return
|
|
199
|
+
await self._run_preview(inner, receive, send, provider, started, scope["method"], path)
|
|
200
|
+
|
|
201
|
+
async def _inner_preview(self, scope: dict, receive: Callable, send: Callable) -> None:
|
|
202
|
+
"""Last check of a re-dispatched preview, after every host middleware has run.
|
|
203
|
+
|
|
204
|
+
Host middleware may have changed the method (method override) or the path. The handler
|
|
205
|
+
runs only when the request still routes to the marked route checked earlier; otherwise
|
|
206
|
+
nothing executes and the preview answers 409.
|
|
207
|
+
"""
|
|
208
|
+
found = find_route(scope["app"].router.routes, scope)
|
|
209
|
+
if found is None or found[1] != Match.FULL or found[0] is not scope[PREVIEW_ROUTE]:
|
|
210
|
+
await _send(send, problem_response(409, "This operation is unavailable for preview."))
|
|
211
|
+
return
|
|
212
|
+
await self.app(scope, receive, send)
|
|
213
|
+
|
|
214
|
+
async def _run_preview(
|
|
215
|
+
self, inner: dict, receive: Callable, send: Callable, provider: Any, started: float, method: str, path: str
|
|
216
|
+
) -> None:
|
|
217
|
+
bench: Any = self.bench
|
|
218
|
+
workbench: Workbench = bench.workbench
|
|
219
|
+
capture = Capture(rollback=True, started=started)
|
|
220
|
+
request_scope = RequestScope(capture, bench.options.environment or "", bench.options.show_sql_values)
|
|
221
|
+
token = activate(request_scope)
|
|
222
|
+
buffered = BufferedResponse()
|
|
223
|
+
failure: BaseException | None = None
|
|
224
|
+
unsafe = False # a store abort or the SQL rollback failed: the Preview can never be confirmed
|
|
225
|
+
envelope: dict[str, Any] | None = None
|
|
226
|
+
session = None
|
|
227
|
+
response: Response | None = None
|
|
228
|
+
interrupted: BaseException | None = None
|
|
229
|
+
begun: list[Any] = []
|
|
230
|
+
try:
|
|
231
|
+
try:
|
|
232
|
+
session = provider.begin(request_scope)
|
|
233
|
+
except PreviewUnavailable as error:
|
|
234
|
+
logger.warning("Sendproof preview unavailable: %s", error)
|
|
235
|
+
response = problem_response(503, "Preview requires one available preview provider.")
|
|
236
|
+
except Exception:
|
|
237
|
+
logger.exception("A Sendproof preview could not begin for %s %s.", method, path)
|
|
238
|
+
response = problem_response(500, "The preview could not be completed safely.")
|
|
239
|
+
if session is not None:
|
|
240
|
+
try:
|
|
241
|
+
for store in bench.stores:
|
|
242
|
+
begun.append(store) # finish runs for a store whose begin failed halfway, too
|
|
243
|
+
await store.abegin(request_scope)
|
|
244
|
+
# Dispatch through the whole application, as .NET does: the host middleware
|
|
245
|
+
# (authentication, path-based policies, method override) sees the target path
|
|
246
|
+
# rather than /sendproof/_preview, and _inner_preview re-checks the route last.
|
|
247
|
+
await inner["app"](inner, receive, buffered)
|
|
248
|
+
except Exception as error:
|
|
249
|
+
failure = error
|
|
250
|
+
except BaseException as error: # cancellation or client abort: roll back first
|
|
251
|
+
failure = interrupted = error
|
|
252
|
+
capture.handler_finished()
|
|
253
|
+
# Pipeline order (spec/data-stores.md): abort every preview-mode store transaction,
|
|
254
|
+
# then roll back SQL. A failure of either withholds confirmation.
|
|
255
|
+
# Every cleanup step runs, shielded from the request's cancellation and whatever an
|
|
256
|
+
# earlier step raised: an interrupt inside one store's abort must not skip the other
|
|
257
|
+
# stores, the SQL rollback or the release (and a MySQL Preview's turn). The first
|
|
258
|
+
# interrupt is re-raised once everything is cleaned up.
|
|
259
|
+
with anyio.CancelScope(shield=True):
|
|
260
|
+
for store in reversed(begun):
|
|
261
|
+
try:
|
|
262
|
+
await store.afinish(request_scope)
|
|
263
|
+
except BaseException as error:
|
|
264
|
+
unsafe = True
|
|
265
|
+
interrupted = interrupted or (None if isinstance(error, Exception) else error)
|
|
266
|
+
logger.error("A Sendproof data store could not finish the preview.", exc_info=error)
|
|
267
|
+
try:
|
|
268
|
+
await session.arollback()
|
|
269
|
+
if (not unsafe and failure is None and not buffered.exceeded and buffered.started
|
|
270
|
+
and _is_application(request_scope, buffered)):
|
|
271
|
+
envelope = workbench.preview_envelope(
|
|
272
|
+
buffered.status, buffered.headers, buffered.body,
|
|
273
|
+
[*session.changes, *request_scope.store_changes],
|
|
274
|
+
session.changes_truncated or request_scope.store_changes_truncated, capture.finish(),
|
|
275
|
+
)
|
|
276
|
+
except BaseException as error:
|
|
277
|
+
unsafe = True
|
|
278
|
+
interrupted = interrupted or (None if isinstance(error, Exception) else error)
|
|
279
|
+
logger.error("A Sendproof preview could not roll back for %s %s.", method, path, exc_info=error)
|
|
280
|
+
finally:
|
|
281
|
+
capture.finish()
|
|
282
|
+
try:
|
|
283
|
+
await session.aclose()
|
|
284
|
+
except BaseException as error:
|
|
285
|
+
unsafe = True
|
|
286
|
+
interrupted = interrupted or (None if isinstance(error, Exception) else error)
|
|
287
|
+
logger.error("A Sendproof preview could not release its transaction.", exc_info=error)
|
|
288
|
+
finally:
|
|
289
|
+
deactivate(token)
|
|
290
|
+
|
|
291
|
+
if interrupted is not None:
|
|
292
|
+
raise interrupted
|
|
293
|
+
if response is None:
|
|
294
|
+
response = self._finish_preview(request_scope, buffered, failure, envelope, method, path, unsafe)
|
|
295
|
+
await _send(send, response)
|
|
296
|
+
|
|
297
|
+
def _finish_preview(
|
|
298
|
+
self, scope: RequestScope, buffered: BufferedResponse, failure: BaseException | None,
|
|
299
|
+
envelope: dict[str, Any] | None, method: str, path: str, unsafe: bool = False,
|
|
300
|
+
) -> Response:
|
|
301
|
+
blocked, fault = scope.capture.blocked, scope.capture.fault
|
|
302
|
+
if unsafe or fault is not None:
|
|
303
|
+
# A failed rollback or abort, a handler COMMIT, or a write that escaped the MongoDB
|
|
304
|
+
# session: nothing can be confirmed, and that outranks a blocked write.
|
|
305
|
+
if fault is not None:
|
|
306
|
+
logger.error("A Sendproof preview was not confirmed for %s %s: %s", method, path, fault)
|
|
307
|
+
return problem_response(500, "The preview could not be completed safely.")
|
|
308
|
+
if blocked is not None:
|
|
309
|
+
# The mark decides, whatever the handler did with the refusal: it may have caught the
|
|
310
|
+
# error and returned 200, or let it escape as a 500.
|
|
311
|
+
return blocked_response(blocked)
|
|
312
|
+
if failure is not None or buffered.exceeded:
|
|
313
|
+
if failure is not None:
|
|
314
|
+
logger.error("A Sendproof preview failed for %s %s.", method, path, exc_info=failure)
|
|
315
|
+
if buffered.exceeded:
|
|
316
|
+
return problem_response(413, "The preview response exceeds the 1 MiB limit.")
|
|
317
|
+
return problem_response(500, "The preview could not be completed safely.")
|
|
318
|
+
if envelope is None:
|
|
319
|
+
if not buffered.started:
|
|
320
|
+
return problem_response(500, "The preview operation did not finish.")
|
|
321
|
+
status, title = protocol.classify_unexecuted(buffered.status if buffered.started else 500)
|
|
322
|
+
extra = [("www-authenticate", challenge)] if (challenge := buffered.header("www-authenticate")) else []
|
|
323
|
+
return problem_response(status, title, extra)
|
|
324
|
+
started = time.perf_counter()
|
|
325
|
+
body = json.dumps(envelope, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
326
|
+
timing = scope.capture.timing((time.perf_counter() - started) * 1000)
|
|
327
|
+
return Response(
|
|
328
|
+
200,
|
|
329
|
+
[
|
|
330
|
+
("content-type", "application/json; charset=utf-8"),
|
|
331
|
+
("cache-control", "no-store"),
|
|
332
|
+
("preference-applied", protocol.ROLLBACK_PREFERENCE),
|
|
333
|
+
("server-timing", timing.server_timing()),
|
|
334
|
+
],
|
|
335
|
+
body,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
# ----------------------------------------------------------------- observed
|
|
339
|
+
async def _observed(self, scope: dict, receive: Callable, send: Callable, headers: Headers, started: float) -> bool:
|
|
340
|
+
"""Run an observed send. Returns ``False`` when the request should proceed untraced."""
|
|
341
|
+
bench: Any = self.bench
|
|
342
|
+
provider = bench.provider
|
|
343
|
+
if provider is None or not provider.is_available or not self._origin_ok(scope, headers):
|
|
344
|
+
return False
|
|
345
|
+
found = find_route(scope["app"].router.routes, scope)
|
|
346
|
+
if found is None or found[1] != Match.FULL or not is_marked(getattr(found[0], "endpoint", None)):
|
|
347
|
+
return False
|
|
348
|
+
identity = await self._identity(scope, receive)
|
|
349
|
+
owner = trace_owner(identity, scope.get("root_path", ""))
|
|
350
|
+
if owner is None or not await self._authorized(scope, receive, identity):
|
|
351
|
+
return False
|
|
352
|
+
capture = Capture(rollback=False, started=started)
|
|
353
|
+
request_scope = RequestScope(capture, bench.options.environment or "", bench.options.show_sql_values)
|
|
354
|
+
try:
|
|
355
|
+
observation = provider.begin_observation(request_scope)
|
|
356
|
+
except Exception:
|
|
357
|
+
logger.warning("Sendproof could not start observing the send.", exc_info=True)
|
|
358
|
+
return False
|
|
359
|
+
if observation is None:
|
|
360
|
+
return False
|
|
361
|
+
|
|
362
|
+
workbench: Workbench = bench.workbench
|
|
363
|
+
reservation = workbench.traces.reserve(owner)
|
|
364
|
+
completed = False
|
|
365
|
+
response_started = False
|
|
366
|
+
|
|
367
|
+
async def traced_send(message: dict) -> None:
|
|
368
|
+
nonlocal response_started
|
|
369
|
+
if message["type"] == "http.response.start" and not response_started:
|
|
370
|
+
response_started = True
|
|
371
|
+
if protocol.is_application_response(request_scope.entered, message["status"]):
|
|
372
|
+
kept = [(k, v) for k, v in message.get("headers", []) if k.lower() not in (b"cache-control", b"server-timing")]
|
|
373
|
+
message = {**message, "headers": [
|
|
374
|
+
*kept,
|
|
375
|
+
(protocol.TRACE_HEADER.lower().encode(), reservation.id.encode()),
|
|
376
|
+
(b"cache-control", b"no-store"),
|
|
377
|
+
(b"server-timing", capture.timing().server_timing().encode()),
|
|
378
|
+
]}
|
|
379
|
+
await send(message)
|
|
380
|
+
|
|
381
|
+
token = activate(request_scope)
|
|
382
|
+
try:
|
|
383
|
+
await self.app(scope, receive, traced_send)
|
|
384
|
+
completed = response_started
|
|
385
|
+
finally:
|
|
386
|
+
deactivate(token)
|
|
387
|
+
capture.handler_finished()
|
|
388
|
+
try:
|
|
389
|
+
if completed:
|
|
390
|
+
began = time.perf_counter()
|
|
391
|
+
snapshot = capture.finish()
|
|
392
|
+
document = workbench.trace_document(
|
|
393
|
+
observation.changes, observation.changes_truncated, snapshot,
|
|
394
|
+
capture.timing((time.perf_counter() - began) * 1000),
|
|
395
|
+
)
|
|
396
|
+
workbench.traces.complete(reservation, document)
|
|
397
|
+
else:
|
|
398
|
+
capture.finish()
|
|
399
|
+
workbench.traces.discard(reservation)
|
|
400
|
+
except Exception:
|
|
401
|
+
logger.warning("Sendproof could not collect the observed send.", exc_info=True)
|
|
402
|
+
workbench.traces.discard(reservation)
|
|
403
|
+
finally:
|
|
404
|
+
try:
|
|
405
|
+
observation.close()
|
|
406
|
+
except Exception:
|
|
407
|
+
logger.warning("Sendproof could not release the send observation.", exc_info=True)
|
|
408
|
+
return True
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _is_application(scope: RequestScope, buffered: BufferedResponse) -> bool:
|
|
412
|
+
"""Whether the response is the application's own answer rather than a transport-level denial."""
|
|
413
|
+
return protocol.is_application_response(scope.entered, buffered.status)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
async def _send(send: Callable, response: Response, head: bool = False) -> None:
|
|
417
|
+
headers = [(k.encode("latin-1"), v.encode("latin-1")) for k, v in response.headers]
|
|
418
|
+
if not any(k == b"content-length" for k, _ in headers):
|
|
419
|
+
headers.append((b"content-length", str(len(response.body)).encode()))
|
|
420
|
+
await send({"type": "http.response.start", "status": response.status, "headers": headers})
|
|
421
|
+
await send({"type": "http.response.body", "body": b"" if head else response.body})
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
__all__ = ["SendproofMiddleware", "json_response"]
|
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Finds the application's own route for a request, using the framework's routing rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Iterable
|
|
6
|
+
|
|
7
|
+
from starlette.routing import Match, Mount
|
|
8
|
+
|
|
9
|
+
from .marker import is_previewable, unavailable_info
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def route_path(scope: dict[str, Any]) -> str:
|
|
13
|
+
"""The request path without the ASGI ``root_path`` (the mount prefix)."""
|
|
14
|
+
path: str = scope["path"]
|
|
15
|
+
root: str = scope.get("root_path", "")
|
|
16
|
+
if root and path.startswith(root):
|
|
17
|
+
stripped = path[len(root):]
|
|
18
|
+
return stripped if stripped.startswith("/") else "/" + stripped
|
|
19
|
+
return path
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def find_route(routes: Iterable[Any], scope: dict[str, Any]) -> tuple[Any, Match] | None:
|
|
23
|
+
"""Return the first fully matching route, else the first partial (wrong method) match."""
|
|
24
|
+
partial: tuple[Any, Match] | None = None
|
|
25
|
+
for route in routes:
|
|
26
|
+
match, child = route.matches(scope)
|
|
27
|
+
if match == Match.FULL:
|
|
28
|
+
if isinstance(route, Mount) and getattr(route, "routes", None):
|
|
29
|
+
nested = find_route(route.routes, {**scope, **child})
|
|
30
|
+
if nested is not None and nested[1] == Match.FULL:
|
|
31
|
+
return nested
|
|
32
|
+
continue
|
|
33
|
+
return route, Match.FULL
|
|
34
|
+
if match == Match.PARTIAL and partial is None:
|
|
35
|
+
partial = (route, Match.PARTIAL)
|
|
36
|
+
return partial
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def preview_operations(routes: Iterable[Any]) -> list[tuple[str, str]]:
|
|
40
|
+
"""Method and OpenAPI path template of every operation a Preview may run."""
|
|
41
|
+
operations = []
|
|
42
|
+
for route in routes:
|
|
43
|
+
endpoint = getattr(route, "endpoint", None)
|
|
44
|
+
if endpoint is None or not is_previewable(endpoint):
|
|
45
|
+
continue
|
|
46
|
+
path = getattr(route, "path_format", None) or route.path
|
|
47
|
+
for method in sorted(route.methods or ()):
|
|
48
|
+
if method not in ("HEAD", "OPTIONS"):
|
|
49
|
+
operations.append((method, path))
|
|
50
|
+
return operations
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def unavailable_operations(routes: Iterable[Any]) -> list[tuple[str, str, str, tuple[str, ...]]]:
|
|
54
|
+
"""Method, path, reason and stores of every operation marked ``preview: false``."""
|
|
55
|
+
operations = []
|
|
56
|
+
for route in routes:
|
|
57
|
+
marked = unavailable_info(getattr(route, "endpoint", None))
|
|
58
|
+
if marked is None:
|
|
59
|
+
continue
|
|
60
|
+
path = getattr(route, "path_format", None) or route.path
|
|
61
|
+
for method in sorted(route.methods or ()):
|
|
62
|
+
if method not in ("HEAD", "OPTIONS"):
|
|
63
|
+
operations.append((method, path, marked.reason, marked.stores))
|
|
64
|
+
return operations
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sendproof-fastapi
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Sendproof workbench, rollback previews and observed sends for FastAPI and Starlette applications.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mprync/sendproof/tree/main/adapters/python/fastapi
|
|
6
|
+
Project-URL: Repository, https://github.com/mprync/sendproof
|
|
7
|
+
Project-URL: Issues, https://github.com/mprync/sendproof/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/mprync/sendproof/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Sendproof contributors
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: api-testing,fastapi,openapi,rollback,starlette,swagger,testing
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: FastAPI
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Software Development :: Testing
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Requires-Dist: fastapi>=0.110
|
|
28
|
+
Requires-Dist: sendproof-core==0.1.0a1
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# sendproof-fastapi
|
|
32
|
+
|
|
33
|
+
Serves the [Sendproof](../../spec/README.md) workbench from a FastAPI or Starlette application
|
|
34
|
+
and runs rollback **Preview** and **Observed Send** through the application's own routing,
|
|
35
|
+
dependencies and authorization.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install sendproof-fastapi sendproof-sqlalchemy
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from fastapi import Depends, FastAPI
|
|
43
|
+
from sendproof_core import Identity
|
|
44
|
+
from sendproof_fastapi import AuthProvider, Sendproof, preview
|
|
45
|
+
from sendproof_sqlalchemy import SQLAlchemyPreview
|
|
46
|
+
|
|
47
|
+
app = FastAPI(title="Inventory")
|
|
48
|
+
|
|
49
|
+
def identity(request) -> Identity | None: # read what your authentication already set up
|
|
50
|
+
user = request.session.get("user")
|
|
51
|
+
return user and Identity(user["name"], user["role"], subject=user["id"], authentication_type="session")
|
|
52
|
+
|
|
53
|
+
Sendproof(
|
|
54
|
+
app,
|
|
55
|
+
provider=SQLAlchemyPreview(engine, database="inventory_dev"),
|
|
56
|
+
identity=identity,
|
|
57
|
+
environment="Development", # off in any environment not listed
|
|
58
|
+
auth_providers=[AuthProvider("Password", "cookie", "/auth/sign-in")],
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
@app.post("/items", status_code=201)
|
|
62
|
+
@preview # below the route decorator
|
|
63
|
+
def create_item(item: ItemIn, db: Session = Depends(get_db)):
|
|
64
|
+
...
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Open `/sendproof/`. Create the `Sendproof` before the application starts serving requests.
|
|
68
|
+
|
|
69
|
+
## How it works
|
|
70
|
+
|
|
71
|
+
- **Opt in per operation.** `@preview` marks a path operation function (sync or `async`). Only
|
|
72
|
+
marked operations are advertised in discovery and accepted by the preview route. The function
|
|
73
|
+
keeps its signature, so dependency injection and OpenAPI are unchanged.
|
|
74
|
+
- **Preview.** A request to `/sendproof/_preview/<path>` with exactly `Prefer: tx=rollback` is routed
|
|
75
|
+
with your application's router, authenticated and validated by your dependencies, and executed
|
|
76
|
+
in-process. Nothing is proxied. The adapter buffers the response (1 MiB cap), rolls the data layer
|
|
77
|
+
back, and only then returns HTTP 200 with the confirmed envelope. Denied, unknown, unmarked,
|
|
78
|
+
oversized or unconfirmed requests never return an envelope. The inner status can be any
|
|
79
|
+
application status, including 409 or a 422 validation failure.
|
|
80
|
+
- **Observed Send.** The same URL with `Prefer: trace` commits normally and, for a caller with a
|
|
81
|
+
stable `Identity.subject`, adds `X-Sendproof-Trace`. Fetch it at `/sendproof/_api/traces/{id}`;
|
|
82
|
+
only the owner can, for five minutes by default (`trace_ttl`, 8 per owner, 32 in total).
|
|
83
|
+
- **Middleware order.** `Sendproof` appends its middleware as the innermost user middleware, so
|
|
84
|
+
your session and authentication middleware have already run when it asks for an identity.
|
|
85
|
+
- **Dispatch.** A preview is re-dispatched in-process through the whole application, so every
|
|
86
|
+
middleware (including path-based policies) sees the target path, with its own copy of the
|
|
87
|
+
session and state. Just before the router, Sendproof checks again that the request still
|
|
88
|
+
routes to the marked operation it checked first; a middleware that changed the method or path
|
|
89
|
+
gets a 409 and nothing runs.
|
|
90
|
+
|
|
91
|
+
## Options
|
|
92
|
+
|
|
93
|
+
| Option | Meaning |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `provider` | Data layer such as `SQLAlchemyPreview`. Without one nothing is advertised and previews answer 503. |
|
|
96
|
+
| `identity` | `(request) -> Identity \| None`, sync or async. Drives capabilities and trace ownership. |
|
|
97
|
+
| `authorize` | `(request, identity) -> bool`. Optional policy for the workbench, previews and traces (401/403). |
|
|
98
|
+
| `environment`, `environments` | Where the workbench is on. Defaults to `$SENDPROOF_ENVIRONMENT`, else `Production`; `("Development",)`. |
|
|
99
|
+
| `auth_providers` | Sign-in integrations shown on the workbench sign-in page (`cookie` for a password JSON endpoint, `personas`, `oidc`...). |
|
|
100
|
+
| `api_name`, `openapi_url`, `documents` | Display name and OpenAPI documents (default: your app title and `openapi_url`). |
|
|
101
|
+
| `field_modules` | Same-origin ES modules that register custom field renderers. |
|
|
102
|
+
| `include_sql_parameter_values` | Show SQL parameter values. Development only by default. |
|
|
103
|
+
| `trace_ttl`, `clock` | Trace lifetime in seconds and an injectable monotonic clock. |
|
|
104
|
+
|
|
105
|
+
## Effects and logs
|
|
106
|
+
|
|
107
|
+
Record outgoing email, HTTP calls, jobs and messages with `sendproof_core.record_email` and
|
|
108
|
+
friends, and skip delivery when they return `True`. Standard `logging` records are captured when
|
|
109
|
+
their logger propagates to the root logger.
|
|
110
|
+
|
|
111
|
+
## Notes
|
|
112
|
+
|
|
113
|
+
- Mount under a prefix with Starlette `Mount` or `root_path`; discovery URLs include it.
|
|
114
|
+
- The adapter does not pass `/sendproof/_preview` through your middleware twice; your middleware sees
|
|
115
|
+
the preview request once, with the preview URL, before dispatch to the real route.
|
|
116
|
+
- Streaming and file-path responses are buffered or rejected in a preview; websockets are not supported.
|
|
117
|
+
- See the [SQLAlchemy coverage notes](../sqlalchemy/README.md#coverage-notes) for what a preview
|
|
118
|
+
can and cannot roll back.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
sendproof_fastapi/__init__.py,sha256=UXSg_9sMvfUZuv5QAneZC5-lI-GbkbvADijUTe4gOlY,324
|
|
2
|
+
sendproof_fastapi/bench.py,sha256=r3e0Jx_GclWBzodURDzDUmapdJQ7aPwxxFspjcC7wR0,5353
|
|
3
|
+
sendproof_fastapi/capture_send.py,sha256=NXKOM0DpudO_DJCqBcVAGpsn934w8uw9p5Ko10HuyiA,1837
|
|
4
|
+
sendproof_fastapi/marker.py,sha256=CYuTdpw0OIYyhfDstwn3ntcbw_bfqCwb8UJUR4enqi0,1745
|
|
5
|
+
sendproof_fastapi/middleware.py,sha256=fOT0x_jbyUuhXawrxrmLeTsHL_r_huZERyQmkiSiO0o,22403
|
|
6
|
+
sendproof_fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
sendproof_fastapi/routing.py,sha256=T108aGu9f8t5uVt1vrD1pGxpPMUNq5dkp0E6MYSSAaI,2571
|
|
8
|
+
sendproof_fastapi-0.1.0a1.dist-info/METADATA,sha256=ierVLYv9MniLsR_npgEsvsOIktRmd4DwqfLCOjjQq7E,6241
|
|
9
|
+
sendproof_fastapi-0.1.0a1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
sendproof_fastapi-0.1.0a1.dist-info/licenses/LICENSE,sha256=FN_kx0TTA_TvTWeb5MzY7v1r6PwKKhW5msNFB2MeWSs,1079
|
|
11
|
+
sendproof_fastapi-0.1.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sendproof contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|