diff --git a/generator/src/api.py b/generator/src/api.py index 5c6a7f8..06fa7a3 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -561,9 +561,16 @@ def auth_github_login(): def _derived_redirect_uri() -> str: - # Works behind cloudflared: the X-Forwarded-Proto/Host headers are set. + # The tunnel does not reliably forward the original scheme, so + # X-Forwarded-Proto can be absent and request.scheme is then http. GitHub + # compares redirect_uri against the callback registered on the OAuth app + # character for character, so an http:// value is rejected with "The + # redirect_uri is not associated with this application" and sign-in becomes + # impossible. Anything that is not a local dev host is served over https. proto = request.headers.get("X-Forwarded-Proto") or request.scheme host = request.headers.get("X-Forwarded-Host") or request.host + if host.split(":")[0] not in ("localhost", "127.0.0.1"): + proto = "https" return f"{proto}://{host}/api/auth/github/callback" diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index 1a18597..7479d8e 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -1002,3 +1002,26 @@ def test_get_user_data_records_request_event(client, monkeypatch): and r["endpoint"] == "/api//data" for r in rows ) + + +def test_oauth_redirect_uri_is_https_in_production(client, monkeypatch): + """GitHub matches redirect_uri against the registered callback character for + character. The tunnel can leave X-Forwarded-Proto unset, which made the app + send http:// and GitHub reject every sign-in with "The redirect_uri is not + associated with this application". Only a local dev host may be plaintext.""" + monkeypatch.setattr(cfg, "GITHUB_OAUTH_REDIRECT_URI", "") + r = client.get("/api/auth/github/login?next=/", + headers={"Host": "gh-stats.com"}) + assert r.status_code == 302 + loc = r.headers["Location"] + assert "redirect_uri=https%3A%2F%2Fgh-stats.com%2Fapi%2Fauth%2Fgithub%2Fcallback" in loc, loc + assert "http%3A%2F%2Fgh-stats.com" not in loc + + +def test_oauth_redirect_uri_stays_http_on_localhost(client, monkeypatch): + """Local development must keep working over plain http.""" + monkeypatch.setattr(cfg, "GITHUB_OAUTH_REDIRECT_URI", "") + r = client.get("/api/auth/github/login?next=/", + headers={"Host": "localhost:5002"}) + assert r.status_code == 302 + assert "redirect_uri=http%3A%2F%2Flocalhost%3A5002" in r.headers["Location"]