Harden production launch defaults

This commit is contained in:
StasonJatham committed 2026-05-20 18:33:48 +02:00
1 parent 8b80e0e3d2
commit 2203852170
8 files changed
+176 -30

No files matched your search

+60 -27
View File
@@ -14,6 +14,7 @@ from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, RedirectResponse
from starlette.concurrency import run_in_threadpool
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from .ddns_api import create_api_router
@@ -24,6 +25,7 @@ from .ddns_security import (
client_ip,
credentials_from_basic_auth,
is_rate_limited_path,
rate_limit_bucket,
require_admin_csrf,
)
from .ddns_service import DdnsService, normalize_domain, normalize_hostname
@@ -60,6 +62,31 @@ OPENAPI_TAGS = [
ASSET_DIR = Path(__file__).with_name("assets")
APP_JS = """
(() => {
const applyTheme = () => {
const theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
document.documentElement.setAttribute("data-bs-theme", theme);
document.documentElement.style.colorScheme = theme;
};
applyTheme();
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyTheme);
})();
document.addEventListener("click", async (event) => {
const button = event.target.closest("[data-copy]");
if (!button) return;
try {
await navigator.clipboard.writeText(button.dataset.copy || "");
const old = button.textContent;
button.textContent = "Copied";
setTimeout(() => {
button.textContent = old;
}, 1200);
} catch (_) {}
});
""".strip()
class RequestBodyTooLargeError(Exception):
pass
@@ -99,6 +126,7 @@ def make_app(settings: DdnsSettings | None = None) -> FastAPI:
settings = settings.model_copy(update={"admin_password": settings.shared_secret})
if settings.require_dns_provider and not dns_backend_configured(settings):
raise RuntimeError("DDNS_REQUIRE_DNS_PROVIDER is set but no DNS backend is configured")
settings.validate_launch_ready()
store = DdnsStore(settings.database_path)
store.cleanup(settings.cleanup_challenge_hours, settings.cleanup_unused_account_hours)
@@ -127,6 +155,7 @@ def make_app(settings: DdnsSettings | None = None) -> FastAPI:
openapi_tags=OPENAPI_TAGS,
lifespan=lifespan,
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.effective_trusted_hosts)
app.add_middleware(RequestBodyLimitMiddleware, max_body_bytes=settings.max_request_body_bytes)
app.include_router(create_api_router(settings, store, service))
@@ -141,7 +170,7 @@ def make_app(settings: DdnsSettings | None = None) -> FastAPI:
if is_rate_limited_path(request.url.path) or _is_admin_path(request.url.path):
limit = settings.admin_rate_limit_per_minute if _is_admin_path(request.url.path) else settings.rate_limit_per_minute
key = f"{client_ip(request, settings)}:{request.url.path}"
key = f"{client_ip(request, settings)}:{rate_limit_bucket(request.url.path)}"
allowed = await run_in_threadpool(store.allow_rate_limit, key, limit)
if not allowed:
return PlainTextResponse("rate limit exceeded", status_code=429)
@@ -154,9 +183,7 @@ def make_app(settings: DdnsSettings | None = None) -> FastAPI:
response.headers["X-Frame-Options"] = "DENY"
response.headers["Referrer-Policy"] = "same-origin"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; script-src 'unsafe-inline' 'self'; style-src 'unsafe-inline' 'self' https://cdn.jsdelivr.net; form-action 'self'; frame-ancestors 'none'"
)
response.headers["Content-Security-Policy"] = _content_security_policy(request.url.path)
if settings.public_base_url.startswith("https://"):
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
return response
@@ -441,6 +468,10 @@ def make_app(settings: DdnsSettings | None = None) -> FastAPI:
def logo_png() -> FileResponse:
return FileResponse(ASSET_DIR / "logo.png", media_type="image/png")
@app.get("/app.js", include_in_schema=False)
def app_js() -> Response:
return Response(APP_JS, media_type="application/javascript")
@app.get("/u/{update_slug}", response_class=PlainTextResponse, response_model=None)
def slug_update(
update_slug: str,
@@ -518,6 +549,30 @@ def _is_secret_response(request: Request) -> bool:
return request.method == "POST" and path in {"/magic", "/request-domain", "/verify-domain", "/accounts"}
def _content_security_policy(path: str) -> str:
if path in {"/docs", "/redoc", "/openapi.json"}:
return (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data: https://fastapi.tiangolo.com; "
"font-src 'self' https://cdn.jsdelivr.net; "
"connect-src 'self'; "
"form-action 'self'; "
"frame-ancestors 'none'"
)
return (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data:; "
"font-src 'self' https://cdn.jsdelivr.net; "
"connect-src 'self'; "
"form-action 'self'; "
"frame-ancestors 'none'"
)
def _render_public_home(
service: DdnsService,
settings: DdnsSettings,
@@ -1038,17 +1093,7 @@ def _page(title: str, body: str) -> str:
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="icon" href="/logo.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/logo.png">
<script>
(() => {{
const applyTheme = () => {{
const theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
document.documentElement.setAttribute("data-bs-theme", theme);
document.documentElement.style.colorScheme = theme;
}};
applyTheme();
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyTheme);
}})();
</script>
<script src="/app.js" defer></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
<style>
:root {{
@@ -1195,18 +1240,6 @@ def _page(title: str, body: str) -> str:
h2 {{ font-size: 25px; }}
}}
</style>
<script>
document.addEventListener("click", async (event) => {{
const button = event.target.closest("[data-copy]");
if (!button) return;
try {{
await navigator.clipboard.writeText(button.dataset.copy || "");
const old = button.textContent;
button.textContent = "Copied";
setTimeout(() => {{ button.textContent = old; }}, 1200);
}} catch (_) {{}}
}});
</script>
</head>
<body>{body}</body>
</html>
+29
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
@@ -13,6 +14,7 @@ class DdnsSettings(BaseModel):
admin_password: str = Field(default="")
allowed_hosts: set[str] = Field(default_factory=set)
public_base_url: str = Field(default="http://localhost:8080")
trusted_hosts: set[str] = Field(default_factory=set)
hostname_suffix: str = Field(default="")
verification_prefix: str = Field(default="_router_dyndns-ddns")
rate_limit_per_minute: int = Field(default=60, ge=1, le=10_000)
@@ -40,6 +42,31 @@ class DdnsSettings(BaseModel):
raise ValueError("public_base_url must start with http:// or https://")
return value.rstrip("/")
@field_validator("trusted_hosts")
@classmethod
def validate_trusted_hosts(cls, value: set[str]) -> set[str]:
return {host.strip().lower() for host in value if host.strip()}
@property
def effective_trusted_hosts(self) -> list[str]:
hosts = set(self.trusted_hosts)
public_host = urllib.parse.urlparse(self.public_base_url).hostname
if public_host:
hosts.add(public_host.lower())
if not self.require_dns_provider:
hosts.update({"testserver", "localhost", "127.0.0.1", "::1"})
return sorted(hosts)
def validate_launch_ready(self) -> None:
if not self.require_dns_provider:
return
if len(self.admin_password) < 16:
raise RuntimeError("DDNS_ADMIN_PASSWORD must be at least 16 characters when DDNS_REQUIRE_DNS_PROVIDER=1")
if not self.hostname_suffix:
raise RuntimeError("DDNS_HOSTNAME_SUFFIX is required when DDNS_REQUIRE_DNS_PROVIDER=1")
if not self.effective_trusted_hosts:
raise RuntimeError("At least one trusted host is required for production")
@classmethod
def from_env(cls) -> DdnsSettings:
allowed = {
@@ -48,6 +75,7 @@ class DdnsSettings(BaseModel):
if item.strip()
}
trusted_proxy_ips = _csv_set("DDNS_TRUSTED_PROXY_IPS")
trusted_hosts = _csv_set("DDNS_TRUSTED_HOSTS")
dns_zones = _csv_set("DDNS_DNS_ZONES")
return cls(
database_path=Path(os.getenv("DDNS_DATABASE", "ddns.sqlite3")),
@@ -55,6 +83,7 @@ class DdnsSettings(BaseModel):
admin_password=os.getenv("DDNS_ADMIN_PASSWORD", os.getenv("DDNS_SHARED_SECRET", "")),
allowed_hosts=allowed,
public_base_url=os.getenv("DDNS_PUBLIC_BASE_URL", "http://localhost:8080"),
trusted_hosts=trusted_hosts,
hostname_suffix=os.getenv("DDNS_HOSTNAME_SUFFIX", ""),
verification_prefix=os.getenv("DDNS_VERIFICATION_PREFIX", "_router_dyndns-ddns"),
rate_limit_per_minute=_env_int("DDNS_RATE_LIMIT_PER_MINUTE", 60),
+9 -2
View File
@@ -71,11 +71,18 @@ def is_rate_limited_path(path: str) -> bool:
"/verify-domain",
"/nic/update",
}
return path in limited_paths or path.startswith(("/u/", "/api/v1/updates/")) or path.startswith(
("/api/v1/hostnames/", "/api/v1/domains/")
return path in limited_paths or path.startswith(("/u/", "/m/", "/d/", "/api/v1/updates/")) or path.startswith(
("/api/v1/hostnames/", "/api/v1/domains/", "/api/v1/management/")
)
def rate_limit_bucket(path: str) -> str:
for prefix in ("/u/", "/m/", "/d/", "/api/v1/updates/", "/api/v1/management/"):
if path.startswith(prefix):
return prefix.rstrip("/")
return path
def _trusted_proxy(peer: str, trusted: set[str]) -> bool:
if not trusted:
return False