interloper-api 0.135.0__tar.gz → 0.136.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.
- {interloper_api-0.135.0 → interloper_api-0.136.0}/PKG-INFO +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/pyproject.toml +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/pyproject.toml.orig +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/__init__.py +2 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/app.py +42 -32
- interloper_api-0.136.0/src/interloper_api/auth/__init__.py +22 -0
- interloper_api-0.136.0/src/interloper_api/auth/base.py +87 -0
- interloper_api-0.136.0/src/interloper_api/auth/google.py +69 -0
- interloper_api-0.136.0/src/interloper_api/auth/provider.py +206 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/cli.py +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/dependencies/__init__.py +4 -4
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/dependencies/state.py +15 -14
- interloper_api-0.136.0/src/interloper_api/oauth/__init__.py +31 -0
- interloper_api-0.135.0/src/interloper_api/authorization.py → interloper_api-0.136.0/src/interloper_api/oauth/base.py +13 -6
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/admin.py +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/auth.py +70 -25
- interloper_api-0.136.0/src/interloper_api/routes/extensions.py +324 -0
- interloper_api-0.135.0/src/interloper_api/routes/authorization.py → interloper_api-0.136.0/src/interloper_api/routes/oauth.py +15 -15
- interloper_api-0.135.0/src/interloper_api/routes/oauth.py → interloper_api-0.136.0/src/interloper_api/routes/providers.py +10 -8
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/tokens.py +1 -1
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/settings.py +7 -7
- interloper_api-0.135.0/src/interloper_api/login.py +0 -237
- interloper_api-0.135.0/src/interloper_api/routes/extensions.py +0 -112
- {interloper_api-0.135.0 → interloper_api-0.136.0}/README.md +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/dependencies/auth.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/dependencies/rbac.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/extension.yaml +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/notifications/__init__.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/notifications/base.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/notifications/invitations.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/notifications/super_admins.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/__init__.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/agent.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/apps.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/backfills.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/catalog.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/components.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/executions.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/health.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/organisations.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/overview.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/relations.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/runs.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/routes/websocket.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/server.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/utils/__init__.py +0 -0
- {interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/utils/time.py +0 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""HTTP API for interloper: catalog, collection, run, and auth endpoints."""
|
|
2
2
|
|
|
3
3
|
from interloper_api.app import create_app
|
|
4
|
+
from interloper_api.routes.extensions import UIBundle
|
|
4
5
|
from interloper_api.server import ApiServer
|
|
5
6
|
|
|
6
|
-
__all__ = ["ApiServer", "create_app"]
|
|
7
|
+
__all__ = ["ApiServer", "UIBundle", "create_app"]
|
|
@@ -23,14 +23,13 @@ from interloper_db import (
|
|
|
23
23
|
)
|
|
24
24
|
from starlette.concurrency import run_in_threadpool
|
|
25
25
|
|
|
26
|
-
from interloper_api.
|
|
26
|
+
from interloper_api.auth import Login
|
|
27
27
|
from interloper_api.dependencies import State, require_viewer
|
|
28
|
-
from interloper_api.
|
|
28
|
+
from interloper_api.oauth import AuthorizationServer, CrossOriginMiddleware
|
|
29
29
|
from interloper_api.routes import (
|
|
30
30
|
admin,
|
|
31
31
|
apps,
|
|
32
32
|
auth,
|
|
33
|
-
authorization,
|
|
34
33
|
backfills,
|
|
35
34
|
components,
|
|
36
35
|
executions,
|
|
@@ -39,6 +38,7 @@ from interloper_api.routes import (
|
|
|
39
38
|
oauth,
|
|
40
39
|
organisations,
|
|
41
40
|
overview,
|
|
41
|
+
providers,
|
|
42
42
|
relations,
|
|
43
43
|
runs,
|
|
44
44
|
tokens,
|
|
@@ -54,10 +54,10 @@ logger = logging.getLogger(__name__)
|
|
|
54
54
|
#: run's ingest, and the probes.
|
|
55
55
|
_ROUTERS: tuple[APIRouter, ...] = (
|
|
56
56
|
auth.router,
|
|
57
|
-
|
|
57
|
+
oauth.router,
|
|
58
58
|
organisations.router,
|
|
59
59
|
admin.router,
|
|
60
|
-
|
|
60
|
+
providers.router,
|
|
61
61
|
tokens.router,
|
|
62
62
|
apps.router,
|
|
63
63
|
extensions.router,
|
|
@@ -189,8 +189,9 @@ def create_app(
|
|
|
189
189
|
"""Create the FastAPI application with all routes.
|
|
190
190
|
|
|
191
191
|
The routes the installed packages declare mount under
|
|
192
|
-
``/api/organisations/{org_id}/ext/<name
|
|
193
|
-
|
|
192
|
+
``/api/organisations/{org_id}/ext/<name>``, their UI bundles under
|
|
193
|
+
``/api/ext/<name>/ui/<digest>``. On startup the application promotes the
|
|
194
|
+
configured super-admins and starts the realtime listener.
|
|
194
195
|
|
|
195
196
|
Args:
|
|
196
197
|
store: The ``Store`` instance for persistence.
|
|
@@ -221,23 +222,26 @@ def create_app(
|
|
|
221
222
|
)
|
|
222
223
|
# Added last, so it answers a client-facing endpoint's preflight before the policy above can refuse it.
|
|
223
224
|
app.add_middleware(CrossOriginMiddleware)
|
|
224
|
-
|
|
225
|
-
if
|
|
226
|
-
|
|
225
|
+
login = _login(settings)
|
|
226
|
+
if login is not None:
|
|
227
|
+
login.install(app)
|
|
227
228
|
|
|
228
229
|
api = APIRouter(prefix="/api")
|
|
229
230
|
for router in _ROUTERS:
|
|
230
231
|
api.include_router(router)
|
|
232
|
+
# The authorization server also answers at its old /api/auth/oauth for one release,
|
|
233
|
+
# for clients that saved an endpoint instead of reading the metadata again.
|
|
234
|
+
api.include_router(oauth.router, prefix="/auth", include_in_schema=False)
|
|
231
235
|
for org_router in _ORG_ROUTERS:
|
|
232
236
|
api.include_router(org_router, prefix=ORG_PREFIX)
|
|
233
237
|
agent_model = _mount_agent(api, settings)
|
|
234
|
-
_mount_extensions(api)
|
|
238
|
+
_mount_extensions(app, api)
|
|
235
239
|
app.include_router(api)
|
|
236
|
-
app.include_router(
|
|
240
|
+
app.include_router(oauth.well_known_router)
|
|
237
241
|
|
|
238
|
-
app.state.interloper = _state(store, catalog, settings, agent_model=agent_model,
|
|
242
|
+
app.state.interloper = _state(store, catalog, settings, agent_model=agent_model, login=login)
|
|
239
243
|
|
|
240
|
-
|
|
244
|
+
providers.log_provider_status()
|
|
241
245
|
|
|
242
246
|
return app
|
|
243
247
|
|
|
@@ -299,18 +303,24 @@ def _mount_agent(api: APIRouter, settings: ApiSettings) -> str | None:
|
|
|
299
303
|
return settings.agent.model
|
|
300
304
|
|
|
301
305
|
|
|
302
|
-
def _mount_extensions(api: APIRouter) -> None:
|
|
303
|
-
"""Mount
|
|
306
|
+
def _mount_extensions(app: FastAPI, api: APIRouter) -> None:
|
|
307
|
+
"""Mount what the installed packages declare: their routers, the viewer role their floor, and their UI bundles.
|
|
304
308
|
|
|
305
|
-
A router that fails to load is skipped and recorded, so the
|
|
306
|
-
the configuration page name it while every other one serves.
|
|
309
|
+
A router or bundle that fails to load is skipped and recorded, so the
|
|
310
|
+
listing and the configuration page name it while every other one serves.
|
|
307
311
|
|
|
308
312
|
Args:
|
|
309
|
-
|
|
313
|
+
app: The application the bundles' files are served from, outside
|
|
314
|
+
every authenticated route.
|
|
315
|
+
api: The ``/api`` router the routers are mounted onto.
|
|
310
316
|
"""
|
|
311
317
|
for name, router in extensions.EXTENSION_ROUTERS.items():
|
|
312
318
|
api.include_router(router, prefix=f"{ORG_PREFIX}/ext/{name}", dependencies=[Depends(require_viewer)])
|
|
313
319
|
logger.info("Extension routes '%s' mounted at /api%s/ext/%s.", name, ORG_PREFIX, name)
|
|
320
|
+
for name, bundle in extensions.UI_BUNDLES.items():
|
|
321
|
+
path = extensions.UI_PATH.format(name=name, digest=bundle.digest)
|
|
322
|
+
app.mount(path, extensions.BundleFiles(bundle), name=f"ext-ui-{name}")
|
|
323
|
+
logger.info("Extension UI '%s' served at %s.", name, path)
|
|
314
324
|
|
|
315
325
|
|
|
316
326
|
def _state(
|
|
@@ -319,7 +329,7 @@ def _state(
|
|
|
319
329
|
settings: ApiSettings,
|
|
320
330
|
*,
|
|
321
331
|
agent_model: str | None,
|
|
322
|
-
|
|
332
|
+
login: Login | None,
|
|
323
333
|
) -> State:
|
|
324
334
|
"""Build the state the request dependencies read back.
|
|
325
335
|
|
|
@@ -330,8 +340,8 @@ def _state(
|
|
|
330
340
|
agent_model: The model the mounted agent runs on, or ``None`` when
|
|
331
341
|
the agent routes are not mounted; recorded as a feature flag and
|
|
332
342
|
in the admin config snapshot.
|
|
333
|
-
|
|
334
|
-
``None``.
|
|
343
|
+
login: The sign-in providers offered, already installed on the
|
|
344
|
+
app, or ``None``.
|
|
335
345
|
|
|
336
346
|
Returns:
|
|
337
347
|
The state.
|
|
@@ -350,25 +360,25 @@ def _state(
|
|
|
350
360
|
agent=agent,
|
|
351
361
|
features=features,
|
|
352
362
|
authorization_server=_authorization_server(store, settings),
|
|
353
|
-
|
|
363
|
+
login=login,
|
|
354
364
|
)
|
|
355
365
|
|
|
356
366
|
|
|
357
|
-
def
|
|
358
|
-
"""
|
|
367
|
+
def _login(settings: ApiSettings) -> Login | None:
|
|
368
|
+
"""Offer the sign-in providers the deployment configures, when it can run a login.
|
|
359
369
|
|
|
360
370
|
Args:
|
|
361
371
|
settings: The API's settings.
|
|
362
372
|
|
|
363
373
|
Returns:
|
|
364
|
-
The login, or ``None`` without a
|
|
365
|
-
encryption key (which signs the cookie
|
|
366
|
-
|
|
374
|
+
The login, or ``None`` without a configured provider or without an
|
|
375
|
+
encryption key (which signs the cookie a login keeps between its two
|
|
376
|
+
legs).
|
|
367
377
|
"""
|
|
368
|
-
|
|
369
|
-
if
|
|
370
|
-
logger.warning("
|
|
371
|
-
return
|
|
378
|
+
login = Login.from_settings(settings)
|
|
379
|
+
if login is None and not settings.encryption.key:
|
|
380
|
+
logger.warning("Sign-in unavailable: INTERLOPER_ENCRYPTION_KEY is not configured.")
|
|
381
|
+
return login
|
|
372
382
|
|
|
373
383
|
|
|
374
384
|
def _authorization_server(store: Store, settings: ApiSettings) -> AuthorizationServer | None:
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Signing in: the identity providers people sign in through, over OpenID Connect.
|
|
2
|
+
|
|
3
|
+
A :class:`LoginProvider` runs one provider's login and turns its verified ID
|
|
4
|
+
token into the :class:`Account` it proves; :class:`Login` holds the providers
|
|
5
|
+
a deployment offers and installs the session their logins keep.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from interloper_api.auth.base import PROVIDERS, SESSION_COOKIE, SESSION_MAX_AGE, SESSION_PATH, Login
|
|
9
|
+
from interloper_api.auth.google import GoogleProvider
|
|
10
|
+
from interloper_api.auth.provider import Account, LoginError, LoginProvider
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"PROVIDERS",
|
|
14
|
+
"SESSION_COOKIE",
|
|
15
|
+
"SESSION_MAX_AGE",
|
|
16
|
+
"SESSION_PATH",
|
|
17
|
+
"Account",
|
|
18
|
+
"GoogleProvider",
|
|
19
|
+
"Login",
|
|
20
|
+
"LoginError",
|
|
21
|
+
"LoginProvider",
|
|
22
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The sign-in providers a deployment offers, and the session a login keeps between its two legs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from fastapi import FastAPI
|
|
11
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
12
|
+
|
|
13
|
+
from interloper_api.auth.google import GoogleProvider
|
|
14
|
+
from interloper_api.auth.provider import LoginProvider
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from interloper_api.settings import ApiSettings
|
|
18
|
+
|
|
19
|
+
SESSION_COOKIE = "login_state"
|
|
20
|
+
SESSION_PATH = "/api/auth"
|
|
21
|
+
SESSION_MAX_AGE = 600
|
|
22
|
+
_SESSION_KEY_LABEL = b"interloper login state"
|
|
23
|
+
|
|
24
|
+
PROVIDERS: tuple[type[LoginProvider], ...] = (GoogleProvider,)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Login:
|
|
28
|
+
"""The sign-in providers a deployment offers, and the session their logins keep.
|
|
29
|
+
|
|
30
|
+
A login keeps its ``state``, nonce, PKCE verifier and destination in a
|
|
31
|
+
signed session cookie scoped to the login routes, alive for the ten
|
|
32
|
+
minutes a login may take. Every API replica must be able to read a cookie
|
|
33
|
+
another one wrote, so it is signed with a key derived from the instance's
|
|
34
|
+
encryption secret; a deployment without one offers no login.
|
|
35
|
+
|
|
36
|
+
Attributes:
|
|
37
|
+
providers: The providers offered, by name.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, providers: Iterable[LoginProvider], *, encryption_key: str, cookie_secure: bool) -> None:
|
|
41
|
+
"""Offer the providers, and derive the session cookie's signing key.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
providers: The providers offered.
|
|
45
|
+
encryption_key: The instance's encryption secret, from which the
|
|
46
|
+
session cookie's signing key is derived.
|
|
47
|
+
cookie_secure: Whether the session cookie is sent over HTTPS only.
|
|
48
|
+
"""
|
|
49
|
+
self.providers = {provider.name: provider for provider in providers}
|
|
50
|
+
self._cookie_secure = cookie_secure
|
|
51
|
+
self._session_secret = hmac.new(encryption_key.encode(), _SESSION_KEY_LABEL, hashlib.sha256).hexdigest()
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_settings(cls, settings: ApiSettings) -> Login | None:
|
|
55
|
+
"""Offer every provider the settings configure a client for.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
settings: The API's settings.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
The login, or ``None`` when no provider is configured or no
|
|
62
|
+
encryption key is.
|
|
63
|
+
"""
|
|
64
|
+
providers = [provider_type.from_settings(settings) for provider_type in PROVIDERS]
|
|
65
|
+
configured = [provider for provider in providers if provider is not None]
|
|
66
|
+
if not configured or not settings.encryption.key:
|
|
67
|
+
return None
|
|
68
|
+
return cls(configured, encryption_key=settings.encryption.key, cookie_secure=settings.auth.cookie_secure)
|
|
69
|
+
|
|
70
|
+
def install(self, app: FastAPI) -> None:
|
|
71
|
+
"""Add the session a login keeps between its two routes.
|
|
72
|
+
|
|
73
|
+
Only the authentication routes receive its cookie, and it lives as
|
|
74
|
+
long as a login may take.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
app: The application.
|
|
78
|
+
"""
|
|
79
|
+
app.add_middleware(
|
|
80
|
+
SessionMiddleware,
|
|
81
|
+
secret_key=self._session_secret,
|
|
82
|
+
session_cookie=SESSION_COOKIE,
|
|
83
|
+
max_age=SESSION_MAX_AGE,
|
|
84
|
+
path=SESSION_PATH,
|
|
85
|
+
same_site="lax",
|
|
86
|
+
https_only=self._cookie_secure,
|
|
87
|
+
)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Sign in with a Google account."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from interloper_api.auth.provider import Account, LoginError, LoginProvider
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from interloper_api.settings import ApiSettings
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GoogleProvider(LoginProvider):
|
|
17
|
+
"""Google, which names an account by the ID token's ``sub`` for the account's whole life.
|
|
18
|
+
|
|
19
|
+
Google vouches for an address only with ``email_verified``, so a login
|
|
20
|
+
without it is refused.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
name = "google"
|
|
24
|
+
label = "Google"
|
|
25
|
+
metadata_url = "https://accounts.google.com/.well-known/openid-configuration"
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def from_settings(cls, settings: ApiSettings) -> GoogleProvider | None:
|
|
29
|
+
"""Build the provider from the deployment's Google OAuth web client.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
settings: The API's settings, whose ``auth`` holds the client and
|
|
33
|
+
whose ``server`` the public URL the callback is served on.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The provider, or ``None`` when no Google client is configured.
|
|
37
|
+
"""
|
|
38
|
+
auth = settings.auth
|
|
39
|
+
if not auth.google_client_id or not auth.google_client_secret:
|
|
40
|
+
return None
|
|
41
|
+
return cls(
|
|
42
|
+
client_id=auth.google_client_id,
|
|
43
|
+
client_secret=auth.google_client_secret,
|
|
44
|
+
public_url=settings.server.public_url,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def account(self, claims: dict[str, Any]) -> Account:
|
|
48
|
+
"""Read the Google account a verified ID token proves.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
claims: The verified ID token's claims.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
The account.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
LoginError: ``login_failed`` when the token names no account or
|
|
58
|
+
address, or Google has not verified the address.
|
|
59
|
+
"""
|
|
60
|
+
if not claims.get("sub") or not claims.get("email") or claims.get("email_verified") is not True:
|
|
61
|
+
logger.warning("Google login refused: the ID token names no account or no verified address")
|
|
62
|
+
raise LoginError("login_failed")
|
|
63
|
+
return Account(
|
|
64
|
+
issuer=claims["iss"],
|
|
65
|
+
subject=claims["sub"],
|
|
66
|
+
email=claims["email"],
|
|
67
|
+
name=claims.get("name"),
|
|
68
|
+
avatar_url=claims.get("picture"),
|
|
69
|
+
)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""A sign-in provider: an OpenID Connect identity provider people sign in through.
|
|
2
|
+
|
|
3
|
+
Authlib runs the OpenID Connect leg: it reads the provider's discovery
|
|
4
|
+
document, sends the browser there with ``state``, a nonce and a PKCE
|
|
5
|
+
challenge, and at the callback checks ``state``, exchanges the code and
|
|
6
|
+
verifies the ID token's signature, issuer, audience, expiry and nonce against
|
|
7
|
+
the provider's keys. What it keeps between the two legs lives in the login
|
|
8
|
+
session :class:`~interloper_api.auth.Login` installs.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from abc import ABC, abstractmethod
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self
|
|
17
|
+
|
|
18
|
+
import httpx2
|
|
19
|
+
from authlib.integrations.base_client import MismatchingStateError, OAuthError
|
|
20
|
+
from authlib.integrations.starlette_client import OAuth
|
|
21
|
+
from joserfc.errors import JoseError
|
|
22
|
+
from starlette.requests import Request
|
|
23
|
+
from starlette.responses import RedirectResponse
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from interloper_api.settings import ApiSettings
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LoginError(Exception):
|
|
32
|
+
"""A login that did not complete.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
reason: What the login page tells the user: ``login_expired`` when
|
|
36
|
+
the callback does not belong to a login this browser started (or
|
|
37
|
+
it took too long), ``login_failed`` for everything else.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, reason: Literal["login_expired", "login_failed"]) -> None:
|
|
41
|
+
"""Record why the login did not complete.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
reason: The login page's error code.
|
|
45
|
+
"""
|
|
46
|
+
super().__init__(reason)
|
|
47
|
+
self.reason = reason
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Account:
|
|
52
|
+
"""The account a login proved, from the provider's verified ID token.
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
issuer: The provider's issuer identifier, verified against its
|
|
56
|
+
discovery document.
|
|
57
|
+
subject: The stable identifier the provider names the person by,
|
|
58
|
+
unique within the issuer.
|
|
59
|
+
email: The person's address, verified by the provider.
|
|
60
|
+
name: The display name, when the provider shares one.
|
|
61
|
+
avatar_url: The profile picture, when the provider has one.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
issuer: str
|
|
65
|
+
subject: str
|
|
66
|
+
email: str
|
|
67
|
+
name: str | None
|
|
68
|
+
avatar_url: str | None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class LoginProvider(ABC):
|
|
72
|
+
"""An identity provider people sign in through, and the Authlib client that talks to it.
|
|
73
|
+
|
|
74
|
+
A subclass names the provider, points at its discovery document, reads its
|
|
75
|
+
client from the settings, and turns verified claims into the account they
|
|
76
|
+
prove, refusing what its own rules do not trust.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
name: The provider's name in the login routes,
|
|
80
|
+
``/api/auth/<name>/login`` and ``/api/auth/<name>/callback``.
|
|
81
|
+
label: The provider's name as the login page shows it.
|
|
82
|
+
metadata_url: The provider's OpenID Connect discovery document.
|
|
83
|
+
redirect_uri: The callback URL registered with the provider.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
name: ClassVar[str]
|
|
87
|
+
label: ClassVar[str]
|
|
88
|
+
metadata_url: ClassVar[str]
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
*,
|
|
93
|
+
client_id: str,
|
|
94
|
+
client_secret: str,
|
|
95
|
+
public_url: str,
|
|
96
|
+
transport: httpx2.AsyncBaseTransport | None = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
"""Register the provider's client.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
client_id: The OAuth client's id at the provider.
|
|
102
|
+
client_secret: Its secret.
|
|
103
|
+
public_url: The app's public base URL, without a trailing slash;
|
|
104
|
+
the callback URL is the provider's callback route on it.
|
|
105
|
+
transport: The HTTP transport Authlib talks to the provider
|
|
106
|
+
through; ``None`` for the network.
|
|
107
|
+
"""
|
|
108
|
+
self.redirect_uri = f"{public_url}/api/auth/{self.name}/callback"
|
|
109
|
+
client_kwargs: dict[str, Any] = {"scope": "openid email profile", "code_challenge_method": "S256"}
|
|
110
|
+
if transport is not None:
|
|
111
|
+
client_kwargs["transport"] = transport
|
|
112
|
+
self._client: Any = OAuth().register(
|
|
113
|
+
self.name,
|
|
114
|
+
client_id=client_id,
|
|
115
|
+
client_secret=client_secret,
|
|
116
|
+
server_metadata_url=self.metadata_url,
|
|
117
|
+
client_kwargs=client_kwargs,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
@abstractmethod
|
|
122
|
+
def from_settings(cls, settings: ApiSettings) -> Self | None:
|
|
123
|
+
"""Build the provider from the application settings.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
settings: The API's settings.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
The provider, or ``None`` when the deployment configures no
|
|
130
|
+
client for it.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
@abstractmethod
|
|
134
|
+
def account(self, claims: dict[str, Any]) -> Account:
|
|
135
|
+
"""Read the account a verified ID token proves.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
claims: The verified ID token's claims.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
The account.
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
LoginError: ``login_failed`` when the claims name no account, or
|
|
145
|
+
an address the provider does not vouch for: the address
|
|
146
|
+
decides signup and super-admin rights.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
async def redirect(self, request: Request, destination: str) -> RedirectResponse:
|
|
150
|
+
"""Send the browser to the provider's account picker.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
request: The login request.
|
|
154
|
+
destination: Where to land once the login completes, as asked.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
The redirect to the provider.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
LoginError: ``login_failed`` when the provider's discovery
|
|
161
|
+
document cannot be read.
|
|
162
|
+
"""
|
|
163
|
+
request.session[self._destination_key] = destination
|
|
164
|
+
try:
|
|
165
|
+
return await self._client.authorize_redirect(request, self.redirect_uri, prompt="select_account")
|
|
166
|
+
except httpx2.HTTPError as error:
|
|
167
|
+
logger.warning("%s login could not start: %s", self.label, error)
|
|
168
|
+
raise LoginError("login_failed") from error
|
|
169
|
+
|
|
170
|
+
async def complete(self, request: Request) -> tuple[Account, str]:
|
|
171
|
+
"""Turn the provider's callback into the account it proves.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
request: The callback request.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
The account and the destination the login asked for, as asked.
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
LoginError: ``login_expired`` when the callback's ``state`` is not
|
|
181
|
+
one this browser's session holds; ``login_failed`` when the
|
|
182
|
+
user declined, the exchange failed, or the ID token is
|
|
183
|
+
missing or does not verify.
|
|
184
|
+
"""
|
|
185
|
+
destination = request.session.pop(self._destination_key, "/")
|
|
186
|
+
try:
|
|
187
|
+
token = await self._client.authorize_access_token(request)
|
|
188
|
+
except MismatchingStateError as error:
|
|
189
|
+
raise LoginError("login_expired") from error
|
|
190
|
+
except (OAuthError, JoseError, httpx2.HTTPError) as error:
|
|
191
|
+
logger.warning("%s login failed: %s", self.label, error)
|
|
192
|
+
raise LoginError("login_failed") from error
|
|
193
|
+
claims = token.get("userinfo")
|
|
194
|
+
if claims is None:
|
|
195
|
+
logger.warning("%s login failed: the token response carries no ID token", self.label)
|
|
196
|
+
raise LoginError("login_failed")
|
|
197
|
+
return self.account(claims), destination
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def _destination_key(self) -> str:
|
|
201
|
+
"""Name the session entry holding this provider's login destination.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
The key, distinct per provider, as Authlib's own entries are.
|
|
205
|
+
"""
|
|
206
|
+
return f"{self.name}_destination"
|
|
@@ -21,7 +21,7 @@ from interloper_db import Store
|
|
|
21
21
|
from interloper_db.provision import bootstrap
|
|
22
22
|
from interloper_db.settings import PostgresSettings
|
|
23
23
|
|
|
24
|
-
from interloper_api.
|
|
24
|
+
from interloper_api.oauth import Client
|
|
25
25
|
from interloper_api.server import ApiServer
|
|
26
26
|
from interloper_api.settings import ApiSettings
|
|
27
27
|
|
{interloper_api-0.135.0 → interloper_api-0.136.0}/src/interloper_api/dependencies/__init__.py
RENAMED
|
@@ -35,7 +35,7 @@ from interloper_api.dependencies.state import (
|
|
|
35
35
|
AuthorizationServerDep,
|
|
36
36
|
CatalogDep,
|
|
37
37
|
FeaturesDep,
|
|
38
|
-
|
|
38
|
+
LoginProviderDep,
|
|
39
39
|
SettingsDep,
|
|
40
40
|
State,
|
|
41
41
|
StateDep,
|
|
@@ -44,7 +44,7 @@ from interloper_api.dependencies.state import (
|
|
|
44
44
|
get_authorization_server,
|
|
45
45
|
get_catalog,
|
|
46
46
|
get_features,
|
|
47
|
-
|
|
47
|
+
get_login_provider,
|
|
48
48
|
get_settings,
|
|
49
49
|
get_state,
|
|
50
50
|
get_store,
|
|
@@ -60,7 +60,7 @@ __all__ = [
|
|
|
60
60
|
"CurrentUserDep",
|
|
61
61
|
"EditorDep",
|
|
62
62
|
"FeaturesDep",
|
|
63
|
-
"
|
|
63
|
+
"LoginProviderDep",
|
|
64
64
|
"OrgDep",
|
|
65
65
|
"OrgScope",
|
|
66
66
|
"SessionUserDep",
|
|
@@ -76,7 +76,7 @@ __all__ = [
|
|
|
76
76
|
"get_caller_credential",
|
|
77
77
|
"get_catalog",
|
|
78
78
|
"get_features",
|
|
79
|
-
"
|
|
79
|
+
"get_login_provider",
|
|
80
80
|
"get_org_scope",
|
|
81
81
|
"get_session_caller",
|
|
82
82
|
"get_settings",
|