From 754fee7a15d25e518bccd5ecc86f29b234673043 Mon Sep 17 00:00:00 2001 From: Lightning Pixel Date: Wed, 18 Nov 2026 09:33:28 +0100 Subject: [PATCH 1/2] feat(security): keep web pages off the local API, Ollama-style While Modly ran, any web page open in the browser could call the whole local API. The backend now refuses requests from web pages (Origin, or a cross-site Sec-Fetch-Site) unless their origin is in MODLY_ORIGINS, and refuses Host names that are not localhost, an IP or in MODLY_HOSTS (DNS rebinding). Scripts, CLIs, the MCP server, OrcaSlicer and extensions send neither header and need no token. The packaged window's file:// pages send Origin: null, like a sandboxed iframe on any site, so Electron adds X-Modly-App with a per-launch secret to the window's API requests; the backend gets it by env and drops it from os.environ. --- api/README.md | 15 +++ api/main.py | 14 +-- api/services/api_guard.py | 211 ++++++++++++++++++++++++++++++++ api/tests/test_api_guard.py | 180 +++++++++++++++++++++++++++ docs/running-on-jetson.md | 4 + electron/main/api-guard.test.ts | 36 ++++++ electron/main/api-guard.ts | 64 ++++++++++ electron/main/index.ts | 32 +++++ electron/main/python-bridge.ts | 6 + package.json | 2 +- 10 files changed, 553 insertions(+), 11 deletions(-) create mode 100644 api/services/api_guard.py create mode 100644 api/tests/test_api_guard.py create mode 100644 electron/main/api-guard.test.ts create mode 100644 electron/main/api-guard.ts diff --git a/api/README.md b/api/README.md index cdcd4d6b0..17d3b1bc7 100644 --- a/api/README.md +++ b/api/README.md @@ -21,6 +21,21 @@ pip install -r requirements.txt uvicorn main:app --host 127.0.0.1 --port 8765 --reload ``` +## Calling the API from other apps + +Scripts, CLIs and other programs (curl, `modly-cli`, the MCP server, OrcaSlicer…) can call the API +with no token or setup. + +**Web pages** are refused (403), so a site open in your browser cannot drive Modly. To let a web app +in, list its origin in `MODLY_ORIGINS` before starting Modly (comma-separated, `*` wildcards): + +```bash +MODLY_ORIGINS="http://localhost:3000,chrome-extension://*" # or "*" for every page +``` + +The request's `Host` must be `localhost` or an IP address (this blocks DNS rebinding). To reach the +API by a machine name, list it in `MODLY_HOSTS`, e.g. `MODLY_HOSTS=jetson.local`. + ## Key endpoints | Method | Path | Description | diff --git a/api/main.py b/api/main.py index 0526d2e37..70dbbd7d6 100644 --- a/api/main.py +++ b/api/main.py @@ -5,13 +5,14 @@ import logging from contextlib import asynccontextmanager from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi import HTTPException from services.stdio_utf8 import ensure_utf8_stdio ensure_utf8_stdio() # must run before any print/logging hits the pipe +from services import api_guard + from routers import generation, model, optimize, status, settings, extensions, export, workflow_runs, agent, llm, image @@ -48,15 +49,8 @@ def filter(self, record): lifespan=lifespan, ) -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_methods=["*"], - allow_headers=["*"], - # drei's SplatLoader reads Content-Length to size its buffers; cross-origin - # JS can only see it when the server explicitly exposes the header. - expose_headers=["Content-Length"], -) +# Web pages off the API (MODLY_ORIGINS / MODLY_HOSTS), and CORS. +api_guard.configure(app) app.include_router(status.router) app.include_router(settings.router) diff --git a/api/services/api_guard.py b/api/services/api_guard.py new file mode 100644 index 000000000..b4f7c7c17 --- /dev/null +++ b/api/services/api_guard.py @@ -0,0 +1,211 @@ +""" +Keeps web pages off the local API, the way Ollama does. + +The backend listens on 127.0.0.1, which every web page in the user's browser can +reach too. Browsers say where a request comes from (``Origin``, +``Sec-Fetch-Site``); other callers (scripts, curl, modly-cli, the MCP server, +OrcaSlicer, extensions) send neither. So: + +- A request from a web page is refused unless its origin is allowed: + the app's own pages, the origins in ``MODLY_ORIGINS`` (comma-separated, + ``*`` wildcards, e.g. ``http://localhost:*,chrome-extension://*``), or the + API's own origin (its /docs page). +- Any other request passes, with no token. +- The ``Host`` must be ``localhost``, an IP address, or a name in + ``MODLY_HOSTS``: a web page that points its own domain at 127.0.0.1 + (DNS rebinding) still sends that domain as the Host. + +The packaged app's pages are files, so their requests carry ``Origin: null``, +which any site can send too (from a sandboxed iframe). Electron therefore adds +``X-Modly-App: `` to its window's requests, with a secret made at each +launch and handed to the backend through ``MODLY_APP_SECRET`` only. +""" +from __future__ import annotations + +import hmac +import ipaddress +import json +import logging +import os +import re +from dataclasses import dataclass, field + +logger = logging.getLogger("modly.api_guard") + +ORIGINS_ENV = "MODLY_ORIGINS" +HOSTS_ENV = "MODLY_HOSTS" +APP_SECRET_ENV = "MODLY_APP_SECRET" +APP_ORIGINS_ENV = "MODLY_APP_ORIGINS" +APP_HEADER = "x-modly-app" + +# Origins the app's own pages send: a packaged build loads files, which send +# "null" (or "file://"); the dev renderer's origin comes in MODLY_APP_ORIGINS. +# Allowed by CORS only: a request from them still needs the app header. +FILE_ORIGINS = ("null", "file://") + +# Sec-Fetch-Site values that mean another site made the request. +_CROSS_SITE = ("cross-site", "same-site") + +_FORBIDDEN_BODY = json.dumps({ + "detail": "Requests from web pages are not allowed. Add the page's origin to MODLY_ORIGINS to allow it.", +}).encode("utf-8") + + +def _split(raw: str | None) -> list[str]: + return [item.strip() for item in (raw or "").split(",") if item.strip()] + + +def _trim(origin: str) -> str: + """``origin`` without a trailing slash, keeping the one of ``file://``.""" + return origin[:-1] if origin.endswith("/") and not origin.endswith("://") else origin + + +def _pattern(patterns: list[str]) -> re.Pattern[str] | None: + """One case-insensitive regex for ``*``-wildcard patterns, or None when empty.""" + if not patterns: + return None + parts = ["".join(".*" if ch == "*" else re.escape(ch) for ch in p) for p in map(_trim, patterns)] + return re.compile("(?:" + "|".join(parts) + ")", re.IGNORECASE) + + +@dataclass(frozen=True) +class GuardConfig: + """What the guard allows, read from the environment at startup.""" + + origins: list[str] = field(default_factory=list) + hosts: list[str] = field(default_factory=list) + app_origins: list[str] = field(default_factory=list) + app_secret: str | None = None + + @classmethod + def from_env(cls, env: os._Environ[str] | dict[str, str] | None = None) -> "GuardConfig": + env = os.environ if env is None else env + return cls( + origins=_split(env.get(ORIGINS_ENV)), + hosts=_split(env.get(HOSTS_ENV)), + app_origins=_split(env.get(APP_ORIGINS_ENV)), + app_secret=(env.get(APP_SECRET_ENV) or "").strip() or None, + ) + + def cors_origin_regex(self) -> str: + """Origins CORS lets read responses: the app's pages and MODLY_ORIGINS.""" + pattern = _pattern([*FILE_ORIGINS, *self.app_origins, *self.origins]) + assert pattern is not None + # Starlette compiles the string itself: carry the case-insensitive flag inline. + return "(?i)" + pattern.pattern + + +def _host_name(host: str) -> str: + """The name of a Host header value, without its port or IPv6 brackets.""" + host = host.strip().lower() + if host.startswith("["): + return host[1:].split("]", 1)[0] + return host.rsplit(":", 1)[0] if host.count(":") == 1 else host + + +def host_allowed(host: str | None, config: GuardConfig) -> bool: + if not host: + return True # HTTP/1.0 tools; every browser sends a Host + name = _host_name(host) + if name == "localhost": + return True + try: + ipaddress.ip_address(name) + return True + except ValueError: + pass + pattern = _pattern(config.hosts) + return bool(pattern and pattern.fullmatch(name)) + + +def origin_allowed(origin: str, config: GuardConfig) -> bool: + """Whether a web page at ``origin`` may call the API (MODLY_ORIGINS, or the dev renderer).""" + pattern = _pattern([*config.app_origins, *config.origins]) + return bool(pattern and pattern.fullmatch(_trim(origin))) + + +def _secret_matches(supplied: str | None, secret: str | None) -> bool: + if not supplied or not secret: + return False + return hmac.compare_digest(supplied.encode("utf-8"), secret.encode("utf-8")) + + +def is_allowed(method: str, headers: dict[str, str], config: GuardConfig) -> bool: + """The guard's whole rule. ``headers`` has lowercase names.""" + host = headers.get("host") + if not host_allowed(host, config): + return False + if method == "OPTIONS": + return True # CORS preflight: answered by CORS, runs nothing + if _secret_matches(headers.get(APP_HEADER), config.app_secret): + return True + + origin = headers.get("origin") + site = (headers.get("sec-fetch-site") or "").lower() + if origin is None and site not in _CROSS_SITE: + return True # not a web page: scripts, CLI, OrcaSlicer, a URL typed in the browser + if origin is None: + return False # another site's ,