Skip to content
Closed
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
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]`

Expand Down
8 changes: 8 additions & 0 deletions src/everos/config/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions src/everos/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 0 additions & 9 deletions src/everos/core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
15 changes: 13 additions & 2 deletions src/everos/entrypoints/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
DEFAULT_CORS_ALLOW_HEADERS,
DEFAULT_CORS_ALLOW_METHODS,
DEFAULT_CORS_ORIGINS,
CrossSiteGuardMiddleware,
ProfileMiddleware,
PrometheusMiddleware,
RequestIdMiddleware,
Expand Down Expand Up @@ -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: ``["*"]``).
Expand Down Expand Up @@ -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
Expand Down
13 changes: 6 additions & 7 deletions src/everos/entrypoints/api/exception_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
)

Expand All @@ -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
)

Expand Down
6 changes: 5 additions & 1 deletion src/everos/entrypoints/api/middleware/__init__.py
Original file line number Diff line number Diff line change
@@ -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::

Expand All @@ -7,6 +8,7 @@
DEFAULT_CORS_ALLOW_HEADERS,
DEFAULT_CORS_ALLOW_METHODS,
DEFAULT_CORS_ORIGINS,
CrossSiteGuardMiddleware,
ProfileMiddleware,
PrometheusMiddleware,
)
Expand All @@ -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
Expand All @@ -26,6 +29,7 @@
"DEFAULT_CORS_ALLOW_HEADERS",
"DEFAULT_CORS_ALLOW_METHODS",
"DEFAULT_CORS_ORIGINS",
"CrossSiteGuardMiddleware",
"ProfileMiddleware",
"PrometheusMiddleware",
"RequestIdMiddleware",
Expand Down
6 changes: 4 additions & 2 deletions src/everos/entrypoints/api/middleware/cors.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"""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

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] = []
118 changes: 118 additions & 0 deletions src/everos/entrypoints/api/middleware/cross_site.py
Original file line number Diff line number Diff line change
@@ -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
Loading