From 98c40ff99301ff6870451d1ae75478264fdedf1d Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:54:44 -0400 Subject: [PATCH] feat(api): add /api/auth/github/login with CSRF state + local-only next Co-Authored-By: Claude Opus 4.7 --- generator/src/api.py | 21 +++++++++++++++++++++ generator/tests/test_auth.py | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/generator/src/api.py b/generator/src/api.py index e1389e5..7cb2428 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -352,6 +352,27 @@ def auth_logout(): return ("", 204) +@app.route("/api/auth/github/login", methods=["GET"]) +def auth_github_login(): + import secrets as _secrets + nxt = request.args.get("next", "/") + # Only accept local relative paths to prevent open-redirect. + if not isinstance(nxt, str) or not nxt.startswith("/"): + nxt = "/" + state = _secrets.token_urlsafe(32) + session["oauth_state"] = state + session["oauth_next"] = nxt + redirect_uri = config.GITHUB_OAUTH_REDIRECT_URI or _derived_redirect_uri() + return auth.github_client().authorize_redirect(redirect_uri, state=state) + + +def _derived_redirect_uri() -> str: + # Works behind cloudflared: the X-Forwarded-Proto/Host headers are set. + proto = request.headers.get("X-Forwarded-Proto") or request.scheme + host = request.headers.get("X-Forwarded-Host") or request.host + return f"{proto}://{host}/api/auth/github/callback" + + @app.route("/api/health", methods=["GET"]) def health(): return jsonify({"status": "ok", "service": "generator"}) diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py index ac48b67..d9474df 100644 --- a/generator/tests/test_auth.py +++ b/generator/tests/test_auth.py @@ -118,3 +118,20 @@ def test_logout_rejects_bad_origin(api_client): s["gh_login"] = "alice" r = api_client.post("/api/auth/logout", headers={"Origin": "https://evil.example"}) assert r.status_code == 403 + + +def test_login_stashes_state_and_redirects(api_client): + """Don't depend on authlib's exact redirect URL — just confirm the route + stashes a random state, records the next path, and returns a 3xx.""" + r = api_client.get("/api/auth/github/login?next=/workshop") + assert r.status_code in (302, 303) + with api_client.session_transaction() as s: + assert s.get("oauth_state") + assert s.get("oauth_next") == "/workshop" + + +def test_login_rejects_external_next(api_client): + r = api_client.get("/api/auth/github/login?next=https://evil.example/foo") + assert r.status_code in (302, 303) + with api_client.session_transaction() as s: + assert s.get("oauth_next") == "/"