jupyterhub-fastapi-adapter 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.
- jupyterhub_fastapi_adapter-0.1.0/.github/workflows/python-publish.yml +70 -0
- jupyterhub_fastapi_adapter-0.1.0/.gitignore +143 -0
- jupyterhub_fastapi_adapter-0.1.0/LICENSE +21 -0
- jupyterhub_fastapi_adapter-0.1.0/PKG-INFO +209 -0
- jupyterhub_fastapi_adapter-0.1.0/README.md +171 -0
- jupyterhub_fastapi_adapter-0.1.0/jupyterhub_fastapi_adapter/__about__.py +1 -0
- jupyterhub_fastapi_adapter-0.1.0/jupyterhub_fastapi_adapter/__init__.py +15 -0
- jupyterhub_fastapi_adapter-0.1.0/jupyterhub_fastapi_adapter/dependencies.py +45 -0
- jupyterhub_fastapi_adapter-0.1.0/jupyterhub_fastapi_adapter/hub_oauth.py +117 -0
- jupyterhub_fastapi_adapter-0.1.0/pyproject.toml +94 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# This workflow will upload a Python Package to PyPI when a release is created
|
|
2
|
+
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
|
|
3
|
+
|
|
4
|
+
# This workflow uses actions that are not certified by GitHub.
|
|
5
|
+
# They are provided by a third-party and are governed by
|
|
6
|
+
# separate terms of service, privacy policy, and support
|
|
7
|
+
# documentation.
|
|
8
|
+
|
|
9
|
+
name: Upload Python Package
|
|
10
|
+
|
|
11
|
+
on:
|
|
12
|
+
release:
|
|
13
|
+
types: [published]
|
|
14
|
+
|
|
15
|
+
permissions:
|
|
16
|
+
contents: read
|
|
17
|
+
|
|
18
|
+
jobs:
|
|
19
|
+
release-build:
|
|
20
|
+
runs-on: ubuntu-latest
|
|
21
|
+
|
|
22
|
+
steps:
|
|
23
|
+
- uses: actions/checkout@v4
|
|
24
|
+
|
|
25
|
+
- uses: actions/setup-python@v5
|
|
26
|
+
with:
|
|
27
|
+
python-version: "3.x"
|
|
28
|
+
|
|
29
|
+
- name: Build release distributions
|
|
30
|
+
run: |
|
|
31
|
+
# NOTE: put your own distribution build steps here.
|
|
32
|
+
python -m pip install build
|
|
33
|
+
python -m build
|
|
34
|
+
|
|
35
|
+
- name: Upload distributions
|
|
36
|
+
uses: actions/upload-artifact@v4
|
|
37
|
+
with:
|
|
38
|
+
name: release-dists
|
|
39
|
+
path: dist/
|
|
40
|
+
|
|
41
|
+
pypi-publish:
|
|
42
|
+
runs-on: ubuntu-latest
|
|
43
|
+
needs:
|
|
44
|
+
- release-build
|
|
45
|
+
permissions:
|
|
46
|
+
# IMPORTANT: this permission is mandatory for trusted publishing
|
|
47
|
+
id-token: write
|
|
48
|
+
|
|
49
|
+
# Dedicated environments with protections for publishing are strongly recommended.
|
|
50
|
+
# For more information, see: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-protection-rules
|
|
51
|
+
environment:
|
|
52
|
+
name: pypi
|
|
53
|
+
# OPTIONAL: uncomment and update to include your PyPI project URL in the deployment status:
|
|
54
|
+
# url: https://pypi.org/p/YOURPROJECT
|
|
55
|
+
#
|
|
56
|
+
# ALTERNATIVE: if your GitHub Release name is the PyPI project version string
|
|
57
|
+
# ALTERNATIVE: exactly, uncomment the following line instead:
|
|
58
|
+
# url: https://pypi.org/project/YOURPROJECT/${{ github.event.release.name }}
|
|
59
|
+
|
|
60
|
+
steps:
|
|
61
|
+
- name: Retrieve release distributions
|
|
62
|
+
uses: actions/download-artifact@v4
|
|
63
|
+
with:
|
|
64
|
+
name: release-dists
|
|
65
|
+
path: dist/
|
|
66
|
+
|
|
67
|
+
- name: Publish release distributions to PyPI
|
|
68
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
69
|
+
with:
|
|
70
|
+
packages-dir: dist/
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# Node modules
|
|
2
|
+
|
|
3
|
+
node_modules
|
|
4
|
+
|
|
5
|
+
# Meta files
|
|
6
|
+
ui/meta.json
|
|
7
|
+
|
|
8
|
+
# Build static files
|
|
9
|
+
share/e2x_course_hub/static/
|
|
10
|
+
|
|
11
|
+
# Byte-compiled / optimized / DLL files
|
|
12
|
+
__pycache__/
|
|
13
|
+
*.py[cod]
|
|
14
|
+
*$py.class
|
|
15
|
+
|
|
16
|
+
# C extensions
|
|
17
|
+
*.so
|
|
18
|
+
|
|
19
|
+
# Distribution / packaging
|
|
20
|
+
.Python
|
|
21
|
+
build/
|
|
22
|
+
develop-eggs/
|
|
23
|
+
dist/
|
|
24
|
+
downloads/
|
|
25
|
+
eggs/
|
|
26
|
+
.eggs/
|
|
27
|
+
lib/*
|
|
28
|
+
!src/lib/
|
|
29
|
+
lib64/
|
|
30
|
+
parts/
|
|
31
|
+
sdist/
|
|
32
|
+
var/
|
|
33
|
+
wheels/
|
|
34
|
+
pip-wheel-metadata/
|
|
35
|
+
share/python-wheels/
|
|
36
|
+
*.egg-info/
|
|
37
|
+
.installed.cfg
|
|
38
|
+
*.egg
|
|
39
|
+
MANIFEST
|
|
40
|
+
|
|
41
|
+
# PyInstaller
|
|
42
|
+
# Usually these files are written by a python script from a template
|
|
43
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
44
|
+
*.manifest
|
|
45
|
+
*.spec
|
|
46
|
+
|
|
47
|
+
# Installer logs
|
|
48
|
+
pip-log.txt
|
|
49
|
+
pip-delete-this-directory.txt
|
|
50
|
+
|
|
51
|
+
# Unit test / coverage reports
|
|
52
|
+
htmlcov/
|
|
53
|
+
.tox/
|
|
54
|
+
.nox/
|
|
55
|
+
.coverage
|
|
56
|
+
.coverage.*
|
|
57
|
+
.cache
|
|
58
|
+
nosetests.xml
|
|
59
|
+
coverage.xml
|
|
60
|
+
*.cover
|
|
61
|
+
*.py,cover
|
|
62
|
+
.hypothesis/
|
|
63
|
+
.pytest_cache/
|
|
64
|
+
|
|
65
|
+
# Translations
|
|
66
|
+
*.mo
|
|
67
|
+
*.pot
|
|
68
|
+
|
|
69
|
+
# Django stuff:
|
|
70
|
+
*.log
|
|
71
|
+
local_settings.py
|
|
72
|
+
db.sqlite3
|
|
73
|
+
db.sqlite3-journal
|
|
74
|
+
|
|
75
|
+
# Flask stuff:
|
|
76
|
+
instance/
|
|
77
|
+
.webassets-cache
|
|
78
|
+
|
|
79
|
+
# Scrapy stuff:
|
|
80
|
+
.scrapy
|
|
81
|
+
|
|
82
|
+
# Sphinx documentation
|
|
83
|
+
docs/_build/
|
|
84
|
+
|
|
85
|
+
# PyBuilder
|
|
86
|
+
target/
|
|
87
|
+
|
|
88
|
+
# Jupyter Notebook
|
|
89
|
+
.ipynb_checkpoints
|
|
90
|
+
|
|
91
|
+
# IPython
|
|
92
|
+
profile_default/
|
|
93
|
+
ipython_config.py
|
|
94
|
+
|
|
95
|
+
# pyenv
|
|
96
|
+
.python-version
|
|
97
|
+
|
|
98
|
+
# pipenv
|
|
99
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
100
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
101
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
102
|
+
# install all needed dependencies.
|
|
103
|
+
#Pipfile.lock
|
|
104
|
+
|
|
105
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
106
|
+
__pypackages__/
|
|
107
|
+
|
|
108
|
+
# Celery stuff
|
|
109
|
+
celerybeat-schedule
|
|
110
|
+
celerybeat.pid
|
|
111
|
+
|
|
112
|
+
# SageMath parsed files
|
|
113
|
+
*.sage.py
|
|
114
|
+
|
|
115
|
+
# Environments
|
|
116
|
+
.env
|
|
117
|
+
.venv
|
|
118
|
+
env/
|
|
119
|
+
venv/
|
|
120
|
+
ENV/
|
|
121
|
+
env.bak/
|
|
122
|
+
venv.bak/
|
|
123
|
+
|
|
124
|
+
# Spyder project settings
|
|
125
|
+
.spyderproject
|
|
126
|
+
.spyproject
|
|
127
|
+
|
|
128
|
+
# Rope project settings
|
|
129
|
+
.ropeproject
|
|
130
|
+
|
|
131
|
+
# mkdocs documentation
|
|
132
|
+
/site
|
|
133
|
+
|
|
134
|
+
# mypy
|
|
135
|
+
.mypy_cache/
|
|
136
|
+
.dmypy.json
|
|
137
|
+
dmypy.json
|
|
138
|
+
|
|
139
|
+
# Pyre type checker
|
|
140
|
+
.pyre/
|
|
141
|
+
|
|
142
|
+
# vscode
|
|
143
|
+
.vscode/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 DigiKlausur
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jupyterhub-fastapi-adapter
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Adapter for jupyterhub services using fastapi, providing HubOAuth
|
|
5
|
+
Project-URL: Documentation, https://github.com/Digiklausur/jupyterhub-fastapi-adapter#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/Digiklausur/jupyterhub-fastapi-adapter/issues
|
|
7
|
+
Project-URL: Source, https://github.com/Digiklausur/jupyterhub-fastapi-adapter
|
|
8
|
+
Author-email: Tim Metzler <tim.metzler@h-brs.de>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Requires-Dist: fastapi>=0.115
|
|
21
|
+
Requires-Dist: httpx>=0.24
|
|
22
|
+
Requires-Dist: jupyterhub>=4.0
|
|
23
|
+
Requires-Dist: pydantic>=2.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build; extra == 'dev'
|
|
26
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
27
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
28
|
+
Requires-Dist: tbump; extra == 'dev'
|
|
29
|
+
Requires-Dist: twine; extra == 'dev'
|
|
30
|
+
Provides-Extra: docs
|
|
31
|
+
Requires-Dist: pydata-sphinx-theme; extra == 'docs'
|
|
32
|
+
Requires-Dist: sphinx; extra == 'docs'
|
|
33
|
+
Provides-Extra: test
|
|
34
|
+
Requires-Dist: pytest; extra == 'test'
|
|
35
|
+
Requires-Dist: pytest-asyncio; extra == 'test'
|
|
36
|
+
Requires-Dist: pytest-cov; extra == 'test'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# jupyterhub-fastapi-adapter
|
|
41
|
+
|
|
42
|
+
[](https://opensource.org/licenses/MIT)
|
|
43
|
+
[](https://www.python.org/downloads/)
|
|
44
|
+
[](https://pypi.org/project/e2x-hub-rbac/)
|
|
45
|
+
|
|
46
|
+
A lightweight adapter for building authenticated **FastAPI** services that run behind **JupyterHub**.
|
|
47
|
+
|
|
48
|
+
The package provides:
|
|
49
|
+
|
|
50
|
+
* OAuth authentication using JupyterHub's service OAuth flow
|
|
51
|
+
* FastAPI dependencies for accessing the authenticated user
|
|
52
|
+
* Automatic browser redirects to the JupyterHub login page
|
|
53
|
+
* Health-check friendly authentication handling
|
|
54
|
+
* Cookie- and token-based authentication support
|
|
55
|
+
|
|
56
|
+
## Features
|
|
57
|
+
|
|
58
|
+
* ✅ OAuth login flow for browser-based services
|
|
59
|
+
* ✅ `require_authenticated_user` FastAPI dependency
|
|
60
|
+
* ✅ `User` model with username, admin status, and groups
|
|
61
|
+
* ✅ Authentication exception and exception handler
|
|
62
|
+
* ✅ Supports both OAuth cookies and `Authorization` headers
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install jupyterhub-fastapi-adapter
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Requirements
|
|
76
|
+
|
|
77
|
+
The service must run as a **JupyterHub Service** and the following environment variables must be available:
|
|
78
|
+
|
|
79
|
+
| Variable | Description |
|
|
80
|
+
| --------------------------- | ------------------------------------- |
|
|
81
|
+
| `JUPYTERHUB_API_URL` | URL of the JupyterHub API |
|
|
82
|
+
| `JUPYTERHUB_API_TOKEN` | Service API token |
|
|
83
|
+
| `JUPYTERHUB_SERVICE_PREFIX` | Service prefix assigned by JupyterHub |
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## Basic Usage
|
|
88
|
+
|
|
89
|
+
Create a FastAPI application:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
"""
|
|
93
|
+
Minimal FastAPI JupyterHub managed service.
|
|
94
|
+
Shows the authenticated user's information as JSON.
|
|
95
|
+
|
|
96
|
+
Uses jupyterhub.services.auth.HubOAuth to identify the logged-in user
|
|
97
|
+
from JupyterHub's OAuth cookie.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
import os
|
|
101
|
+
|
|
102
|
+
from fastapi import Depends, FastAPI
|
|
103
|
+
from jupyterhub.utils import url_path_join
|
|
104
|
+
from jupyterhub_fastapi_adapter import (
|
|
105
|
+
AuthenticationRequired,
|
|
106
|
+
User,
|
|
107
|
+
authentication_required_handler,
|
|
108
|
+
oauth_callback,
|
|
109
|
+
require_authenticated_user,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
JUPYTERHUB_SERVICE_PREFIX = os.environ["JUPYTERHUB_SERVICE_PREFIX"]
|
|
113
|
+
|
|
114
|
+
app = FastAPI()
|
|
115
|
+
|
|
116
|
+
# Register exception handler
|
|
117
|
+
app.exception_handler(AuthenticationRequired)(authentication_required_handler)
|
|
118
|
+
|
|
119
|
+
# Register OAuth callback route
|
|
120
|
+
app.get(url_path_join(JUPYTERHUB_SERVICE_PREFIX, "oauth_callback"))(oauth_callback)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@app.get(JUPYTERHUB_SERVICE_PREFIX)
|
|
124
|
+
async def index(user: User = Depends(require_authenticated_user)):
|
|
125
|
+
"""Return authenticated user information."""
|
|
126
|
+
return user
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@app.get(url_path_join(JUPYTERHUB_SERVICE_PREFIX, "hello"))
|
|
130
|
+
async def hello(user: User = Depends(require_authenticated_user)):
|
|
131
|
+
return {"message": f"Hello, {user.username}!"}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
When an unauthenticated browser visits the service, they are automatically redirected to the JupyterHub OAuth login flow.
|
|
135
|
+
|
|
136
|
+
After successful authentication, JupyterHub redirects the user back to the service and authentication is handled using an OAuth cookie.
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Authentication Dependency
|
|
141
|
+
|
|
142
|
+
Use the provided dependency to require authentication:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from fastapi import Depends
|
|
146
|
+
|
|
147
|
+
from jupyterhub_fastapi_adapter.dependencies import require_authenticated_user
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@app.get("/protected")
|
|
151
|
+
async def protected(user=Depends(require_authenticated_user)):
|
|
152
|
+
return {"hello": user.username}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The dependency returns a `User` object:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
class User(BaseModel):
|
|
159
|
+
username: str
|
|
160
|
+
admin: bool
|
|
161
|
+
groups: list[str]
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## OAuth Flow
|
|
167
|
+
|
|
168
|
+
The package implements the standard JupyterHub service OAuth flow:
|
|
169
|
+
|
|
170
|
+
1. A user accesses a protected endpoint.
|
|
171
|
+
2. If no valid authentication is present, `AuthenticationRequired` is raised.
|
|
172
|
+
3. The exception handler redirects the browser to JupyterHub's OAuth endpoint.
|
|
173
|
+
4. JupyterHub authenticates the user.
|
|
174
|
+
5. The OAuth callback exchanges the authorization code for an access token.
|
|
175
|
+
6. The access token is stored in a cookie.
|
|
176
|
+
7. Future requests authenticate using that cookie.
|
|
177
|
+
|
|
178
|
+
For API clients, bearer tokens supplied via the `Authorization` header are also supported.
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## Health Checks
|
|
183
|
+
|
|
184
|
+
Requests that do not advertise `Accept: text/html` receive a simple `200 OK` response instead of an OAuth redirect when authentication is required.
|
|
185
|
+
|
|
186
|
+
This allows JupyterHub and other infrastructure to perform health checks without triggering the login flow.
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## API
|
|
191
|
+
|
|
192
|
+
### `hub_oauth`
|
|
193
|
+
|
|
194
|
+
* `AuthenticationRequired`
|
|
195
|
+
* `authentication_required_handler()`
|
|
196
|
+
* `oauth_callback()`
|
|
197
|
+
* `get_token_from_request()`
|
|
198
|
+
|
|
199
|
+
### `dependencies`
|
|
200
|
+
|
|
201
|
+
* `require_authenticated_user()`
|
|
202
|
+
* `get_current_user()`
|
|
203
|
+
* `User`
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
MIT
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
|
|
2
|
+
# jupyterhub-fastapi-adapter
|
|
3
|
+
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://www.python.org/downloads/)
|
|
6
|
+
[](https://pypi.org/project/e2x-hub-rbac/)
|
|
7
|
+
|
|
8
|
+
A lightweight adapter for building authenticated **FastAPI** services that run behind **JupyterHub**.
|
|
9
|
+
|
|
10
|
+
The package provides:
|
|
11
|
+
|
|
12
|
+
* OAuth authentication using JupyterHub's service OAuth flow
|
|
13
|
+
* FastAPI dependencies for accessing the authenticated user
|
|
14
|
+
* Automatic browser redirects to the JupyterHub login page
|
|
15
|
+
* Health-check friendly authentication handling
|
|
16
|
+
* Cookie- and token-based authentication support
|
|
17
|
+
|
|
18
|
+
## Features
|
|
19
|
+
|
|
20
|
+
* ✅ OAuth login flow for browser-based services
|
|
21
|
+
* ✅ `require_authenticated_user` FastAPI dependency
|
|
22
|
+
* ✅ `User` model with username, admin status, and groups
|
|
23
|
+
* ✅ Authentication exception and exception handler
|
|
24
|
+
* ✅ Supports both OAuth cookies and `Authorization` headers
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install jupyterhub-fastapi-adapter
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Requirements
|
|
38
|
+
|
|
39
|
+
The service must run as a **JupyterHub Service** and the following environment variables must be available:
|
|
40
|
+
|
|
41
|
+
| Variable | Description |
|
|
42
|
+
| --------------------------- | ------------------------------------- |
|
|
43
|
+
| `JUPYTERHUB_API_URL` | URL of the JupyterHub API |
|
|
44
|
+
| `JUPYTERHUB_API_TOKEN` | Service API token |
|
|
45
|
+
| `JUPYTERHUB_SERVICE_PREFIX` | Service prefix assigned by JupyterHub |
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Basic Usage
|
|
50
|
+
|
|
51
|
+
Create a FastAPI application:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
"""
|
|
55
|
+
Minimal FastAPI JupyterHub managed service.
|
|
56
|
+
Shows the authenticated user's information as JSON.
|
|
57
|
+
|
|
58
|
+
Uses jupyterhub.services.auth.HubOAuth to identify the logged-in user
|
|
59
|
+
from JupyterHub's OAuth cookie.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
import os
|
|
63
|
+
|
|
64
|
+
from fastapi import Depends, FastAPI
|
|
65
|
+
from jupyterhub.utils import url_path_join
|
|
66
|
+
from jupyterhub_fastapi_adapter import (
|
|
67
|
+
AuthenticationRequired,
|
|
68
|
+
User,
|
|
69
|
+
authentication_required_handler,
|
|
70
|
+
oauth_callback,
|
|
71
|
+
require_authenticated_user,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
JUPYTERHUB_SERVICE_PREFIX = os.environ["JUPYTERHUB_SERVICE_PREFIX"]
|
|
75
|
+
|
|
76
|
+
app = FastAPI()
|
|
77
|
+
|
|
78
|
+
# Register exception handler
|
|
79
|
+
app.exception_handler(AuthenticationRequired)(authentication_required_handler)
|
|
80
|
+
|
|
81
|
+
# Register OAuth callback route
|
|
82
|
+
app.get(url_path_join(JUPYTERHUB_SERVICE_PREFIX, "oauth_callback"))(oauth_callback)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@app.get(JUPYTERHUB_SERVICE_PREFIX)
|
|
86
|
+
async def index(user: User = Depends(require_authenticated_user)):
|
|
87
|
+
"""Return authenticated user information."""
|
|
88
|
+
return user
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@app.get(url_path_join(JUPYTERHUB_SERVICE_PREFIX, "hello"))
|
|
92
|
+
async def hello(user: User = Depends(require_authenticated_user)):
|
|
93
|
+
return {"message": f"Hello, {user.username}!"}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
When an unauthenticated browser visits the service, they are automatically redirected to the JupyterHub OAuth login flow.
|
|
97
|
+
|
|
98
|
+
After successful authentication, JupyterHub redirects the user back to the service and authentication is handled using an OAuth cookie.
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## Authentication Dependency
|
|
103
|
+
|
|
104
|
+
Use the provided dependency to require authentication:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from fastapi import Depends
|
|
108
|
+
|
|
109
|
+
from jupyterhub_fastapi_adapter.dependencies import require_authenticated_user
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@app.get("/protected")
|
|
113
|
+
async def protected(user=Depends(require_authenticated_user)):
|
|
114
|
+
return {"hello": user.username}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The dependency returns a `User` object:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
class User(BaseModel):
|
|
121
|
+
username: str
|
|
122
|
+
admin: bool
|
|
123
|
+
groups: list[str]
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## OAuth Flow
|
|
129
|
+
|
|
130
|
+
The package implements the standard JupyterHub service OAuth flow:
|
|
131
|
+
|
|
132
|
+
1. A user accesses a protected endpoint.
|
|
133
|
+
2. If no valid authentication is present, `AuthenticationRequired` is raised.
|
|
134
|
+
3. The exception handler redirects the browser to JupyterHub's OAuth endpoint.
|
|
135
|
+
4. JupyterHub authenticates the user.
|
|
136
|
+
5. The OAuth callback exchanges the authorization code for an access token.
|
|
137
|
+
6. The access token is stored in a cookie.
|
|
138
|
+
7. Future requests authenticate using that cookie.
|
|
139
|
+
|
|
140
|
+
For API clients, bearer tokens supplied via the `Authorization` header are also supported.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Health Checks
|
|
145
|
+
|
|
146
|
+
Requests that do not advertise `Accept: text/html` receive a simple `200 OK` response instead of an OAuth redirect when authentication is required.
|
|
147
|
+
|
|
148
|
+
This allows JupyterHub and other infrastructure to perform health checks without triggering the login flow.
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## API
|
|
153
|
+
|
|
154
|
+
### `hub_oauth`
|
|
155
|
+
|
|
156
|
+
* `AuthenticationRequired`
|
|
157
|
+
* `authentication_required_handler()`
|
|
158
|
+
* `oauth_callback()`
|
|
159
|
+
* `get_token_from_request()`
|
|
160
|
+
|
|
161
|
+
### `dependencies`
|
|
162
|
+
|
|
163
|
+
* `require_authenticated_user()`
|
|
164
|
+
* `get_current_user()`
|
|
165
|
+
* `User`
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## License
|
|
170
|
+
|
|
171
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .dependencies import User, get_current_user, require_authenticated_user
|
|
2
|
+
from .hub_oauth import (
|
|
3
|
+
AuthenticationRequired,
|
|
4
|
+
authentication_required_handler,
|
|
5
|
+
oauth_callback,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"AuthenticationRequired",
|
|
10
|
+
"authentication_required_handler",
|
|
11
|
+
"oauth_callback",
|
|
12
|
+
"get_current_user",
|
|
13
|
+
"require_authenticated_user",
|
|
14
|
+
"User",
|
|
15
|
+
]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
from fastapi import Request
|
|
3
|
+
from pydantic import BaseModel, Field
|
|
4
|
+
|
|
5
|
+
from .hub_oauth import JUPYTERHUB_API_URL, AuthenticationRequired, get_token_from_request
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class User(BaseModel):
|
|
9
|
+
"""
|
|
10
|
+
Represents a user in the system.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
username: str
|
|
14
|
+
admin: bool = Field(default=False)
|
|
15
|
+
groups: list[str] = Field(default_factory=list)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def get_current_user(request: Request) -> dict | None:
|
|
19
|
+
"""Validate token against JupyterHub API and return the user model."""
|
|
20
|
+
token = get_token_from_request(request)
|
|
21
|
+
if not token:
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
async with httpx.AsyncClient(
|
|
25
|
+
base_url=JUPYTERHUB_API_URL, headers={"Authorization": f"token {token}"}
|
|
26
|
+
) as client:
|
|
27
|
+
resp = await client.get(url="/user")
|
|
28
|
+
if resp.status_code != 200:
|
|
29
|
+
return None
|
|
30
|
+
return resp.json()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def require_authenticated_user(request: Request) -> User:
|
|
34
|
+
"""Dependency that requires authentication.
|
|
35
|
+
|
|
36
|
+
Raises AuthenticationRequired if not logged in.
|
|
37
|
+
"""
|
|
38
|
+
user_data = await get_current_user(request)
|
|
39
|
+
if user_data is None:
|
|
40
|
+
raise AuthenticationRequired(request)
|
|
41
|
+
return User(
|
|
42
|
+
username=user_data["name"],
|
|
43
|
+
admin=user_data.get("admin", False),
|
|
44
|
+
groups=user_data.get("groups", []),
|
|
45
|
+
)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""
|
|
2
|
+
JupyterHub OAuth authentication utilities for FastAPI services.
|
|
3
|
+
|
|
4
|
+
Provides OAuth redirect-based authentication with cookie support,
|
|
5
|
+
as opposed to the token-based auth in dependencies.py.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from urllib.parse import urlencode
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from fastapi import Request
|
|
13
|
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
14
|
+
from jupyterhub.services.auth import HubOAuth
|
|
15
|
+
|
|
16
|
+
# Environment variables
|
|
17
|
+
JUPYTERHUB_API_URL = os.environ["JUPYTERHUB_API_URL"]
|
|
18
|
+
JUPYTERHUB_API_TOKEN = os.environ["JUPYTERHUB_API_TOKEN"]
|
|
19
|
+
JUPYTERHUB_SERVICE_PREFIX = os.environ["JUPYTERHUB_SERVICE_PREFIX"]
|
|
20
|
+
|
|
21
|
+
# Initialize HubOAuth instance at module level
|
|
22
|
+
hub_auth = HubOAuth()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AuthenticationRequired(Exception):
|
|
26
|
+
"""Raised when authentication is required but user is not logged in."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, request: Request):
|
|
29
|
+
self.request = request
|
|
30
|
+
super().__init__("Authentication required")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_token_from_request(request: Request) -> str | None:
|
|
34
|
+
"""Extract the user's OAuth token from JupyterHub's cookie or Authorization header."""
|
|
35
|
+
# JupyterHub sets this cookie after OAuth login
|
|
36
|
+
token = request.cookies.get(hub_auth.cookie_name)
|
|
37
|
+
if token:
|
|
38
|
+
return token
|
|
39
|
+
|
|
40
|
+
# Fallback: Authorization header
|
|
41
|
+
auth_header = request.headers.get("Authorization", "")
|
|
42
|
+
if auth_header.startswith("token "):
|
|
43
|
+
return auth_header[len("token ") :]
|
|
44
|
+
if auth_header.startswith("Bearer "):
|
|
45
|
+
return auth_header[len("Bearer ") :]
|
|
46
|
+
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def authentication_required_handler(request: Request, exc: AuthenticationRequired):
|
|
51
|
+
"""Handle authentication required by redirecting to OAuth.
|
|
52
|
+
|
|
53
|
+
Returns OK for health checks.
|
|
54
|
+
"""
|
|
55
|
+
# For health checks (no Accept: text/html), return 200 so
|
|
56
|
+
# JupyterHub knows the service is alive
|
|
57
|
+
accept = request.headers.get("Accept", "")
|
|
58
|
+
if "text/html" not in accept:
|
|
59
|
+
return HTMLResponse(content="OK", status_code=200)
|
|
60
|
+
|
|
61
|
+
# Detect redirect loop: if we just came from oauth_callback but still failed auth,
|
|
62
|
+
# something is broken (e.g., JupyterHub API down, token validation issues)
|
|
63
|
+
referer = request.headers.get("Referer", "")
|
|
64
|
+
if "oauth_callback" in referer:
|
|
65
|
+
return HTMLResponse(
|
|
66
|
+
content=(
|
|
67
|
+
"<h1>Authentication Error</h1>"
|
|
68
|
+
"<p>Unable to validate credentials after successful OAuth login.</p>"
|
|
69
|
+
"<p>This may indicate a temporary service issue. Please try again later.</p>"
|
|
70
|
+
),
|
|
71
|
+
status_code=500,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# For browser requests, redirect to OAuth login
|
|
75
|
+
state = str(request.url)
|
|
76
|
+
authorize_url = (
|
|
77
|
+
hub_auth.oauth_authorization_url
|
|
78
|
+
+ "?"
|
|
79
|
+
+ urlencode(
|
|
80
|
+
{
|
|
81
|
+
"client_id": hub_auth.oauth_client_id,
|
|
82
|
+
"redirect_uri": hub_auth.oauth_redirect_uri,
|
|
83
|
+
"response_type": "code",
|
|
84
|
+
"state": state,
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
return RedirectResponse(url=authorize_url)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def oauth_callback(request: Request, code: str = "", state: str = ""):
|
|
92
|
+
"""Exchange the OAuth code for a token — JupyterHub sets the cookie automatically."""
|
|
93
|
+
async with httpx.AsyncClient() as client:
|
|
94
|
+
resp = await client.post(
|
|
95
|
+
f"{JUPYTERHUB_API_URL}/oauth2/token",
|
|
96
|
+
data={
|
|
97
|
+
"client_id": hub_auth.oauth_client_id,
|
|
98
|
+
"client_secret": JUPYTERHUB_API_TOKEN,
|
|
99
|
+
"grant_type": "authorization_code",
|
|
100
|
+
"code": code,
|
|
101
|
+
"redirect_uri": hub_auth.oauth_redirect_uri,
|
|
102
|
+
},
|
|
103
|
+
)
|
|
104
|
+
if resp.status_code != 200:
|
|
105
|
+
return HTMLResponse(content="<h1>Authentication failed</h1>", status_code=502)
|
|
106
|
+
|
|
107
|
+
token_data = resp.json()
|
|
108
|
+
token = token_data["access_token"]
|
|
109
|
+
|
|
110
|
+
next_url = state or JUPYTERHUB_SERVICE_PREFIX
|
|
111
|
+
response = RedirectResponse(url=next_url)
|
|
112
|
+
response.set_cookie(
|
|
113
|
+
key=hub_auth.cookie_name,
|
|
114
|
+
value=token,
|
|
115
|
+
path=hub_auth.base_url,
|
|
116
|
+
)
|
|
117
|
+
return response
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "jupyterhub-fastapi-adapter"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = 'Adapter for jupyterhub services using fastapi, providing HubOAuth'
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
keywords = []
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Tim Metzler", email = "tim.metzler@h-brs.de" },
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Programming Language :: Python",
|
|
19
|
+
"Programming Language :: Python :: 3.8",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: Implementation :: PyPy",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"fastapi>=0.115",
|
|
28
|
+
"httpx>=0.24",
|
|
29
|
+
"jupyterhub>=4.0",
|
|
30
|
+
"pydantic>=2.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Documentation = "https://github.com/Digiklausur/jupyterhub-fastapi-adapter#readme"
|
|
35
|
+
Issues = "https://github.com/Digiklausur/jupyterhub-fastapi-adapter/issues"
|
|
36
|
+
Source = "https://github.com/Digiklausur/jupyterhub-fastapi-adapter"
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = [
|
|
40
|
+
"pre-commit",
|
|
41
|
+
"ruff",
|
|
42
|
+
"tbump",
|
|
43
|
+
"build",
|
|
44
|
+
"twine",
|
|
45
|
+
]
|
|
46
|
+
test = [
|
|
47
|
+
"pytest",
|
|
48
|
+
"pytest-cov",
|
|
49
|
+
"pytest-asyncio",
|
|
50
|
+
]
|
|
51
|
+
docs = [
|
|
52
|
+
"sphinx",
|
|
53
|
+
"pydata-sphinx-theme",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
[tool.hatch.version]
|
|
57
|
+
path = "jupyterhub_fastapi_adapter/__about__.py"
|
|
58
|
+
|
|
59
|
+
[tool.pytest.ini_options]
|
|
60
|
+
testpaths = ["tests"]
|
|
61
|
+
|
|
62
|
+
[tool.tbump]
|
|
63
|
+
github_url = "https://github.com/Digiklausur/jupyterhub-fastapi-adapter"
|
|
64
|
+
|
|
65
|
+
[tool.tbump.version]
|
|
66
|
+
current = "0.1.0"
|
|
67
|
+
regex = '''
|
|
68
|
+
(?P<major>\d+)
|
|
69
|
+
\.
|
|
70
|
+
(?P<minor>\d+)
|
|
71
|
+
\.
|
|
72
|
+
(?P<patch>\d+)
|
|
73
|
+
(?P<rc>rc\d+)?
|
|
74
|
+
'''
|
|
75
|
+
|
|
76
|
+
[tool.tbump.git]
|
|
77
|
+
message_template = "Bump to {new_version}"
|
|
78
|
+
tag_template = "v{new_version}"
|
|
79
|
+
|
|
80
|
+
# Files with the version to update
|
|
81
|
+
[[tool.tbump.file]]
|
|
82
|
+
src = "jupyterhub_fastapi_adapter/__about__.py"
|
|
83
|
+
|
|
84
|
+
[[tool.tbump.before_commit]]
|
|
85
|
+
name = "Build"
|
|
86
|
+
cmd = "python -m build"
|
|
87
|
+
|
|
88
|
+
[[tool.tbump.before_commit]]
|
|
89
|
+
name = "Check with twine"
|
|
90
|
+
cmd = "twine check dist/*"
|
|
91
|
+
|
|
92
|
+
[tool.ruff]
|
|
93
|
+
line-length = 100
|
|
94
|
+
lint.select = ["F", "E", "I"]
|