resource-engine-fastapi 0.1.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.
- resource_engine_fastapi-0.1.0/.gitignore +18 -0
- resource_engine_fastapi-0.1.0/CHANGELOG.md +15 -0
- resource_engine_fastapi-0.1.0/LICENSE +202 -0
- resource_engine_fastapi-0.1.0/PKG-INFO +32 -0
- resource_engine_fastapi-0.1.0/README.md +5 -0
- resource_engine_fastapi-0.1.0/pyproject.toml +35 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/__init__.py +39 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/access.py +110 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/asyncapi.py +47 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/auth.py +158 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/authz.py +100 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/caching.py +111 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/docs.py +77 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/documents.py +219 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/email_events.py +85 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/errors.py +178 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/events.py +109 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/__init__.py +441 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/auth.js +171 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/console.js +340 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/events.js +189 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/explorer.css +156 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/explorer.js +275 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/jobs.js +143 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/messages.js +85 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/assets/publish.js +117 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/data.py +84 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/events.py +182 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/jobs.py +167 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/labels.py +198 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/messages.py +73 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/explorer/publish.py +85 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/exports.py +186 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/i18n.py +76 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/py.typed +0 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/router.py +1031 -0
- resource_engine_fastapi-0.1.0/src/resource_engine_fastapi/versioning.py +49 -0
- resource_engine_fastapi-0.1.0/tests/test_api_versions.py +164 -0
- resource_engine_fastapi-0.1.0/tests/test_asyncapi_route.py +28 -0
- resource_engine_fastapi-0.1.0/tests/test_authz_routes.py +196 -0
- resource_engine_fastapi-0.1.0/tests/test_bearer_auth.py +116 -0
- resource_engine_fastapi-0.1.0/tests/test_docs_mount.py +43 -0
- resource_engine_fastapi-0.1.0/tests/test_document_routes.py +147 -0
- resource_engine_fastapi-0.1.0/tests/test_email_events.py +30 -0
- resource_engine_fastapi-0.1.0/tests/test_event_receiver.py +100 -0
- resource_engine_fastapi-0.1.0/tests/test_explorer.py +507 -0
- resource_engine_fastapi-0.1.0/tests/test_export_route.py +143 -0
- resource_engine_fastapi-0.1.0/tests/test_locale.py +83 -0
- resource_engine_fastapi-0.1.0/tests/test_polymorphic_api.py +192 -0
- resource_engine_fastapi-0.1.0/tests/test_rate_limits.py +76 -0
- resource_engine_fastapi-0.1.0/tests/test_tenant_routes.py +102 -0
- resource_engine_fastapi-0.1.0/tests/test_version_routes.py +101 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.ruff_cache/
|
|
6
|
+
dist/
|
|
7
|
+
build/
|
|
8
|
+
*.egg-info/
|
|
9
|
+
*.db
|
|
10
|
+
site/
|
|
11
|
+
.emulators/
|
|
12
|
+
|
|
13
|
+
# Local notes, not committed
|
|
14
|
+
reviews/
|
|
15
|
+
.coverage
|
|
16
|
+
.coverage.*
|
|
17
|
+
htmlcov/
|
|
18
|
+
python-coverage-comment-action.txt
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog: resource-engine-fastapi
|
|
2
|
+
|
|
3
|
+
Notable changes to this package, newest first. Versions follow
|
|
4
|
+
[semantic versioning](https://semver.org) with the project's
|
|
5
|
+
[stability rules](https://github.com/EloiSans/python-resource-engine/blob/main/docs/stability.md).
|
|
6
|
+
|
|
7
|
+
## Unreleased
|
|
8
|
+
|
|
9
|
+
## 0.1.0 (2026-12-05)
|
|
10
|
+
|
|
11
|
+
First release.
|
|
12
|
+
|
|
13
|
+
- HTTP adapter: generated routes, document routes, bearer auth, error mapping, event push endpoint
|
|
14
|
+
- Lists take `q` (search) and `field[op]` filters (`amount[gte]=100`, `status[in]=a,b`), exports too
|
|
15
|
+
- `mount_email_events(app, parser, handler, *, token, path="/webhooks/email")`: `path` is a keyword with a default, like the other `mount_*` functions; `install_access_log` names its options; `mount_explorer` and `mount_docs` are typed
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: resource-engine-fastapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: FastAPI HTTP adapter for Resource Engine.
|
|
5
|
+
Project-URL: Homepage, https://github.com/EloiSans/python-resource-engine
|
|
6
|
+
Project-URL: Documentation, https://github.com/EloiSans/python-resource-engine/tree/main/docs
|
|
7
|
+
Project-URL: Source, https://github.com/EloiSans/python-resource-engine/tree/main/packages/resource-engine-fastapi
|
|
8
|
+
Project-URL: Issues, https://github.com/EloiSans/python-resource-engine/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/EloiSans/python-resource-engine/blob/main/packages/resource-engine-fastapi/CHANGELOG.md
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: fastapi>=0.110
|
|
24
|
+
Requires-Dist: python-multipart>=0.0.9
|
|
25
|
+
Requires-Dist: resource-engine<0.2,>=0.1.0
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# resource-engine-fastapi
|
|
29
|
+
|
|
30
|
+
FastAPI adapter for Resource Engine: generates routes from registered resources and maps engine errors to HTTP; `build_event_receiver` is a push endpoint for inbound events.
|
|
31
|
+
|
|
32
|
+
Part of [Resource Engine](../../README.md).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "resource-engine-fastapi"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "FastAPI HTTP adapter for Resource Engine."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 3 - Alpha",
|
|
11
|
+
"Framework :: AsyncIO",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Programming Language :: Python :: 3.14",
|
|
18
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["resource-engine>=0.1.0,<0.2", "fastapi>=0.110", "python-multipart>=0.0.9"]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/EloiSans/python-resource-engine"
|
|
25
|
+
Documentation = "https://github.com/EloiSans/python-resource-engine/tree/main/docs"
|
|
26
|
+
Source = "https://github.com/EloiSans/python-resource-engine/tree/main/packages/resource-engine-fastapi"
|
|
27
|
+
Issues = "https://github.com/EloiSans/python-resource-engine/issues"
|
|
28
|
+
Changelog = "https://github.com/EloiSans/python-resource-engine/blob/main/packages/resource-engine-fastapi/CHANGELOG.md"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["hatchling>=1.27"]
|
|
32
|
+
build-backend = "hatchling.build"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/resource_engine_fastapi"]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""FastAPI adapter for Resource Engine."""
|
|
2
|
+
|
|
3
|
+
from resource_engine_fastapi.access import AccessLogMiddleware, install_access_log
|
|
4
|
+
from resource_engine_fastapi.asyncapi import mount_asyncapi
|
|
5
|
+
from resource_engine_fastapi.auth import (
|
|
6
|
+
bearer_actor,
|
|
7
|
+
bearer_token,
|
|
8
|
+
forwarded_client_certificate,
|
|
9
|
+
request_credentials,
|
|
10
|
+
)
|
|
11
|
+
from resource_engine_fastapi.docs import mount_docs
|
|
12
|
+
from resource_engine_fastapi.email_events import mount_email_events
|
|
13
|
+
from resource_engine_fastapi.errors import install_exception_handlers, status_for
|
|
14
|
+
from resource_engine_fastapi.events import build_event_receiver, default_decoder
|
|
15
|
+
from resource_engine_fastapi.explorer import mount_explorer
|
|
16
|
+
from resource_engine_fastapi.i18n import LocaleMiddleware, install_locale
|
|
17
|
+
from resource_engine_fastapi.router import build_resource_router, build_router, mount_resources
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"AccessLogMiddleware",
|
|
21
|
+
"LocaleMiddleware",
|
|
22
|
+
"bearer_actor",
|
|
23
|
+
"bearer_token",
|
|
24
|
+
"build_event_receiver",
|
|
25
|
+
"build_resource_router",
|
|
26
|
+
"build_router",
|
|
27
|
+
"default_decoder",
|
|
28
|
+
"forwarded_client_certificate",
|
|
29
|
+
"install_access_log",
|
|
30
|
+
"install_exception_handlers",
|
|
31
|
+
"install_locale",
|
|
32
|
+
"mount_asyncapi",
|
|
33
|
+
"mount_docs",
|
|
34
|
+
"mount_email_events",
|
|
35
|
+
"mount_explorer",
|
|
36
|
+
"mount_resources",
|
|
37
|
+
"request_credentials",
|
|
38
|
+
"status_for",
|
|
39
|
+
]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Access log and request ids for the HTTP adapter.
|
|
2
|
+
|
|
3
|
+
``install_access_log(app)`` (or ``mount_resources(..., access_log=True)``)
|
|
4
|
+
writes one line per request on ``resource_engine.access``: method, route
|
|
5
|
+
template, status, duration, the caller and the request id. The request id
|
|
6
|
+
comes from ``X-Request-Id`` (or is generated), is returned in the response, and
|
|
7
|
+
is in the log context of everything the request does (operation logs, error
|
|
8
|
+
reports), so one id finds all of it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from resource_engine.logs import bind_log_context
|
|
20
|
+
from starlette.applications import Starlette
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("resource_engine.access")
|
|
23
|
+
|
|
24
|
+
_VALID = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AccessLogMiddleware:
|
|
28
|
+
"""ASGI middleware: request ids and one access log line per HTTP request.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
header: The request id header (accepted when it looks like an id).
|
|
32
|
+
skip: Paths not logged (health checks).
|
|
33
|
+
level: Log level of successful requests; 4xx log at the same level, 5xx at
|
|
34
|
+
``ERROR`` is left to the error reporter, so they log at ``WARNING``.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
app: Any,
|
|
40
|
+
*,
|
|
41
|
+
header: str = "x-request-id",
|
|
42
|
+
skip: tuple[str, ...] = ("/health", "/healthz", "/ready"),
|
|
43
|
+
level: int = logging.INFO,
|
|
44
|
+
) -> None:
|
|
45
|
+
self.app = app
|
|
46
|
+
self.header = header.lower().encode()
|
|
47
|
+
self.skip = skip
|
|
48
|
+
self.level = level
|
|
49
|
+
|
|
50
|
+
async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
|
|
51
|
+
"""Handle one ASGI call: set the request id and log the response."""
|
|
52
|
+
if scope["type"] != "http":
|
|
53
|
+
await self.app(scope, receive, send)
|
|
54
|
+
return
|
|
55
|
+
sent = dict(scope.get("headers") or ())
|
|
56
|
+
raw = sent.get(self.header, b"").decode("latin-1")
|
|
57
|
+
request_id = raw if _VALID.match(raw) else uuid.uuid4().hex
|
|
58
|
+
status = 500
|
|
59
|
+
started = time.perf_counter()
|
|
60
|
+
|
|
61
|
+
async def send_with_id(message: dict[str, Any]) -> None:
|
|
62
|
+
nonlocal status
|
|
63
|
+
if message["type"] == "http.response.start":
|
|
64
|
+
status = message["status"]
|
|
65
|
+
headers = list(message.get("headers") or ())
|
|
66
|
+
headers.append((self.header, request_id.encode()))
|
|
67
|
+
message = {**message, "headers": headers}
|
|
68
|
+
await send(message)
|
|
69
|
+
|
|
70
|
+
with bind_log_context(request_id=request_id):
|
|
71
|
+
try:
|
|
72
|
+
await self.app(scope, receive, send_with_id)
|
|
73
|
+
finally:
|
|
74
|
+
path = scope.get("path", "")
|
|
75
|
+
if not path.startswith(self.skip):
|
|
76
|
+
self._log(scope, status, time.perf_counter() - started, request_id)
|
|
77
|
+
|
|
78
|
+
def _log(self, scope: Any, status: int, seconds: float, request_id: str) -> None:
|
|
79
|
+
route = getattr(scope.get("route"), "path", None) or scope.get("path", "")
|
|
80
|
+
state = scope.get("state") or {}
|
|
81
|
+
principal = state.get("principal") if isinstance(state, dict) else None
|
|
82
|
+
level = self.level if status < 500 else logging.WARNING
|
|
83
|
+
logger.log(
|
|
84
|
+
level,
|
|
85
|
+
"%s %s %s %.1f ms",
|
|
86
|
+
scope.get("method"),
|
|
87
|
+
route,
|
|
88
|
+
status,
|
|
89
|
+
seconds * 1000,
|
|
90
|
+
extra={
|
|
91
|
+
"http_method": scope.get("method"),
|
|
92
|
+
"http_route": route,
|
|
93
|
+
"http_status": status,
|
|
94
|
+
"duration_ms": round(seconds * 1000, 1),
|
|
95
|
+
"principal": getattr(principal, "id", None),
|
|
96
|
+
"request_id": request_id,
|
|
97
|
+
},
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def install_access_log(
|
|
102
|
+
app: Starlette,
|
|
103
|
+
*,
|
|
104
|
+
header: str = "x-request-id",
|
|
105
|
+
skip: tuple[str, ...] = ("/health", "/healthz", "/ready"),
|
|
106
|
+
level: int = logging.INFO,
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Add ``AccessLogMiddleware`` to a FastAPI or Starlette ``app``, with its
|
|
109
|
+
options (see ``AccessLogMiddleware``)."""
|
|
110
|
+
app.add_middleware(AccessLogMiddleware, header=header, skip=skip, level=level)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Serve the AsyncAPI document next to OpenAPI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
10
|
+
from resource_engine import ResourceRegistry
|
|
11
|
+
from resource_engine.messaging import EventRouter, asyncapi_document
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def mount_asyncapi(
|
|
15
|
+
app: FastAPI,
|
|
16
|
+
registry: ResourceRegistry,
|
|
17
|
+
*,
|
|
18
|
+
path: str = "/asyncapi.json",
|
|
19
|
+
consumers: Sequence[EventRouter] = (),
|
|
20
|
+
document: Mapping[str, Any] | None = None,
|
|
21
|
+
**options: Any,
|
|
22
|
+
) -> dict[str, Any]:
|
|
23
|
+
"""Serve the AsyncAPI 3.0 document of the app's events at ``path``.
|
|
24
|
+
|
|
25
|
+
The document is built once, from ``registry`` and ``consumers`` with the
|
|
26
|
+
``asyncapi_document`` ``options`` (``title``, ``servers``, ``channels``,
|
|
27
|
+
``format``...), or given as ``document`` (for example the file written by
|
|
28
|
+
``resource-engine docs asyncapi``). The title and version default to the
|
|
29
|
+
app's. Returns the document.
|
|
30
|
+
"""
|
|
31
|
+
if document is None:
|
|
32
|
+
options.setdefault("title", app.title)
|
|
33
|
+
options.setdefault("version", app.version)
|
|
34
|
+
document = asyncapi_document(registry, consumers=consumers, **options)
|
|
35
|
+
body = dict(document)
|
|
36
|
+
|
|
37
|
+
async def asyncapi() -> JSONResponse:
|
|
38
|
+
return JSONResponse(body)
|
|
39
|
+
|
|
40
|
+
app.add_api_route(
|
|
41
|
+
path,
|
|
42
|
+
asyncapi,
|
|
43
|
+
methods=["GET"],
|
|
44
|
+
include_in_schema=False,
|
|
45
|
+
summary="AsyncAPI document",
|
|
46
|
+
)
|
|
47
|
+
return body
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Bearer-token authentication for the generated routes.
|
|
2
|
+
|
|
3
|
+
Use the returned dependency as ``actor_dependency``::
|
|
4
|
+
|
|
5
|
+
mount_resources(app, registry, manager, actor_dependency=bearer_actor(authenticator))
|
|
6
|
+
|
|
7
|
+
The engine then receives a ``Principal`` as ``actor``; with an authorizer
|
|
8
|
+
(``ResourceManager(authorizer=...)``) it decides what the principal may do.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import binascii
|
|
15
|
+
from collections.abc import Awaitable, Callable
|
|
16
|
+
from typing import Any
|
|
17
|
+
from urllib.parse import unquote
|
|
18
|
+
|
|
19
|
+
from fastapi import Request
|
|
20
|
+
from resource_engine.errors import AuthenticationFailed
|
|
21
|
+
from resource_engine.identity import authenticate, parse_authorization
|
|
22
|
+
from resource_engine.ports.identity import Authenticator, Credentials, Principal
|
|
23
|
+
|
|
24
|
+
type CertificateSource = Callable[[Request], bytes | None]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def bearer_token(request: Request) -> str | None:
|
|
28
|
+
"""``Authorization: Bearer|DPoP <token>``, or an API key in ``X-API-Key``."""
|
|
29
|
+
parsed = parse_authorization(request.headers.get("authorization"))
|
|
30
|
+
if parsed is not None:
|
|
31
|
+
return parsed[1]
|
|
32
|
+
api_key = request.headers.get("x-api-key", "").strip()
|
|
33
|
+
return api_key or None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def request_credentials(
|
|
37
|
+
request: Request,
|
|
38
|
+
*,
|
|
39
|
+
client_certificate: CertificateSource | None = None,
|
|
40
|
+
public_url: str | None = None,
|
|
41
|
+
) -> Credentials | None:
|
|
42
|
+
"""The request's token, scheme, DPoP proof and client certificate.
|
|
43
|
+
|
|
44
|
+
``public_url`` (``https://api.example.com``) replaces the scheme and host
|
|
45
|
+
the server sees, for the URL a DPoP proof must name behind a proxy.
|
|
46
|
+
"""
|
|
47
|
+
parsed = parse_authorization(request.headers.get("authorization"))
|
|
48
|
+
if parsed is None:
|
|
49
|
+
api_key = request.headers.get("x-api-key", "").strip()
|
|
50
|
+
if not api_key:
|
|
51
|
+
return None
|
|
52
|
+
parsed = ("bearer", api_key)
|
|
53
|
+
scheme, token = parsed
|
|
54
|
+
proofs = request.headers.getlist("dpop")
|
|
55
|
+
if len(proofs) > 1:
|
|
56
|
+
raise AuthenticationFailed("Send a single DPoP header", reason="invalid_dpop_proof")
|
|
57
|
+
base = public_url.rstrip("/") if public_url else f"{request.url.scheme}://{request.url.netloc}"
|
|
58
|
+
return Credentials(
|
|
59
|
+
token=token,
|
|
60
|
+
scheme=scheme,
|
|
61
|
+
method=request.method,
|
|
62
|
+
url=base + request.url.path,
|
|
63
|
+
proof=proofs[0] if proofs else None,
|
|
64
|
+
client_certificate=client_certificate(request) if client_certificate else None,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def forwarded_client_certificate(header: str = "x-client-cert") -> CertificateSource:
|
|
69
|
+
"""The client certificate a TLS-terminating proxy forwards in ``header``:
|
|
70
|
+
PEM, URL-encoded PEM (nginx ``$ssl_client_escaped_cert``) or base64 DER
|
|
71
|
+
(``X-Forwarded-Client-Cert`` from Envoy needs its ``Cert=`` element).
|
|
72
|
+
|
|
73
|
+
Only use it behind a proxy that verifies the certificate and always
|
|
74
|
+
overwrites the header: anyone can send it otherwise.
|
|
75
|
+
"""
|
|
76
|
+
name = header.lower()
|
|
77
|
+
|
|
78
|
+
def source(request: Request) -> bytes | None:
|
|
79
|
+
value = request.headers.get(name, "").strip()
|
|
80
|
+
if not value:
|
|
81
|
+
return None
|
|
82
|
+
text = unquote(value) if "%" in value else value
|
|
83
|
+
if "-----BEGIN" in text:
|
|
84
|
+
body = text.split("-----BEGIN CERTIFICATE-----", 1)[-1]
|
|
85
|
+
body = body.split("-----END CERTIFICATE-----", 1)[0]
|
|
86
|
+
text = "".join(body.split())
|
|
87
|
+
try:
|
|
88
|
+
return base64.b64decode(text, validate=True)
|
|
89
|
+
except (binascii.Error, ValueError):
|
|
90
|
+
raise AuthenticationFailed(
|
|
91
|
+
"The forwarded client certificate is malformed", reason="invalid_certificate"
|
|
92
|
+
) from None
|
|
93
|
+
|
|
94
|
+
return source
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def bearer_actor(
|
|
98
|
+
authenticator: Authenticator,
|
|
99
|
+
*,
|
|
100
|
+
required: bool = True,
|
|
101
|
+
rate_limiter: Any = None,
|
|
102
|
+
client_certificate: CertificateSource | None = None,
|
|
103
|
+
public_url: str | None = None,
|
|
104
|
+
translations: Any = None,
|
|
105
|
+
) -> Callable[[Request], Awaitable[Principal | None]]:
|
|
106
|
+
"""FastAPI dependency: ``Authorization: Bearer <token>`` → ``Principal``.
|
|
107
|
+
|
|
108
|
+
Sender-constrained tokens (``Authorization: DPoP`` with a ``DPoP`` proof,
|
|
109
|
+
or certificate-bound tokens) need an authenticator that checks them
|
|
110
|
+
(``resource_engine_oidc.SenderConstrained``); ``client_certificate``
|
|
111
|
+
reads the TLS client certificate (``forwarded_client_certificate()``)
|
|
112
|
+
and ``public_url`` fixes the URL proofs name behind a proxy.
|
|
113
|
+
|
|
114
|
+
With ``translations``, a ``locale`` claim in the token sets the request's
|
|
115
|
+
language (see ``install_locale``).
|
|
116
|
+
|
|
117
|
+
With ``required=False`` anonymous requests get ``actor=None`` (invalid tokens
|
|
118
|
+
are still rejected). With a ``RateLimiter``, callers get its ``default``
|
|
119
|
+
limit, anonymous clients its ``anonymous`` one by IP, and addresses that
|
|
120
|
+
failed authentication ``failed_auth`` times are refused before their
|
|
121
|
+
credentials are checked (429, RE-E710; see docs/rate-limits.md). The client
|
|
122
|
+
address is ``request.client.host``: behind a proxy, run uvicorn with
|
|
123
|
+
``--proxy-headers --forwarded-allow-ips`` so it is the real client's.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
async def actor(request: Request) -> Principal | None:
|
|
127
|
+
address = request.client.host if request.client else None
|
|
128
|
+
credentials = request_credentials(
|
|
129
|
+
request, client_certificate=client_certificate, public_url=public_url
|
|
130
|
+
)
|
|
131
|
+
if credentials is None:
|
|
132
|
+
if required:
|
|
133
|
+
raise AuthenticationFailed(
|
|
134
|
+
"Missing bearer token",
|
|
135
|
+
reason="missing",
|
|
136
|
+
hint="Send 'Authorization: Bearer <access token>'.",
|
|
137
|
+
)
|
|
138
|
+
if rate_limiter is not None:
|
|
139
|
+
request.state.rate_limit = await rate_limiter.client(address)
|
|
140
|
+
return None
|
|
141
|
+
if rate_limiter is not None:
|
|
142
|
+
await rate_limiter.before_auth(address)
|
|
143
|
+
try:
|
|
144
|
+
principal = await authenticate(authenticator, credentials)
|
|
145
|
+
except AuthenticationFailed:
|
|
146
|
+
if rate_limiter is not None:
|
|
147
|
+
await rate_limiter.failed(address)
|
|
148
|
+
raise
|
|
149
|
+
request.state.principal = principal # for the access log and error reports
|
|
150
|
+
if translations is not None: # the user's own language beats the browser's
|
|
151
|
+
from resource_engine_fastapi.i18n import principal_locale
|
|
152
|
+
|
|
153
|
+
principal_locale(principal, translations)
|
|
154
|
+
if rate_limiter is not None:
|
|
155
|
+
request.state.rate_limit = await rate_limiter.caller(principal)
|
|
156
|
+
return principal
|
|
157
|
+
|
|
158
|
+
return actor
|