Coverage for app/redirects.py: 95%
22 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-31 11:18 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-31 11:18 +0000
1"""Where svc-auth may send a browser after login.
3``/login?return_to=`` is taken from the query string and followed after the
4Auth0 callback, so an unchecked value turns the platform's own auth domain
5into an open redirect: a link that really does sign the user in, then lands
6them on a look-alike page. Only the platform's own hosts are allowed.
7"""
9from __future__ import annotations
11from urllib.parse import urlsplit
13from app.config import settings
14from app.cors import ALLOWED_ORIGINS
17def _host(url: str) -> str:
18 return (urlsplit(url).hostname or "").lower()
21def _allowed_host(host: str) -> bool:
22 if not host:
23 return False
24 if host in {_host(origin) for origin in ALLOWED_ORIGINS}:
25 return True
26 # Every vhost that shares the session cookie is the platform's own —
27 # app., auth., monitoring. — which is also exactly what nginx sends here
28 # when it bounces an unauthenticated request.
29 domain = (settings.COOKIE_DOMAIN or "").lstrip(".").lower()
30 return bool(domain) and (host == domain or host.endswith("." + domain))
33def safe_return_to(url: str | None) -> str:
34 """``url`` if it points at one of the platform's hosts, else the app.
36 Absolute http(s) URLs only: a scheme-relative ``//evil.example`` or a
37 backslash variant some browsers normalise to one are refused along with
38 everything else that does not parse to an allowed host.
39 """
40 if not url or "\\" in url:
41 return settings.FRONTEND_URL
42 parts = urlsplit(url)
43 if parts.scheme not in ("http", "https") or parts.username or parts.password:
44 return settings.FRONTEND_URL
45 if not _allowed_host((parts.hostname or "").lower()):
46 return settings.FRONTEND_URL
47 return url