coderfastapi 6.0.0__tar.gz → 6.1.1__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.
- coderfastapi-6.1.1/LICENSE +190 -0
- coderfastapi-6.1.1/PKG-INFO +153 -0
- coderfastapi-6.1.1/README.md +122 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/handlers/version.py +2 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/decorators/__init__.py +8 -3
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/decorators/pagination.py +13 -9
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/decorators/util.py +5 -1
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/router.py +11 -10
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/acl.py +2 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/jwt/__init__.py +12 -1
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/jwt/providers/__init__.py +3 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/jwt/providers/expiration.py +4 -2
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/jwt/providers/recovery.py +5 -2
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/jwt/providers/user.py +6 -3
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/session.py +8 -3
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authorization/__init__.py +5 -4
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authorization/user.py +10 -4
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/session/base.py +5 -1
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/session/user.py +10 -2
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/signature.py +5 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/pagination.py +6 -1
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/query.py +4 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/request.py +4 -2
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/version.py +2 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/logging/__init__.py +4 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/logging/context.py +4 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/logging/filter.py +3 -1
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/logging/middleware.py +5 -0
- coderfastapi-6.1.1/coderfastapi.egg-info/PKG-INFO +153 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi.egg-info/SOURCES.txt +1 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi.egg-info/requires.txt +5 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/pyproject.toml +14 -2
- coderfastapi-6.0.0/PKG-INFO +0 -25
- coderfastapi-6.0.0/README.md +0 -1
- coderfastapi-6.0.0/coderfastapi.egg-info/PKG-INFO +0 -25
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/handlers/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/policies/authentication/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/security/session/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/__init__.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/lib/validation/schemas/aggregation.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi/test.py +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi.egg-info/dependency_links.txt +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/coderfastapi.egg-info/top_level.txt +0 -0
- {coderfastapi-6.0.0 → coderfastapi-6.1.1}/setup.cfg +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2022 Code R
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: coderfastapi
|
|
3
|
+
Version: 6.1.1
|
|
4
|
+
Summary: coderfastapi
|
|
5
|
+
Author-email: Code R <hello@coderstudio.dev>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: codercore~=8.0
|
|
10
|
+
Requires-Dist: fastapi[all]~=0.89
|
|
11
|
+
Requires-Dist: google-cloud-logging~=3.7
|
|
12
|
+
Requires-Dist: orjson~=3.8
|
|
13
|
+
Requires-Dist: pydantic~=2.4
|
|
14
|
+
Requires-Dist: python-jose~=3.3
|
|
15
|
+
Provides-Extra: test
|
|
16
|
+
Requires-Dist: pytest~=7.2; extra == "test"
|
|
17
|
+
Requires-Dist: pytest-asyncio~=0.20; extra == "test"
|
|
18
|
+
Requires-Dist: pytest-cov~=4.0; extra == "test"
|
|
19
|
+
Requires-Dist: pytest-mock~=3.10; extra == "test"
|
|
20
|
+
Requires-Dist: pytest-xdist[psutil]~=3.1; extra == "test"
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: black~=22.12; extra == "dev"
|
|
23
|
+
Requires-Dist: bumpver~=2023.1127; extra == "dev"
|
|
24
|
+
Requires-Dist: flake8~=6.0; extra == "dev"
|
|
25
|
+
Requires-Dist: isort~=5.12; extra == "dev"
|
|
26
|
+
Requires-Dist: ty~=0.0; extra == "dev"
|
|
27
|
+
Provides-Extra: docs
|
|
28
|
+
Requires-Dist: mkdocs-material; extra == "docs"
|
|
29
|
+
Requires-Dist: mkdocstrings[python]; extra == "docs"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# Coder FastAPI
|
|
33
|
+
|
|
34
|
+
Security and utility library for building FastAPI applications with authentication, authorization, and pagination out of the box.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- **SecureRouter** — Drop-in `APIRouter` replacement that enforces authentication and ACL-based authorization on every route
|
|
39
|
+
- **Authentication policies** — Pluggable strategies for JWT (Bearer token) and session-based authentication
|
|
40
|
+
- **Authorization policies** — Pyramid-style ACL authorization with Allow/Deny rules and composable principals
|
|
41
|
+
- **JWT providers** — Extensible provider system for token creation and request augmentation (expiration, user data, recovery mode)
|
|
42
|
+
- **Session management** — Abstract session manager backed by Redis with configurable TTL and secure token generation
|
|
43
|
+
- **Pagination** — Cursor-based pagination decorator that auto-generates RFC 5988 `Link` headers
|
|
44
|
+
- **Cloud logging** — Google Cloud Logging integration with Cloud Trace context propagation middleware
|
|
45
|
+
- **Validation schemas** — Pydantic models for query parameters, pagination cursors, and aggregation filters
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install coderfastapi
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Quick Start
|
|
54
|
+
|
|
55
|
+
### Secure Router with JWT Authentication
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from coderfastapi.lib.router import SecureRouter
|
|
59
|
+
from coderfastapi.lib.security.acl import ACLProvider
|
|
60
|
+
from coderfastapi.lib.security.policies.authentication.jwt import JWTAuthenticationPolicy
|
|
61
|
+
from coderfastapi.lib.security.policies.authorization.user import UserAuthorizationPolicy
|
|
62
|
+
from fastapi import FastAPI
|
|
63
|
+
|
|
64
|
+
app = FastAPI()
|
|
65
|
+
authentication_policy = JWTAuthenticationPolicy(secret_key="your-secret-key")
|
|
66
|
+
authorization_policy = UserAuthorizationPolicy(acl_provider=ACLProvider())
|
|
67
|
+
router = SecureRouter(authentication_policy, authorization_policy)
|
|
68
|
+
|
|
69
|
+
@router.get("/users", permission="public")
|
|
70
|
+
async def list_users(request):
|
|
71
|
+
...
|
|
72
|
+
|
|
73
|
+
app.include_router(router)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Session Management
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from datetime import timedelta
|
|
80
|
+
|
|
81
|
+
from codercore.lib.redis import connection
|
|
82
|
+
from coderfastapi.lib.security import UserSessionManager
|
|
83
|
+
|
|
84
|
+
cache_connection = connection(host="localhost")
|
|
85
|
+
session_manager = UserSessionManager(
|
|
86
|
+
cache_connection=cache_connection,
|
|
87
|
+
session_ttl=timedelta(hours=24),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
session = await session_manager.create_session(user_id=str(user.id))
|
|
91
|
+
retrieved = await session_manager.get_session_by_id(session.id)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Paginated Endpoints
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from coderfastapi.lib.decorators import paginate
|
|
98
|
+
from coderfastapi.lib.validation.schemas.query import QueryParameters
|
|
99
|
+
|
|
100
|
+
@router.get("/items")
|
|
101
|
+
@paginate("id")
|
|
102
|
+
async def list_items(params: QueryParameters = Depends()):
|
|
103
|
+
... # return list of items. Link headers are generated automatically
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Requirements
|
|
107
|
+
|
|
108
|
+
- Python 3.12+
|
|
109
|
+
- Redis 7+ (required by session management only)
|
|
110
|
+
|
|
111
|
+
All other features — JWT authentication, authorization, pagination, cloud logging — work without Redis.
|
|
112
|
+
|
|
113
|
+
## Documentation
|
|
114
|
+
|
|
115
|
+
Build and serve the API reference locally:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
pip install -e ".[docs]"
|
|
119
|
+
mkdocs serve
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Then visit `http://127.0.0.1:8000`. To build static HTML:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
mkdocs build
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e ".[test,dev]"
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Running Tests
|
|
135
|
+
|
|
136
|
+
Tests run against a real Redis instance via Docker Compose:
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
docker compose -f test-compose.yml up --build
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Linting
|
|
143
|
+
|
|
144
|
+
This project uses [pre-commit](https://pre-commit.com/) for linting:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
pre-commit install
|
|
148
|
+
pre-commit run --all-files
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
[Apache-2.0](LICENSE)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Coder FastAPI
|
|
2
|
+
|
|
3
|
+
Security and utility library for building FastAPI applications with authentication, authorization, and pagination out of the box.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **SecureRouter** — Drop-in `APIRouter` replacement that enforces authentication and ACL-based authorization on every route
|
|
8
|
+
- **Authentication policies** — Pluggable strategies for JWT (Bearer token) and session-based authentication
|
|
9
|
+
- **Authorization policies** — Pyramid-style ACL authorization with Allow/Deny rules and composable principals
|
|
10
|
+
- **JWT providers** — Extensible provider system for token creation and request augmentation (expiration, user data, recovery mode)
|
|
11
|
+
- **Session management** — Abstract session manager backed by Redis with configurable TTL and secure token generation
|
|
12
|
+
- **Pagination** — Cursor-based pagination decorator that auto-generates RFC 5988 `Link` headers
|
|
13
|
+
- **Cloud logging** — Google Cloud Logging integration with Cloud Trace context propagation middleware
|
|
14
|
+
- **Validation schemas** — Pydantic models for query parameters, pagination cursors, and aggregation filters
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install coderfastapi
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
### Secure Router with JWT Authentication
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from coderfastapi.lib.router import SecureRouter
|
|
28
|
+
from coderfastapi.lib.security.acl import ACLProvider
|
|
29
|
+
from coderfastapi.lib.security.policies.authentication.jwt import JWTAuthenticationPolicy
|
|
30
|
+
from coderfastapi.lib.security.policies.authorization.user import UserAuthorizationPolicy
|
|
31
|
+
from fastapi import FastAPI
|
|
32
|
+
|
|
33
|
+
app = FastAPI()
|
|
34
|
+
authentication_policy = JWTAuthenticationPolicy(secret_key="your-secret-key")
|
|
35
|
+
authorization_policy = UserAuthorizationPolicy(acl_provider=ACLProvider())
|
|
36
|
+
router = SecureRouter(authentication_policy, authorization_policy)
|
|
37
|
+
|
|
38
|
+
@router.get("/users", permission="public")
|
|
39
|
+
async def list_users(request):
|
|
40
|
+
...
|
|
41
|
+
|
|
42
|
+
app.include_router(router)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Session Management
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from datetime import timedelta
|
|
49
|
+
|
|
50
|
+
from codercore.lib.redis import connection
|
|
51
|
+
from coderfastapi.lib.security import UserSessionManager
|
|
52
|
+
|
|
53
|
+
cache_connection = connection(host="localhost")
|
|
54
|
+
session_manager = UserSessionManager(
|
|
55
|
+
cache_connection=cache_connection,
|
|
56
|
+
session_ttl=timedelta(hours=24),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
session = await session_manager.create_session(user_id=str(user.id))
|
|
60
|
+
retrieved = await session_manager.get_session_by_id(session.id)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Paginated Endpoints
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from coderfastapi.lib.decorators import paginate
|
|
67
|
+
from coderfastapi.lib.validation.schemas.query import QueryParameters
|
|
68
|
+
|
|
69
|
+
@router.get("/items")
|
|
70
|
+
@paginate("id")
|
|
71
|
+
async def list_items(params: QueryParameters = Depends()):
|
|
72
|
+
... # return list of items. Link headers are generated automatically
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Requirements
|
|
76
|
+
|
|
77
|
+
- Python 3.12+
|
|
78
|
+
- Redis 7+ (required by session management only)
|
|
79
|
+
|
|
80
|
+
All other features — JWT authentication, authorization, pagination, cloud logging — work without Redis.
|
|
81
|
+
|
|
82
|
+
## Documentation
|
|
83
|
+
|
|
84
|
+
Build and serve the API reference locally:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
pip install -e ".[docs]"
|
|
88
|
+
mkdocs serve
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then visit `http://127.0.0.1:8000`. To build static HTML:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
mkdocs build
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Development
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
pip install -e ".[test,dev]"
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Running Tests
|
|
104
|
+
|
|
105
|
+
Tests run against a real Redis instance via Docker Compose:
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
docker compose -f test-compose.yml up --build
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Linting
|
|
112
|
+
|
|
113
|
+
This project uses [pre-commit](https://pre-commit.com/) for linting:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pre-commit install
|
|
117
|
+
pre-commit run --all-files
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
[Apache-2.0](LICENSE)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from functools import wraps
|
|
2
2
|
from http import HTTPStatus
|
|
3
|
-
from typing import Awaitable, Callable,
|
|
3
|
+
from typing import Awaitable, Callable, TypeVar
|
|
4
4
|
|
|
5
5
|
from fastapi import HTTPException
|
|
6
6
|
|
|
@@ -11,9 +11,14 @@ T = TypeVar("T")
|
|
|
11
11
|
|
|
12
12
|
def http_require(
|
|
13
13
|
entity_name: str, boolean: bool = False
|
|
14
|
-
) -> Callable[[Callable[..., Awaitable[
|
|
14
|
+
) -> Callable[[Callable[..., Awaitable[T | None]]], Callable[..., Awaitable[T]]]:
|
|
15
|
+
"""Decorator that raises HTTP 404 if the wrapped function returns None.
|
|
16
|
+
|
|
17
|
+
When boolean=True, checks for False instead of None.
|
|
18
|
+
"""
|
|
19
|
+
|
|
15
20
|
def decorate(
|
|
16
|
-
func: Callable[..., Awaitable[
|
|
21
|
+
func: Callable[..., Awaitable[T | None]],
|
|
17
22
|
) -> Callable[..., Awaitable[T]]:
|
|
18
23
|
@wraps(func)
|
|
19
24
|
async def wrapper(*args, **kwargs) -> T:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from inspect import Parameter, Signature, isclass, signature
|
|
2
|
-
from typing import Any, Awaitable, Callable,
|
|
2
|
+
from typing import Any, Awaitable, Callable, Sequence, TypeVar
|
|
3
3
|
from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
|
|
4
4
|
|
|
5
5
|
from codercore.lib.collection import Direction
|
|
@@ -9,12 +9,12 @@ from fastapi.params import Depends
|
|
|
9
9
|
|
|
10
10
|
from coderfastapi.lib.decorators.util import propagate_params
|
|
11
11
|
from coderfastapi.lib.signature import copy_parameters
|
|
12
|
-
from coderfastapi.lib.validation.schemas.pagination import
|
|
12
|
+
from coderfastapi.lib.validation.schemas.pagination import Cursor
|
|
13
13
|
from coderfastapi.lib.validation.schemas.query import QueryParameters
|
|
14
14
|
|
|
15
15
|
T = TypeVar("T")
|
|
16
16
|
S = TypeVar("S", bound=QueryParameters)
|
|
17
|
-
Entities =
|
|
17
|
+
Entities = Sequence[T]
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
def paginate(
|
|
@@ -23,6 +23,8 @@ def paginate(
|
|
|
23
23
|
[Callable[..., Awaitable[Entities]]],
|
|
24
24
|
Callable[[Request, Response, ...], Awaitable[Entities]],
|
|
25
25
|
]:
|
|
26
|
+
"""Add RFC 5988 cursor-based pagination Link headers to an endpoint."""
|
|
27
|
+
|
|
26
28
|
def decorate(
|
|
27
29
|
func: Callable[..., Awaitable[Entities]],
|
|
28
30
|
) -> Callable[[Request, Response, ...], Awaitable[Entities]]:
|
|
@@ -49,7 +51,7 @@ def paginate(
|
|
|
49
51
|
return result
|
|
50
52
|
|
|
51
53
|
wrapped_signature = signature(wrapped)
|
|
52
|
-
wrapped.__signature__ = copy_parameters(
|
|
54
|
+
wrapped.__signature__ = copy_parameters( # ty: ignore[unresolved-attribute]
|
|
53
55
|
wrapped_signature, func_signature, ["request", "response"]
|
|
54
56
|
)
|
|
55
57
|
return wrapped
|
|
@@ -57,7 +59,9 @@ def paginate(
|
|
|
57
59
|
return decorate
|
|
58
60
|
|
|
59
61
|
|
|
60
|
-
def _get_query_schema(
|
|
62
|
+
def _get_query_schema(
|
|
63
|
+
func_signature: Signature, request: Request
|
|
64
|
+
) -> tuple[str, S | None]:
|
|
61
65
|
for name, parameter in func_signature.parameters.items():
|
|
62
66
|
if _is_valid_query_parameter(parameter):
|
|
63
67
|
if _is_injectable(parameter):
|
|
@@ -115,8 +119,8 @@ def _create_cursor(
|
|
|
115
119
|
id_attr: SequentialCollection[str],
|
|
116
120
|
value_attr: str | SequentialCollection[str],
|
|
117
121
|
item: T,
|
|
118
|
-
) ->
|
|
119
|
-
return
|
|
122
|
+
) -> Cursor:
|
|
123
|
+
return Cursor(
|
|
120
124
|
last_id=_get_last_id(item, id_attr),
|
|
121
125
|
last_value=_get_last_value(item, value_attr),
|
|
122
126
|
direction=direction,
|
|
@@ -140,12 +144,12 @@ def _get_last_value(item: T, value_attr: str | SequentialCollection[str]) -> Any
|
|
|
140
144
|
return getattr(item, value_attr)
|
|
141
145
|
|
|
142
146
|
|
|
143
|
-
def _construct_link(cursor:
|
|
147
|
+
def _construct_link(cursor: Cursor, rel: str, request: Request) -> str:
|
|
144
148
|
url = _construct_url_with_cursor(cursor, request)
|
|
145
149
|
return f'<{url}>; rel="{rel}"'
|
|
146
150
|
|
|
147
151
|
|
|
148
|
-
def _construct_url_with_cursor(cursor:
|
|
152
|
+
def _construct_url_with_cursor(cursor: Cursor, request: Request) -> str:
|
|
149
153
|
scheme, netloc, path, query_string, fragment = urlsplit(str(request.url))
|
|
150
154
|
query_params = parse_qs(query_string)
|
|
151
155
|
query_params["cursor"] = [str(cursor)]
|
|
@@ -8,9 +8,13 @@ P = ParamSpec("P")
|
|
|
8
8
|
|
|
9
9
|
def propagate_params(
|
|
10
10
|
func: Callable[P, Awaitable[T] | T],
|
|
11
|
-
kwargs: [str, Any],
|
|
11
|
+
kwargs: dict[str, Any],
|
|
12
12
|
**to_propagate,
|
|
13
13
|
) -> dict[str, Any]:
|
|
14
|
+
"""Build a dict of keyword arguments to forward to the given function.
|
|
15
|
+
|
|
16
|
+
Only includes arguments that appear in the function's signature.
|
|
17
|
+
"""
|
|
14
18
|
new_kwargs = copy.copy(kwargs)
|
|
15
19
|
func_signature = inspect.signature(func)
|
|
16
20
|
for key, value in to_propagate.items():
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import inspect
|
|
2
|
-
from
|
|
2
|
+
from collections.abc import Awaitable
|
|
3
|
+
from typing import Any, Callable, TypeVar
|
|
3
4
|
|
|
4
5
|
from fastapi import APIRouter, Request
|
|
5
6
|
|
|
@@ -10,10 +11,11 @@ from coderfastapi.lib.security.policies.authorization import AuthorizationPolicy
|
|
|
10
11
|
from coderfastapi.lib.signature import copy_parameters
|
|
11
12
|
|
|
12
13
|
T = TypeVar("T")
|
|
13
|
-
P = ParamSpec("P")
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
class SecureRouter(APIRouter):
|
|
17
|
+
"""APIRouter with authentication and ACL-based authorization."""
|
|
18
|
+
|
|
17
19
|
authentication_policy: AuthenticationPolicy
|
|
18
20
|
authorization_policy: AuthorizationPolicy
|
|
19
21
|
|
|
@@ -30,12 +32,12 @@ class SecureRouter(APIRouter):
|
|
|
30
32
|
|
|
31
33
|
async def _call_handler_with_authentication(
|
|
32
34
|
self,
|
|
33
|
-
handler: Callable[
|
|
35
|
+
handler: Callable[..., Awaitable[T] | T],
|
|
34
36
|
permission: str,
|
|
35
37
|
request: Request,
|
|
36
38
|
context: Any | None,
|
|
37
|
-
*args
|
|
38
|
-
**kwargs
|
|
39
|
+
*args,
|
|
40
|
+
**kwargs,
|
|
39
41
|
) -> T:
|
|
40
42
|
context_acl_provider = None
|
|
41
43
|
if isinstance(context, ACLProvider):
|
|
@@ -55,9 +57,8 @@ class SecureRouter(APIRouter):
|
|
|
55
57
|
context=context,
|
|
56
58
|
)
|
|
57
59
|
output = handler(*args, **kwargs)
|
|
58
|
-
if
|
|
59
|
-
|
|
60
|
-
|
|
60
|
+
if isinstance(output, Awaitable):
|
|
61
|
+
return await output
|
|
61
62
|
return output
|
|
62
63
|
|
|
63
64
|
async def _authenticate_request(self, request: Request) -> Request:
|
|
@@ -109,12 +110,12 @@ class SecureRouter(APIRouter):
|
|
|
109
110
|
|
|
110
111
|
def _http_method(
|
|
111
112
|
self,
|
|
112
|
-
func: Callable[
|
|
113
|
+
func: Callable[..., Awaitable[T] | T],
|
|
113
114
|
http_method: str,
|
|
114
115
|
*outer_args,
|
|
115
116
|
permission: str = "public",
|
|
116
117
|
**outer_kwargs,
|
|
117
|
-
) -> Callable[
|
|
118
|
+
) -> Callable[..., Awaitable[T]]:
|
|
118
119
|
route = getattr(super(SecureRouter, self), http_method)
|
|
119
120
|
|
|
120
121
|
@route(*outer_args, **outer_kwargs)
|