wiltech-labs-auth 1.0.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.
- wiltech_labs_auth-1.0.1/.gitignore +220 -0
- wiltech_labs_auth-1.0.1/PKG-INFO +185 -0
- wiltech_labs_auth-1.0.1/README.md +164 -0
- wiltech_labs_auth-1.0.1/pyproject.toml +53 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/__init__.py +63 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/api_keys/__init__.py +23 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/api_keys/api_keys.py +169 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/authorization/__init__.py +21 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/authorization/authorization.py +111 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/clerk/__init__.py +3 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/clerk/clerk_auth.py +152 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/py.typed +0 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/roles/__init__.py +3 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/roles/roles.py +33 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/webhooks/__init__.py +3 -0
- wiltech_labs_auth-1.0.1/src/wiltech_labs_auth/webhooks/svix.py +80 -0
- wiltech_labs_auth-1.0.1/tests/test_auth.py +232 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
219
|
+
/NEXT_STEPS11111.md
|
|
220
|
+
.idea/*
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: wiltech-labs-auth
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: Authentication and authorization for Wiltech FastAPI apps: Clerk JWT verification, the Caller with saved roles, require_admin / require_owner, service API keys and Clerk webhook verification.
|
|
5
|
+
Project-URL: Homepage, https://github.com/wilferraciolli/py-libraries/tree/main/packages/auth
|
|
6
|
+
Project-URL: Repository, https://github.com/wilferraciolli/py-libraries
|
|
7
|
+
Project-URL: Conventions, https://github.com/wilferraciolli/py-libraries/blob/main/docs/PYTHON_APP_CONVENTIONS.md
|
|
8
|
+
Author: Wiliam Ferraciolli
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
Keywords: api-keys,authorization,clerk,cloudflare-workers,fastapi,jwt
|
|
11
|
+
Classifier: Framework :: FastAPI
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Requires-Dist: fastapi>=0.110
|
|
16
|
+
Requires-Dist: httpx>=0.27
|
|
17
|
+
Requires-Dist: pyjwt[crypto]>=2.8
|
|
18
|
+
Requires-Dist: wiltech-labs-core>=0.1.0
|
|
19
|
+
Requires-Dist: wiltech-labs-rest>=1.0.0
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# wiltech-labs-auth
|
|
23
|
+
|
|
24
|
+
Who is calling a Wiltech FastAPI app, and may they? Clerk JWT verification, the `Caller`
|
|
25
|
+
with the roles **saved in the app's database**, `require_admin` / `require_owner`,
|
|
26
|
+
**service API keys** for app-to-app calls, and **Clerk webhook** (Svix) verification.
|
|
27
|
+
|
|
28
|
+
Builds on [`wiltech-labs-core`](../core) (config, `Database`) and
|
|
29
|
+
[`wiltech-labs-rest`](../rest) (`EmbeddedRef` for role options). Pure Python
|
|
30
|
+
(`pyjwt[crypto]`, `httpx`), so it runs in Cloudflare Workers.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
uv add wiltech-labs-auth
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
### Signed-in users (Clerk)
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
# main.py
|
|
44
|
+
from fastapi import Depends
|
|
45
|
+
from wiltech_labs_auth import get_authenticated_user, require_admin
|
|
46
|
+
|
|
47
|
+
app.include_router(todo_router.router, prefix="/api", dependencies=[Depends(get_authenticated_user)])
|
|
48
|
+
app.include_router(system_settings_router.router, prefix="/api", dependencies=[Depends(require_admin)])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
# todos/todo_router.py — personal resources: only the user in the path, not even an admin
|
|
53
|
+
from wiltech_labs_auth import Caller, get_caller, require_owner
|
|
54
|
+
|
|
55
|
+
router = APIRouter(prefix="/users/{user_id}/todos")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@router.get("")
|
|
59
|
+
async def list_todos(user_id: str = Depends(require_owner), service: TodoService = Depends(get_todo_service)):
|
|
60
|
+
...
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`get_caller` finds the saved user through `get_caller_lookup`, which by default reads
|
|
64
|
+
`user_detail_view (id, external_user_id, role_ids)`, the view every app built from
|
|
65
|
+
`fastapi-template` has. An app with a different schema overrides it:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from wiltech_labs_auth import SavedUser, get_caller_lookup
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class MembersLookup:
|
|
72
|
+
def __init__(self, db): self.db = db
|
|
73
|
+
|
|
74
|
+
async def find(self, external_id: str) -> SavedUser | None:
|
|
75
|
+
row = await self.db.fetch_one("SELECT id, roles FROM members WHERE clerk_id = ?", (external_id,))
|
|
76
|
+
return SavedUser(row["id"], row["roles"].split(",")) if row else None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
app.dependency_overrides[get_caller_lookup] = lambda request: MembersLookup(get_database(request))
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Service API keys (app → app)
|
|
83
|
+
|
|
84
|
+
For a Worker calling a shared service at home (a PDF parser, a transcriber) where there is
|
|
85
|
+
no signed-in person.
|
|
86
|
+
|
|
87
|
+
1. Add the table: copy `API_KEYS_TABLE_SQL` into a migration (and `schema.sql` for D1).
|
|
88
|
+
2. Issue a key from an admin route or a one-off script. The plain key is returned **once**;
|
|
89
|
+
only its SHA-256 is stored.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
saved, plain_key = await ApiKeyRepository(db).create("docs-worker", ["docs:parse"])
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
3. Protect routes:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from wiltech_labs_auth import ServiceCaller, require_api_key
|
|
99
|
+
|
|
100
|
+
@router.post("/documents/parse")
|
|
101
|
+
async def parse(service: ServiceCaller = Depends(require_api_key("docs:parse"))): ...
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
4. The caller sends `X-Api-Key: wtk_...`. A missing or revoked key gets 401, a missing
|
|
105
|
+
scope gets 403. `last_used_date` updates at most once an hour per key, to save D1 writes.
|
|
106
|
+
|
|
107
|
+
Rotate a key by creating a new one, deploying it, then calling `revoke(old_id)`.
|
|
108
|
+
|
|
109
|
+
### Clerk webhooks
|
|
110
|
+
|
|
111
|
+
Keep the local `users` table in step with Clerk (for example, delete a user's data on
|
|
112
|
+
`user.deleted`). In Clerk: *Webhooks → Add endpoint* → `https://api.example.com/api/webhooks/clerk`,
|
|
113
|
+
then put its signing secret in `CLERK_WEBHOOK_SECRET`.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from wiltech_labs_auth import clerk_webhook_event
|
|
117
|
+
|
|
118
|
+
@router.post("/webhooks/clerk") # NOT behind get_authenticated_user
|
|
119
|
+
async def clerk(event: dict = Depends(clerk_webhook_event)):
|
|
120
|
+
if event["type"] == "user.deleted":
|
|
121
|
+
await users.delete_by_external_id(event["data"]["id"])
|
|
122
|
+
return {"received": True}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`verify_svix_signature(secret, headers, raw_body)` is also exported for non-FastAPI use.
|
|
126
|
+
|
|
127
|
+
## Configuration
|
|
128
|
+
|
|
129
|
+
| Variable | Used by | Notes |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `CLERK_JWKS_URL` | `get_authenticated_user` | The issuer is this URL minus `/.well-known/jwks.json` |
|
|
132
|
+
| `CLERK_AUDIENCE` | `get_authenticated_user` | Default `wiltech-dev-api` (as in the template) |
|
|
133
|
+
| `CLERK_AUTHORIZED_PARTIES` | `get_authenticated_user` | Optional, comma-separated allowed `azp` |
|
|
134
|
+
| `CLERK_WEBHOOK_SECRET` | `clerk_webhook_event` | `whsec_...` |
|
|
135
|
+
|
|
136
|
+
## Public API
|
|
137
|
+
|
|
138
|
+
| Name | What it is |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `get_authenticated_user`, `AuthenticatedUser` | Verify the Clerk bearer token (JWKS cached for 1 h, refreshed on an unknown `kid`) |
|
|
141
|
+
| `get_caller`, `Caller` | The caller with **saved** roles (`user_id` is `None` before their first `/me`) |
|
|
142
|
+
| `get_caller_lookup`, `CallerLookup`, `SavedUser`, `UserDetailViewLookup` | Where `get_caller` looks users up; override per app |
|
|
143
|
+
| `require_admin` | 403 unless the saved roles include `ADMIN` |
|
|
144
|
+
| `require_owner` | For `/users/{user_id}/...`: 403 unless the caller *is* `user_id` |
|
|
145
|
+
| `UserRole`, `ROLE_LABELS`, `role_options()`, `parse_role_ids()` | Roles and their metadata option list |
|
|
146
|
+
| `require_api_key(*scopes)`, `ServiceCaller` | Service-to-service dependency (`X-Api-Key`) |
|
|
147
|
+
| `ApiKeyRepository`, `ApiKeyModel`, `API_KEYS_TABLE_SQL`, `get_api_key_repository` | Key storage |
|
|
148
|
+
| `generate_api_key()`, `hash_api_key()`, `API_KEY_HEADER` | Key helpers |
|
|
149
|
+
| `clerk_webhook_event`, `verify_svix_signature`, `WebhookVerificationError` | Webhook verification |
|
|
150
|
+
|
|
151
|
+
## Development
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
uv run --package wiltech-labs-auth pytest packages/auth
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Publishing
|
|
158
|
+
|
|
159
|
+
Publish `wiltech-labs-core` first; this package depends on it.
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
cd packages/auth
|
|
163
|
+
|
|
164
|
+
# 1. Test, bump, build
|
|
165
|
+
uv run pytest
|
|
166
|
+
uv version --bump patch # or minor / major; skip for the first 0.1.0
|
|
167
|
+
rm -rf ../../dist && uv build # -> ../../dist/
|
|
168
|
+
|
|
169
|
+
# 2. TestPyPI (optional rehearsal), using a token from test.pypi.org
|
|
170
|
+
read -rsp "TestPyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
|
|
171
|
+
uv publish --index testpypi ../../dist/*
|
|
172
|
+
unset UV_PUBLISH_TOKEN
|
|
173
|
+
|
|
174
|
+
# 3. PyPI (the real thing), using a token from pypi.org
|
|
175
|
+
read -rsp "PyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
|
|
176
|
+
uv publish ../../dist/*
|
|
177
|
+
unset UV_PUBLISH_TOKEN
|
|
178
|
+
|
|
179
|
+
# 4. Commit and tag
|
|
180
|
+
git commit -am "wiltech-labs-auth <version>"
|
|
181
|
+
git tag auth-v<version> && git push && git push --tags
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
A version number can only be uploaded once to each site. To retry after a fix, bump the
|
|
185
|
+
version and rebuild.
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# wiltech-labs-auth
|
|
2
|
+
|
|
3
|
+
Who is calling a Wiltech FastAPI app, and may they? Clerk JWT verification, the `Caller`
|
|
4
|
+
with the roles **saved in the app's database**, `require_admin` / `require_owner`,
|
|
5
|
+
**service API keys** for app-to-app calls, and **Clerk webhook** (Svix) verification.
|
|
6
|
+
|
|
7
|
+
Builds on [`wiltech-labs-core`](../core) (config, `Database`) and
|
|
8
|
+
[`wiltech-labs-rest`](../rest) (`EmbeddedRef` for role options). Pure Python
|
|
9
|
+
(`pyjwt[crypto]`, `httpx`), so it runs in Cloudflare Workers.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
uv add wiltech-labs-auth
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
### Signed-in users (Clerk)
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
# main.py
|
|
23
|
+
from fastapi import Depends
|
|
24
|
+
from wiltech_labs_auth import get_authenticated_user, require_admin
|
|
25
|
+
|
|
26
|
+
app.include_router(todo_router.router, prefix="/api", dependencies=[Depends(get_authenticated_user)])
|
|
27
|
+
app.include_router(system_settings_router.router, prefix="/api", dependencies=[Depends(require_admin)])
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
# todos/todo_router.py — personal resources: only the user in the path, not even an admin
|
|
32
|
+
from wiltech_labs_auth import Caller, get_caller, require_owner
|
|
33
|
+
|
|
34
|
+
router = APIRouter(prefix="/users/{user_id}/todos")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@router.get("")
|
|
38
|
+
async def list_todos(user_id: str = Depends(require_owner), service: TodoService = Depends(get_todo_service)):
|
|
39
|
+
...
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`get_caller` finds the saved user through `get_caller_lookup`, which by default reads
|
|
43
|
+
`user_detail_view (id, external_user_id, role_ids)`, the view every app built from
|
|
44
|
+
`fastapi-template` has. An app with a different schema overrides it:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from wiltech_labs_auth import SavedUser, get_caller_lookup
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MembersLookup:
|
|
51
|
+
def __init__(self, db): self.db = db
|
|
52
|
+
|
|
53
|
+
async def find(self, external_id: str) -> SavedUser | None:
|
|
54
|
+
row = await self.db.fetch_one("SELECT id, roles FROM members WHERE clerk_id = ?", (external_id,))
|
|
55
|
+
return SavedUser(row["id"], row["roles"].split(",")) if row else None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
app.dependency_overrides[get_caller_lookup] = lambda request: MembersLookup(get_database(request))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Service API keys (app → app)
|
|
62
|
+
|
|
63
|
+
For a Worker calling a shared service at home (a PDF parser, a transcriber) where there is
|
|
64
|
+
no signed-in person.
|
|
65
|
+
|
|
66
|
+
1. Add the table: copy `API_KEYS_TABLE_SQL` into a migration (and `schema.sql` for D1).
|
|
67
|
+
2. Issue a key from an admin route or a one-off script. The plain key is returned **once**;
|
|
68
|
+
only its SHA-256 is stored.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
saved, plain_key = await ApiKeyRepository(db).create("docs-worker", ["docs:parse"])
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
3. Protect routes:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from wiltech_labs_auth import ServiceCaller, require_api_key
|
|
78
|
+
|
|
79
|
+
@router.post("/documents/parse")
|
|
80
|
+
async def parse(service: ServiceCaller = Depends(require_api_key("docs:parse"))): ...
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
4. The caller sends `X-Api-Key: wtk_...`. A missing or revoked key gets 401, a missing
|
|
84
|
+
scope gets 403. `last_used_date` updates at most once an hour per key, to save D1 writes.
|
|
85
|
+
|
|
86
|
+
Rotate a key by creating a new one, deploying it, then calling `revoke(old_id)`.
|
|
87
|
+
|
|
88
|
+
### Clerk webhooks
|
|
89
|
+
|
|
90
|
+
Keep the local `users` table in step with Clerk (for example, delete a user's data on
|
|
91
|
+
`user.deleted`). In Clerk: *Webhooks → Add endpoint* → `https://api.example.com/api/webhooks/clerk`,
|
|
92
|
+
then put its signing secret in `CLERK_WEBHOOK_SECRET`.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from wiltech_labs_auth import clerk_webhook_event
|
|
96
|
+
|
|
97
|
+
@router.post("/webhooks/clerk") # NOT behind get_authenticated_user
|
|
98
|
+
async def clerk(event: dict = Depends(clerk_webhook_event)):
|
|
99
|
+
if event["type"] == "user.deleted":
|
|
100
|
+
await users.delete_by_external_id(event["data"]["id"])
|
|
101
|
+
return {"received": True}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`verify_svix_signature(secret, headers, raw_body)` is also exported for non-FastAPI use.
|
|
105
|
+
|
|
106
|
+
## Configuration
|
|
107
|
+
|
|
108
|
+
| Variable | Used by | Notes |
|
|
109
|
+
|---|---|---|
|
|
110
|
+
| `CLERK_JWKS_URL` | `get_authenticated_user` | The issuer is this URL minus `/.well-known/jwks.json` |
|
|
111
|
+
| `CLERK_AUDIENCE` | `get_authenticated_user` | Default `wiltech-dev-api` (as in the template) |
|
|
112
|
+
| `CLERK_AUTHORIZED_PARTIES` | `get_authenticated_user` | Optional, comma-separated allowed `azp` |
|
|
113
|
+
| `CLERK_WEBHOOK_SECRET` | `clerk_webhook_event` | `whsec_...` |
|
|
114
|
+
|
|
115
|
+
## Public API
|
|
116
|
+
|
|
117
|
+
| Name | What it is |
|
|
118
|
+
|---|---|
|
|
119
|
+
| `get_authenticated_user`, `AuthenticatedUser` | Verify the Clerk bearer token (JWKS cached for 1 h, refreshed on an unknown `kid`) |
|
|
120
|
+
| `get_caller`, `Caller` | The caller with **saved** roles (`user_id` is `None` before their first `/me`) |
|
|
121
|
+
| `get_caller_lookup`, `CallerLookup`, `SavedUser`, `UserDetailViewLookup` | Where `get_caller` looks users up; override per app |
|
|
122
|
+
| `require_admin` | 403 unless the saved roles include `ADMIN` |
|
|
123
|
+
| `require_owner` | For `/users/{user_id}/...`: 403 unless the caller *is* `user_id` |
|
|
124
|
+
| `UserRole`, `ROLE_LABELS`, `role_options()`, `parse_role_ids()` | Roles and their metadata option list |
|
|
125
|
+
| `require_api_key(*scopes)`, `ServiceCaller` | Service-to-service dependency (`X-Api-Key`) |
|
|
126
|
+
| `ApiKeyRepository`, `ApiKeyModel`, `API_KEYS_TABLE_SQL`, `get_api_key_repository` | Key storage |
|
|
127
|
+
| `generate_api_key()`, `hash_api_key()`, `API_KEY_HEADER` | Key helpers |
|
|
128
|
+
| `clerk_webhook_event`, `verify_svix_signature`, `WebhookVerificationError` | Webhook verification |
|
|
129
|
+
|
|
130
|
+
## Development
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
uv run --package wiltech-labs-auth pytest packages/auth
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Publishing
|
|
137
|
+
|
|
138
|
+
Publish `wiltech-labs-core` first; this package depends on it.
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
cd packages/auth
|
|
142
|
+
|
|
143
|
+
# 1. Test, bump, build
|
|
144
|
+
uv run pytest
|
|
145
|
+
uv version --bump patch # or minor / major; skip for the first 0.1.0
|
|
146
|
+
rm -rf ../../dist && uv build # -> ../../dist/
|
|
147
|
+
|
|
148
|
+
# 2. TestPyPI (optional rehearsal), using a token from test.pypi.org
|
|
149
|
+
read -rsp "TestPyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
|
|
150
|
+
uv publish --index testpypi ../../dist/*
|
|
151
|
+
unset UV_PUBLISH_TOKEN
|
|
152
|
+
|
|
153
|
+
# 3. PyPI (the real thing), using a token from pypi.org
|
|
154
|
+
read -rsp "PyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
|
|
155
|
+
uv publish ../../dist/*
|
|
156
|
+
unset UV_PUBLISH_TOKEN
|
|
157
|
+
|
|
158
|
+
# 4. Commit and tag
|
|
159
|
+
git commit -am "wiltech-labs-auth <version>"
|
|
160
|
+
git tag auth-v<version> && git push && git push --tags
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
A version number can only be uploaded once to each site. To retry after a fix, bump the
|
|
164
|
+
version and rebuild.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "wiltech-labs-auth"
|
|
3
|
+
version = "1.0.1"
|
|
4
|
+
description = "Authentication and authorization for Wiltech FastAPI apps: Clerk JWT verification, the Caller with saved roles, require_admin / require_owner, service API keys and Clerk webhook verification."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.13"
|
|
8
|
+
authors = [{ name = "Wiliam Ferraciolli" }]
|
|
9
|
+
keywords = ["fastapi", "clerk", "jwt", "authorization", "api-keys", "cloudflare-workers"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Framework :: FastAPI",
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Typing :: Typed",
|
|
14
|
+
]
|
|
15
|
+
dependencies = [
|
|
16
|
+
"fastapi>=0.110",
|
|
17
|
+
"httpx>=0.27",
|
|
18
|
+
"pyjwt[crypto]>=2.8",
|
|
19
|
+
"wiltech-labs-core>=0.1.0",
|
|
20
|
+
"wiltech-labs-rest>=1.0.0",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/wilferraciolli/py-libraries/tree/main/packages/auth"
|
|
25
|
+
Repository = "https://github.com/wilferraciolli/py-libraries"
|
|
26
|
+
Conventions = "https://github.com/wilferraciolli/py-libraries/blob/main/docs/PYTHON_APP_CONVENTIONS.md"
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"aiosqlite",
|
|
31
|
+
"pytest",
|
|
32
|
+
"pytest-asyncio",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# In the workspace, use the local core; `uv build` drops this, so the
|
|
36
|
+
# published wheel depends on wiltech-labs-core from PyPI.
|
|
37
|
+
[tool.uv.sources]
|
|
38
|
+
wiltech-labs-core = { workspace = true }
|
|
39
|
+
wiltech-labs-rest = { workspace = true }
|
|
40
|
+
|
|
41
|
+
[build-system]
|
|
42
|
+
requires = ["hatchling"]
|
|
43
|
+
build-backend = "hatchling.build"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
exclude = ["CLAUDE.md", ".pytest_cache"]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/wiltech_labs_auth"]
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
asyncio_mode = "auto"
|
|
53
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""
|
|
2
|
+
wiltech-labs-auth: who is calling a Wiltech FastAPI app, and may they?
|
|
3
|
+
|
|
4
|
+
Clerk JWT verification, the Caller with the roles saved in the app's
|
|
5
|
+
database, require_admin / require_owner, service API keys for app-to-app
|
|
6
|
+
calls, and Clerk (Svix) webhook verification.
|
|
7
|
+
|
|
8
|
+
This module is the entire public surface — import from `wiltech_labs_auth`,
|
|
9
|
+
not from its sub-packages.
|
|
10
|
+
"""
|
|
11
|
+
from wiltech_labs_auth.api_keys import (
|
|
12
|
+
API_KEY_HEADER,
|
|
13
|
+
API_KEYS_TABLE_SQL,
|
|
14
|
+
ApiKeyModel,
|
|
15
|
+
ApiKeyRepository,
|
|
16
|
+
ServiceCaller,
|
|
17
|
+
generate_api_key,
|
|
18
|
+
get_api_key_repository,
|
|
19
|
+
hash_api_key,
|
|
20
|
+
require_api_key,
|
|
21
|
+
)
|
|
22
|
+
from wiltech_labs_auth.authorization import (
|
|
23
|
+
Caller,
|
|
24
|
+
CallerLookup,
|
|
25
|
+
SavedUser,
|
|
26
|
+
UserDetailViewLookup,
|
|
27
|
+
get_caller,
|
|
28
|
+
get_caller_lookup,
|
|
29
|
+
require_admin,
|
|
30
|
+
require_owner,
|
|
31
|
+
)
|
|
32
|
+
from wiltech_labs_auth.clerk import AuthenticatedUser, get_authenticated_user
|
|
33
|
+
from wiltech_labs_auth.roles import ROLE_LABELS, UserRole, parse_role_ids, role_options
|
|
34
|
+
from wiltech_labs_auth.webhooks import WebhookVerificationError, clerk_webhook_event, verify_svix_signature
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"API_KEYS_TABLE_SQL",
|
|
38
|
+
"API_KEY_HEADER",
|
|
39
|
+
"ApiKeyModel",
|
|
40
|
+
"ApiKeyRepository",
|
|
41
|
+
"AuthenticatedUser",
|
|
42
|
+
"Caller",
|
|
43
|
+
"CallerLookup",
|
|
44
|
+
"ROLE_LABELS",
|
|
45
|
+
"SavedUser",
|
|
46
|
+
"ServiceCaller",
|
|
47
|
+
"UserDetailViewLookup",
|
|
48
|
+
"UserRole",
|
|
49
|
+
"WebhookVerificationError",
|
|
50
|
+
"clerk_webhook_event",
|
|
51
|
+
"generate_api_key",
|
|
52
|
+
"get_api_key_repository",
|
|
53
|
+
"get_authenticated_user",
|
|
54
|
+
"get_caller",
|
|
55
|
+
"get_caller_lookup",
|
|
56
|
+
"hash_api_key",
|
|
57
|
+
"parse_role_ids",
|
|
58
|
+
"require_admin",
|
|
59
|
+
"require_api_key",
|
|
60
|
+
"require_owner",
|
|
61
|
+
"role_options",
|
|
62
|
+
"verify_svix_signature",
|
|
63
|
+
]
|