interloper-api 0.122.0__tar.gz → 0.122.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.
Files changed (38) hide show
  1. {interloper_api-0.122.0 → interloper_api-0.122.1}/PKG-INFO +3 -1
  2. {interloper_api-0.122.0 → interloper_api-0.122.1}/pyproject.toml +3 -1
  3. {interloper_api-0.122.0 → interloper_api-0.122.1}/pyproject.toml.orig +3 -1
  4. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/app.py +35 -2
  5. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/dependencies/__init__.py +4 -0
  6. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/dependencies/state.py +23 -0
  7. interloper_api-0.122.1/src/interloper_api/login.py +235 -0
  8. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/auth.py +56 -134
  9. {interloper_api-0.122.0 → interloper_api-0.122.1}/README.md +0 -0
  10. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/__init__.py +0 -0
  11. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/authorization.py +0 -0
  12. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/cli.py +0 -0
  13. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/dependencies/auth.py +0 -0
  14. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/dependencies/rbac.py +0 -0
  15. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/notifications/__init__.py +0 -0
  16. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/notifications/base.py +0 -0
  17. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/notifications/invitations.py +0 -0
  18. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/notifications/super_admins.py +0 -0
  19. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/__init__.py +0 -0
  20. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/admin.py +0 -0
  21. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/agent.py +0 -0
  22. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/apps.py +0 -0
  23. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/authorization.py +0 -0
  24. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/backfills.py +0 -0
  25. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/catalog.py +0 -0
  26. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/components.py +0 -0
  27. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/executions.py +0 -0
  28. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/health.py +0 -0
  29. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/oauth.py +0 -0
  30. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/organisations.py +0 -0
  31. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/overview.py +0 -0
  32. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/relations.py +0 -0
  33. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/runs.py +0 -0
  34. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/tokens.py +0 -0
  35. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/routes/websocket.py +0 -0
  36. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/server.py +0 -0
  37. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/utils/__init__.py +0 -0
  38. {interloper_api-0.122.0 → interloper_api-0.122.1}/src/interloper_api/utils/time.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: interloper-api
3
- Version: 0.122.0
3
+ Version: 0.122.1
4
4
  Summary: Interloper FastAPI routes
5
5
  Author: Guillaume Onfroy
6
6
  Author-email: Guillaume Onfroy <guillaume@digitlcloud.com>
@@ -14,6 +14,8 @@ Requires-Dist: httpx2>=2.13.1
14
14
  Requires-Dist: psycopg2-binary>=2.9.0
15
15
  Requires-Dist: uvicorn[standard]>=0.41.0
16
16
  Requires-Dist: wsproto>=1.2.0
17
+ Requires-Dist: itsdangerous>=2.2
18
+ Requires-Dist: joserfc>=1.7
17
19
  Requires-Dist: interloper-agent ; extra == 'agent'
18
20
  Requires-Dist: interloper-core[otel] ; extra == 'otel'
19
21
  Requires-Dist: opentelemetry-instrumentation-fastapi>=0.65b0 ; extra == 'otel'
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "interloper-api"
3
- version = "0.122.0"
3
+ version = "0.122.1"
4
4
  description = "Interloper FastAPI routes"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -15,6 +15,8 @@ dependencies = [
15
15
  "psycopg2-binary>=2.9.0",
16
16
  "uvicorn[standard]>=0.41.0",
17
17
  "wsproto>=1.2.0",
18
+ "itsdangerous>=2.2",
19
+ "joserfc>=1.7",
18
20
  ]
19
21
 
20
22
  [[project.authors]]
@@ -3,7 +3,7 @@
3
3
  # ###############
4
4
  [project]
5
5
  name = "interloper-api"
6
- version = "0.122.0"
6
+ version = "0.122.1"
7
7
  description = "Interloper FastAPI routes"
8
8
  readme = "README.md"
9
9
  authors = [{ name = "Guillaume Onfroy", email = "guillaume@digitlcloud.com" }]
@@ -19,6 +19,8 @@ dependencies = [
19
19
  "psycopg2-binary>=2.9.0",
20
20
  "uvicorn[standard]>=0.41.0",
21
21
  "wsproto>=1.2.0",
22
+ "itsdangerous>=2.2",
23
+ "joserfc>=1.7",
22
24
  ]
23
25
 
24
26
  [project.optional-dependencies]
@@ -22,6 +22,7 @@ from interloper_db import (
22
22
 
23
23
  from interloper_api.authorization import AuthorizationServer, CrossOriginMiddleware
24
24
  from interloper_api.dependencies import State
25
+ from interloper_api.login import GoogleLogin
25
26
  from interloper_api.routes import (
26
27
  admin,
27
28
  apps,
@@ -209,6 +210,9 @@ def create_app(
209
210
  )
210
211
  # Added last, so it answers a client-facing endpoint's preflight before the policy above can refuse it.
211
212
  app.add_middleware(CrossOriginMiddleware)
213
+ google_login = _google_login(settings)
214
+ if google_login is not None:
215
+ google_login.install(app)
212
216
 
213
217
  api = APIRouter(prefix="/api")
214
218
  for router in _ROUTERS:
@@ -219,7 +223,7 @@ def create_app(
219
223
  app.include_router(api)
220
224
  app.include_router(authorization.well_known_router)
221
225
 
222
- app.state.interloper = _state(store, catalog, settings, agent_available=agent_available)
226
+ app.state.interloper = _state(store, catalog, settings, agent_available=agent_available, google_login=google_login)
223
227
 
224
228
  oauth.log_provider_status()
225
229
 
@@ -257,7 +261,14 @@ def _mount_agent(api: APIRouter, settings: Any | None) -> bool:
257
261
  return True
258
262
 
259
263
 
260
- def _state(store: Store | None, catalog: Catalog | None, settings: Any | None, *, agent_available: bool) -> State:
264
+ def _state(
265
+ store: Store | None,
266
+ catalog: Catalog | None,
267
+ settings: Any | None,
268
+ *,
269
+ agent_available: bool,
270
+ google_login: GoogleLogin | None,
271
+ ) -> State:
261
272
  """Build the state the request dependencies read back.
262
273
 
263
274
  Args:
@@ -267,6 +278,8 @@ def _state(store: Store | None, catalog: Catalog | None, settings: Any | None, *
267
278
  authorization server nor an admin config snapshot.
268
279
  agent_available: Whether the agent routes mounted, recorded as a
269
280
  feature flag and in the admin config snapshot.
281
+ google_login: The Google login, already installed on the app, or
282
+ ``None``.
270
283
 
271
284
  Returns:
272
285
  The state.
@@ -288,9 +301,29 @@ def _state(store: Store | None, catalog: Catalog | None, settings: Any | None, *
288
301
  features=features,
289
302
  admin_config=admin.AdminConfigResponse.from_settings(settings, features=features, catalog=catalog),
290
303
  authorization_server=_authorization_server(store, settings),
304
+ google_login=google_login,
291
305
  )
292
306
 
293
307
 
308
+ def _google_login(settings: Any | None) -> GoogleLogin | None:
309
+ """Build the Google login, when the deployment can run one.
310
+
311
+ Args:
312
+ settings: Full ``AppSettings``, or ``None``.
313
+
314
+ Returns:
315
+ The login, or ``None`` without settings, without a Google client, or
316
+ without an encryption key (which signs the cookie the login keeps
317
+ between Google's two legs).
318
+ """
319
+ if settings is None:
320
+ return None
321
+ google_login = GoogleLogin.from_settings(settings)
322
+ if google_login is None and settings.auth.google_client_id and not settings.secrets.encryption_key:
323
+ logger.warning("Google login unavailable: INTERLOPER_ENCRYPTION_KEY is not configured.")
324
+ return google_login
325
+
326
+
294
327
  def _authorization_server(store: Store | None, settings: Any) -> AuthorizationServer | None:
295
328
  """Build the OAuth authorization server, when the deployment can run one.
296
329
 
@@ -31,6 +31,7 @@ from interloper_api.dependencies.state import (
31
31
  AgentDep,
32
32
  AuthorizationServerDep,
33
33
  CatalogDep,
34
+ GoogleLoginDep,
34
35
  SettingsDep,
35
36
  State,
36
37
  StateDep,
@@ -38,6 +39,7 @@ from interloper_api.dependencies.state import (
38
39
  get_agent,
39
40
  get_authorization_server,
40
41
  get_catalog,
42
+ get_google_login,
41
43
  get_settings,
42
44
  get_state,
43
45
  get_store,
@@ -50,6 +52,7 @@ __all__ = [
50
52
  "CatalogDep",
51
53
  "CurrentUserDep",
52
54
  "EditorDep",
55
+ "GoogleLoginDep",
53
56
  "OrgDep",
54
57
  "OrgScope",
55
58
  "SessionUserDep",
@@ -63,6 +66,7 @@ __all__ = [
63
66
  "get_authorization_server",
64
67
  "get_caller",
65
68
  "get_catalog",
69
+ "get_google_login",
66
70
  "get_org_scope",
67
71
  "get_session_caller",
68
72
  "get_settings",
@@ -16,6 +16,7 @@ from interloper_db import Store
16
16
  from starlette.requests import HTTPConnection
17
17
 
18
18
  from interloper_api.authorization import AuthorizationServer
19
+ from interloper_api.login import GoogleLogin
19
20
 
20
21
 
21
22
  @dataclass(frozen=True)
@@ -33,6 +34,8 @@ class State:
33
34
  super-admin surface shows.
34
35
  authorization_server: The OAuth authorization server, or ``None`` on
35
36
  a deployment that cannot run one.
37
+ google_login: The Google login, or ``None`` on a deployment that
38
+ cannot run one.
36
39
  """
37
40
 
38
41
  store: Store | None = None
@@ -42,6 +45,7 @@ class State:
42
45
  features: dict[str, bool] = field(default_factory=dict)
43
46
  admin_config: Any | None = None
44
47
  authorization_server: AuthorizationServer | None = None
48
+ google_login: GoogleLogin | None = None
45
49
 
46
50
 
47
51
  def get_state(connection: HTTPConnection) -> State:
@@ -145,8 +149,27 @@ def get_authorization_server(state: StateDep) -> AuthorizationServer:
145
149
  return state.authorization_server
146
150
 
147
151
 
152
+ def get_google_login(state: StateDep) -> GoogleLogin:
153
+ """The Google login.
154
+
155
+ Args:
156
+ state: The application's state.
157
+
158
+ Returns:
159
+ The login.
160
+
161
+ Raises:
162
+ HTTPException: 503 when the deployment runs none (no Google client or
163
+ no encryption key).
164
+ """
165
+ if state.google_login is None:
166
+ raise HTTPException(status_code=503, detail="Google login not configured")
167
+ return state.google_login
168
+
169
+
148
170
  StoreDep = Annotated[Store, Depends(get_store)]
149
171
  CatalogDep = Annotated[Catalog, Depends(get_catalog)]
150
172
  SettingsDep = Annotated[Any, Depends(get_settings)]
151
173
  AgentDep = Annotated[Any, Depends(get_agent)]
152
174
  AuthorizationServerDep = Annotated[AuthorizationServer, Depends(get_authorization_server)]
175
+ GoogleLoginDep = Annotated[GoogleLogin, Depends(get_google_login)]
@@ -0,0 +1,235 @@
1
+ """Google login, on Authlib's Starlette client.
2
+
3
+ Authlib runs the OpenID Connect leg: it reads Google's discovery document,
4
+ sends the browser to Google with ``state``, a nonce and a PKCE challenge, and
5
+ at the callback checks ``state``, exchanges the code and verifies the ID
6
+ token's signature, issuer, audience, expiry and nonce against Google's keys.
7
+
8
+ What it keeps between the two legs lives in a signed session cookie scoped to
9
+ the login routes, alive for the ten minutes a login may take. Every API
10
+ replica must be able to read a cookie another one wrote, so it is signed with a
11
+ key derived from the instance's encryption secret; a deployment without one
12
+ has no Google login.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import hmac
19
+ import logging
20
+ from dataclasses import dataclass
21
+ from typing import Any, Literal
22
+
23
+ import httpx2
24
+ from authlib.integrations.base_client import MismatchingStateError, OAuthError
25
+ from authlib.integrations.starlette_client import OAuth
26
+ from fastapi import FastAPI
27
+ from joserfc.errors import JoseError
28
+ from starlette.middleware.sessions import SessionMiddleware
29
+ from starlette.requests import Request
30
+ from starlette.responses import RedirectResponse
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ GOOGLE_METADATA_URL = "https://accounts.google.com/.well-known/openid-configuration"
35
+ SESSION_COOKIE = "login_state"
36
+ SESSION_PATH = "/api/auth/google"
37
+ SESSION_MAX_AGE = 600
38
+ _DESTINATION = "destination"
39
+ _SESSION_KEY_LABEL = b"interloper login state"
40
+
41
+
42
+ class LoginError(Exception):
43
+ """A Google login that did not complete.
44
+
45
+ Attributes:
46
+ reason: What the login page tells the user: ``login_expired`` when
47
+ the callback does not belong to a login this browser started (or
48
+ it took too long), ``login_failed`` for everything else.
49
+ """
50
+
51
+ def __init__(self, reason: Literal["login_expired", "login_failed"]) -> None:
52
+ """Record why the login did not complete.
53
+
54
+ Args:
55
+ reason: The login page's error code.
56
+ """
57
+ super().__init__(reason)
58
+ self.reason = reason
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class GoogleAccount:
63
+ """The Google account a login proved, from its verified ID token.
64
+
65
+ Attributes:
66
+ google_id: The account's stable identifier (the token's ``sub``).
67
+ email: The account's address, verified by Google.
68
+ name: The display name, when the account shares one.
69
+ avatar_url: The profile picture, when the account has one.
70
+ """
71
+
72
+ google_id: str
73
+ email: str
74
+ name: str | None
75
+ avatar_url: str | None
76
+
77
+ @classmethod
78
+ def from_claims(cls, claims: dict[str, Any]) -> GoogleAccount:
79
+ """Read the account from the ID token's claims.
80
+
81
+ Args:
82
+ claims: The verified ID token's claims.
83
+
84
+ Returns:
85
+ The account.
86
+
87
+ Raises:
88
+ LoginError: ``login_failed`` when the token names no account or
89
+ address, or Google has not verified the address: the address
90
+ decides signup and super-admin rights.
91
+ """
92
+ if not claims.get("sub") or not claims.get("email") or claims.get("email_verified") is not True:
93
+ logger.warning("Google login refused: the ID token names no account or no verified address")
94
+ raise LoginError("login_failed")
95
+ return cls(
96
+ google_id=claims["sub"],
97
+ email=claims["email"],
98
+ name=claims.get("name"),
99
+ avatar_url=claims.get("picture"),
100
+ )
101
+
102
+
103
+ class GoogleLogin:
104
+ """The Google client the login routes run, and the session it keeps between them.
105
+
106
+ Attributes:
107
+ redirect_uri: The callback URL registered on the Google client.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ *,
113
+ client_id: str,
114
+ client_secret: str,
115
+ redirect_uri: str,
116
+ encryption_key: str,
117
+ cookie_secure: bool,
118
+ transport: httpx2.AsyncBaseTransport | None = None,
119
+ ) -> None:
120
+ """Register the Google client.
121
+
122
+ Args:
123
+ client_id: The Google OAuth web client's id.
124
+ client_secret: Its secret.
125
+ redirect_uri: The callback URL registered on it.
126
+ encryption_key: The instance's encryption secret, from which the
127
+ session cookie's signing key is derived.
128
+ cookie_secure: Whether the session cookie is sent over HTTPS only.
129
+ transport: The HTTP transport Authlib talks to Google through;
130
+ ``None`` for the network.
131
+ """
132
+ self.redirect_uri = redirect_uri
133
+ self._cookie_secure = cookie_secure
134
+ self._session_secret = hmac.new(encryption_key.encode(), _SESSION_KEY_LABEL, hashlib.sha256).hexdigest()
135
+ client_kwargs: dict[str, Any] = {"scope": "openid email profile", "code_challenge_method": "S256"}
136
+ if transport is not None:
137
+ client_kwargs["transport"] = transport
138
+ self._client: Any = OAuth().register(
139
+ "google",
140
+ client_id=client_id,
141
+ client_secret=client_secret,
142
+ server_metadata_url=GOOGLE_METADATA_URL,
143
+ client_kwargs=client_kwargs,
144
+ )
145
+
146
+ @classmethod
147
+ def from_settings(cls, settings: Any) -> GoogleLogin | None:
148
+ """Build the login from the application settings.
149
+
150
+ Args:
151
+ settings: The full ``AppSettings``.
152
+
153
+ Returns:
154
+ The login, or ``None`` when no Google client or no encryption key
155
+ is configured.
156
+ """
157
+ auth = settings.auth
158
+ if not auth.google_client_id or not auth.google_client_secret or not settings.secrets.encryption_key:
159
+ return None
160
+ return cls(
161
+ client_id=auth.google_client_id,
162
+ client_secret=auth.google_client_secret,
163
+ redirect_uri=auth.google_redirect_uri,
164
+ encryption_key=settings.secrets.encryption_key,
165
+ cookie_secure=auth.cookie_secure,
166
+ )
167
+
168
+ def install(self, app: FastAPI) -> None:
169
+ """Add the session the login keeps between its two routes.
170
+
171
+ Only the login routes receive its cookie, and it lives as long as a
172
+ login may take.
173
+
174
+ Args:
175
+ app: The application.
176
+ """
177
+ app.add_middleware(
178
+ SessionMiddleware,
179
+ secret_key=self._session_secret,
180
+ session_cookie=SESSION_COOKIE,
181
+ max_age=SESSION_MAX_AGE,
182
+ path=SESSION_PATH,
183
+ same_site="lax",
184
+ https_only=self._cookie_secure,
185
+ )
186
+
187
+ async def redirect(self, request: Request, destination: str) -> RedirectResponse:
188
+ """Send the browser to Google's account picker.
189
+
190
+ Args:
191
+ request: The login request.
192
+ destination: Where to land once the login completes, as asked.
193
+
194
+ Returns:
195
+ The redirect to Google.
196
+
197
+ Raises:
198
+ LoginError: ``login_failed`` when Google's discovery document
199
+ cannot be read.
200
+ """
201
+ request.session[_DESTINATION] = destination
202
+ try:
203
+ return await self._client.authorize_redirect(request, self.redirect_uri, prompt="select_account")
204
+ except httpx2.HTTPError as error:
205
+ logger.warning("Google login could not start: %s", error)
206
+ raise LoginError("login_failed") from error
207
+
208
+ async def complete(self, request: Request) -> tuple[GoogleAccount, str]:
209
+ """Turn Google's callback into the account it proves.
210
+
211
+ Args:
212
+ request: The callback request.
213
+
214
+ Returns:
215
+ The account and the destination the login asked for, as asked.
216
+
217
+ Raises:
218
+ LoginError: ``login_expired`` when the callback's ``state`` is not
219
+ one this browser's session holds; ``login_failed`` when the
220
+ user declined, the exchange failed, or the ID token is
221
+ missing or does not verify.
222
+ """
223
+ destination = request.session.pop(_DESTINATION, "/")
224
+ try:
225
+ token = await self._client.authorize_access_token(request)
226
+ except MismatchingStateError as error:
227
+ raise LoginError("login_expired") from error
228
+ except (OAuthError, JoseError, httpx2.HTTPError) as error:
229
+ logger.warning("Google login failed: %s", error)
230
+ raise LoginError("login_failed") from error
231
+ claims = token.get("userinfo")
232
+ if claims is None:
233
+ logger.warning("Google login failed: the token response carries no ID token")
234
+ raise LoginError("login_failed")
235
+ return GoogleAccount.from_claims(claims), destination
@@ -2,34 +2,29 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import secrets
6
- from typing import Annotated, Any
7
- from urllib.parse import urlencode, urlsplit
5
+ from typing import Any
6
+ from urllib.parse import urlsplit
8
7
  from uuid import UUID
9
8
  from zoneinfo import ZoneInfo
10
9
 
11
- import httpx2
12
- from fastapi import APIRouter, Cookie, HTTPException, Response
10
+ from fastapi import APIRouter, HTTPException, Request, Response
13
11
  from fastapi.responses import RedirectResponse
14
12
  from interloper_db import OrganisationQuery, Profile, Store
15
13
  from pydantic import BaseModel, Field
14
+ from starlette.concurrency import run_in_threadpool
16
15
 
17
16
  from interloper_api.dependencies import (
18
17
  CurrentUserDep,
18
+ GoogleLoginDep,
19
19
  SessionUserDep,
20
20
  SettingsDep,
21
21
  StateDep,
22
22
  StoreDep,
23
23
  get_org_scope,
24
24
  )
25
+ from interloper_api.login import GoogleAccount, LoginError
25
26
  from interloper_api.routes.organisations import OrganisationResponse
26
27
 
27
- GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
28
- GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
29
- GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo"
30
- LOGIN_STATE_COOKIE = "login_state"
31
- LOGIN_STATE_MAX_AGE = 600
32
-
33
28
  router = APIRouter(prefix="/auth", tags=["auth"])
34
29
 
35
30
 
@@ -144,164 +139,91 @@ class AuthUserResponse(BaseModel):
144
139
 
145
140
 
146
141
  @router.get("/google")
147
- def google_login(
148
- settings: SettingsDep,
149
- redirect: str | None = None,
150
- ) -> RedirectResponse:
151
- """Redirect user to Google's OAuth consent screen.
142
+ async def google_login(request: Request, login: GoogleLoginDep, redirect: str | None = None) -> RedirectResponse:
143
+ """Send the browser to Google's account picker.
152
144
 
153
145
  Args:
154
- settings: The settings, whose ``auth`` names the Google client.
146
+ request: The login request, whose session keeps the login's state.
147
+ login: The Google login.
155
148
  redirect: App-relative destination to return to once the login
156
- completes; carried through Google in the ``state`` parameter after
157
- a random nonce, defaulting to the app root.
149
+ completes, defaulting to the app root.
158
150
 
159
151
  Returns:
160
- A redirect to Google's consent screen, setting the nonce in a
161
- short-lived cookie the callback checks ``state`` against.
162
-
163
- Raises:
164
- HTTPException: 500 when no Google client id is configured.
152
+ A redirect to Google, or to the login page when Google cannot be
153
+ reached.
165
154
  """
166
- auth_config = settings.auth
167
- client_id = auth_config.google_client_id
168
- redirect_uri = auth_config.google_redirect_uri
169
-
170
- if not client_id:
171
- raise HTTPException(status_code=500, detail="Google OAuth not configured")
172
-
173
- nonce = secrets.token_urlsafe(32)
174
- params = urlencode(
175
- {
176
- "client_id": client_id,
177
- "redirect_uri": redirect_uri,
178
- "response_type": "code",
179
- "scope": "openid email profile",
180
- "access_type": "offline",
181
- "prompt": "consent",
182
- "state": f"{nonce}:{redirect or '/'}",
183
- }
184
- )
185
- response = RedirectResponse(url=f"{GOOGLE_AUTH_URL}?{params}")
186
- response.set_cookie(
187
- key=LOGIN_STATE_COOKIE,
188
- value=nonce,
189
- httponly=True,
190
- samesite="lax",
191
- secure=auth_config.cookie_secure,
192
- max_age=LOGIN_STATE_MAX_AGE,
193
- path="/",
194
- )
195
- return response
155
+ try:
156
+ return await login.redirect(request, redirect or "/")
157
+ except LoginError as error:
158
+ return RedirectResponse(url=f"/login?error={error.reason}", status_code=302)
196
159
 
197
160
 
198
161
  @router.get("/google/callback")
199
- def google_callback(
200
- code: str,
201
- store: StoreDep,
202
- settings: SettingsDep,
203
- state: str | None = None,
204
- login_state: Annotated[str | None, Cookie()] = None,
162
+ async def google_callback(
163
+ request: Request, login: GoogleLoginDep, store: StoreDep, settings: SettingsDep
205
164
  ) -> RedirectResponse:
206
- """Exchange Google's authorization code, upsert the profile, and open a login session.
165
+ """Complete the Google login and open a login session.
207
166
 
208
167
  Args:
209
- code: The single-use authorization code handed back by Google.
210
- state: The nonce and destination recorded at the start of the flow; the
211
- destination is honoured only when it is app-relative, otherwise the
212
- app root is used.
168
+ request: Google's callback, carrying the code and ``state``.
169
+ login: The Google login.
213
170
  store: The database store.
214
- settings: The settings, whose ``auth`` names the Google client.
215
- login_state: The nonce cookie :func:`google_login` set; a callback whose
216
- ``state`` does not carry it was not started by this browser.
171
+ settings: The settings, whose ``auth`` holds the signup and session
172
+ policy.
217
173
 
218
174
  Returns:
219
- A redirect to the post-login destination carrying the session cookie, or
220
- a redirect back to the login page when the nonce does not match or
221
- signup is not allowed.
222
-
223
- Raises:
224
- HTTPException: 500 when Google OAuth is not configured, 401 when the code
225
- exchange or the user-info lookup fails or comes back incomplete.
175
+ A redirect to the login's destination carrying the session cookie, or
176
+ to the login page when the login did not complete or signup is not
177
+ allowed.
226
178
  """
227
- auth_config = settings.auth
228
- client_id = auth_config.google_client_id
229
- client_secret = auth_config.google_client_secret
230
- redirect_uri = auth_config.google_redirect_uri
231
- cookie_secure: bool = auth_config.cookie_secure
232
- session_expiry_days: int = auth_config.session_expiry_days
233
-
234
- if not client_id or not client_secret:
235
- raise HTTPException(status_code=500, detail="Google OAuth not configured")
236
-
237
- nonce, _, redirect = (state or "").partition(":")
238
- if not login_state or not secrets.compare_digest(nonce, login_state):
239
- response = RedirectResponse(url="/login?error=login_expired", status_code=302)
240
- response.delete_cookie(LOGIN_STATE_COOKIE, path="/")
241
- return response
242
-
243
- token_resp = httpx2.post(
244
- GOOGLE_TOKEN_URL,
245
- data={
246
- "code": code,
247
- "client_id": client_id,
248
- "client_secret": client_secret,
249
- "redirect_uri": redirect_uri,
250
- "grant_type": "authorization_code",
251
- },
252
- )
253
- if token_resp.status_code != 200:
254
- raise HTTPException(status_code=401, detail="Failed to exchange authorization code")
179
+ try:
180
+ account, destination = await login.complete(request)
181
+ except LoginError as error:
182
+ return RedirectResponse(url=f"/login?error={error.reason}", status_code=302)
183
+ return await run_in_threadpool(_sign_in, account, destination, store, settings.auth)
255
184
 
256
- tokens = token_resp.json()
257
- access_token = tokens.get("access_token")
258
- if not access_token:
259
- raise HTTPException(status_code=401, detail="No access token in response")
260
185
 
261
- userinfo_resp = httpx2.get(
262
- GOOGLE_USERINFO_URL,
263
- headers={"Authorization": f"Bearer {access_token}"},
264
- )
265
- if userinfo_resp.status_code != 200:
266
- raise HTTPException(status_code=401, detail="Failed to fetch user info")
267
-
268
- userinfo = userinfo_resp.json()
269
- google_id = userinfo.get("id")
270
- email = userinfo.get("email")
271
- name = userinfo.get("name")
272
- avatar_url = userinfo.get("picture")
186
+ def _sign_in(account: GoogleAccount, destination: str, store: Store, auth_config: Any) -> RedirectResponse:
187
+ """Open a login session for the account Google proved.
273
188
 
274
- if not google_id or not email:
275
- raise HTTPException(status_code=401, detail="Incomplete user info from Google")
189
+ Args:
190
+ account: The verified Google account.
191
+ destination: The destination the login asked for; honoured only when
192
+ it is app-relative, otherwise the app root is used.
193
+ store: The database store.
194
+ auth_config: The resolved auth configuration.
276
195
 
196
+ Returns:
197
+ A redirect to the destination carrying the session cookie, or to the
198
+ login page when signup is not allowed.
199
+ """
277
200
  # Gate signup only: existing profiles always sign in, a first login must
278
201
  # pass the allowlist before a profile is created.
279
- if not store.profiles.get_by_google_id(google_id) and not _signup_allowed(email, auth_config, store):
202
+ if not store.profiles.get_by_google_id(account.google_id) and not _signup_allowed(
203
+ account.email, auth_config, store
204
+ ):
280
205
  return RedirectResponse(url="/login?error=signup_not_allowed", status_code=302)
281
206
 
282
207
  profile = store.profiles.upsert(
283
- google_id=google_id,
284
- email=email,
285
- name=name,
286
- avatar_url=avatar_url,
208
+ google_id=account.google_id,
209
+ email=account.email,
210
+ name=account.name,
211
+ avatar_url=account.avatar_url,
287
212
  )
288
213
 
289
214
  # Bootstrap super-admins from settings. Promote-only: removing an email from
290
215
  # the list never demotes an existing super-admin.
291
- if not profile.is_super_admin and email.lower() in auth_config.super_admin_emails:
216
+ if not profile.is_super_admin and account.email.lower() in auth_config.super_admin_emails:
292
217
  profile = store.profiles.set_super_admin(profile.id, value=True)
293
218
 
294
- token = store.tokens.create_session(profile.id)
295
-
296
- response = RedirectResponse(url=_app_relative(redirect), status_code=302)
297
- response.delete_cookie(LOGIN_STATE_COOKIE, path="/")
219
+ response = RedirectResponse(url=_app_relative(destination), status_code=302)
298
220
  response.set_cookie(
299
221
  key="session_token",
300
- value=token,
222
+ value=store.tokens.create_session(profile.id),
301
223
  httponly=True,
302
224
  samesite="lax",
303
- secure=cookie_secure,
304
- max_age=session_expiry_days * 86400,
225
+ secure=auth_config.cookie_secure,
226
+ max_age=auth_config.session_expiry_days * 86400,
305
227
  path="/",
306
228
  )
307
229
  return response