From cb7fff2359fe33cbe224c6e5c24889b5753d7638 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:47:28 +0800 Subject: [PATCH] fix(api): refuse requests from browser pages of other sites CORS allowed every origin with credentials and only the purge routes checked Origin, so any page open in a browser on the same machine could read, write and delete memories through the loopback server; a page that rebinds its own domain to 127.0.0.1 could do the same. CrossSiteGuardMiddleware now answers 403 CROSS_SITE_REFUSED, on every route and preflight, to a request that carries another site's Origin or arrives under a public domain name in Host. IP addresses, single-label names and the reserved localhost / internal / test / invalid domains are always accepted. [api] cors_origins and [api] allowed_hosts list the web UIs and reverse-proxy domains a deployment needs; CORS allows no origin by default. The purge-only check is folded into the middleware. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 +++ SECURITY.md | 5 + docs/configuration.md | 2 + src/everos/config/default.toml | 8 + src/everos/config/settings.py | 16 ++ src/everos/core/errors.py | 9 -- src/everos/entrypoints/api/app.py | 15 +- .../entrypoints/api/exception_handlers.py | 13 +- .../entrypoints/api/middleware/__init__.py | 6 +- src/everos/entrypoints/api/middleware/cors.py | 6 +- .../entrypoints/api/middleware/cross_site.py | 118 +++++++++++++++ src/everos/entrypoints/api/routes/purge.py | 30 +--- .../test_middleware/test_cross_site.py | 141 ++++++++++++++++++ 13 files changed, 339 insertions(+), 47 deletions(-) create mode 100644 src/everos/entrypoints/api/middleware/cross_site.py create mode 100644 tests/unit/test_entrypoints/test_api/test_middleware/test_cross_site.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c53aceea0..1b7f63387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 their old ids; a batch sent before the upgrade and resent after it is not recognized as a resend. +### Security + +- **Browser pages of other sites can no longer call the API.** CORS used to + allow every origin, so any page open in a browser on the same machine could + read, write and delete memories through a loopback server, and a page that + rebinds its own domain to `127.0.0.1` could do the same. Every route now + answers `403 CROSS_SITE_REFUSED` to a request carrying another site's + `Origin` or arriving under a public domain name in `Host`. Before only the + purge routes refused cross-site requests. + +### Upgrade + +- curl, SDKs, MCP, the plugins and a compose service name are unaffected. A + web UI on another origin that calls the API from the browser needs its + origin in `[api] cors_origins`; a reverse proxy that forwards its own domain + in `Host` needs that domain in `[api] allowed_hosts`. + ## [1.7.1] - 2026-11-20 EverOS 1.7.1 writes each conversation's memory in its own language: a short diff --git a/SECURITY.md b/SECURITY.md index 79f72036a..9048803f9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -49,6 +49,11 @@ following in mind: is loopback-only. Only set the bind to `0.0.0.0` (or any routable interface) after you have placed your own gateway / auth layer in front; `everos server start` will log a warning when you bind to `0.0.0.0`. +- A browser on the same machine can reach a loopback server, so the API + refuses requests that only a browser page of another site would send: an + `Origin` of another site (unless listed in `[api] cors_origins`) and a + public domain name in `Host` (DNS rebinding; unless listed in + `[api] allowed_hosts`). - **Documents you ingest are untrusted input.** Filenames, metadata, and content that originate outside your control are parsed, indexed, and written to disk. An instance that ingests third-party documents is processing diff --git a/docs/configuration.md b/docs/configuration.md index 37f9145f7..c288b9a11 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -84,6 +84,8 @@ everos init --root /data/everos |---|---|---|---| | `host` | string | `"127.0.0.1"` | HTTP server bind address. | | `port` | int | `8000` | HTTP server bind port (1–65535). | +| `allowed_hosts` | list[string] | `[]` | Public domain names the server is reached under, such as a reverse proxy's. A request whose `Host` is any other public domain is refused with `403 CROSS_SITE_REFUSED`, which stops DNS rebinding. IP addresses, single-label names (a compose service) and the `localhost` / `internal` / `test` / `invalid` domains are always accepted; `"*"` accepts any. | +| `cors_origins` | list[string] | `[]` | Browser origins (`scheme://host[:port]`) allowed to call the API from another site, such as a local web UI. A request carrying any other site's `Origin` is refused with `403 CROSS_SITE_REFUSED`; curl, SDKs, MCP and the plugins send no `Origin` and are unaffected. `"*"` allows any site. | ### `[sqlite]` diff --git a/src/everos/config/default.toml b/src/everos/config/default.toml index 877290154..065af7bb5 100644 --- a/src/everos/config/default.toml +++ b/src/everos/config/default.toml @@ -25,6 +25,14 @@ timezone = "UTC" # Override via EVEROS_API__HOST and EVEROS_API__PORT. host = "127.0.0.1" port = 8000 +# Browsers on this machine can reach a loopback server too, so requests are +# refused when a browser page of another site sends them (its ``Origin``) or +# when they arrive under a public domain name (``Host``; DNS rebinding). +# IP addresses, single-label names and the localhost / internal / test / +# invalid domains are always accepted. List a reverse proxy's domain here: +# allowed_hosts = ["memory.example.com"] # EVEROS_API__ALLOWED_HOSTS +# and the origin of a web UI that calls the API from the browser: +# cors_origins = ["http://localhost:3000"] # EVEROS_API__CORS_ORIGINS [sqlite] # PRAGMA journal_mode — WAL is the recommended high-concurrency mode. diff --git a/src/everos/config/settings.py b/src/everos/config/settings.py index 2051bac92..cb757d3aa 100644 --- a/src/everos/config/settings.py +++ b/src/everos/config/settings.py @@ -110,13 +110,29 @@ class ApiSettings(BaseModel): (``0.0.0.0`` etc.) without your own gateway / auth layer in front is unsupported. + A browser can still reach a loopback server: a page of another site can + send it requests, and DNS rebinding can make such a page same-origin with + it. Requests are therefore refused when their ``Host`` is a public domain + name not listed in ``allowed_hosts``, or when they carry the ``Origin`` of + another site not listed in ``cors_origins``. + Env binding: EVEROS_API__HOST EVEROS_API__PORT + EVEROS_API__ALLOWED_HOSTS (JSON list, e.g. '["memory.example.com"]') + EVEROS_API__CORS_ORIGINS (JSON list, e.g. '["http://localhost:3000"]') """ host: str = "127.0.0.1" port: int = Field(default=8000, ge=1, le=65535) + allowed_hosts: list[str] = [] + """Public domain names this server is reached under, such as a reverse + proxy's (``"*"`` accepts any). IP addresses, single-label names and the + reserved ``localhost`` / ``internal`` / ``test`` / ``invalid`` domains are + always accepted.""" + cors_origins: list[str] = [] + """Browser origins (``scheme://host[:port]``) allowed to call the API from + another site, such as a local web UI. Empty: none; ``"*"``: any.""" class SqliteSettings(BaseModel): diff --git a/src/everos/core/errors.py b/src/everos/core/errors.py index 7dbcd99ef..5049744f1 100644 --- a/src/everos/core/errors.py +++ b/src/everos/core/errors.py @@ -179,15 +179,6 @@ class PurgeInProgressError(DomainError): """ -class CrossSiteRefusedError(DomainError): - """A browser page of another site asked for a purge. - - Nothing was counted or deleted. The API layer maps it to HTTP 403 - ``CROSS_SITE_REFUSED``; the caller purges from a client that is not a - browser page of another site (curl, an SDK, a plugin). - """ - - class PurgeNonceInvalidError(DomainError): """A purge confirmation named an unknown, expired or already-used nonce. diff --git a/src/everos/entrypoints/api/app.py b/src/everos/entrypoints/api/app.py index e1a5d505d..d25e94540 100644 --- a/src/everos/entrypoints/api/app.py +++ b/src/everos/entrypoints/api/app.py @@ -25,6 +25,7 @@ DEFAULT_CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_METHODS, DEFAULT_CORS_ORIGINS, + CrossSiteGuardMiddleware, ProfileMiddleware, PrometheusMiddleware, RequestIdMiddleware, @@ -72,7 +73,8 @@ def create_app( application: A pre-built application (tests inject one assembled over fakes). It is reachable by routes at once, and the lifespan starts and closes it like one it built itself. - cors_origins: Allowed CORS origins (default: ``["*"]``). + cors_origins: Allowed CORS origins (default: ``[api] cors_origins``, + which is empty: no other site may call the API from a browser). cors_allow_credentials: Whether to allow credentials (default: True). cors_allow_methods: Allowed CORS methods (default: ``["*"]``). cors_allow_headers: Allowed CORS headers (default: ``["*"]``). @@ -114,13 +116,22 @@ async def lifespan(fastapi_app: FastAPI) -> AsyncIterator[None]: # Write tracking innermost: it stamps the request the handler runs in. app.add_middleware(WriteTrackingMiddleware) # CORS next (matches base_app.py legacy pattern). + api = (settings or load_settings()).api + origins = cors_origins or api.cors_origins or DEFAULT_CORS_ORIGINS app.add_middleware( CORSMiddleware, - allow_origins=cors_origins or DEFAULT_CORS_ORIGINS, + allow_origins=origins, allow_credentials=cors_allow_credentials, allow_methods=cors_allow_methods or DEFAULT_CORS_ALLOW_METHODS, allow_headers=cors_allow_headers or DEFAULT_CORS_ALLOW_HEADERS, ) + # Outside CORS, so it also answers preflights: a browser page of another + # site, or one rebinding a public name to this server, gets 403. + app.add_middleware( + CrossSiteGuardMiddleware, + allowed_hosts=api.allowed_hosts, + allowed_origins=origins, + ) app.add_middleware(PrometheusMiddleware) app.add_middleware(ProfileMiddleware) # Outermost: every request gets a request id before any other middleware diff --git a/src/everos/entrypoints/api/exception_handlers.py b/src/everos/entrypoints/api/exception_handlers.py index 659ee762b..8962ea0a3 100644 --- a/src/everos/entrypoints/api/exception_handlers.py +++ b/src/everos/entrypoints/api/exception_handlers.py @@ -36,7 +36,7 @@ class -> status code, ``ErrorCode``, optional fixed message and optional log type _Handler = Callable[[Request, Exception], Awaitable[JSONResponse]] -def _error_response( +def error_response( request: Request, status_code: int, code: ErrorCode, message: str ) -> JSONResponse: """Build a JSONResponse with the canonical error envelope.""" @@ -87,7 +87,6 @@ class _Rule: # A deletion that found its session busy deleted nothing: retry later. errors.SessionBusyError: _Rule(503, ErrorCode.SESSION_BUSY), errors.PurgeInProgressError: _Rule(409, ErrorCode.PURGE_IN_PROGRESS), - errors.CrossSiteRefusedError: _Rule(403, ErrorCode.CROSS_SITE_REFUSED), errors.PurgeNonceInvalidError: _Rule(404, ErrorCode.PURGE_NONCE_INVALID), errors.DeletionIncompleteError: _Rule( 500, @@ -136,7 +135,7 @@ async def handle(request: Request, exc: Exception) -> JSONResponse: fields = rule.log_fields(exc) getattr(logger, level)(event, path=str(request.url.path), **fields) message = str(exc) if rule.message is None else rule.message - return _error_response(request, rule.status_code, rule.code, message) + return error_response(request, rule.status_code, rule.code, message) return handle @@ -174,18 +173,18 @@ async def request_validation_handler( ) -> JSONResponse: """FastAPI RequestValidationError -> 422.""" message = _validation_message(exc) - return _error_response(request, 422, ErrorCode.INVALID_INPUT, message) + return error_response(request, 422, ErrorCode.INVALID_INPUT, message) async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse: """FastAPI HTTPException -> its own status code; a 5xx hides ``detail``.""" if exc.status_code < 500: - return _error_response( + return error_response( request, exc.status_code, ErrorCode.BAD_REQUEST, str(exc.detail) ) path = str(request.url.path) logger.error("http_exception_5xx", path=path, status_code=exc.status_code) - return _error_response( + return error_response( request, exc.status_code, ErrorCode.INTERNAL_ERROR, _INTERNAL_ERROR_MESSAGE ) @@ -198,7 +197,7 @@ async def unexpected_handler(request: Request, exc: Exception) -> JSONResponse: exception_type=type(exc).__name__, exc_info=True, ) - return _error_response( + return error_response( request, 500, ErrorCode.INTERNAL_ERROR, _INTERNAL_ERROR_MESSAGE ) diff --git a/src/everos/entrypoints/api/middleware/__init__.py b/src/everos/entrypoints/api/middleware/__init__.py index 333b09531..de2ae786a 100644 --- a/src/everos/entrypoints/api/middleware/__init__.py +++ b/src/everos/entrypoints/api/middleware/__init__.py @@ -1,4 +1,5 @@ -"""The HTTP API layer's middleware (CORS defaults, profiling, metrics, request id). +"""The HTTP API layer's middleware (CORS defaults, cross-site guard, profiling, +metrics, request id). External usage:: @@ -7,6 +8,7 @@ DEFAULT_CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_METHODS, DEFAULT_CORS_ORIGINS, + CrossSiteGuardMiddleware, ProfileMiddleware, PrometheusMiddleware, ) @@ -16,6 +18,7 @@ from .cors import DEFAULT_CORS_ALLOW_HEADERS as DEFAULT_CORS_ALLOW_HEADERS from .cors import DEFAULT_CORS_ALLOW_METHODS as DEFAULT_CORS_ALLOW_METHODS from .cors import DEFAULT_CORS_ORIGINS as DEFAULT_CORS_ORIGINS +from .cross_site import CrossSiteGuardMiddleware as CrossSiteGuardMiddleware from .profile import ProfileMiddleware as ProfileMiddleware from .prometheus import PrometheusMiddleware as PrometheusMiddleware from .request_id import RequestIdMiddleware as RequestIdMiddleware @@ -26,6 +29,7 @@ "DEFAULT_CORS_ALLOW_HEADERS", "DEFAULT_CORS_ALLOW_METHODS", "DEFAULT_CORS_ORIGINS", + "CrossSiteGuardMiddleware", "ProfileMiddleware", "PrometheusMiddleware", "RequestIdMiddleware", diff --git a/src/everos/entrypoints/api/middleware/cors.py b/src/everos/entrypoints/api/middleware/cors.py index c5fad3c27..6826a211a 100644 --- a/src/everos/entrypoints/api/middleware/cors.py +++ b/src/everos/entrypoints/api/middleware/cors.py @@ -1,7 +1,9 @@ """CORS configuration defaults. The CORS middleware itself is FastAPI's stock ``CORSMiddleware``; this module -centralises the default policy values used by the application factory. +centralises the default policy values used by the application factory. No +origin is allowed by default: browser pages of other sites may not call the +API unless ``[api] cors_origins`` lists them. """ from __future__ import annotations @@ -9,4 +11,4 @@ DEFAULT_CORS_ALLOW_CREDENTIALS: bool = True DEFAULT_CORS_ALLOW_HEADERS: list[str] = ["*"] DEFAULT_CORS_ALLOW_METHODS: list[str] = ["*"] -DEFAULT_CORS_ORIGINS: list[str] = ["*"] +DEFAULT_CORS_ORIGINS: list[str] = [] diff --git a/src/everos/entrypoints/api/middleware/cross_site.py b/src/everos/entrypoints/api/middleware/cross_site.py new file mode 100644 index 000000000..b7bed1343 --- /dev/null +++ b/src/everos/entrypoints/api/middleware/cross_site.py @@ -0,0 +1,118 @@ +"""Refuse what only a browser page of another site would send. + +EverOS has no authentication: its boundary is "only this machine can connect" +(``[api] host`` defaults to loopback). A browser on that machine crosses it in +two ways, and this middleware closes both: + +* **Cross-site requests.** Any page the user opens can send requests to + ``127.0.0.1``. Browsers put an ``Origin`` header on every cross-site request + and every ``POST``; curl, SDKs, MCP and the plugins send none. A request + whose ``Origin`` is neither this server's own nor listed in + ``[api] cors_origins`` is refused. +* **DNS rebinding.** A page of ``attacker.com`` re-points its own name at + ``127.0.0.1`` and is then same-origin with this server, so ``Origin`` alone + cannot tell it apart. Rebinding needs a public domain the attacker controls, + so a request is refused when its ``Host`` is such a name and not listed in + ``[api] allowed_hosts``. IP addresses, single-label names (``everos`` in a + compose network) and names under the TLDs reserved from public registration + (``localhost``, ``internal``, ``test``, ``invalid``) are always accepted. + +Refusals answer ``403 CROSS_SITE_REFUSED`` in the usual error envelope and +cover every route, including CORS preflights, ``/health`` and ``/metrics``. +""" + +from __future__ import annotations + +__all__ = ["CrossSiteGuardMiddleware"] + +import ipaddress +from collections.abc import Collection +from urllib.parse import urlsplit + +from starlette.requests import Request +from starlette.types import ASGIApp, Receive, Scope, Send + +from everos.core.errors import ErrorCode +from everos.core.observability.logging import get_logger + +from ..exception_handlers import error_response + +logger = get_logger(__name__) + +_RESERVED_TLDS = frozenset({"localhost", "internal", "test", "invalid"}) + + +def _host_is_private(hostname: str) -> bool: + """Whether no one else can make a browser resolve ``hostname`` to us.""" + try: + ipaddress.ip_address(hostname) + except ValueError: + return "." not in hostname or hostname.rsplit(".", 1)[1] in _RESERVED_TLDS + return True + + +class CrossSiteGuardMiddleware: + """Pure ASGI middleware; see the module docstring for the rules. + + Args: + app: The wrapped ASGI app. + allowed_hosts: ``[api] allowed_hosts``; ``"*"`` accepts any ``Host``. + allowed_origins: ``[api] cors_origins``; ``"*"`` accepts any ``Origin``. + """ + + def __init__( + self, + app: ASGIApp, + *, + allowed_hosts: Collection[str] = (), + allowed_origins: Collection[str] = (), + ) -> None: + self._app = app + self._hosts = {h.lower() for h in allowed_hosts} + self._origins = {o.lower().rstrip("/") for o in allowed_origins} + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self._app(scope, receive, send) + return + request = Request(scope) + reason = self._refusal(request) + if reason is None: + await self._app(scope, receive, send) + return + logger.warning( + "cross_site_refused", + path=request.url.path, + host=request.headers.get("host"), + origin=request.headers.get("origin"), + ) + response = error_response(request, 403, ErrorCode.CROSS_SITE_REFUSED, reason) + await response(scope, receive, send) + + def _refusal(self, request: Request) -> str | None: + host = request.headers.get("host", "") + hostname = urlsplit(f"//{host}").hostname if host else None + if ( + hostname is not None + and "*" not in self._hosts + and hostname not in self._hosts + and not _host_is_private(hostname) + ): + return ( + f"host {hostname!r} is not accepted; if this server is reached " + "under that name, add it to [api] allowed_hosts " + "(EVEROS_API__ALLOWED_HOSTS)" + ) + origin = request.headers.get("origin") + if ( + origin is not None + and "*" not in self._origins + and origin.lower().rstrip("/") not in self._origins + and urlsplit(origin).netloc.lower() != host.lower() + ): + return ( + "requests from a browser page of another site are refused; " + "to allow that site, add its origin to [api] cors_origins " + "(EVEROS_API__CORS_ORIGINS)" + ) + return None diff --git a/src/everos/entrypoints/api/routes/purge.py b/src/everos/entrypoints/api/routes/purge.py index 3444c3e6a..a7eb8c26d 100644 --- a/src/everos/entrypoints/api/routes/purge.py +++ b/src/everos/entrypoints/api/routes/purge.py @@ -3,11 +3,9 @@ from __future__ import annotations from typing import Annotated, Any -from urllib.parse import urlsplit -from fastapi import APIRouter, Depends, Path, Request +from fastapi import APIRouter, Path -from everos.core.errors import CrossSiteRefusedError from everos.entrypoints.api.dependencies import ApplicationDep, RequestIdDep from everos.entrypoints.api.schemas import ( ErrorResponse, @@ -30,23 +28,8 @@ """The answer of a write route while a purge clears the range it names.""" -def _refuse_cross_site(request: Request) -> None: - """Refuse a purge sent by a browser page of another site. - - There is no authentication and CORS allows any origin by default, so any - page the user opens could read a nonce and confirm it. Browsers send - ``Origin`` with these requests; curl, SDKs, MCP and the plugins send - none and pass, and so does a page this server serves itself. - """ - origin = request.headers.get("origin") - host = request.headers.get("host", "") - if origin is not None and urlsplit(origin).netloc.lower() != host.lower(): - raise CrossSiteRefusedError( - "a purge is refused from a browser page of another site; " - "send it from curl, an SDK or a plugin" - ) - - +# Every route refuses browser pages of other sites (CrossSiteGuardMiddleware); +# the purge routes document it because they are the irreversible ones. _CROSS_SITE_RESPONSE: dict[int | str, dict[str, Any]] = { 403: { "model": ErrorResponse, @@ -59,11 +42,7 @@ def _refuse_cross_site(request: Request) -> None: ] -@router.post( - "/purge", - dependencies=[Depends(_refuse_cross_site)], - responses=_CROSS_SITE_RESPONSE, -) +@router.post("/purge", responses=_CROSS_SITE_RESPONSE) async def request_purge( req: PurgeRequest, app: ApplicationDep, request_id: RequestIdDep ) -> SuccessEnvelope[PurgeRequestData]: @@ -81,7 +60,6 @@ async def request_purge( @router.post( "/purge/confirm", status_code=202, - dependencies=[Depends(_refuse_cross_site)], responses={ **_CROSS_SITE_RESPONSE, 404: { diff --git a/tests/unit/test_entrypoints/test_api/test_middleware/test_cross_site.py b/tests/unit/test_entrypoints/test_api/test_middleware/test_cross_site.py new file mode 100644 index 000000000..7d6094529 --- /dev/null +++ b/tests/unit/test_entrypoints/test_api/test_middleware/test_cross_site.py @@ -0,0 +1,141 @@ +"""CrossSiteGuardMiddleware: a browser page of another site cannot drive the API. + +The server has no authentication and listens on loopback; a browser on the same +machine is the way around that. These tests pin both doors: an ``Origin`` of +another site (CSRF / cross-site reads) and a public ``Host`` (DNS rebinding). +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Sequence + +import pytest +from httpx import ASGITransport, AsyncClient + +from everos.config import load_settings +from everos.entrypoints.api.app import create_app +from tests.fakes import make_application + + +def _client( + base_url: str = "http://127.0.0.1:8000", + *, + allowed_hosts: Sequence[str] = (), + cors_origins: Sequence[str] = (), +) -> AsyncClient: + base = load_settings() + hosts, origins = list(allowed_hosts), list(cors_origins) + api = base.api.model_copy(update={"allowed_hosts": hosts, "cors_origins": origins}) + settings = base.model_copy(update={"api": api}) + app = create_app(settings, application=make_application()) + return AsyncClient(transport=ASGITransport(app=app), base_url=base_url) + + +@pytest.fixture +async def client() -> AsyncIterator[AsyncClient]: + async with _client() as c: + yield c + + +def _refused(resp: object) -> bool: + status = resp.status_code # type: ignore[attr-defined] + if status != 403: + return False + body = resp.json() # type: ignore[attr-defined] + assert body["error"]["code"] == "CROSS_SITE_REFUSED" + assert body["request_id"] + return True + + +@pytest.mark.parametrize( + ("host", "accepted"), + [ + ("127.0.0.1:8000", True), + ("localhost:8000", True), + ("[::1]:8000", True), + ("192.168.1.20:8000", True), # bound to a LAN address + ("everos:8000", True), # a compose / k8s service name + ("gw.internal", True), # reserved TLDs: nobody can register them + ("server.test", True), + ("app.localhost:8000", True), + ("attacker.com:8000", False), # DNS rebinding needs a public name + ("attacker.example:8000", False), + ("127.0.0.1.nip.io:8000", False), # public name that resolves to loopback + ("memory.example.com", False), + ], +) +async def test_host_must_not_be_a_public_name(host: str, accepted: bool) -> None: + async with _client() as c: + resp = await c.get("/health", headers={"host": host}) + assert _refused(resp) is not accepted, resp.text + + +async def test_a_listed_public_name_is_accepted() -> None: + async with _client(allowed_hosts=["Memory.Example.com"]) as c: + listed = await c.get("/health", headers={"host": "memory.example.com"}) + other = await c.get("/health", headers={"host": "attacker.com"}) + assert listed.status_code == 200, listed.text + assert _refused(other) + + +async def test_a_star_accepts_any_host() -> None: + async with _client(allowed_hosts=["*"]) as c: + resp = await c.get("/health", headers={"host": "attacker.com"}) + assert resp.status_code == 200, resp.text + + +@pytest.mark.parametrize( + ("origin", "accepted"), + [ + (None, True), # curl, SDKs, MCP, plugins send no Origin + ("http://127.0.0.1:8000", True), # a page this server serves itself + ("HTTP://127.0.0.1:8000", True), + ("http://127.0.0.1:8001", False), # same host, another port: another site + ("http://localhost:3000", False), # a local web UI, until it is listed + ("https://evil.example", False), + ("null", False), # a sandboxed or file:// page + ], +) +async def test_origin_must_be_this_server( + client: AsyncClient, origin: str | None, accepted: bool +) -> None: + headers = {"origin": origin} if origin is not None else {} + get = await client.get("/health", headers=headers) + post = await client.post("/api/v2/memory/search", json={}, headers=headers) + assert _refused(get) is not accepted, get.text + assert _refused(post) is not accepted, post.text + + +async def test_a_foreign_preflight_is_refused_without_cors_headers( + client: AsyncClient, +) -> None: + resp = await client.options( + "/api/v2/memory/search", + headers={ + "origin": "https://evil.example", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + ) + assert _refused(resp) + assert "access-control-allow-origin" not in resp.headers + + +async def test_a_listed_origin_gets_cors_and_passes() -> None: + ui = "http://localhost:3000" + async with _client(cors_origins=[ui]) as c: + preflight = await c.options( + "/api/v2/memory/search", + headers={ + "origin": ui, + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + ) + get = await c.get("/health", headers={"origin": ui}) + other = await c.get("/health", headers={"origin": "https://evil.example"}) + assert preflight.status_code == 200, preflight.text + assert preflight.headers["access-control-allow-origin"] == ui + assert get.status_code == 200, get.text + assert get.headers["access-control-allow-origin"] == ui + assert _refused(other)