Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ All notable changes to this project are documented in this file. The format is b
- Inertia / Hosting: authenticated HTML responses now emit `Cache-Control: private, no-store` (with `ETag` removed) and authenticated Inertia pages enable `encryptHistory` by default so signed-in pages are not restorable via Back after logout (#1232).
- UI: darken `--input` border contrast in light and dark themes to meet WCAG 1.4.11 (≥ 3:1), expand touch targets on `Input`, `Checkbox`, and `RadioGroupItem`, and prevent horizontal overflow in `SidebarLayout` at 200% zoom (#1232).
- OIDC: **Behaviour change:** `OidcSettings.role_mapping` now defaults to `{}` instead of `{"admin": "admin", "user": "user"}` so no shared-IdP role grants application privileges until explicitly mapped (#1217).
- **Behaviour change:** account emails (including companion verification emails for HTTP-initiated single and bulk invites) 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, #1136).
- `ForwardedHostMiddleware` and the allowlist now accept bracketed IPv6 hosts (`[2001:db8::1]:8443`) and reject ports above 65535 and values with trailing characters (#1126).

### Fixed

Expand Down
2 changes: 1 addition & 1 deletion docs/framework/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ Set it to a comma-separated list of proxy IPs/CIDRs (network addresses, such as

### `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`

Expand Down
31 changes: 22 additions & 9 deletions docs/framework/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,29 @@ 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 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.

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.

The module overrides `users.base_url` and `tenants.public_base_url` accept blank
or an absolute HTTP(S) URL without credentials, query strings or fragments, up to
Expand Down
19 changes: 18 additions & 1 deletion docs/modules/users.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. Accepts blank or an absolute HTTP(S) URL without credentials, query strings or fragments, up to 2,083 characters after trimming; path prefixes are preserved and saves persist the trimmed string. Invalid saves return a field-level 422; invalid stored values are logged and ignored without deleting their rows. 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`; an explicit users origin wins. Accepts blank or an absolute HTTP(S) URL without credentials, query strings or fragments, up to 2,083 characters after trimming; path prefixes are preserved and saves persist the trimmed string. Invalid saves return a field-level 422; invalid stored values are logged and ignored without deleting their rows. When both are blank, account emails can use an allowlisted request origin; otherwise 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. |
| `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 |
Expand All @@ -229,6 +229,23 @@ 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` / `oauth_oidc_associate_by_email` | `""` / `""` / `""` / `"OIDC"` / `True` — generic OIDC (uses S256 PKCE, nonce, JWKS-validated ID token, and issuer-scoped `(oauth_name, issuer, account_id)` linking; turn `oauth_oidc_associate_by_email` off to disable email-based linking) |

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 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`
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.

### Pre-creating OAuth-linked users (`ensure_oauth_user`)

Modules or migration scripts that import users before their first OAuth/OIDC sign-in can call `users.contracts.ensure_oauth_user(session, oauth_name, account_id, *, issuer=None, username=None, full_name=None, email=None, user_id=None) -> UUID`. The call is idempotent, allows `email=None` (no placeholder address needed — `User.email` is nullable with uniqueness enforced on non-null `lower(email)`), and flushes inside a savepoint. When the user later signs in with a verified IdP email claim while `User.email` is still `None`, the email is backfilled automatically.
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<host>[a-z0-9]([a-z0-9._-]*[a-z0-9])?)(:(?P<port>\d{1,5}))?$")
TRUSTED_PROXY_SCOPE_KEY = "sm.trusted_proxy_peer"
_HOST_PATTERN = re.compile(
r"(?P<host>[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?|\[[a-f0-9:.]+\])(?::(?P<port>[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:
Expand Down Expand Up @@ -112,6 +125,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:
Expand All @@ -123,6 +140,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)

Expand All @@ -135,8 +153,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
Expand All @@ -147,4 +165,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)
56 changes: 55 additions & 1 deletion framework/hosting/simple_module_hosting/pipeline/public_urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,64 @@
"""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 _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)
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 (_proxy_declared_http(request) or _is_loopback(host.strip("[]"))):
return None
return f"{scheme}://{host}" if port is None else f"{scheme}://{host}:{port}"
12 changes: 12 additions & 0 deletions framework/hosting/tests/pipeline/test_forwarded_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading