From 15edc2c7b7b6be7e00d704b59c931ed795aaf880 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:08:42 +0000 Subject: [PATCH 1/2] feat(users): use an allowlisted request origin for account email links When neither users.base_url nor host.public_base_url is set, password-reset, verification and invitation emails link to the current request's origin, but only if its host matches host.forwarded_host_allowlist (the matcher ForwardedHostMiddleware uses, applied after proxy handling). Plain http is accepted only from a trusted proxy or for a loopback host. Otherwise the mail is still skipped with an ERROR and the public response stays generic. Sends with no request keep requiring a configured origin. The shared host parser now uses fullmatch, rejects ports above 65535 and accepts bracketed IPv6, which ForwardedHostMiddleware also picks up; that is covered by new middleware tests. Split out of #1137 (the CIDR fix and the Doctor hook are separate PRs). Fixes #1126 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FXHA3ZEgbUuM5mzoeC4DTw --- CHANGELOG.md | 3 + docs/framework/middleware.md | 2 +- docs/framework/settings.md | 30 +++-- docs/modules/users.md | 18 ++- docs/reference/env-vars.md | 2 +- .../config/host_settings.py | 6 +- .../pipeline/_forwarded_host.py | 30 ++++- .../pipeline/public_urls.py | 45 +++++++- .../tests/pipeline/test_forwarded_host.py | 12 ++ .../tests/pipeline/test_public_urls.py | 79 +++++++++++++ .../api/test_users_missing_mail_origin.py | 109 +++++++++++++++++- .../test_users_invite_request_origin.py | 35 ++++++ .../mailer/templated/test_users_mailer.py | 54 +++++++++ modules/users/users/accounts/manager.py | 14 +-- modules/users/users/admin/api.py | 4 +- modules/users/users/admin/views.py | 4 +- modules/users/users/auth_local/views.py | 5 +- modules/users/users/invites/bulk.py | 12 +- modules/users/users/invites/resend.py | 7 +- modules/users/users/mailer/__init__.py | 65 ++++++++++- modules/users/users/mailer/templated.py | 62 ++++++++-- 21 files changed, 535 insertions(+), 63 deletions(-) create mode 100644 framework/hosting/tests/pipeline/test_public_urls.py create mode 100644 modules/users/tests/invites/test_users_invite_request_origin.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 025a2c5ca..c1e9395ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,9 @@ All notable changes to this project are documented in this file. The format is b ### Changed +- **Behaviour change:** account emails fall back to the resolved request origin when the host is allowlisted and both configured origins are blank. Non-loopback HTTP requires a trusted proxy peer (#1126). +- `ForwardedHostMiddleware` and the allowlist now accept bracketed IPv6 hosts (`[2001:db8::1]:8443`) and reject ports above 65535 and values with trailing characters (#1126). + - **Behaviour change:** mail exposes DB-backed `smtp_tls_mode` (`auto`, `starttls`, `implicit`); `auto` retains implicit TLS on 465 and STARTTLS elsewhere. Deployments that previously used implicit TLS on custom ports must select `implicit`; `smtp_tls=false` disables TLS in every mode (#1099). - **Behaviour change:** worker images use a separate non-root runtime without build tools or uv; web and worker images copy only their runtime artifacts (#1088). diff --git a/docs/framework/middleware.md b/docs/framework/middleware.md index 9b61c0a2a..6e2e1d540 100644 --- a/docs/framework/middleware.md +++ b/docs/framework/middleware.md @@ -88,7 +88,7 @@ Set it to a comma-separated list of proxy IPs/CIDRs, or `*` to trust any peer ### `ForwardedHostMiddleware` *(opt-in)* -Installed only when **both** `SM_TRUSTED_PROXY` and the `forwarded_host_allowlist` host setting (restart-required) are set. uvicorn's `ProxyHeadersMiddleware` fixes scheme and client but not the host, so behind a proxy that rewrites `Host`, `request.url_for(...)` and the tenants subdomain resolver see the upstream name. This middleware replaces the `host` header and `scope["server"]` with the rightmost `X-Forwarded-Host` value (the one the trusted proxy added) when the TCP peer is trusted (same `*` / IP / CIDR rule as uvicorn) **and** the value matches the allowlist: an exact host or `*.example.com` (any subdomain, never the apex), each with an optional `:port` (an entry without a port accepts any port). Anything else is ignored and logged at debug, so a forged header cannot poison absolute URLs. It is added after `ProxyHeaders` so it runs first and still sees the proxy's own address. `Forwarded:` (RFC 7239) is not supported. Email links are unaffected: they are built from configured base URLs (for example `tenants.public_base_url`), never from the request. +Installed only when **both** `SM_TRUSTED_PROXY` and the `forwarded_host_allowlist` host setting (restart-required) are set. uvicorn's `ProxyHeadersMiddleware` fixes scheme and client but not the host, so behind a proxy that rewrites `Host`, `request.url_for(...)` and the tenants subdomain resolver see the upstream name. This middleware replaces the `host` header and `scope["server"]` with the rightmost `X-Forwarded-Host` value (the one the trusted proxy added) when the TCP peer is trusted (same `*` / IP / CIDR rule as uvicorn) **and** the value matches the allowlist: an exact host or `*.example.com` (any subdomain, never the apex), each with an optional `:port` (an entry without a port accepts any port). Write an IPv6 literal in brackets (`[2001:db8::1]`). Anything else is ignored and logged at debug, so a forged header cannot poison absolute URLs. It is added after `ProxyHeaders` so it runs first and still sees the proxy's own address. `Forwarded:` (RFC 7239) is not supported. The same allowlist governs the [account email origin fallback](/framework/settings#shared-host-policy), including for direct requests. Tenant invitation emails use their configured base URL. ### `CorrelationIdMiddleware` diff --git a/docs/framework/settings.md b/docs/framework/settings.md index ebf45884e..a2f44f613 100644 --- a/docs/framework/settings.md +++ b/docs/framework/settings.md @@ -82,16 +82,28 @@ save and by the existing cross-process settings invalidation/reload. ### Shared host policy Set `host.public_base_url` once for canonical URLs, account emails, copied -account links and tenant invitations. Blank `users.base_url` (the new default) -and blank `tenants.public_base_url` inherit it; explicit module origins still -win. The shared `simple_module_hosting.pipeline.public_urls.public_origin` helper never -uses the inbound Host header. With both values blank, copied and invitation links stay relative for -fresh development installs. Account emails (password reset, verification, -invitations) are skipped with an ERROR log naming `host.public_base_url` until an -absolute origin is configured; the public responses stay the same, and startup -still succeeds. +account links and tenant invitations. Blank `users.base_url` and +`tenants.public_base_url` inherit it. Explicit module origins win. +The shared `simple_module_hosting.pipeline.public_urls.public_origin` helper +uses configured origins, with relative URLs as the default for copied +account and tenant invitation links. + +When both account email origins are blank, `trusted_request_origin(request)` +can supply an origin for password reset, verification and invitation emails. +It uses the scheme and authority resolved by the hosting middleware. +`host.forwarded_host_allowlist` must match the authority using the same exact +host, wildcard subdomain and optional port rules as [ForwardedHost](/framework/middleware#forwardedhostmiddleware-opt-in). +The middleware accepts `X-Forwarded-Host` only from a trusted proxy. HTTPS is +eligible for any allowlisted host. HTTP requires a trusted proxy peer or a +loopback host (`localhost`, its subdomains, `127.0.0.0/8` or `[::1]`), which must also be +allowlisted. Use brackets when listing an IPv6 address and add an optional +port after the closing bracket. + +If there is no eligible request origin, including sends without a request, +the mailer skips delivery and logs an ERROR naming `host.public_base_url`. +Public reset and verification responses stay generic. An explicitly stored users origin, including the old localhost default, keeps -winning: clear it to inherit the host. +winning. Clear it to inherit the host. `host.session_cookie_secure` controls both session and users auth cookies. Unset means Secure outside development/testing and HTTP-compatible within them; diff --git a/docs/modules/users.md b/docs/modules/users.md index 48b35be33..ec74277bc 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -206,7 +206,7 @@ Edit the remaining settings under Users at `/admin/settings/`: | `cookie_name` | `"sm_auth"` | | `cookie_max_age_seconds` | `1_209_600` (14 days) | | `cookie_samesite` | `"lax"` | -| `base_url` | `""` — inherit `host.public_base_url`; an explicit users origin wins. Both blank: copied links remain relative and account emails are skipped with an ERROR log naming `host.public_base_url` / `SM_PUBLIC_BASE_URL`. Public reset and verification responses remain unchanged. | +| `base_url` | `""` — inherit `host.public_base_url`. When both are blank, account emails can use an allowlisted request origin. | | `mail_template_dirs` | `[]` — ordered absolute template directories, restart required; see [Overriding auth email templates](#overriding-auth-email-templates) | | `login_rate_limit_failures` | `5` — failures from one IP for one username before that source is throttled for the window | | `login_rate_limit_window_seconds` | `300` — the window for both lockout tiers | @@ -229,6 +229,22 @@ Edit the remaining settings under Users at `/admin/settings/`: | `oauth_sync_profile` | `False` — update `full_name` from the IdP's display name on every sign-in, not only when the account is created | | `oauth_oidc_client_id` / `oauth_oidc_client_secret` / `oauth_oidc_discovery_url` / `oauth_oidc_display_name` | `""` / `""` / `""` / `"OIDC"` — generic OIDC | +Password reset, verification and invitation emails use `users.base_url` first, +then `host.public_base_url` (including `SM_PUBLIC_BASE_URL`), then the resolved +request origin if it matches `host.forwarded_host_allowlist`. HTTPS is +eligible. HTTP requires a trusted proxy peer or an allowlisted loopback host +(`localhost`, its subdomains, `127.0.0.0/8` or `[::1]`). Sends without a request require a +configured origin. The trusted proxy peer is recognised by the framework's +`host.trusted_proxy` handling; if Uvicorn itself runs with `--proxy-headers` +it replaces the peer address first, so plain-HTTP links behind a proxy are +skipped (HTTPS is unaffected). A custom `TemplatedMailer` subclass whose send +methods keep the original signature never receives a request origin. If no +origin qualifies, delivery is skipped with an ERROR +log. Public reset and verification responses remain generic. Copied links stay +relative when both configured origins are blank. See the +[shared host policy](/framework/settings#shared-host-policy) for allowlist +matching and proxy handling. + ## Permissions | Code | Purpose | diff --git a/docs/reference/env-vars.md b/docs/reference/env-vars.md index d95b63630..1100d31d3 100644 --- a/docs/reference/env-vars.md +++ b/docs/reference/env-vars.md @@ -65,7 +65,7 @@ settings can change live unless pinned by the environment. See [Settings](/frame | `SM_I18N_COOKIE_NAME` | `locale` | Locale preference cookie name. Restart required. | | `SM_MAINTENANCE_MODE` | `false` | Serve a 503 to everyone except admins. Runtime. | | `SM_MAINTENANCE_MESSAGE` | `""` | Optional maintenance notice. Runtime. | -| `SM_PUBLIC_BASE_URL` | `""` | Shared public origin for canonical and `og:url` links, account emails and invitation links. `users.base_url` and `tenants.public_base_url` inherit it when blank. Never derived from the request `Host`. Runtime. | +| `SM_PUBLIC_BASE_URL` | `""` | Shared public origin for canonical and `og:url` links, account emails and invitation links. `users.base_url` and `tenants.public_base_url` inherit it when blank. Account emails can fall back to an [allowlisted request origin](/framework/settings#shared-host-policy) when both configured origins are blank. Runtime. | | `SM_LOGIN_REDIRECT_URL` | `/dashboard/` | Where every auth provider sends a user after sign-in; falls back to another view when the Dashboard module is absent. Runtime. | | `SM_NATIVE_LINK_PREFIXES` | `[]` | JSON array of path prefixes whose links use full browser navigation. Runtime. | | `SM_LOG_LEVEL` | `INFO` | Application logging threshold. Restart required. | diff --git a/framework/hosting/simple_module_hosting/config/host_settings.py b/framework/hosting/simple_module_hosting/config/host_settings.py index d47a95a86..2362afd0b 100644 --- a/framework/hosting/simple_module_hosting/config/host_settings.py +++ b/framework/hosting/simple_module_hosting/config/host_settings.py @@ -171,9 +171,9 @@ def _check_login_redirect(cls, value: str) -> str: leaves authenticated requests unlimited.""" forwarded_host_allowlist: list[str] = Field(default=[], json_schema_extra=_RESTART_GUARD) - """Hosts a trusted proxy may substitute through ``X-Forwarded-Host``: an exact - host or ``*.example.com``, each with an optional port. Empty (default) ignores - the header. Only honoured together with ``trusted_proxy``.""" + """Exact hosts or ``*.example.com`` entries with optional ports. Used by the + account email request-origin fallback and, when ``trusted_proxy`` is set, + by the ``X-Forwarded-Host`` middleware.""" cors_allow_origins: list[str] = Field(default=[], json_schema_extra={"group": "CORS"}) """Origins allowed to call ``/api/`` cross-origin. Empty (default) installs no diff --git a/framework/hosting/simple_module_hosting/pipeline/_forwarded_host.py b/framework/hosting/simple_module_hosting/pipeline/_forwarded_host.py index 68791d3c3..8a5af68ca 100644 --- a/framework/hosting/simple_module_hosting/pipeline/_forwarded_host.py +++ b/framework/hosting/simple_module_hosting/pipeline/_forwarded_host.py @@ -30,12 +30,25 @@ _FORWARDED_PROTO_HEADER = b"x-forwarded-proto" _DEFAULT_PORTS = {"https": 443, "wss": 443} _FALLBACK_PORT = 80 -_HOST_PATTERN = re.compile(r"^(?P[a-z0-9]([a-z0-9._-]*[a-z0-9])?)(:(?P\d{1,5}))?$") +TRUSTED_PROXY_SCOPE_KEY = "sm.trusted_proxy_peer" +_HOST_PATTERN = re.compile( + r"(?P[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?|\[[a-f0-9:.]+\])(?::(?P[0-9]{1,5}))?" +) def _split_host(value: str) -> tuple[str, str | None] | None: - match = _HOST_PATTERN.match(value.strip().lower()) - return (match["host"], match["port"]) if match else None + match = _HOST_PATTERN.fullmatch(value.strip().lower()) + if match is None: + return None + host, port = match["host"], match["port"] + if host.startswith("["): + try: + ipaddress.IPv6Address(host[1:-1]) + except ValueError: + return None + if port is not None and int(port) > 65535: + return None + return host, port def _forwarded_proto(scope: Scope) -> str | None: @@ -97,6 +110,10 @@ def port_ok(allowed: str | None) -> bool: return True return any(host.endswith("." + name) and port_ok(p) for name, p in self._suffixes) + def match(self, authority: str) -> tuple[str, str | None] | None: + parsed = _split_host(authority) + return parsed if parsed is not None and self.allows(*parsed) else None + class ForwardedHostMiddleware: def __init__(self, app: ASGIApp, *, trusted_hosts: str, allowlist: Iterable[str]) -> None: @@ -108,6 +125,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] in ("http", "websocket"): client = scope.get("client") if client and client[0] in self._peers: + scope[TRUSTED_PROXY_SCOPE_KEY] = True self._rewrite(scope) await self.app(scope, receive, send) @@ -120,8 +138,8 @@ def _rewrite(self, scope: Scope) -> None: # Rightmost value: the one our trusted proxy added. Earlier values came # from upstream hops or the client and cannot be trusted (an appending # proxy keeps whatever the client sent at the front). - parsed = _split_host(raw.split(",")[-1]) - if parsed is None or not self._allowed.allows(*parsed): + parsed = self._allowed.match(raw.split(",")[-1]) + if parsed is None: logger.debug("Ignoring X-Forwarded-Host %r: not on the allowlist", raw) return host, port = parsed @@ -132,4 +150,4 @@ def _rewrite(self, scope: Scope) -> None: ] proto = _forwarded_proto(scope) or scope.get("scheme", "") default = _DEFAULT_PORTS.get(proto, _FALLBACK_PORT) - scope["server"] = (host, int(port) if port else default) + scope["server"] = (host.strip("[]"), int(port) if port else default) diff --git a/framework/hosting/simple_module_hosting/pipeline/public_urls.py b/framework/hosting/simple_module_hosting/pipeline/public_urls.py index b254d3622..e67716da6 100644 --- a/framework/hosting/simple_module_hosting/pipeline/public_urls.py +++ b/framework/hosting/simple_module_hosting/pipeline/public_urls.py @@ -1,10 +1,53 @@ -"""Trusted public origins for links, independent of the inbound Host header.""" +"""Configured and allowlisted origins for public links.""" from __future__ import annotations +from functools import lru_cache + +from simple_module_core.modules.app_state import get_host_services +from starlette.datastructures import URL +from starlette.requests import Request + from simple_module_hosting.config.host_settings import HostSettings +from simple_module_hosting.pipeline._forwarded_host import TRUSTED_PROXY_SCOPE_KEY, HostAllowlist +from simple_module_hosting.pipeline._insecure_transport import _is_loopback + +__all__ = ["public_origin", "trusted_request_origin"] def public_origin(settings: HostSettings | None, override: str = "") -> str: """Explicit module origin → host origin → relative links (fresh installs).""" return (override.strip() or (settings.public_base_url if settings else "")).rstrip("/") + + +@lru_cache(maxsize=16) +def _allowlist(entries: tuple[str, ...]) -> HostAllowlist: + return HostAllowlist(entries) + + +def trusted_request_origin(request: Request) -> str | None: + """Accept an allowlisted HTTP(S) authority from the resolved request scope.""" + settings = getattr(get_host_services(request.app), "settings", None) + scheme = request.scope.get("scheme") + if not settings or not settings.forwarded_host_allowlist or scheme not in ("http", "https"): + return None + + # Use the authority after proxy handling without interpreting the path or query. + host_headers = request.headers.getlist("host") + if len(host_headers) == 1: + (authority,) = host_headers + if authority != authority.strip(): + return None + elif not host_headers: + authority = URL(scope={**request.scope, "path": "/", "query_string": b""}).netloc + else: + return None + parsed = _allowlist(tuple(settings.forwarded_host_allowlist)).match(authority) + if parsed is None: + return None + host, port = parsed + if scheme == "http" and not ( + request.scope.get(TRUSTED_PROXY_SCOPE_KEY) or _is_loopback(host.strip("[]")) + ): + return None + return f"{scheme}://{host}" if port is None else f"{scheme}://{host}:{port}" diff --git a/framework/hosting/tests/pipeline/test_forwarded_host.py b/framework/hosting/tests/pipeline/test_forwarded_host.py index 851093b7c..da5c42d6a 100644 --- a/framework/hosting/tests/pipeline/test_forwarded_host.py +++ b/framework/hosting/tests/pipeline/test_forwarded_host.py @@ -111,6 +111,18 @@ async def test_port_is_kept_and_checked(self) -> None: async def test_malformed_values_are_ignored(self, value: str) -> None: assert (await _get(_mw(["*.example.com"]), value))["host"] == "internal" + async def test_bracketed_ipv6_host_is_rewritten(self) -> None: + body = await _get(_mw(["[2001:db8::1]"]), "[2001:db8::1]:8443") + assert body == { + "url": f"http://[2001:db8::1]:8443{_PROBE_PATH}", + "host": "2001:db8::1", + } + + @pytest.mark.parametrize("value", ["[2001:db8::zz]", "[::1", f"{_PUBLIC_HOST}:65536"]) + async def test_invalid_ipv6_or_port_is_ignored(self, value: str) -> None: + allowlist = ["[2001:db8::zz]", "[::1]", _PUBLIC_HOST] + assert (await _get(_mw(allowlist), value))["host"] == "internal" + class TestPeers: @pytest.mark.parametrize( diff --git a/framework/hosting/tests/pipeline/test_public_urls.py b/framework/hosting/tests/pipeline/test_public_urls.py new file mode 100644 index 000000000..f664832c6 --- /dev/null +++ b/framework/hosting/tests/pipeline/test_public_urls.py @@ -0,0 +1,79 @@ +"""The account-link fallback accepts only a safe, allowlisted request authority.""" + +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI, Request +from simple_module_hosting.config.host_settings import HostSettings +from simple_module_hosting.pipeline._forwarded_host import TRUSTED_PROXY_SCOPE_KEY +from simple_module_hosting.pipeline.public_urls import trusted_request_origin + + +@pytest.mark.parametrize( + ("scheme", "authority", "allowlist", "trusted_peer", "expected"), + [ + ("https", "APP.EXAMPLE", ["app.example"], False, "https://app.example"), + ("https", "a.b.example", ["*.example"], False, "https://a.b.example"), + ("https", "example", ["*.example"], False, None), + ("https", "app.example:444", ["app.example:443"], False, None), + ("https", "app.example:65536", ["app.example"], False, None), + ("https", "app.example@other.example", ["*.example"], False, None), + ("https", "app.example\\@other.example", ["*.example"], False, None), + ("http", "127.255.0.2:8000", ["127.255.0.2"], False, "http://127.255.0.2:8000"), + ("http", "127.0.0.1.example", ["127.0.0.1.example"], False, None), + ("http", "app.localhost", ["*.localhost"], False, "http://app.localhost"), + ("http", "[::1]:8000", ["[::1]"], False, "http://[::1]:8000"), + ("http", "[::2]", ["[::2]"], False, None), + ( + "https", + "[::ffff:192.0.2.10]", + ["[::ffff:192.0.2.10]"], + False, + "https://[::ffff:192.0.2.10]", + ), + ("http", "app.example:8000", ["app.example"], True, "http://app.example:8000"), + ("ws", "app.example", ["app.example"], True, None), + ], +) +def test_trusted_request_origin(scheme, authority, allowlist, trusted_peer, expected): + app = FastAPI() + app.state.host = SimpleNamespace(settings=HostSettings(forwarded_host_allowlist=allowlist)) + request = Request( + { + "type": "http", + "app": app, + "scheme": scheme, + "path": "/irrelevant", + "query_string": b"label=\xff", + "headers": [(b"host", authority.encode())], + TRUSTED_PROXY_SCOPE_KEY: trusted_peer, + } + ) + assert trusted_request_origin(request) == expected + + +@pytest.mark.parametrize( + ("headers", "expected"), + [ + ([], "https://app.example"), + ([(b"host", b"evil.example/path")], None), + ([(b"host", b"app.example"), (b"host", b"evil.example")], None), + ], +) +def test_server_authority_is_eligible_only_without_a_conflicting_host(headers, expected): + app = FastAPI() + app.state.host = SimpleNamespace( + settings=HostSettings(forwarded_host_allowlist=["app.example"]) + ) + request = Request( + { + "type": "http", + "app": app, + "scheme": "https", + "path": "/", + "headers": headers, + "server": ("app.example", 443), + } + ) + + assert trusted_request_origin(request) == expected diff --git a/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py b/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py index 202faf54e..790a5ce49 100644 --- a/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py +++ b/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py @@ -8,6 +8,7 @@ from fastapi import APIRouter, FastAPI from fastapi_users.db import BaseUserDatabase from simple_module_hosting.config.host_settings import HostSettings +from simple_module_hosting.pipeline._forwarded_host import ForwardedHostMiddleware from users.accounts.db_adapter import get_user_db from users.auth_local.rate_limit import ThroughputLimiter from users.core.settings import UsersSettings @@ -15,6 +16,7 @@ from users.core.token_secrets import resolve_token_secrets from users.models import User from users.module import UsersModule +from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware class _AccountLookup(BaseUserDatabase[User, UUID]): @@ -28,12 +30,100 @@ async def get_by_email(self, email: str) -> User | None: @pytest.mark.parametrize("endpoint", ["forgot-password", "request-verify-token"]) -async def test_missing_mail_origin_preserves_public_response(captured_mail, caplog, endpoint): +@pytest.mark.parametrize( + "request_origin, allowlist, headers, proxy, host_origin, users_origin, expected", + [ + ("https://app.example", [], {}, None, "", "", None), + ( + "https://app.example:8443", + ["app.example:8443"], + {}, + None, + "", + "", + "https://app.example:8443", + ), + ("https://app.example", ["app.example"], {"host": "evil.example"}, None, "", "", None), + ("https://app.example", ["app.example"], {"host": "evil.example/path"}, None, "", "", None), + ( + "https://internal.example", + ["app.example"], + {"x-forwarded-host": "app.example"}, + "10.0.0.1", + "", + "", + None, + ), + ( + "http://internal.example", + ["app.example"], + {"x-forwarded-host": "app.example", "x-forwarded-proto": "https"}, + "127.0.0.1", + "", + "", + "https://app.example", + ), + ("https://one.app.example", ["*.app.example"], {}, None, "", "", "https://one.app.example"), + ("http://localhost:8000", ["localhost"], {}, None, "", "", "http://localhost:8000"), + ("http://app.example", ["app.example"], {}, None, "", "", None), + ("http://app.example", ["app.example"], {}, "10.0.0.1", "", "", None), + ( + "http://internal.example", + ["app.example"], + { + "x-forwarded-host": "app.example", + "x-forwarded-proto": "http", + "x-forwarded-for": "203.0.113.10", + }, + "127.0.0.1", + "", + "", + "http://app.example", + ), + ( + "https://app.example", + ["app.example"], + {}, + None, + "https://host.example", + "", + "https://host.example", + ), + ( + "https://app.example", + ["app.example"], + {}, + None, + "https://host.example", + "https://users.example", + "https://users.example", + ), + ], +) +async def test_account_mail_origin_preserves_public_response( + captured_mail, + caplog, + endpoint, + request_origin, + allowlist, + headers, + proxy, + host_origin, + users_origin, + expected, +): app = FastAPI() - app.state.host = SimpleNamespace(settings=HostSettings(_env_file=None, public_base_url="")) + app.state.host = SimpleNamespace( + settings=HostSettings( + _env_file=None, public_base_url=host_origin, forwarded_host_allowlist=allowlist + ) + ) + if proxy: + app.add_middleware(ProxyHeadersMiddleware, trusted_hosts=proxy) + app.add_middleware(ForwardedHostMiddleware, trusted_hosts=proxy, allowlist=allowlist) app.state.users = SimpleNamespace( settings=UsersSettings( - base_url="", + base_url=users_origin, ), auth_throughput_limiter=ThroughputLimiter(), token_secrets=resolve_token_secrets("test-secret-key"), @@ -56,7 +146,9 @@ async def user_db(): UsersModule().register_routes(api, APIRouter()) app.include_router(api) transport = httpx.ASGITransport(app=app) - async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + async with httpx.AsyncClient( + transport=transport, base_url=request_origin, headers=headers + ) as client: unknown = await client.post( f"/api/users/auth/{endpoint}", json={"email": "unknown@example.com"} ) @@ -67,8 +159,15 @@ async def user_db(): assert unknown.status_code == 202 assert existing.status_code == unknown.status_code assert existing.content == unknown.content - assert not captured_mail.messages errors = [record for record in caplog.records if record.name == "users.mailer.templated"] + if expected: + assert len(captured_mail.messages) == 1 + path = "reset-password" if endpoint == "forgot-password" else "verify" + assert f"{expected}/users/{path}?token=" in captured_mail.messages[0].text + assert not errors + return + + assert not captured_mail.messages assert len(errors) == 1 assert errors[0].levelname == "ERROR" assert "host.public_base_url" in errors[0].message diff --git a/modules/users/tests/invites/test_users_invite_request_origin.py b/modules/users/tests/invites/test_users_invite_request_origin.py new file mode 100644 index 000000000..c63a75064 --- /dev/null +++ b/modules/users/tests/invites/test_users_invite_request_origin.py @@ -0,0 +1,35 @@ +"""Request-based invite links survive the transaction and the resend path.""" + +import pytest + +_ADMIN = "/api/users/admin" + + +@pytest.mark.parametrize("bulk", [False, True]) +async def test_invite_and_resend_use_allowlisted_request_origin( + admin_client, users_app, captured_mail, bulk +): + users_app.state.users.settings.base_url = "" + users_app.state.host.settings.public_base_url = "" + users_app.state.host.settings.forwarded_host_allowlist = ["app.example"] + origin = "https://app.example" + email = "allowlisted@example.com" + if bulk: + response = await admin_client.post( + f"{origin}{_ADMIN}/invite/bulk", json={"emails": [email]} + ) + assert response.status_code == 200, response.text + assert response.json()["results"][0]["status"] == "sent" + users = await admin_client.get(f"{origin}{_ADMIN}", params={"q": email}) + user_id = next(user["id"] for user in users.json() if user["email"] == email) + else: + response = await admin_client.post(f"{origin}{_ADMIN}/invite", json={"email": email}) + assert response.status_code == 201, response.text + user_id = response.json()["id"] + + response = await admin_client.post(f"{origin}{_ADMIN}/{user_id}/resend-invite") + assert response.status_code == 202, response.text + assert response.json()["status"] == "sent" + messages = captured_mail.to(email) + assert len(messages) == 2 + assert all(f"{origin}/users/invite/accept?token=" in msg.text for msg in messages) diff --git a/modules/users/tests/mailer/templated/test_users_mailer.py b/modules/users/tests/mailer/templated/test_users_mailer.py index 6119fc3cc..fb2e6072e 100644 --- a/modules/users/tests/mailer/templated/test_users_mailer.py +++ b/modules/users/tests/mailer/templated/test_users_mailer.py @@ -2,10 +2,45 @@ from __future__ import annotations +from types import SimpleNamespace + import pytest +from fastapi import FastAPI, Request +from simple_module_hosting.config.host_settings import HostSettings +from users.mailer import mailer_delivers, request_mail_options from users.mailer.templated import TemplatedMailer +def test_positional_only_origin_is_not_passed_as_a_keyword(): + class CustomMailer(TemplatedMailer): + async def send_verification(self, email, token, link_origin=None, /): # ty: ignore[incompatible-method-override] + pass + + app = FastAPI() + app.state.host = SimpleNamespace( + settings=HostSettings(forwarded_host_allowlist=["app.example"]) + ) + request = Request( + { + "type": "http", + "app": app, + "scheme": "https", + "headers": [(b"host", b"app.example")], + } + ) + assert request_mail_options(CustomMailer(base_url=""), request) == {} + + +def test_custom_mailer_can_disable_delivery(captured_mail): + class CustomMailer(TemplatedMailer): + @property + def delivers_email(self) -> bool: + return False + + mailer = CustomMailer(base_url="https://app.example") + assert not mailer_delivers(mailer) + + @pytest.mark.parametrize("url", ["http://localhost:8000", "https://app.example.com"]) @pytest.mark.anyio async def test_send_verification_mails_link(url, captured_mail): @@ -67,3 +102,22 @@ async def test_default_app_name_when_no_provider(captured_mail): await TemplatedMailer(base_url="http://localhost:8000").send_verification("a@b.com", "tok") assert "SimpleModule" in captured_mail.messages[0].subject + + +@pytest.mark.parametrize( + ("method", "arguments", "path"), + [ + ("send_password_reset", (), "reset-password"), + ("send_verification", (), "verify"), + ("send_invite", ("Alice Admin",), "invite/accept"), + ], +) +async def test_request_origin_is_per_send(method, arguments, path, captured_mail, caplog): + mailer = TemplatedMailer(base_url="") + send = getattr(mailer, method) + await send("user@example.com", "token", *arguments, link_origin="https://app.example") + await send("user@example.com", "next-token", *arguments) + + (message,) = captured_mail.messages + assert f"https://app.example/users/{path}?token=token" in message.text + assert "Account email skipped: configure host.public_base_url" in caplog.text diff --git a/modules/users/users/accounts/manager.py b/modules/users/users/accounts/manager.py index 62527e27e..c4e8db375 100644 --- a/modules/users/users/accounts/manager.py +++ b/modules/users/users/accounts/manager.py @@ -29,7 +29,7 @@ from users.core.exceptions import ExternalUserNoPasswordError from users.core.password_hashing import PASSWORD_HELPER, PasswordHashingMixin from users.core.token_secrets import TokenSecretsMixin -from users.mailer import Mailer +from users.mailer import Mailer, request_mail_options from users.models import User if TYPE_CHECKING: @@ -67,8 +67,6 @@ def __init__( self.allow_signup = settings.allow_signup self.require_verification = settings.require_verification - # ── Password policy ────────────────────────────────────── - async def validate_password(self, password: str, user) -> None: # Measured after stripping: " " is eight characters and passed # the raw length check, so a whitespace-only password was accepted @@ -83,8 +81,6 @@ async def validate_password(self, password: str, user) -> None: if password.isdigit(): raise exceptions.InvalidPasswordException(reason="Password cannot be all numbers") - # ── Auth (password-credential guards) ──────────────────── - async def authenticate(self, credentials): """Authenticate by email + password. @@ -179,7 +175,9 @@ async def _publish_user_registered(self, user: User, request: Request | None) -> async def on_after_forgot_password( self, user: User, token: str, request: Request | None = None ) -> None: - await self.mailer.send_password_reset(user.email, token) + await self.mailer.send_password_reset( + user.email, token, **request_mail_options(self.mailer, request) + ) async def on_after_reset_password(self, user: User, request: Request | None = None) -> None: """Lift a login lockout (GH #530): proving control of the mailbox is the way out. @@ -200,7 +198,9 @@ async def on_after_reset_password(self, user: User, request: Request | None = No async def on_after_request_verify( self, user: User, token: str, request: Request | None = None ) -> None: - await self.mailer.send_verification(user.email, token) + await self.mailer.send_verification( + user.email, token, **request_mail_options(self.mailer, request) + ) async def on_after_login( self, user: User, request: Request | None = None, response=None diff --git a/modules/users/users/admin/api.py b/modules/users/users/admin/api.py index 30887479b..e84492bc3 100644 --- a/modules/users/users/admin/api.py +++ b/modules/users/users/admin/api.py @@ -41,6 +41,7 @@ ) from users.invites.bulk import bulk_router from users.invites.resend import resend_router +from users.mailer import request_mail_options from users.web.deps import get_event_bus, get_mailer, get_user_service _DUPLICATE_EMAIL = "A user with this email already exists." @@ -105,7 +106,8 @@ async def admin_invite_user( ) except fa_exceptions.UserAlreadyExists: raise HTTPException(status_code=409, detail=_DUPLICATE_EMAIL) from None - db.on_commit(lambda: mailer.send_invite(user.email, token, invited_by_name)) + mail_options = request_mail_options(mailer, request) + db.on_commit(lambda: mailer.send_invite(user.email, token, invited_by_name, **mail_options)) await publish_admin_event( bus, UserInvited( diff --git a/modules/users/users/admin/views.py b/modules/users/users/admin/views.py index 1e2e5bfbe..ba22ff209 100644 --- a/modules/users/users/admin/views.py +++ b/modules/users/users/admin/views.py @@ -21,7 +21,7 @@ from users.core.constants import Permissions, sanitize_list_filters from users.core.exceptions import UserNotFoundError from users.core.roles_cache import get_roles_cache -from users.mailer import mailer_delivers +from users.mailer import mailer_delivers, request_mail_options from users.web.deps import get_user_service router = APIRouter() @@ -122,7 +122,7 @@ async def admin_add_people_page( users_state = getattr(request.app.state, "users", None) mailer = getattr(users_state, "mailer", None) settings = getattr(users_state, "settings", None) - delivers = mailer_delivers(mailer) + delivers = mailer_delivers(mailer, **request_mail_options(mailer, request)) return await inertia.render( _PAGE_ADMIN_ADD, { diff --git a/modules/users/users/auth_local/views.py b/modules/users/users/auth_local/views.py index 4fa71797d..4f0e73f3d 100644 --- a/modules/users/users/auth_local/views.py +++ b/modules/users/users/auth_local/views.py @@ -22,7 +22,7 @@ from users.core.bootstrap import resolve_bootstrap_credentials from users.demo import resolve_demo_accounts from users.invites.preview import preview_invite -from users.mailer import mailer_delivers +from users.mailer import mailer_delivers, request_mail_options from users.models import User from users.oauth.errors import OAUTH_ERROR_CODES @@ -49,7 +49,8 @@ def _mailer_delivers(request: Request) -> bool: """Drives the amber "the link is in the server log" callout.""" - return mailer_delivers(getattr(getattr(request.app.state, "users", None), "mailer", None)) + mailer = getattr(getattr(request.app.state, "users", None), "mailer", None) + return mailer_delivers(mailer, **request_mail_options(mailer, request)) @router.get("/login", response_model=None) diff --git a/modules/users/users/invites/bulk.py b/modules/users/users/invites/bulk.py index 6b88a1eb9..5e038ea1a 100644 --- a/modules/users/users/invites/bulk.py +++ b/modules/users/users/invites/bulk.py @@ -23,7 +23,7 @@ from users.admin.service import UserService from users.contracts.events import UserInvited from users.contracts.schemas import BulkInviteResponse, BulkInviteResult, UserBulkInvite -from users.mailer import mailer_delivers +from users.mailer import mailer_delivers, request_mail_options from users.models import OAuthAccount, User from users.web.deps import get_event_bus, get_mailer @@ -83,8 +83,7 @@ async def admin_bulk_invite( await check_request_role_assignment(request, data.role_names) invited_by_name = invited_by.name if invited_by else "Administrator" - # Same question the page's ``mailer_delivers`` prop answers, asked once. - delivers = mailer_delivers(mailer) + mail_options = request_mail_options(mailer, request) # Preserve submit order but drop repeats: pasting a list with the same # address twice should not create two invites for it. A malformed address @@ -111,6 +110,7 @@ async def admin_bulk_invite( accepted, overflow = ordered[:MAX_ADDRESSES], ordered[MAX_ADDRESSES:] results: list[BulkInviteResult] = [] + delivers: bool | None = None for email in accepted: try: async with independent_session(request.app) as checkpoint: @@ -136,9 +136,13 @@ async def admin_bulk_invite( ) continue + if delivers is None: + delivers = mailer_delivers(mailer, **mail_options, log_missing_origin=True) if delivers: try: - await mailer.send_invite(user.email, token, invited_by_name, data.message) + await mailer.send_invite( + user.email, token, invited_by_name, data.message, **mail_options + ) except Exception: # The account exists and the token is valid — the delivery # failed. Handing back the link turns a dead end into a diff --git a/modules/users/users/invites/resend.py b/modules/users/users/invites/resend.py index b23359c8e..84cd810d8 100644 --- a/modules/users/users/invites/resend.py +++ b/modules/users/users/invites/resend.py @@ -28,7 +28,7 @@ STATUS_SENT, invite_link, ) -from users.mailer import mailer_delivers +from users.mailer import mailer_delivers, request_mail_options from users.web.deps import get_mailer, get_user_service logger = logging.getLogger(__name__) @@ -70,9 +70,10 @@ async def admin_resend_invite( invited_by_name = getattr(actor, "name", None) or "Administrator" - if mailer_delivers(mailer): + mail_options = request_mail_options(mailer, request) + if mailer_delivers(mailer, **mail_options, log_missing_origin=True): try: - await mailer.send_invite(user.email, token, invited_by_name) + await mailer.send_invite(user.email, token, invited_by_name, **mail_options) except Exception: # The token is valid and the account is waiting; only delivery # failed. Handing back the link turns a dead end into a copy-paste. diff --git a/modules/users/users/mailer/__init__.py b/modules/users/users/mailer/__init__.py index 08053b5c3..c19906fee 100644 --- a/modules/users/users/mailer/__init__.py +++ b/modules/users/users/mailer/__init__.py @@ -3,12 +3,15 @@ from __future__ import annotations from collections.abc import Callable, Sequence +from inspect import Parameter, signature from pathlib import Path -from typing import Protocol, runtime_checkable +from typing import Protocol, TypedDict, runtime_checkable -from simple_module_hosting.pipeline.public_urls import public_origin +from simple_module_hosting.pipeline.public_urls import public_origin, trusted_request_origin +from starlette.requests import Request from users.core.settings import UsersSettings +from users.mailer.templated import TemplatedMailer #: Returns the live application name (e.g. from the branding module) so emails #: are branded with the deployment's name rather than the framework default. @@ -22,8 +25,52 @@ def default_app_name() -> str: return DEFAULT_APP_NAME +class MailLinkOptions(TypedDict, total=False): + link_origin: str + + +_SEND_METHODS = ("send_verification", "send_password_reset", "send_invite") + + +def _accepts_link_origin(mailer: TemplatedMailer) -> bool: + """A subclass overriding a send method with the original signature opts out.""" + for name in _SEND_METHODS: + params = signature(getattr(mailer, name)).parameters + origin = params.get("link_origin") + if origin is not None and origin.kind in ( + Parameter.POSITIONAL_OR_KEYWORD, + Parameter.KEYWORD_ONLY, + ): + continue + if not any(p.kind is Parameter.VAR_KEYWORD for p in params.values()): + return False + return True + + +def request_mail_options(mailer: object, request: Request | None) -> MailLinkOptions: + # A configured origin always wins, so the request origin is only offered + # without one, and only to mailers whose send methods take the keyword. + if ( + isinstance(mailer, TemplatedMailer) + and not mailer.has_configured_origin + and request is not None + and _accepts_link_origin(mailer) + and (origin := trusted_request_origin(request)) is not None + ): + return {"link_origin": origin} + return {} + + @runtime_checkable class Mailer(Protocol): + """The send interface a third-party mailer implements. + + The built-in ``TemplatedMailer`` also accepts a keyword-only + ``link_origin``; callers pass it only after ``request_mail_options`` + confirms the concrete mailer takes it, so this protocol keeps the original + signatures and existing implementations still type-check. + """ + async def send_verification(self, email: str, token: str) -> None: ... async def send_password_reset(self, email: str, token: str) -> None: ... # *message* is the optional note the inviter typed on the batch form. @@ -38,7 +85,12 @@ async def send_invite( ) -> None: ... -def mailer_delivers(mailer: object | None) -> bool: +def mailer_delivers( + mailer: object | None, + *, + link_origin: str | None = None, + log_missing_origin: bool = False, +) -> bool: """Whether *mailer* actually puts mail in front of a person. Four screens branch on this — the reset-sent card, add-people, resend @@ -49,6 +101,11 @@ def mailer_delivers(mailer: object | None) -> bool: rather than the settings because ``delivers_email`` is the mailer's own claim; a third-party mailer that never set the flag is taken at its word. """ + if ( + isinstance(mailer, TemplatedMailer) + and type(mailer).delivers_email is TemplatedMailer.delivers_email + ): + return mailer.delivers_with_origin(link_origin, log_missing_origin=log_missing_origin) return bool(mailer is not None and getattr(mailer, "delivers_email", True)) @@ -59,8 +116,6 @@ def build_mailer( template_dirs: Sequence[str | Path] = (), base_url_provider: Callable[[], str] | None = None, ) -> Mailer: - from users.mailer.templated import TemplatedMailer - return TemplatedMailer( base_url=base_url_provider or public_origin(None, settings.base_url), app_name_provider=app_name_provider, diff --git a/modules/users/users/mailer/templated.py b/modules/users/users/mailer/templated.py index bd859510e..55be1af9f 100644 --- a/modules/users/users/mailer/templated.py +++ b/modules/users/users/mailer/templated.py @@ -23,6 +23,10 @@ from users.mailer import AppNameProvider logger = logging.getLogger(__name__) +_MISSING_ORIGIN = ( + "Account email skipped: configure host.public_base_url / SM_PUBLIC_BASE_URL " + "(or users.base_url) for absolute links" +) class TemplatedMailer: @@ -63,23 +67,50 @@ def _base(self) -> str: origin = self._base_url() if callable(self._base_url) else self._base_url return origin.rstrip("/") + @property + def has_configured_origin(self) -> bool: + return bool(self._base) + @property def delivers_email(self) -> bool: """Whether the installed sender puts mail in front of a person.""" - return bool(self._base) and current_mail_sender().delivers_email - - async def send_verification(self, email: str, token: str) -> None: + return self.delivers_with_origin() + + def delivers_with_origin( + self, link_origin: str | None = None, *, log_missing_origin: bool = False + ) -> bool: + if not (self._base or link_origin): + if log_missing_origin: + logger.error(_MISSING_ORIGIN) + return False + return current_mail_sender().delivers_email + + async def send_verification( + self, email: str, token: str, *, link_origin: str | None = None + ) -> None: app = self._app_name() link = f"/users/verify?token={token}" await self._send( - email, f"Verify your email for {app}", MAIL_TEMPLATE_VERIFY, app_name=app, link=link + email, + f"Verify your email for {app}", + MAIL_TEMPLATE_VERIFY, + app_name=app, + link=link, + link_origin=link_origin, ) - async def send_password_reset(self, email: str, token: str) -> None: + async def send_password_reset( + self, email: str, token: str, *, link_origin: str | None = None + ) -> None: app = self._app_name() link = f"/users/reset-password?token={token}" await self._send( - email, f"Reset your {app} password", MAIL_TEMPLATE_RESET, app_name=app, link=link + email, + f"Reset your {app} password", + MAIL_TEMPLATE_RESET, + app_name=app, + link=link, + link_origin=link_origin, ) async def send_invite( @@ -88,6 +119,8 @@ async def send_invite( token: str, invited_by_name: str, message: str | None = None, + *, + link_origin: str | None = None, ) -> None: app = self._app_name() link = f"/users/invite/accept?token={token}" @@ -97,6 +130,7 @@ async def send_invite( MAIL_TEMPLATE_INVITE, app_name=app, link=link, + link_origin=link_origin, invited_by_name=invited_by_name, # Stripped here rather than in the template: a message of nothing # but whitespace should leave no quoted block behind. @@ -104,14 +138,18 @@ async def send_invite( ) async def _send( - self, to: str, subject: str, template_name: str, *, link: str, **context: Any + self, + to: str, + subject: str, + template_name: str, + *, + link: str, + link_origin: str | None, + **context: Any, ) -> None: - base = self._base + base = self._base or link_origin if not base: - logger.error( - "Account email skipped: configure host.public_base_url / SM_PUBLIC_BASE_URL " - "(or users.base_url) for absolute links" - ) + logger.error(_MISSING_ORIGIN) return context["link"] = f"{base}{link}" body = self._template_env.get_template(template_name).render(**context) From b430dd6686b789ffd468fae7e174bd2b5269a386 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Sun, 29 Nov 2026 09:49:52 +0100 Subject: [PATCH 2/2] feat(users): carry allowlisted request origin to invite verification mail (#1136) --- docs/framework/settings.md | 3 +- docs/modules/users.md | 3 +- .../pipeline/public_urls.py | 17 ++- .../tests/pipeline/test_public_urls.py | 33 ++++- .../api/test_users_missing_mail_origin.py | 22 +++ .../test_users_invite_request_origin.py | 129 ++++++++++++++++-- modules/users/users/accounts/manager.py | 33 +++-- modules/users/users/admin/api.py | 5 +- modules/users/users/admin/service.py | 5 +- modules/users/users/invites/bulk.py | 2 +- modules/users/users/mailer/__init__.py | 47 ++++++- 11 files changed, 259 insertions(+), 40 deletions(-) diff --git a/docs/framework/settings.md b/docs/framework/settings.md index 6563b2788..e4cbe2ea4 100644 --- a/docs/framework/settings.md +++ b/docs/framework/settings.md @@ -116,7 +116,8 @@ It uses the scheme and authority resolved by the hosting middleware. `host.forwarded_host_allowlist` must match the authority using the same exact host, wildcard subdomain and optional port rules as [ForwardedHost](/framework/middleware#forwardedhostmiddleware-opt-in). The middleware accepts `X-Forwarded-Host` only from a trusted proxy. HTTPS is -eligible for any allowlisted host. HTTP requires a trusted proxy peer or a +eligible for any allowlisted host. HTTP requires a trusted proxy peer that +explicitly forwards `X-Forwarded-Proto: http`, or a loopback host (`localhost`, its subdomains, `127.0.0.0/8` or `[::1]`), which must also be allowlisted. Use brackets when listing an IPv6 address and add an optional port after the closing bracket. diff --git a/docs/modules/users.md b/docs/modules/users.md index f270d44a4..182501d24 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -232,7 +232,8 @@ Edit the remaining settings under Users at `/admin/settings/`: Password reset, verification and invitation emails use `users.base_url` first, then `host.public_base_url` (including `SM_PUBLIC_BASE_URL`), then the resolved request origin if it matches `host.forwarded_host_allowlist`. HTTPS is -eligible. HTTP requires a trusted proxy peer or an allowlisted loopback host +eligible. HTTP requires a trusted proxy peer that explicitly forwards +`X-Forwarded-Proto: http`, or an allowlisted loopback host (`localhost`, its subdomains, `127.0.0.0/8` or `[::1]`). Sends without a request require a configured origin. The trusted proxy peer is recognised by the framework's `host.trusted_proxy` handling; if Uvicorn itself runs with `--proxy-headers` diff --git a/framework/hosting/simple_module_hosting/pipeline/public_urls.py b/framework/hosting/simple_module_hosting/pipeline/public_urls.py index e67716da6..c7acd7d2b 100644 --- a/framework/hosting/simple_module_hosting/pipeline/public_urls.py +++ b/framework/hosting/simple_module_hosting/pipeline/public_urls.py @@ -25,6 +25,19 @@ def _allowlist(entries: tuple[str, ...]) -> HostAllowlist: return HostAllowlist(entries) +def _proxy_declared_http(request: Request) -> bool: + """Require an explicit single-value ``X-Forwarded-Proto: http`` from a trusted proxy. + + A missing or comma-separated header leaves ``scope["scheme"]`` at the + backend's plain-HTTP transport scheme; accepting that would silently + downgrade TLS-terminated links to plaintext HTTP. + """ + if not request.scope.get(TRUSTED_PROXY_SCOPE_KEY): + return False + values = request.headers.getlist("x-forwarded-proto") + return len(values) == 1 and values[0].strip().lower() == "http" + + def trusted_request_origin(request: Request) -> str | None: """Accept an allowlisted HTTP(S) authority from the resolved request scope.""" settings = getattr(get_host_services(request.app), "settings", None) @@ -46,8 +59,6 @@ def trusted_request_origin(request: Request) -> str | None: if parsed is None: return None host, port = parsed - if scheme == "http" and not ( - request.scope.get(TRUSTED_PROXY_SCOPE_KEY) or _is_loopback(host.strip("[]")) - ): + if scheme == "http" and not (_proxy_declared_http(request) or _is_loopback(host.strip("[]"))): return None return f"{scheme}://{host}" if port is None else f"{scheme}://{host}:{port}" diff --git a/framework/hosting/tests/pipeline/test_public_urls.py b/framework/hosting/tests/pipeline/test_public_urls.py index f664832c6..dcac91772 100644 --- a/framework/hosting/tests/pipeline/test_public_urls.py +++ b/framework/hosting/tests/pipeline/test_public_urls.py @@ -31,7 +31,7 @@ False, "https://[::ffff:192.0.2.10]", ), - ("http", "app.example:8000", ["app.example"], True, "http://app.example:8000"), + ("http", "app.example:8000", ["app.example"], True, None), ("ws", "app.example", ["app.example"], True, None), ], ) @@ -52,6 +52,37 @@ def test_trusted_request_origin(scheme, authority, allowlist, trusted_peer, expe assert trusted_request_origin(request) == expected +@pytest.mark.parametrize( + ("proto_headers", "trusted_peer", "expected"), + [ + ([(b"x-forwarded-proto", b"http")], True, "http://app.example:8000"), + ([(b"x-forwarded-proto", b"HTTP")], True, "http://app.example:8000"), + ([], True, None), + ([(b"x-forwarded-proto", b"https, http")], True, None), + ([(b"x-forwarded-proto", b"https"), (b"x-forwarded-proto", b"http")], True, None), + ([(b"x-forwarded-proto", b"http")], False, None), + ], +) +def test_proxied_http_requires_explicit_single_forwarded_proto( + proto_headers, trusted_peer, expected +): + app = FastAPI() + app.state.host = SimpleNamespace( + settings=HostSettings(forwarded_host_allowlist=["app.example"]) + ) + request = Request( + { + "type": "http", + "app": app, + "scheme": "http", + "path": "/", + "headers": [(b"host", b"app.example:8000"), *proto_headers], + TRUSTED_PROXY_SCOPE_KEY: trusted_peer, + } + ) + assert trusted_request_origin(request) == expected + + @pytest.mark.parametrize( ("headers", "expected"), [ diff --git a/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py b/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py index 790a5ce49..f36512886 100644 --- a/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py +++ b/modules/users/tests/auth_local/api/test_users_missing_mail_origin.py @@ -80,6 +80,28 @@ async def get_by_email(self, email: str) -> User | None: "", "http://app.example", ), + ( + "http://internal.example", + ["app.example"], + {"x-forwarded-host": "app.example", "x-forwarded-for": "203.0.113.10"}, + "127.0.0.1", + "", + "", + None, + ), + ( + "http://internal.example", + ["app.example"], + { + "x-forwarded-host": "app.example", + "x-forwarded-proto": "https, https", + "x-forwarded-for": "203.0.113.10", + }, + "127.0.0.1", + "", + "", + None, + ), ( "https://app.example", ["app.example"], diff --git a/modules/users/tests/invites/test_users_invite_request_origin.py b/modules/users/tests/invites/test_users_invite_request_origin.py index c63a75064..6db4be437 100644 --- a/modules/users/tests/invites/test_users_invite_request_origin.py +++ b/modules/users/tests/invites/test_users_invite_request_origin.py @@ -1,17 +1,28 @@ -"""Request-based invite links survive the transaction and the resend path.""" +"""Request-based invite and companion verification links (#1126, #1136).""" import pytest +from simple_module_db import independent_session +from users.accounts.db_adapter import UserDatabaseWithRoles +from users.accounts.manager import UserManager +from users.admin.service import UserService +from users.mailer import current_mail_origin +from users.models import OAuthAccount, User _ADMIN = "/api/users/admin" +def _clear_configured_origins(users_app, allowlist: list[str]) -> None: + users_app.state.users.settings.base_url = "" + users_app.state.host.settings.public_base_url = "" + users_app.state.host.settings.forwarded_host_allowlist = allowlist + + @pytest.mark.parametrize("bulk", [False, True]) async def test_invite_and_resend_use_allowlisted_request_origin( - admin_client, users_app, captured_mail, bulk + admin_client, users_app, captured_mail, caplog, bulk ): - users_app.state.users.settings.base_url = "" - users_app.state.host.settings.public_base_url = "" - users_app.state.host.settings.forwarded_host_allowlist = ["app.example"] + """Single and bulk HTTP invites carry the allowlisted origin to both invite and verify mail.""" + _clear_configured_origins(users_app, ["app.example"]) origin = "https://app.example" email = "allowlisted@example.com" if bulk: @@ -27,9 +38,111 @@ async def test_invite_and_resend_use_allowlisted_request_origin( assert response.status_code == 201, response.text user_id = response.json()["id"] + initial = captured_mail.to(email) + invite_msgs = [m for m in initial if f"{origin}/users/invite/accept?token=" in m.text] + verify_msgs = [m for m in initial if f"{origin}/users/verify?token=" in m.text] + assert len(invite_msgs) == 1 + assert len(verify_msgs) == 1 + response = await admin_client.post(f"{origin}{_ADMIN}/{user_id}/resend-invite") assert response.status_code == 202, response.text assert response.json()["status"] == "sent" - messages = captured_mail.to(email) - assert len(messages) == 2 - assert all(f"{origin}/users/invite/accept?token=" in msg.text for msg in messages) + all_messages = captured_mail.to(email) + assert len(all_messages) == 3 + assert sum(f"{origin}/users/invite/accept?token=" in msg.text for msg in all_messages) == 2 + assert sum(f"{origin}/users/verify?token=" in msg.text for msg in all_messages) == 1 + assert current_mail_origin() is None + assert not [r for r in caplog.records if r.name == "users.mailer.templated"] + + +@pytest.mark.parametrize("bulk", [False, True]) +async def test_invite_with_unallowlisted_host_skips_both_emails( + admin_client, users_app, captured_mail, caplog, bulk +): + """An unallowlisted request host skips both invitation and companion verification mail.""" + _clear_configured_origins(users_app, ["app.example"]) + origin = "https://evil.example" + email = "unallowlisted@example.com" + if bulk: + response = await admin_client.post( + f"{origin}{_ADMIN}/invite/bulk", json={"emails": [email]} + ) + assert response.status_code == 200, response.text + assert response.json()["results"][0]["status"] == "link" + else: + response = await admin_client.post(f"{origin}{_ADMIN}/invite", json={"email": email}) + assert response.status_code == 201, response.text + + assert captured_mail.to(email) == [] + assert current_mail_origin() is None + errors = [r for r in caplog.records if r.name == "users.mailer.templated"] + assert errors + assert all(r.levelname == "ERROR" for r in errors) + + +async def test_non_http_invite_without_configured_origin_skips_verification( + users_app, captured_mail, caplog +): + """Background/CLI invites (request=None) still require a configured origin for verify mail.""" + _clear_configured_origins(users_app, ["app.example"]) + email = "cli-invite@example.com" + async with independent_session(users_app) as db: + manager = UserManager( + UserDatabaseWithRoles(db, User, OAuthAccount), + users_app.state.users.mailer, + users_app.state.users.settings, + users_app.state.users.token_secrets, + ) + service = UserService(db, manager, users_app, request=None) + await service.invite(email, None, []) + + assert captured_mail.to(email) == [] + assert current_mail_origin() is None + errors = [r for r in caplog.records if r.name == "users.mailer.templated"] + assert len(errors) == 1 + assert errors[0].levelname == "ERROR" + + +async def test_interleaved_invites_keep_origins_isolated_and_reset_on_error( + admin_client, users_app, captured_mail, monkeypatch +): + """Distinct request origins do not leak across invites, even when a send raises.""" + _clear_configured_origins(users_app, ["one.example", "two.example"]) + first = await admin_client.post( + f"https://one.example{_ADMIN}/invite", json={"email": "first@example.com"} + ) + second = await admin_client.post( + f"https://two.example{_ADMIN}/invite", json={"email": "second@example.com"} + ) + assert first.status_code == 201, first.text + assert second.status_code == 201, second.text + + first_verify = [ + m for m in captured_mail.to("first@example.com") if "/users/verify?token=" in m.text + ] + second_verify = [ + m for m in captured_mail.to("second@example.com") if "/users/verify?token=" in m.text + ] + assert len(first_verify) == 1 + assert "https://one.example/users/verify?token=" in first_verify[0].text + assert len(second_verify) == 1 + assert "https://two.example/users/verify?token=" in second_verify[0].text + + observed_after_error: list[str | None] = [] + real_send_invite = users_app.state.users.mailer.send_invite + + async def _boom(*_args, **_kwargs): + raise RuntimeError("smtp down") + + async def _spy_send_invite(*args, **kwargs): + observed_after_error.append(current_mail_origin()) + return await real_send_invite(*args, **kwargs) + + monkeypatch.setattr(users_app.state.users.mailer, "send_verification", _boom) + monkeypatch.setattr(users_app.state.users.mailer, "send_invite", _spy_send_invite) + third = await admin_client.post( + f"https://one.example{_ADMIN}/invite", json={"email": "boom@example.com"} + ) + assert third.status_code == 201, third.text + assert observed_after_error == [None] + assert current_mail_origin() is None diff --git a/modules/users/users/accounts/manager.py b/modules/users/users/accounts/manager.py index 363272273..e506b9aed 100644 --- a/modules/users/users/accounts/manager.py +++ b/modules/users/users/accounts/manager.py @@ -29,7 +29,13 @@ from users.core.exceptions import ExternalUserNoPasswordError from users.core.password_hashing import PASSWORD_HELPER, PasswordHashingMixin from users.core.token_secrets import TokenSecretsMixin -from users.mailer import Mailer, request_mail_options +from users.mailer import ( + Mailer, + bind_mail_origin, + current_mail_origin, + request_mail_options, + verify_mail_options, +) from users.models import User if TYPE_CHECKING: @@ -155,7 +161,13 @@ async def on_after_register(self, user: User, request: Request | None = None) -> # Kicks off on_after_request_verify, which sends the email if request is None: # Admin invites also send verification mail; neither may precede the commit. - register_on_commit(self.user_db.session, lambda: self.request_verify(user, request)) + deferred_origin = current_mail_origin() + + async def _send_deferred_verify() -> None: + with bind_mail_origin(deferred_origin): + await self.request_verify(user, None) + + register_on_commit(self.user_db.session, _send_deferred_verify) else: await self.request_verify(user, request) @@ -197,7 +209,7 @@ async def on_after_request_verify( ) -> None: if user.email: await self.mailer.send_verification( - user.email, token, **request_mail_options(self.mailer, request) + user.email, token, **verify_mail_options(self.mailer, request) ) async def on_after_login( @@ -239,18 +251,9 @@ async def on_after_login( def mint_invite_token(self, user: User, invited_by: str | None = None) -> str: """Mint a verify-audience JWT without firing on_after_request_verify. - The one place these are minted — the bulk form, the resend action and - plain verification all come through here — because the accept-invite - card reads ``invited_by`` and ``exp`` straight off the token. A second - mint site that forgot the claim would produce links that work but say - "you have been invited" by nobody, which is the failure the claim - exists to fix. ``request_verify()`` couples minting with sending; this - decouples them, which is what the admin flows need. - - ``invited_by`` is the inviter's display name, not their id: it is only - ever shown, and a token that outlives the inviter's account should - still read sensibly. Omitted for a plain verification link, where - nobody invited anyone. + Shared by bulk invite, resend and plain verification so the accept-invite + card always reads ``invited_by`` (display name, omitted for plain + verification) and ``exp`` off the token. Decouples minting from sending. """ token_data: dict[str, object] = { "sub": str(user.id), diff --git a/modules/users/users/admin/api.py b/modules/users/users/admin/api.py index 323fc3a9a..abc58b4fc 100644 --- a/modules/users/users/admin/api.py +++ b/modules/users/users/admin/api.py @@ -188,10 +188,7 @@ async def admin_delete_user( """Hard-delete a user. An admin cannot delete their own account.""" actor = getattr(request.state, "user", None) if actor is not None and str(user_id) == actor.id: - raise HTTPException( - status_code=400, - detail="You cannot delete your own account.", - ) + raise HTTPException(status_code=400, detail="You cannot delete your own account.") try: await service.delete_user(user_id) except UserNotFoundError: diff --git a/modules/users/users/admin/service.py b/modules/users/users/admin/service.py index b7dcc55c8..eac89cb2e 100644 --- a/modules/users/users/admin/service.py +++ b/modules/users/users/admin/service.py @@ -20,6 +20,7 @@ NotPendingInviteError, UserNotFoundError, ) +from users.mailer import bind_mail_origin, request_mail_options from users.models import OAuthAccount, RefreshToken, User, UserAccessToken, UserRole @@ -155,7 +156,9 @@ async def invite( is_active=True, is_verified=False, ) - user = await self._manager.create(user_create, safe=False) + origin = request_mail_options(self._manager.mailer, self._request).get("link_origin") + with bind_mail_origin(origin): + user = await self._manager.create(user_create, safe=False) user.invited_at = datetime.now(UTC) publish_after_commit(self._app, self._db) diff --git a/modules/users/users/invites/bulk.py b/modules/users/users/invites/bulk.py index 3c766622a..53205b594 100644 --- a/modules/users/users/invites/bulk.py +++ b/modules/users/users/invites/bulk.py @@ -141,7 +141,7 @@ async def admin_bulk_invite( if delivers: try: await mailer.send_invite( - user.email, token, invited_by_name, data.message, **mail_options + user.email or email, token, invited_by_name, data.message, **mail_options ) except Exception: # The account exists and the token is valid — the delivery diff --git a/modules/users/users/mailer/__init__.py b/modules/users/users/mailer/__init__.py index c19906fee..7b37780d2 100644 --- a/modules/users/users/mailer/__init__.py +++ b/modules/users/users/mailer/__init__.py @@ -2,7 +2,9 @@ from __future__ import annotations -from collections.abc import Callable, Sequence +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from contextvars import ContextVar from inspect import Parameter, signature from pathlib import Path from typing import Protocol, TypedDict, runtime_checkable @@ -30,6 +32,22 @@ class MailLinkOptions(TypedDict, total=False): _SEND_METHODS = ("send_verification", "send_password_reset", "send_invite") +_deferred_mail_origin: ContextVar[str | None] = ContextVar("_deferred_mail_origin", default=None) + + +@contextmanager +def bind_mail_origin(origin: str | None) -> Generator[None]: + """Scope an allowlisted request origin for deferred request-less mail sends.""" + token = _deferred_mail_origin.set(origin) + try: + yield + finally: + _deferred_mail_origin.reset(token) + + +def current_mail_origin() -> str | None: + """Return the active deferred mail origin, if any.""" + return _deferred_mail_origin.get() def _accepts_link_origin(mailer: TemplatedMailer) -> bool: @@ -47,20 +65,39 @@ def _accepts_link_origin(mailer: TemplatedMailer) -> bool: return True -def request_mail_options(mailer: object, request: Request | None) -> MailLinkOptions: - # A configured origin always wins, so the request origin is only offered +def _can_use_link_origin(mailer: object) -> bool: + # A configured origin always wins, so a fallback origin is only offered # without one, and only to mailers whose send methods take the keyword. - if ( + return ( isinstance(mailer, TemplatedMailer) and not mailer.has_configured_origin - and request is not None and _accepts_link_origin(mailer) + ) + + +def origin_mail_options(mailer: object, link_origin: str | None) -> MailLinkOptions: + if link_origin and _can_use_link_origin(mailer): + return {"link_origin": link_origin} + return {} + + +def request_mail_options(mailer: object, request: Request | None) -> MailLinkOptions: + if ( + request is not None + and _can_use_link_origin(mailer) and (origin := trusted_request_origin(request)) is not None ): return {"link_origin": origin} return {} +def verify_mail_options(mailer: object, request: Request | None) -> MailLinkOptions: + """Resolve link options for verification mail (live request or deferred invite origin).""" + if request is not None: + return request_mail_options(mailer, request) + return origin_mail_options(mailer, current_mail_origin()) + + @runtime_checkable class Mailer(Protocol): """The send interface a third-party mailer implements.