rn-forge-fastapi 0.4.1__tar.gz → 0.5.0__tar.gz
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.
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/PKG-INFO +30 -22
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/README.md +25 -17
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/pyproject.toml +5 -5
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/pyproject.toml.orig +5 -5
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/__init__.py +0 -2
- rn_forge_fastapi-0.5.0/src/rn_forge/fastapi/_batch.py +147 -0
- rn_forge_fastapi-0.5.0/src/rn_forge/fastapi/_tabular.py +106 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/__init__.py +0 -2
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/dependencies.py +12 -44
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/rate_limit.py +9 -6
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/redis.py +2 -1
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/routes.py +24 -76
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/idempotency.py +13 -4
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/transfer.py +60 -200
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/LICENSE +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/app.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/authorization.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/csrf.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/proxies.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/sessions.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/cors.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/dependencies.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/deprecation.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/health.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/merge_patch.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/openapi.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/problem.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/py.typed +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/read_mask.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/soft_delete.py +0 -0
- {rn_forge_fastapi-0.4.1 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/sse.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rn-forge-fastapi
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: FastAPI adapters over rn-forge-web
|
|
5
5
|
Author: Rohit Narayanan
|
|
6
6
|
Author-email: Rohit Narayanan <rohit.nn@gmail.com>
|
|
@@ -14,13 +14,13 @@ Classifier: Programming Language :: Python :: 3
|
|
|
14
14
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.14
|
|
16
16
|
Classifier: Typing :: Typed
|
|
17
|
-
Requires-Dist: rn-forge-auth>=0.
|
|
18
|
-
Requires-Dist: rn-forge-commons>=0.8.0,<0.
|
|
17
|
+
Requires-Dist: rn-forge-auth>=0.2.0,<0.3
|
|
18
|
+
Requires-Dist: rn-forge-commons>=0.8.0,<0.11
|
|
19
19
|
Requires-Dist: rn-forge-web[security]>=0.3.0,<0.4
|
|
20
20
|
Requires-Dist: fastapi>=0.141.1
|
|
21
21
|
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.65b0
|
|
22
|
-
Requires-Dist: rn-forge-auth[oidc]>=0.
|
|
23
|
-
Requires-Dist: rn-forge-auth[redis]>=0.
|
|
22
|
+
Requires-Dist: rn-forge-auth[oidc]>=0.2.0,<0.3 ; extra == 'oidc'
|
|
23
|
+
Requires-Dist: rn-forge-auth[redis]>=0.2.0,<0.3 ; extra == 'redis'
|
|
24
24
|
Requires-Dist: sse-starlette>=3.4.11 ; extra == 'sse'
|
|
25
25
|
Requires-Dist: assertpy>=2.35 ; extra == 'testing'
|
|
26
26
|
Requires-Dist: httpx>=0.28.1 ; extra == 'testing'
|
|
@@ -68,16 +68,9 @@ router factory and an OpenAPI repair. **It makes no wire decision of its own.**
|
|
|
68
68
|
|
|
69
69
|
## Where it sits
|
|
70
70
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
`rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI. It
|
|
77
|
-
never imports `rn_forge.django` — the two framework packages are independent
|
|
78
|
-
siblings — nor `rn_forge.cli` or `rn_forge.tooling`. `.importlinter` carries the
|
|
79
|
-
`fastapi-runtime-has-no-tooling` and `web-layers` contracts, and
|
|
80
|
-
`uv run lint-imports` proves them.
|
|
71
|
+
`rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI; it
|
|
72
|
+
never imports `rn_forge.django`, `rn_forge.cli` or `rn_forge.tooling`;
|
|
73
|
+
`task lint` proves it.
|
|
81
74
|
|
|
82
75
|
## The import path
|
|
83
76
|
|
|
@@ -101,8 +94,24 @@ problem types, the auth contract), and this package does not re-export it.
|
|
|
101
94
|
Declare `rn-forge-web` as well, so the import is not an undeclared transitive
|
|
102
95
|
dependency.
|
|
103
96
|
|
|
104
|
-
|
|
105
|
-
|
|
97
|
+
Extras: `oidc` (JWKS bearer auth and OIDC login, `rn-forge-auth[oidc]`), `redis`
|
|
98
|
+
(the Redis stores and `rn_forge.fastapi.auth.redis`), `transfer`
|
|
99
|
+
(`rn-forge-data` and `python-multipart`, for `rn_forge.fastapi.transfer`), `sse`
|
|
100
|
+
(`sse-starlette`, for `rn_forge.fastapi.sse`) and `testing` (`assertpy`, `httpx`
|
|
101
|
+
and `pytest`).
|
|
102
|
+
|
|
103
|
+
## Minimum example
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from rn_forge.fastapi import FastApiApp
|
|
107
|
+
|
|
108
|
+
app = FastApiApp(title="Orders")
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The app serves `/healthz` and `/readyz` and renders every error as a problem
|
|
112
|
+
body; the
|
|
113
|
+
[quickstart](https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/guides/quickstart.html)
|
|
114
|
+
adds pagination and readiness checks.
|
|
106
115
|
|
|
107
116
|
## What this package deliberately does not ship
|
|
108
117
|
|
|
@@ -129,8 +138,8 @@ local checkout, for local development only.
|
|
|
129
138
|
## Dependencies
|
|
130
139
|
|
|
131
140
|
**`rn-forge-web`** — every module adapts one of its primitives.
|
|
132
|
-
|
|
133
|
-
|
|
141
|
+
|
|
142
|
+
**`rn-forge-commons`** — declared directly: `problem` uses its `AppLogger`.
|
|
134
143
|
|
|
135
144
|
**`rn-forge-auth`** — a base dependency: the `auth` package is built on its
|
|
136
145
|
login flows, `Principal`, `Requirement` and authenticator contracts. Its OIDC
|
|
@@ -164,6 +173,5 @@ the same literal segment collide silently here.
|
|
|
164
173
|
|
|
165
174
|
## Documentation
|
|
166
175
|
|
|
167
|
-
`
|
|
168
|
-
|
|
169
|
-
application is written from.
|
|
176
|
+
`task docs:build` builds the combined site and every package site. The wiring
|
|
177
|
+
guide is the page an application is written from.
|
|
@@ -27,16 +27,9 @@ router factory and an OpenAPI repair. **It makes no wire decision of its own.**
|
|
|
27
27
|
|
|
28
28
|
## Where it sits
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
`rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI. It
|
|
36
|
-
never imports `rn_forge.django` — the two framework packages are independent
|
|
37
|
-
siblings — nor `rn_forge.cli` or `rn_forge.tooling`. `.importlinter` carries the
|
|
38
|
-
`fastapi-runtime-has-no-tooling` and `web-layers` contracts, and
|
|
39
|
-
`uv run lint-imports` proves them.
|
|
30
|
+
`rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI; it
|
|
31
|
+
never imports `rn_forge.django`, `rn_forge.cli` or `rn_forge.tooling`;
|
|
32
|
+
`task lint` proves it.
|
|
40
33
|
|
|
41
34
|
## The import path
|
|
42
35
|
|
|
@@ -60,8 +53,24 @@ problem types, the auth contract), and this package does not re-export it.
|
|
|
60
53
|
Declare `rn-forge-web` as well, so the import is not an undeclared transitive
|
|
61
54
|
dependency.
|
|
62
55
|
|
|
63
|
-
|
|
64
|
-
|
|
56
|
+
Extras: `oidc` (JWKS bearer auth and OIDC login, `rn-forge-auth[oidc]`), `redis`
|
|
57
|
+
(the Redis stores and `rn_forge.fastapi.auth.redis`), `transfer`
|
|
58
|
+
(`rn-forge-data` and `python-multipart`, for `rn_forge.fastapi.transfer`), `sse`
|
|
59
|
+
(`sse-starlette`, for `rn_forge.fastapi.sse`) and `testing` (`assertpy`, `httpx`
|
|
60
|
+
and `pytest`).
|
|
61
|
+
|
|
62
|
+
## Minimum example
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from rn_forge.fastapi import FastApiApp
|
|
66
|
+
|
|
67
|
+
app = FastApiApp(title="Orders")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The app serves `/healthz` and `/readyz` and renders every error as a problem
|
|
71
|
+
body; the
|
|
72
|
+
[quickstart](https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/guides/quickstart.html)
|
|
73
|
+
adds pagination and readiness checks.
|
|
65
74
|
|
|
66
75
|
## What this package deliberately does not ship
|
|
67
76
|
|
|
@@ -88,8 +97,8 @@ local checkout, for local development only.
|
|
|
88
97
|
## Dependencies
|
|
89
98
|
|
|
90
99
|
**`rn-forge-web`** — every module adapts one of its primitives.
|
|
91
|
-
|
|
92
|
-
|
|
100
|
+
|
|
101
|
+
**`rn-forge-commons`** — declared directly: `problem` uses its `AppLogger`.
|
|
93
102
|
|
|
94
103
|
**`rn-forge-auth`** — a base dependency: the `auth` package is built on its
|
|
95
104
|
login flows, `Principal`, `Requirement` and authenticator contracts. Its OIDC
|
|
@@ -123,6 +132,5 @@ the same literal segment collide silently here.
|
|
|
123
132
|
|
|
124
133
|
## Documentation
|
|
125
134
|
|
|
126
|
-
`
|
|
127
|
-
|
|
128
|
-
application is written from.
|
|
135
|
+
`task docs:build` builds the combined site and every package site. The wiring
|
|
136
|
+
guide is the page an application is written from.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "rn-forge-fastapi"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.5.0"
|
|
4
4
|
description = "FastAPI adapters over rn-forge-web"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -17,8 +17,8 @@ classifiers = [
|
|
|
17
17
|
]
|
|
18
18
|
requires-python = ">=3.14"
|
|
19
19
|
dependencies = [
|
|
20
|
-
"rn-forge-auth>=0.
|
|
21
|
-
"rn-forge-commons>=0.8.0,<0.
|
|
20
|
+
"rn-forge-auth>=0.2.0,<0.3",
|
|
21
|
+
"rn-forge-commons>=0.8.0,<0.11",
|
|
22
22
|
"rn-forge-web[security]>=0.3.0,<0.4",
|
|
23
23
|
"fastapi>=0.141.1",
|
|
24
24
|
"opentelemetry-instrumentation-fastapi>=0.65b0",
|
|
@@ -34,8 +34,8 @@ testing = [
|
|
|
34
34
|
"httpx>=0.28.1",
|
|
35
35
|
"pytest>=9.1.1",
|
|
36
36
|
]
|
|
37
|
-
oidc = ["rn-forge-auth[oidc]>=0.
|
|
38
|
-
redis = ["rn-forge-auth[redis]>=0.
|
|
37
|
+
oidc = ["rn-forge-auth[oidc]>=0.2.0,<0.3"]
|
|
38
|
+
redis = ["rn-forge-auth[redis]>=0.2.0,<0.3"]
|
|
39
39
|
transfer = [
|
|
40
40
|
"rn-forge-data>=0.1.1,<0.2",
|
|
41
41
|
"python-multipart>=0.0.20",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "rn-forge-fastapi"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.5.0"
|
|
4
4
|
description = "FastAPI adapters over rn-forge-web"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
|
|
@@ -19,8 +19,8 @@ classifiers = [
|
|
|
19
19
|
requires-python = ">=3.14"
|
|
20
20
|
# Internal requirements are version ranges (ADR-0004).
|
|
21
21
|
dependencies = [
|
|
22
|
-
"rn-forge-auth>=0.
|
|
23
|
-
"rn-forge-commons>=0.8.0,<0.
|
|
22
|
+
"rn-forge-auth>=0.2.0,<0.3",
|
|
23
|
+
"rn-forge-commons>=0.8.0,<0.11",
|
|
24
24
|
# `[security]` is a hard requirement, not an extra: `FastApiApp` installs
|
|
25
25
|
# `SecurityHeadersMiddleware` by default (`AppConfig.security_headers`).
|
|
26
26
|
"rn-forge-web[security]>=0.3.0,<0.4",
|
|
@@ -38,10 +38,10 @@ testing = ["assertpy>=2.35", "httpx>=0.28.1", "pytest>=9.1.1"]
|
|
|
38
38
|
# JWKS bearer auth: `rn_forge.auth.oidc.OidcAuthenticator` passed to
|
|
39
39
|
# `bearer_auth()`. Nothing in this package imports it; the extra exists so a
|
|
40
40
|
# consumer asks for it by name rather than reaching into auth's extras.
|
|
41
|
-
oidc = ["rn-forge-auth[oidc]>=0.
|
|
41
|
+
oidc = ["rn-forge-auth[oidc]>=0.2.0,<0.3"]
|
|
42
42
|
# Redis-backed login sessions and transactions for `rn_forge.fastapi.auth`:
|
|
43
43
|
# `rn_forge.auth.redis`, and the CSRF token store `rn_forge.fastapi.auth.redis`.
|
|
44
|
-
redis = ["rn-forge-auth[redis]>=0.
|
|
44
|
+
redis = ["rn-forge-auth[redis]>=0.2.0,<0.3"]
|
|
45
45
|
# Tabular export and import: `rn_forge.fastapi.transfer`. Not imported by the
|
|
46
46
|
# package facade. `python-multipart` is what FastAPI's `UploadFile` needs.
|
|
47
47
|
transfer = ["rn-forge-data>=0.1.1,<0.2", "python-multipart>=0.0.20"]
|
|
@@ -7,7 +7,6 @@ from rn_forge.fastapi.auth import (
|
|
|
7
7
|
CSRF_COOKIE,
|
|
8
8
|
CSRF_HEADER,
|
|
9
9
|
SESSION_COOKIE,
|
|
10
|
-
TRANSACTION_COOKIE,
|
|
11
10
|
ActiveSession,
|
|
12
11
|
AuthRoutesConfig,
|
|
13
12
|
BearerAuth,
|
|
@@ -62,7 +61,6 @@ __all__ = [
|
|
|
62
61
|
"CSRF_COOKIE",
|
|
63
62
|
"CSRF_HEADER",
|
|
64
63
|
"SESSION_COOKIE",
|
|
65
|
-
"TRANSACTION_COOKIE",
|
|
66
64
|
"ActiveSession",
|
|
67
65
|
"AppConfig",
|
|
68
66
|
"AuthRoutesConfig",
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Checks and validates a batch request body: the guards and the threaded JSON route."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Callable, Coroutine, Mapping, Sequence
|
|
5
|
+
from typing import Annotated, Any, cast
|
|
6
|
+
|
|
7
|
+
from fastapi import Depends, Request
|
|
8
|
+
from fastapi.concurrency import run_in_threadpool
|
|
9
|
+
from fastapi.exceptions import RequestValidationError
|
|
10
|
+
from fastapi.params import Depends as DependsParam
|
|
11
|
+
from fastapi.responses import Response
|
|
12
|
+
from fastapi.routing import APIRoute
|
|
13
|
+
from pydantic import (
|
|
14
|
+
BaseModel,
|
|
15
|
+
SkipValidation,
|
|
16
|
+
TypeAdapter,
|
|
17
|
+
ValidationError,
|
|
18
|
+
create_model,
|
|
19
|
+
)
|
|
20
|
+
from rn_forge.web import (
|
|
21
|
+
NULL_FIELD_DETAIL,
|
|
22
|
+
REQUIRED_FIELD_DETAIL,
|
|
23
|
+
RowsInvalid,
|
|
24
|
+
)
|
|
25
|
+
from rn_forge.web.transfer import NON_EMPTY_LIST_DETAIL, RowError, row_cap_problem
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def list_model(
|
|
29
|
+
name: str, member: str, item: Any, *, validate_items: bool = True
|
|
30
|
+
) -> type[BaseModel]:
|
|
31
|
+
"""Build ``{member: [item]}``, the schema FastAPI documents and validates."""
|
|
32
|
+
make = cast("Callable[..., type[BaseModel]]", create_model)
|
|
33
|
+
# The guard has already validated each item; FastAPI would do it again.
|
|
34
|
+
items = list[item] if validate_items else Annotated[list[item], SkipValidation]
|
|
35
|
+
return make(name, **{member: (items, ...)})
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def rejection(loc: str, kind: str, message: str) -> RequestValidationError:
|
|
39
|
+
return RequestValidationError(
|
|
40
|
+
[{"type": kind, "loc": ("body", loc), "msg": message}]
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def error_message(err: Mapping[str, Any]) -> str:
|
|
45
|
+
if err["type"] == "missing":
|
|
46
|
+
return REQUIRED_FIELD_DETAIL
|
|
47
|
+
if "input" in err and err["input"] is None:
|
|
48
|
+
return NULL_FIELD_DETAIL
|
|
49
|
+
if err["type"] == "value_error" and "ctx" in err:
|
|
50
|
+
return str(err["ctx"]["error"])
|
|
51
|
+
return err["msg"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def item_errors(index: int, exc: ValidationError) -> list[RowError]:
|
|
55
|
+
return [
|
|
56
|
+
RowError(index, ".".join(str(part) for part in err["loc"]), error_message(err))
|
|
57
|
+
for err in exc.errors()
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def checked_list(
|
|
62
|
+
request: Request, key: str, max_rows: int | None
|
|
63
|
+
) -> list[object]:
|
|
64
|
+
"""Return the raw body's *key* member, which must be a non-empty list within *max_rows*."""
|
|
65
|
+
try:
|
|
66
|
+
body: object = await request.json()
|
|
67
|
+
except ValueError:
|
|
68
|
+
body = None
|
|
69
|
+
members: Mapping[str, object] = (
|
|
70
|
+
cast("Mapping[str, object]", body) if isinstance(body, Mapping) else {}
|
|
71
|
+
)
|
|
72
|
+
if key not in members:
|
|
73
|
+
raise rejection(key, "missing", "Field required")
|
|
74
|
+
value: object = members[key]
|
|
75
|
+
if not isinstance(value, list) or not value:
|
|
76
|
+
raise rejection(key, "value_error", NON_EMPTY_LIST_DETAIL)
|
|
77
|
+
entries = cast("list[object]", value)
|
|
78
|
+
if max_rows is not None and len(entries) > max_rows:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
row_cap_problem("batch", max_rows, instance=request.url.path).problem.detail
|
|
81
|
+
)
|
|
82
|
+
return entries
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def list_guard(key: str, max_rows: int | None) -> DependsParam:
|
|
86
|
+
"""Check the raw body's *key* member before FastAPI validates the body."""
|
|
87
|
+
|
|
88
|
+
async def guard(request: Request) -> None:
|
|
89
|
+
await checked_list(request, key, max_rows)
|
|
90
|
+
|
|
91
|
+
return Depends(guard)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def validate_items[T: BaseModel](
|
|
95
|
+
items: TypeAdapter[T], entries: Sequence[object]
|
|
96
|
+
) -> tuple[list[T], list[RowError]]:
|
|
97
|
+
valid: list[T] = []
|
|
98
|
+
errors: list[RowError] = []
|
|
99
|
+
for index, item in enumerate(entries):
|
|
100
|
+
try:
|
|
101
|
+
valid.append(items.validate_python(item))
|
|
102
|
+
except ValidationError as exc:
|
|
103
|
+
errors.extend(item_errors(index, exc))
|
|
104
|
+
return valid, errors
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def models_guard[T: BaseModel](
|
|
108
|
+
key: str, max_rows: int | None, item_model: type[T]
|
|
109
|
+
) -> Any:
|
|
110
|
+
"""Check the body's *key* member, validate each item into *item_model* and yield the models.
|
|
111
|
+
|
|
112
|
+
Runs before FastAPI validates the body. The checks fire in the order the
|
|
113
|
+
wire contract states, and item failures use the row-error wording.
|
|
114
|
+
"""
|
|
115
|
+
items = TypeAdapter(item_model)
|
|
116
|
+
|
|
117
|
+
async def guard(request: Request) -> list[T]:
|
|
118
|
+
entries = await checked_list(request, key, max_rows)
|
|
119
|
+
valid, errors = await run_in_threadpool(validate_items, items, entries)
|
|
120
|
+
if errors:
|
|
121
|
+
raise RowsInvalid(errors, root=key)
|
|
122
|
+
return valid
|
|
123
|
+
|
|
124
|
+
return Depends(guard)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class ThreadedJsonRequest(Request):
|
|
128
|
+
"""A request whose JSON body is parsed in a worker thread."""
|
|
129
|
+
|
|
130
|
+
async def json(self) -> Any:
|
|
131
|
+
if not hasattr(self, "_json"):
|
|
132
|
+
self._json = await run_in_threadpool(json.loads, await self.body())
|
|
133
|
+
return self._json
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class ThreadedJsonRoute(APIRoute):
|
|
137
|
+
"""A route that reads its request body through :class:`ThreadedJsonRequest`."""
|
|
138
|
+
|
|
139
|
+
# FastAPI parses the body before any dependency runs, so the route has to
|
|
140
|
+
# swap the request class to move that parse off the event loop.
|
|
141
|
+
def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
|
|
142
|
+
handler = super().get_route_handler()
|
|
143
|
+
|
|
144
|
+
async def route(request: Request) -> Response:
|
|
145
|
+
return await handler(ThreadedJsonRequest(request.scope, request.receive))
|
|
146
|
+
|
|
147
|
+
return route
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Reads tabular files into validated rows and writes rows as CSV chunks or tables."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import io
|
|
5
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import tablib
|
|
9
|
+
from pydantic import BaseModel, TypeAdapter, ValidationError
|
|
10
|
+
from rn_forge.data import write_xlsx
|
|
11
|
+
from rn_forge.web.transfer import (
|
|
12
|
+
TABULAR_FORMATS,
|
|
13
|
+
RowError,
|
|
14
|
+
TabularFormat,
|
|
15
|
+
unreadable_file_detail,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
CSV_CHUNK_ROWS = 1_000
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def columns(model: type[BaseModel]) -> list[str]:
|
|
22
|
+
fields = [
|
|
23
|
+
info.serialization_alias or name for name, info in model.model_fields.items()
|
|
24
|
+
]
|
|
25
|
+
computed = [
|
|
26
|
+
info.alias or name for name, info in model.model_computed_fields.items()
|
|
27
|
+
]
|
|
28
|
+
return [*fields, *computed]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def records(
|
|
32
|
+
rows: Iterable[Any], model: type[BaseModel], mode: str
|
|
33
|
+
) -> Iterator[dict[str, Any]]:
|
|
34
|
+
for row in rows:
|
|
35
|
+
yield model.model_validate(row, from_attributes=True).model_dump(
|
|
36
|
+
by_alias=True,
|
|
37
|
+
mode=mode,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def csv_chunks(
|
|
42
|
+
rows: Iterable[Any], model: type[BaseModel], names: list[str]
|
|
43
|
+
) -> Iterator[str]:
|
|
44
|
+
"""Yield the CSV text of *rows*, the header first, in chunks of ``CSV_CHUNK_ROWS`` rows."""
|
|
45
|
+
# Streaming one row per chunk costs a worker-thread hop per row.
|
|
46
|
+
buffer = io.StringIO()
|
|
47
|
+
writer = csv.writer(buffer)
|
|
48
|
+
writer.writerow(names)
|
|
49
|
+
count = 0
|
|
50
|
+
for record in records(rows, model, "json"):
|
|
51
|
+
writer.writerow([record[c] for c in names])
|
|
52
|
+
count += 1
|
|
53
|
+
if count == CSV_CHUNK_ROWS:
|
|
54
|
+
yield buffer.getvalue()
|
|
55
|
+
buffer.seek(0)
|
|
56
|
+
buffer.truncate()
|
|
57
|
+
count = 0
|
|
58
|
+
if buffer.tell():
|
|
59
|
+
yield buffer.getvalue()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_body(
|
|
63
|
+
rows: Iterable[Any], model: type[BaseModel], fmt: TabularFormat, names: list[str]
|
|
64
|
+
) -> bytes | str:
|
|
65
|
+
dataset: Any = tablib.Dataset(headers=names)
|
|
66
|
+
for record in records(rows, model, "python"):
|
|
67
|
+
dataset.append([record[c] for c in names])
|
|
68
|
+
if fmt.extension == "xlsx":
|
|
69
|
+
return write_xlsx(dataset)
|
|
70
|
+
return dataset.export(fmt.tablib_name)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_table[T: BaseModel](
|
|
74
|
+
raw: bytes, extension: str, model: type[T]
|
|
75
|
+
) -> tuple[list[T], list[RowError], int]:
|
|
76
|
+
"""Load *raw* as *extension* and validate each row; return the valid rows, errors and row count."""
|
|
77
|
+
data: bytes | str = raw if extension == "xlsx" else raw.decode("utf-8-sig")
|
|
78
|
+
try:
|
|
79
|
+
dataset: Any = tablib.Dataset()
|
|
80
|
+
dataset.load(data, format=TABULAR_FORMATS[extension].tablib_name)
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
raise ValueError(unreadable_file_detail(extension)) from exc
|
|
83
|
+
adapter = TypeAdapter(model)
|
|
84
|
+
rows = dicts(dataset)
|
|
85
|
+
valid: list[T] = []
|
|
86
|
+
errors: list[RowError] = []
|
|
87
|
+
for index, row in enumerate(rows):
|
|
88
|
+
try:
|
|
89
|
+
valid.append(adapter.validate_python(row))
|
|
90
|
+
except ValidationError as exc:
|
|
91
|
+
errors.extend(row_errors(index, exc))
|
|
92
|
+
return valid, errors, len(rows)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def dicts(dataset: Any) -> list[Mapping[str, Any]]:
|
|
96
|
+
return dataset.dict
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def row_errors(index: int, exc: ValidationError) -> Iterator[RowError]:
|
|
100
|
+
for err in exc.errors():
|
|
101
|
+
message = (
|
|
102
|
+
str(err["ctx"]["error"])
|
|
103
|
+
if err["type"] == "value_error" and "ctx" in err
|
|
104
|
+
else err["msg"]
|
|
105
|
+
)
|
|
106
|
+
yield RowError(index, str(err["loc"][0]) if err["loc"] else "", message)
|
|
@@ -24,7 +24,6 @@ from rn_forge.fastapi.auth.rate_limit import (
|
|
|
24
24
|
RateLimiter,
|
|
25
25
|
)
|
|
26
26
|
from rn_forge.fastapi.auth.routes import (
|
|
27
|
-
TRANSACTION_COOKIE,
|
|
28
27
|
AuthRoutesConfig,
|
|
29
28
|
auth_router,
|
|
30
29
|
sessions_for,
|
|
@@ -44,7 +43,6 @@ __all__ = [
|
|
|
44
43
|
"CSRF_COOKIE",
|
|
45
44
|
"CSRF_HEADER",
|
|
46
45
|
"SESSION_COOKIE",
|
|
47
|
-
"TRANSACTION_COOKIE",
|
|
48
46
|
"ActiveSession",
|
|
49
47
|
"AuthRoutesConfig",
|
|
50
48
|
"BearerAuth",
|
|
@@ -8,7 +8,6 @@ from __future__ import annotations
|
|
|
8
8
|
|
|
9
9
|
import inspect
|
|
10
10
|
from collections.abc import Awaitable, Callable, Mapping
|
|
11
|
-
from dataclasses import replace
|
|
12
11
|
from typing import cast
|
|
13
12
|
|
|
14
13
|
from fastapi import Depends, Request, Security
|
|
@@ -23,15 +22,16 @@ from rn_forge.auth import (
|
|
|
23
22
|
AccountResolver,
|
|
24
23
|
AsyncAuthenticator,
|
|
25
24
|
Authenticator,
|
|
26
|
-
AuthorizationContext,
|
|
27
25
|
AuthorizationContextProvider,
|
|
28
26
|
Authorizer,
|
|
29
27
|
Principal,
|
|
28
|
+
PrincipalLinkError,
|
|
30
29
|
Requirement,
|
|
31
30
|
ScopeAuthorizer,
|
|
32
31
|
audit,
|
|
33
|
-
|
|
32
|
+
link_bearer_principal,
|
|
34
33
|
requirement_for,
|
|
34
|
+
session_principal,
|
|
35
35
|
)
|
|
36
36
|
from rn_forge.fastapi.auth.sessions import ActiveSession, active_session
|
|
37
37
|
from rn_forge.fastapi.problem import Log
|
|
@@ -104,30 +104,15 @@ class BearerAuth:
|
|
|
104
104
|
raise
|
|
105
105
|
|
|
106
106
|
def _link(self, principal: Principal) -> Principal:
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if account_id is None:
|
|
113
|
-
raise AuthenticationFailed("No account is linked to the token subject")
|
|
114
|
-
context = self._contexts.resolve(account_id)
|
|
115
|
-
if not context.active:
|
|
116
|
-
raise AuthenticationFailed("The account is not active")
|
|
117
|
-
return replace(
|
|
118
|
-
principal,
|
|
119
|
-
subject=account_id,
|
|
120
|
-
external_subject=principal.subject,
|
|
121
|
-
permissions=effective_permissions(
|
|
122
|
-
context.permissions,
|
|
123
|
-
mechanism="bearer",
|
|
124
|
-
scopes=principal.scopes,
|
|
107
|
+
try:
|
|
108
|
+
return link_bearer_principal(
|
|
109
|
+
principal,
|
|
110
|
+
accounts=self._accounts,
|
|
111
|
+
contexts=self._contexts,
|
|
125
112
|
scope_map=self._scope_map,
|
|
126
|
-
)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
attributes=context.attributes,
|
|
130
|
-
)
|
|
113
|
+
)
|
|
114
|
+
except PrincipalLinkError as exc:
|
|
115
|
+
raise AuthenticationFailed(str(exc)) from exc
|
|
131
116
|
|
|
132
117
|
async def __call__(
|
|
133
118
|
self,
|
|
@@ -224,25 +209,8 @@ def current_principal(*, bearer: BearerAuth | None = None) -> PrincipalDependenc
|
|
|
224
209
|
return dependency
|
|
225
210
|
|
|
226
211
|
|
|
227
|
-
def _tenant(context: AuthorizationContext) -> str | None:
|
|
228
|
-
tenant = context.attributes.get("tenant")
|
|
229
|
-
return tenant if isinstance(tenant, str) else None
|
|
230
|
-
|
|
231
|
-
|
|
232
212
|
def _session_principal(active: ActiveSession) -> Principal:
|
|
233
|
-
|
|
234
|
-
return Principal(
|
|
235
|
-
subject=info.account_id,
|
|
236
|
-
issuer=info.issuer,
|
|
237
|
-
external_subject=info.external_subject,
|
|
238
|
-
permissions=context.permissions,
|
|
239
|
-
roles=context.roles,
|
|
240
|
-
tenant=_tenant(context),
|
|
241
|
-
attributes=context.attributes,
|
|
242
|
-
mechanism="session",
|
|
243
|
-
auth_time=info.auth_time,
|
|
244
|
-
amr=info.amr,
|
|
245
|
-
)
|
|
213
|
+
return session_principal(active.info, active.context)
|
|
246
214
|
|
|
247
215
|
|
|
248
216
|
def basic_auth(
|
|
@@ -2,8 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import hashlib
|
|
6
|
-
import math
|
|
7
5
|
import threading
|
|
8
6
|
import time
|
|
9
7
|
from collections.abc import Callable
|
|
@@ -11,6 +9,12 @@ from dataclasses import dataclass
|
|
|
11
9
|
from datetime import timedelta
|
|
12
10
|
from typing import Protocol, runtime_checkable
|
|
13
11
|
|
|
12
|
+
from rn_forge.auth import (
|
|
13
|
+
fixed_window_key,
|
|
14
|
+
fixed_window_retry_after,
|
|
15
|
+
fixed_window_seconds,
|
|
16
|
+
)
|
|
17
|
+
|
|
14
18
|
__all__ = [
|
|
15
19
|
"InMemoryRateLimiter",
|
|
16
20
|
"RateLimit",
|
|
@@ -53,13 +57,12 @@ class RateLimiter(Protocol):
|
|
|
53
57
|
|
|
54
58
|
def window_seconds(rate: RateLimit) -> int:
|
|
55
59
|
"""The length of *rate*'s window in whole seconds, at least one."""
|
|
56
|
-
return
|
|
60
|
+
return fixed_window_seconds(rate.window)
|
|
57
61
|
|
|
58
62
|
|
|
59
63
|
def window_key(scope: str, subject: str, rate: RateLimit, now: float) -> str:
|
|
60
64
|
"""The counter key for a hit at *now*: a digest, so *subject* is never stored."""
|
|
61
|
-
|
|
62
|
-
return f"{digest}:{int(now // window_seconds(rate))}"
|
|
65
|
+
return fixed_window_key(scope, subject, window_seconds(rate), now)
|
|
63
66
|
|
|
64
67
|
|
|
65
68
|
class InMemoryRateLimiter:
|
|
@@ -88,4 +91,4 @@ class InMemoryRateLimiter:
|
|
|
88
91
|
self._counts[key] = (count, ends)
|
|
89
92
|
if count <= rate.limit:
|
|
90
93
|
return None
|
|
91
|
-
return
|
|
94
|
+
return fixed_window_retry_after(window, now)
|
|
@@ -12,6 +12,7 @@ from collections.abc import Callable
|
|
|
12
12
|
from datetime import timedelta
|
|
13
13
|
|
|
14
14
|
from redis import Redis
|
|
15
|
+
from rn_forge.auth import fixed_window_retry_after
|
|
15
16
|
from rn_forge.fastapi.auth.rate_limit import RateLimit, window_key, window_seconds
|
|
16
17
|
|
|
17
18
|
__all__ = ["RedisCsrfStore", "RedisRateLimiter"]
|
|
@@ -85,4 +86,4 @@ class RedisRateLimiter:
|
|
|
85
86
|
count = int(pipeline.execute()[0])
|
|
86
87
|
if count <= rate.limit:
|
|
87
88
|
return None
|
|
88
|
-
return
|
|
89
|
+
return fixed_window_retry_after(window, now)
|