pre-alpha

GuidesSecurity and checks

Restrict hosts, origins and HTTPS

implemented Updated November 20, 2026 7 min read

A new application answers any Host, sends no CORS headers, never redirects to HTTPS and trusts no proxy. That keeps development friction-free; before a deployment, name what it serves:

# notes/settings.py
from hinoki import settings


class ProjectSettings(settings.AppSettings, prefix="NOTES_", dotenv=".env"):
    allowed_hosts: tuple[str, ...] = ("api.example.com",)
    cors: settings.CorsSettings = settings.CorsSettings(
        origins=("https://app.example.com",),
    )
    security: settings.SecuritySettings = settings.SecuritySettings(
        redirect_https=True,
        hsts_seconds=31_536_000,
    )
    server: settings.ServerSettings = settings.ServerSettings(
        trusted_proxies=("10.20.0.0/16",),
    )

Every field can also come from the environment, which is usually where a deployment sets them:

NOTES_ALLOWED_HOSTS=api.example.com,.example.org
NOTES_CORS__ORIGINS=https://app.example.com,http://localhost:5173
NOTES_SECURITY__REDIRECT_HTTPS=true

Debug, allowed hosts and CORS

These three are off or permissive by default, so an application behaves the same until you set them.

debug

With debug on, the 500 internal_error answer for an unhandled exception also carries a debug object:

{
  "error": "internal_error",
  "request_id": "5f0c…",
  "debug": {
    "exception": "builtins.RuntimeError",
    "message": "the cache is cold",
    "traceback": ["Traceback (most recent call last):\n", "…"]
  }
}

Declared errors, validation errors and the other framework answers are unchanged, and the exception is logged either way. Exception messages can contain data you would not publish, so keep debug off in a deployment; each worker logs a warning at startup while it is on. debug changes nothing else: it does not enable documentation pages, relax authentication or skip the host check, and hinoki dev does not set it.

allowed_hosts

The Host header of every request must match one entry:

Entry Matches
* (the default) Any host; nothing is checked
api.example.com That host, on any port
.example.org example.org and every subdomain
127.0.0.1, ::1 That address ([::1]:8000 in the header)

Matching ignores case, the port and a trailing dot. The header must be exactly one host with an optional port; a request for another host, with two Host headers or without a usable one, receives 400 disallowed_host before routing, authentication and body reading; documentation routes are covered too. Entries are names: a scheme, port, path, non-ASCII text (write an international name in its ASCII IDNA form, xn--...) or a partial wildcard such as *.example.com fails at load, and * cannot be mixed with other entries. A dot entry is as wide as it reads: .com allows every .com host.

Set the list in a deployment that is reachable under more names than it should answer to. While allowed_hosts is * and debug is off, each worker logs a warning at startup (logger hinoki.runtime, shown with the default logging settings): every Host header is accepted, so links, redirects and cache keys built from it, such as a password-reset link, can name a host the client chose (Host header injection). Name the hosts the deployment serves to silence it, for example allowed_hosts=("app.example.com",), or (".example.com",) for a domain and its subdomains (NOTES_ALLOWED_HOSTS=app.example.com). It is a warning, not an error, so the default keeps working in development; with debug on it is not logged, and the in-process test clients (ASGIClient, SyncClient) and the MCP run_scenario tool, which receive no network Host header, do not log it either.

The in-process test clients send no Host header, so a test of an application with a restrictive list passes one: await client.get("/x", headers={"host": "api.example.com"}).

cors

CORS is off while cors.origins is empty: no header is added and OPTIONS requests receive 405. With origins configured:

  • A request whose Origin is listed receives access-control-allow-origin with that origin and vary: origin, on every answer including errors, so a browser client can read a 401 or 422 body. credentials = true adds access-control-allow-credentials: true; expose_headers is sent as access-control-expose-headers.
  • A request from any other origin, or without an Origin, is served normally without the permission headers and still carries vary: origin, so a shared cache never hands one origin's answer to another; the browser refuses to hand the response to the page. CORS tells browsers what to allow. It is not authentication and does not stop a non-browser client.
  • A preflight (OPTIONS with Origin and Access-Control-Request-Method) is answered with 204, the configured methods, headers and max_age, without reaching a route or its access policy. A preflight from an origin that is not listed receives 403 cors_origin_denied.

Origins are compared exactly, in lower case as browsers send them: https://app.example.com and https://app.example.com:8443 are different origins, and a trailing slash or path is refused at load. Browsers leave a default port out of Origin, so list https://app.example.com, not https://app.example.com:443. The single entry * answers every origin with access-control-allow-origin: *; it cannot be combined with credentials, and browsers will not send cookies or HTTP authentication to it.

The policy applies to the whole application, including the ASGI and WSGI adapters; there is no per-route CORS option. An answer that already sets access-control-allow-origin itself (a Response with that header) is sent as it is, without the policy's headers.

Security headers and HTTPS

Every HTTP response gets X-Content-Type-Options: nosniff, the configured X-Frame-Options and Referrer-Policy, including errors, OpenAPI/docs and admin responses. Defaults are SAMEORIGIN and same-origin, preserving the admin's existing referrer privacy default. These fields are owned by the app security policy: configured values replace same-named headers returned by a route.

The choices are enums rather than arbitrary strings, and environment/TOML values must match the listed wire values exactly. FrameOptions provides deny and sameorigin. ReferrerPolicy provides no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin and unsafe-url. unsafe-url can disclose the full referring URL to another origin; use it only when that is intended.

# notes/settings.py
from hinoki import settings


class ProjectSettings(settings.AppSettings, prefix="NOTES_", dotenv=".env"):
    security: settings.SecuritySettings = settings.SecuritySettings(
        redirect_https=True,
        hsts_seconds=31_536_000,
        hsts_include_subdomains=True,
        frame_options=settings.FrameOptions.DENY,
        referrer_policy=settings.ReferrerPolicy.STRICT_ORIGIN,
    )

For configuration loaded from the environment, set NOTES_ALLOWED_HOSTS=api.example.com and NOTES_SECURITY__REDIRECT_HTTPS=true. A wildcard host policy cannot be combined with the redirect: Hinoki requires an explicit host allowlist before constructing an absolute Location, which avoids redirecting an attacker supplied Host value. The redirect is 308, preserves the method and raw path/query, and runs before route lookup, authentication and body reading. A configured CORS preflight is answered before redirecting so browser preflight requests remain usable.

HSTS defaults off. Hinoki emits it only when the request's effective scheme is HTTPS. Behind TLS termination, configure the exact proxy addresses in server.trusted_proxies; an untrusted X-Forwarded-Proto does not enable HSTS or suppress the redirect. hsts_preload also requires hsts_include_subdomains and a max-age of at least one year. Use HSTS only after confirming that HTTPS is available for every covered host: browsers retain the policy after the response.

Reverse proxies and request IDs

Forwarded metadata is ignored unless the immediate socket peer matches server.trusted_proxies. Configure only the addresses or CIDRs of proxies that remove client-supplied forwarding headers and write their own values. For example:

# notes/settings.py
from hinoki import settings


class ProjectSettings(settings.AppSettings, prefix="NOTES_", dotenv=".env"):
    # The private address used by this deployment's ingress, not every private network.
    server: settings.ServerSettings = settings.ServerSettings(
        trusted_proxies=("10.20.0.0/16",),
        request_id_header="x-correlation-id",
        trust_request_id=True,
    )

From a trusted peer, Hinoki accepts a single X-Forwarded-Proto value of http or https and walks a bounded X-Forwarded-For chain from the peer side to the first untrusted address. Request.scheme and Request.client use those validated values. Invalid, repeated or ambiguous values fall back to the socket scope. X-Forwarded-Host is never used: Host, allowed_hosts and generated URLs continue to use the original Host header.

On a listener bound to ::, an IPv4 peer can appear as ::ffff:a.b.c.d, which a plain IPv4 entry does not match (the proxy is then untrusted); see behind a reverse proxy.

Request IDs are generated by default. With trust_request_id=True, one inbound configured header is accepted only from a trusted immediate peer and only when it is 1–128 visible ASCII characters without commas or controls. Otherwise Hinoki generates a new ID. The selected value appears in Request.request_id, built-in error JSON and the configured response header. The proxy must sanitize the incoming header before forwarding it; do not trust a broad network range merely because it is private.

Set logging.include_request_id=true to add the resolved ID to Hinoki's own log records while a request is being handled. Text logs append request_id=<id> and JSON logs include a request_id field. The ID matches the response's configured request ID header. Startup and other records outside a request omit the field. This setting is off by default, and it does not change application or third-party logger handlers.

Errors and edge cases

  • An invalid allowed_hosts entry, a * mixed with names, or a CORS origin with a path fails when settings load, before any worker starts.
  • redirect_https=True with allowed_hosts left at * is refused at load: the redirect needs a host it can trust.
  • A request for an unlisted host receives 400 disallowed_host; a preflight from an unlisted origin receives 403 cors_origin_denied.
  • Tests with a restrictive host list pass the header: await client.get("/health", headers={"host": "api.example.com"}).

See also

  • Settings: how values are loaded, named and inspected.
  • Kiso server: addresses behind a proxy on Kiso.
  • Errors: the JSON bodies of these answers.