A raised redirect stays a redirect, and /language honours ?next=

Both found by porting homepage, which is the first service to raise a
redirect from a dependency and the first with a language switcher that
returns you to the page you were on.

A dependency saying "you are not logged in, go here" raises rather than
returns, because it has no other way to stop the request. The error handler
treated every HTTPException as something to render, so a 307 came back
carrying the themed error page and no Location at all - a redirect that
does not redirect, with a 307 status to make it look like it had. Now a 3xx
with a Location is passed through as one.

chrome's /language/{code} already existed and took the destination from
Referer. homepage's own version additionally honoured ?next=, and chrome's
route shadowed it - so the feature silently disappeared on adoption rather
than conflicting visibly. The parameter moves into chrome instead, with the
open-redirect guard homepage had: anything carrying a scheme or a host is
discarded rather than patched up, including the protocol-relative
`//evil.example/x`, which urlparse reports as a netloc with no scheme and
which a naive `startswith("/")` check waves through.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Michał Kopeć 2026-10-04 19:35:34 +02:00
parent ef35636694
commit 67f8a80ef4
5 changed files with 71 additions and 4 deletions

View file

@ -78,7 +78,7 @@ Pin a tag, not a branch:
```toml
dependencies = [
"chrome @ git+https://git.wierzbowa.cloud/michal/chrome@v0.3.0",
"chrome @ git+https://git.wierzbowa.cloud/michal/chrome@v0.4.0",
]
```

View file

@ -7,7 +7,7 @@ need an `if service == "marketplace"`, it belongs in the service.
from pathlib import Path
__version__ = "0.3.0"
__version__ = "0.4.0"
PACKAGE_DIR = Path(__file__).parent
STATIC_DIR = PACKAGE_DIR / "static"

View file

@ -17,9 +17,27 @@ from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from jinja2 import ChoiceLoader, FileSystemLoader
from urllib.parse import urlparse
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import STATIC_DIR, TEMPLATES_DIR, WEBAWESOME_VERSION, assets, i18n
def _safe_local(target: str | None) -> str | None:
"""``target`` if it is a local path, else None.
`next` is attacker-controllable, so anything carrying a scheme or a host
- including the protocol-relative `//evil.example/x`, which urlparse
reports as a netloc with no scheme - is discarded rather than patched up.
"""
if not target:
return None
parsed = urlparse(target)
if parsed.scheme or parsed.netloc or not parsed.path.startswith("/"):
return None
return target
from .health import health_router
#: Default location for chrome's own static tree. Distinct from the service's
@ -170,7 +188,14 @@ class Chrome:
# Server-side so the choice survives a new browser and so the
# page renders in the right language on first paint rather than
# being swapped after load.
target = request.headers.get("referer") or "/"
#
# `next` wins over Referer when it is a local path. It is
# attacker-controllable, so anything with a scheme or a host -
# including the protocol-relative `//evil.example` - is discarded
# rather than sanitised.
target = _safe_local(request.query_params.get("next")) or (
request.headers.get("referer") or "/"
)
response = RedirectResponse(target, status_code=303)
if code in i18n.SUPPORTED:
response.set_cookie(
@ -181,6 +206,14 @@ class Chrome:
def _install_error_pages(self) -> None:
@self.app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, exc: StarletteHTTPException) -> Response:
# A 3xx raised from a dependency - "you are not logged in, go
# here" - is a destination, not an error. Rendering it as the
# error page drops the Location and leaves a 307 whose body is
# a stack of tiles.
headers = getattr(exc, "headers", None) or {}
if 300 <= exc.status_code < 400 and headers.get("Location"):
return RedirectResponse(headers["Location"], status_code=exc.status_code)
if request.url.path.startswith(("/api/", "/healthz")):
from fastapi.responses import JSONResponse

View file

@ -1,6 +1,6 @@
[project]
name = "chrome"
version = "0.3.0"
version = "0.4.0"
description = "Shared page shell, design tokens and service helpers for the internal services."
requires-python = ">=3.13"
dependencies = [

View file

@ -310,3 +310,37 @@ def test_a_service_can_inject_per_request_context(tmp_path):
return ui.render(request, "index.html", who="override")
assert "<p>override</p>" in TestClient(app).get("/explicit").text
def test_a_redirect_raised_from_a_dependency_stays_a_redirect(tmp_path):
"""A dependency saying "you are not logged in, go here" is a destination,
not an error. JSON-ifying it drops the Location and leaves a blank 307."""
from fastapi import Depends, HTTPException
app = FastAPI()
Chrome(app, service="t", version="1", title="T")
def needs_login():
raise HTTPException(307, "", headers={"Location": "/login"})
@app.get("/private")
def private(_user=Depends(needs_login)):
return {"never": "reached"}
r = TestClient(app).get("/private", follow_redirects=False)
assert r.status_code == 307
assert r.headers["location"] == "/login"
def test_the_language_route_honours_a_local_next_and_refuses_anything_else(tmp_path):
app = FastAPI()
Chrome(app, service="t", version="1", title="T")
client = TestClient(app)
r = client.get("/language/en?next=/access", follow_redirects=False)
assert r.headers["location"] == "/access"
for hostile in ("https://evil.example.invalid/x", "//evil.example.invalid/x",
"javascript:alert(1)"):
r = client.get(f"/language/en?next={hostile}", follow_redirects=False)
assert r.headers["location"] == "/", f"{hostile} was not rejected"