diff --git a/server/app/auth/routes.py b/server/app/auth/routes.py index 0f50978..ec52d7e 100644 --- a/server/app/auth/routes.py +++ b/server/app/auth/routes.py @@ -1,12 +1,15 @@ from __future__ import annotations +import hmac from datetime import UTC, datetime from typing import Any +from urllib.parse import urlsplit from fastapi import APIRouter, Depends, HTTPException, Query, Request from fastapi.responses import JSONResponse, RedirectResponse from gnexus_gauth.exceptions import WebhookPayloadException, WebhookVerificationException from pydantic import BaseModel +from starlette.concurrency import run_in_threadpool from ..config import Settings, get_settings from ..storage.db import Database @@ -41,7 +44,12 @@ def _safe_return_to(value: str | None) -> str | None: - if not value or not value.startswith("/") or value.startswith("//"): + if not value or "\\" in value or any(ord(character) < 32 for character in value): + return None + parts = urlsplit(value) + if parts.scheme or parts.netloc: + return None + if not value.startswith("/") or value.startswith("//"): return None return value @@ -84,8 +92,18 @@ ) -> RedirectResponse: if service is None: raise HTTPException(status_code=400, detail="Authentication is not configured") - url = service.build_login_url(return_to=_safe_return_to(return_to)) - return RedirectResponse(url, status_code=303) + url, state = service.build_login_url(return_to=_safe_return_to(return_to)) + response = RedirectResponse(url, status_code=303) + response.set_cookie( + key=settings.auth_state_cookie, + value=state, + max_age=settings.auth_state_ttl_seconds, + httponly=True, + secure=settings.auth_cookie_secure, + samesite="lax", + path="/", + ) + return response @router.get("/auth/callback") @@ -100,12 +118,18 @@ if service is None: raise HTTPException(status_code=400, detail="Authentication is not configured") if error: - return RedirectResponse("/?auth_error=access_denied", status_code=303) + response = RedirectResponse("/?auth_error=access_denied", status_code=303) + response.delete_cookie(settings.auth_state_cookie, path="/") + return response if not code or not state: raise HTTPException(status_code=400, detail="Missing code or state") + state_cookie = request.cookies.get(settings.auth_state_cookie) + if not state_cookie or not hmac.compare_digest(state, state_cookie): + raise HTTPException(status_code=400, detail="Invalid OAuth state") + try: - _, token, expires_at = service.exchange_code( + _, token, expires_at, return_to = service.exchange_code( code, state, user_agent=request.headers.get("user-agent"), @@ -116,7 +140,8 @@ except Exception as exc: raise HTTPException(status_code=400, detail="Authentication failed") from exc - response = RedirectResponse("/", status_code=303) + response = RedirectResponse(_safe_return_to(return_to) or "/", status_code=303) + response.delete_cookie(settings.auth_state_cookie, path="/") max_age = max(0, int((expires_at - datetime.now(UTC)).total_seconds())) response.set_cookie( key=settings.auth_session_cookie, @@ -164,5 +189,7 @@ except WebhookPayloadException as exc: raise HTTPException(status_code=400, detail="Invalid webhook payload") from exc - processed = handle_webhook_event(Database.from_settings(settings), event) + processed = await run_in_threadpool( + handle_webhook_event, Database.from_settings(settings), event + ) return {"status": "ok", "event_id": event.event_id, "duplicate": not processed} diff --git a/server/app/auth/service.py b/server/app/auth/service.py index 97181c6..504a432 100644 --- a/server/app/auth/service.py +++ b/server/app/auth/service.py @@ -41,7 +41,7 @@ self._webhook_verifier = HmacWebhookVerifier(self.config) self._webhook_parser = JsonWebhookParser() - def build_login_url(self, return_to: str | None = None) -> str: + def build_login_url(self, return_to: str | None = None) -> tuple[str, str]: state = PkceGenerator.generate_state() verifier = PkceGenerator.generate_verifier() challenge = PkceGenerator.generate_challenge(verifier) @@ -60,12 +60,13 @@ ) ) - return self._urls.build( + url = self._urls.build( state=state, pkce_challenge=challenge, return_to=return_to, scopes=list(self.settings.auth_scopes), ) + return url, state def exchange_code( self, @@ -73,7 +74,7 @@ state: str, user_agent: str | None = None, ip_address: str | None = None, - ) -> tuple[CurrentUser, str, Any]: + ) -> tuple[CurrentUser, str, Any, str | None]: now = utcnow() state_hash = token_hash(state) with self.database.session() as session: @@ -81,6 +82,7 @@ if record is None or record.expires_at <= now: raise AuthError("Unknown or expired authorization state") verifier = record.code_verifier + return_to = record.return_to if not verifier: raise AuthError("Missing PKCE verifier") @@ -103,7 +105,7 @@ user_agent=user_agent, ip_address=ip_address, ) - return user, token, expires_at + return user, token, expires_at, return_to def verify_and_parse_webhook( self, raw_body: str, headers: dict[str, str] diff --git a/server/tests/test_auth.py b/server/tests/test_auth.py index 5bbc7f0..1aafb4e 100644 --- a/server/tests/test_auth.py +++ b/server/tests/test_auth.py @@ -104,7 +104,8 @@ assert response.status_code == 303 location = response.headers["location"] assert location.startswith("https://auth.example.test/oauth/authorize?") - assert _authorization_state(location) + state = _authorization_state(location) + assert client.cookies.get("gnb_oauth_state") == state assert "scope=" in location @@ -150,13 +151,14 @@ monkeypatch.setattr(HttpRuntimeUserProvider, "fetch_user", fake_fetch) client = TestClient(app) - login = client.get("/auth/login", follow_redirects=False) + login = client.get("/auth/login?return_to=/docs", follow_redirects=False) state = _authorization_state(login.headers["location"]) callback = client.get( f"/auth/callback?code=test-code&state={state}", follow_redirects=False ) assert callback.status_code == 303 + assert callback.headers["location"] == "/docs" assert "gnb_session=" in callback.headers["set-cookie"] me = client.get("/me").json() @@ -182,6 +184,34 @@ assert user.locale == "en" +def test_callback_requires_state_cookie(auth_settings: Settings) -> None: + client = TestClient(app) + login = client.get("/auth/login", follow_redirects=False) + state = _authorization_state(login.headers["location"]) + + other = TestClient(app) + response = other.get( + f"/auth/callback?code=test-code&state={state}", + follow_redirects=False, + ) + + assert response.status_code == 400 + + +def test_callback_rejects_mismatched_state_cookie(auth_settings: Settings) -> None: + client = TestClient(app) + login = client.get("/auth/login", follow_redirects=False) + state = _authorization_state(login.headers["location"]) + client.cookies.set("gnb_oauth_state", "wrong-state") + + response = client.get( + f"/auth/callback?code=test-code&state={state}", + follow_redirects=False, + ) + + assert response.status_code == 400 + + def test_protected_route_requires_session(auth_settings: Settings) -> None: client = TestClient(app)