From 6a94bc599a909a15adda75562bdad11fa9b5415d Mon Sep 17 00:00:00 2001 From: skl Date: Thu, 8 Oct 2026 04:36:08 +0200 Subject: [PATCH 1/3] Access token for the public tunnel launcher.py publishes Apollo on a public trycloudflare.com URL, and Apollo had no authentication: anyone with the link could read uploaded documents, upload files and run ComfyUI or LoRA jobs on the host GPU. The tunnel's requests reach uvicorn from localhost, so the fix cannot trust "local" either. - With APOLLO_ACCESS_TOKEN set, every request except /live and /health needs the token: the X-Apollo-Token header, or an HttpOnly, SameSite=Lax cookie that opening /?token= sets once (then redirects without the token). Constant-time comparison. Unset, Apollo stays open as a local tool. - The launcher generates a token (unless you set one), and prints, copies and opens the link with the token. - 6 tests; checked in a browser: no token 401, the link sets the cookie and lands on /, all 7 of the page's API calls succeed. 259 tests pass. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++++++- app/main.py | 37 +++++++++++++++++- launcher.py | 24 +++++++++--- tests/test_access_token.py | 77 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 tests/test_access_token.py diff --git a/README.md b/README.md index 4918ad0..95b55a8 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Each module is independent: **chat and RAG keep working when ComfyUI, Ollama, or python launcher.py ``` -Open **http://localhost:8000**, or use the auto-generated Cloudflare tunnel URL for a public demo. +Open **http://localhost:8000**, or use the auto-generated Cloudflare tunnel URL for a public demo. The launcher protects that public URL with an access token: it prints (and copies) a link ending in `?token=...`, and only people with that link get in. --- @@ -219,7 +219,15 @@ python -m pip install -r requirements.txt python launcher.py ``` -Starts the API, waits for `/health`, launches a Cloudflare quick tunnel, copies the public URL to clipboard, and opens the dashboard. +Starts the API, waits for `/health`, launches a Cloudflare quick tunnel, copies the public link to the clipboard, and opens the dashboard. + +Because the tunnel makes Apollo reachable from the internet, the launcher sets an access token (`APOLLO_ACCESS_TOKEN`, random unless you set your own): + +- **Browsers:** the printed link ends in `?token=...`. Opening it once sets an HttpOnly cookie and drops the token from the address bar. +- **API clients:** send the `X-Apollo-Token` header. +- **Open probes:** `/live` and `/health` stay open for health checks. + +Run uvicorn directly without the variable and Apollo stays open, as a local tool. **Local API only:** @@ -262,6 +270,7 @@ python main.py --api | `DATA_DIR` | `./data` | Where `documents.json` / `sessions.json` persistence lives | | `MAX_IMAGE_UPLOAD_MB` | `25` | Per-image cap for dataset uploads | | `PORT` | `8000` | Server port (`launcher.py`) | +| `APOLLO_ACCESS_TOKEN` | unset (the launcher generates one) | When set, every request except `/live` and `/health` needs this token | | `CLOUDFLARED_PATH` | auto-detect | Path to `cloudflared` executable | A `.env` file in the project root is loaded automatically (real environment diff --git a/app/main.py b/app/main.py index cffde65..13d9a77 100644 --- a/app/main.py +++ b/app/main.py @@ -1,9 +1,12 @@ +import hmac import logging +import os from pathlib import Path +from urllib.parse import urlencode -from fastapi import FastAPI +from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, PlainTextResponse, RedirectResponse from app.api.comfyui_routes import jobs_router from app.api.comfyui_routes import router as comfyui_router @@ -38,6 +41,9 @@ def _iter_api_routes(routes): yield route +ACCESS_COOKIE = "apollo_access" + + def create_app(service: object | None = None) -> FastAPI: """Create and configure the FastAPI application. @@ -66,6 +72,33 @@ def create_app(service: object | None = None) -> FastAPI: allow_headers=["*"], # Allow all headers ) + # ============ ACCESS TOKEN (optional) ============ + # launcher.py publishes Apollo through a public Cloudflare tunnel whose traffic reaches + # uvicorn from localhost, so "local" proves nothing. With APOLLO_ACCESS_TOKEN set, every + # request needs that token: the X-Apollo-Token header, or the cookie set by opening + # /?token= once. Unset (a plain local run) leaves Apollo open, as before. + @app.middleware("http") + async def require_access_token(request: Request, call_next): + token = os.environ.get("APOLLO_ACCESS_TOKEN", "") + if not token or request.url.path in ("/live", "/health"): + return await call_next(request) + offered = request.query_params.get("token") + if offered is not None and hmac.compare_digest(offered.encode(), token.encode()): + rest = urlencode([(k, v) for k, v in request.query_params.multi_items() if k != "token"]) + response = RedirectResponse(request.url.path + (f"?{rest}" if rest else ""), status_code=303) + https = request.url.scheme == "https" or request.headers.get("x-forwarded-proto") == "https" + response.set_cookie(ACCESS_COOKIE, token, max_age=30 * 24 * 3600, httponly=True, + samesite="lax", secure=https) + return response + presented = request.headers.get("x-apollo-token") or request.cookies.get(ACCESS_COOKIE) or "" + if hmac.compare_digest(presented.encode(), token.encode()): + return await call_next(request) + return PlainTextResponse( + "Apollo is private. Open the link launcher.py printed (it ends in ?token=...), " + "or send the X-Apollo-Token header.", + status_code=401, + ) + # ============ INITIALIZE SERVICES ============ app.state.llm_service = service or LLMService() app.state.memory_service = MemoryService() diff --git a/launcher.py b/launcher.py index 1663ce1..7d6146f 100644 --- a/launcher.py +++ b/launcher.py @@ -10,6 +10,7 @@ import atexit import os import re +import secrets import signal import subprocess import sys @@ -106,19 +107,27 @@ def _on_tunnel_line(line: str) -> None: _announce_public_url(_public_url) +def _with_token(base: str) -> str: + """The dashboard link that carries the access token (opening it once sets a cookie).""" + token = os.environ.get("APOLLO_ACCESS_TOKEN") + return f"{base}/?token={token}" if token else base + + def _announce_public_url(url: str) -> None: """Print, copy, and open the public dashboard URL.""" + link = _with_token(url) print("\n" + "=" * 70) print(" APOLLO — LIVE") print("=" * 70) - print(f"\n Local: http://localhost:{PORT}") - print(f" Public: {url}") - print(f" API: {url}/chat") + print(f"\n Local: {_with_token(f'http://localhost:{PORT}')}") + print(f" Public: {link}") + print(f" API: {url}/chat (send the X-Apollo-Token header)") + print(" Only people with this link can open Apollo; keep it private.") print() if pyperclip is not None: try: - pyperclip.copy(url) + pyperclip.copy(link) print(" Clipboard: public URL copied") except pyperclip.PyperclipException as exc: print(f" Clipboard: could not copy ({exc})") @@ -128,7 +137,7 @@ def _announce_public_url(url: str) -> None: print("\n Opening dashboard in browser...") print("=" * 70 + "\n", flush=True) - webbrowser.open(url) + webbrowser.open(link) _url_announced.set() @@ -386,6 +395,9 @@ def main() -> int: print(f"ERROR: {exc}", file=sys.stderr) return 1 + # The quick tunnel makes Apollo reachable from the internet, so the API gets an access token + # (keep your own by setting APOLLO_ACCESS_TOKEN). uvicorn inherits it from this environment. + os.environ.setdefault("APOLLO_ACCESS_TOKEN", secrets.token_urlsafe(24)) uvicorn_proc = _start_uvicorn() startup = _wait_for_backend() if not startup.ok: @@ -412,7 +424,7 @@ def _local_fallback() -> None: f"http://localhost:{PORT}\n", flush=True, ) - webbrowser.open(f"http://localhost:{PORT}") + webbrowser.open(_with_token(f"http://localhost:{PORT}")) threading.Thread(target=_local_fallback, daemon=True).start() diff --git a/tests/test_access_token.py b/tests/test_access_token.py new file mode 100644 index 0000000..9e53a9a --- /dev/null +++ b/tests/test_access_token.py @@ -0,0 +1,77 @@ +"""Optional access token: off by default, required everywhere (but /live and /health) once set.""" + +import pytest +from fastapi.testclient import TestClient + +TOKEN = "test-token-123" + + +class StubLLM: + def health_check(self): + return {"status": "ok", "ollama_reachable": True, "model": "llama3.2"} + + def chat(self, prompt, model=None): + return f"echo:{prompt}" + + def list_models(self): + return ["llama3.2"] + + +@pytest.fixture +def make_client(tmp_settings): + from app.main import create_app + + def _make(): + return TestClient(create_app(service=StubLLM())) + + return _make + + +def test_without_a_token_configured_apollo_stays_open(make_client, monkeypatch): + monkeypatch.delenv("APOLLO_ACCESS_TOKEN", raising=False) + with make_client() as client: + assert client.get("/").status_code == 200 + + +def test_with_a_token_every_page_and_route_needs_it(make_client, monkeypatch): + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + assert client.get("/").status_code == 401 + assert client.get("/prompts").status_code == 401 + assert client.get("/", headers={"X-Apollo-Token": "wrong"}).status_code == 401 + assert client.get("/", headers={"X-Apollo-Token": TOKEN}).status_code == 200 + + +def test_probes_stay_open_for_the_launcher(make_client, monkeypatch): + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + assert client.get("/live").status_code != 401 + assert client.get("/health").status_code != 401 + + +def test_the_token_link_sets_a_cookie_and_drops_the_token_from_the_url(make_client, monkeypatch): + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + first = client.get(f"/?token={TOKEN}&tab=docs", follow_redirects=False) + assert first.status_code == 303 + assert first.headers["location"] == "/?tab=docs" + cookie = first.headers["set-cookie"].lower() + assert "httponly" in cookie and "samesite=lax" in cookie + assert client.get("/").status_code == 200 # the client kept the cookie + + +def test_a_wrong_token_link_sets_nothing(make_client, monkeypatch): + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + response = client.get("/?token=nope", follow_redirects=False) + assert response.status_code == 401 + assert "set-cookie" not in response.headers + + +def test_launcher_links_carry_the_token(monkeypatch): + import launcher + + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + assert launcher._with_token("https://x.trycloudflare.com") == f"https://x.trycloudflare.com/?token={TOKEN}" + monkeypatch.delenv("APOLLO_ACCESS_TOKEN") + assert launcher._with_token("http://localhost:8000") == "http://localhost:8000" From 006316f3f2a59475d243f747165e19b0160afb63 Mon Sep 17 00:00:00 2001 From: skl Date: Thu, 8 Oct 2026 04:43:49 +0200 Subject: [PATCH 2/3] CORS: any origin, but never with credentials With allow_origins=["*"] and allow_credentials=True, Starlette echoes the caller's Origin whenever the request carries a cookie, so another site could read responses made with the access cookie (checked: Origin evil + cookie -> allow-origin evil, allow-credentials true). The dashboard is same-origin and needs no CORS; API clients use the header. Credentials off; a test pins it. 260 tests pass. Co-Authored-By: Claude Opus 5.5 --- app/main.py | 8 +++++--- tests/test_access_token.py | 9 +++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 13d9a77..9981cf3 100644 --- a/app/main.py +++ b/app/main.py @@ -63,11 +63,13 @@ def create_app(service: object | None = None) -> FastAPI: ) # ============ CORS MIDDLEWARE ============ - # Allow frontend to call backend from same origin and across network + # Any origin may call the API, but never with credentials: the access cookie must not + # ride along on another site's request (with credentials on, Starlette echoes any + # origin that sends a cookie). The dashboard itself is same-origin and needs no CORS. app.add_middleware( CORSMiddleware, - allow_origins=["*"], # Allow all origins (safe for local network) - allow_credentials=True, + allow_origins=["*"], + allow_credentials=False, allow_methods=["*"], # Allow all HTTP methods allow_headers=["*"], # Allow all headers ) diff --git a/tests/test_access_token.py b/tests/test_access_token.py index 9e53a9a..9ba91e7 100644 --- a/tests/test_access_token.py +++ b/tests/test_access_token.py @@ -75,3 +75,12 @@ def test_launcher_links_carry_the_token(monkeypatch): assert launcher._with_token("https://x.trycloudflare.com") == f"https://x.trycloudflare.com/?token={TOKEN}" monkeypatch.delenv("APOLLO_ACCESS_TOKEN") assert launcher._with_token("http://localhost:8000") == "http://localhost:8000" + + +def test_other_sites_cannot_read_responses_with_the_cookie(make_client, monkeypatch): + """With CORS credentials on, Starlette echoed any Origin that sent a cookie.""" + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + response = client.get("/prompts", headers={"Origin": "https://evil.example", "Cookie": f"apollo_access={TOKEN}"}) + assert response.headers.get("access-control-allow-origin") != "https://evil.example" + assert response.headers.get("access-control-allow-credentials") is None From 547f18be80f1452745a24e6b9fc9f63ddf6b02ca Mon Sep 17 00:00:00 2001 From: skl Date: Thu, 8 Oct 2026 04:51:47 +0200 Subject: [PATCH 3/3] Security headers, the 401 and the redirect included nosniff, X-Frame-Options DENY plus CSP frame-ancestors/base-uri/object-src (the directives that cannot break the dashboard's inline scripts), and Referrer-Policy no-referrer: the token arrives once in a URL, so no Referer header may carry it anywhere. The middleware wraps the token check, so the 401 and the cookie redirect carry the headers too. Test included. Co-Authored-By: Claude Opus 5.5 --- app/main.py | 12 ++++++++++++ tests/test_access_token.py | 11 +++++++++++ 2 files changed, 23 insertions(+) diff --git a/app/main.py b/app/main.py index 9981cf3..e7c0bfc 100644 --- a/app/main.py +++ b/app/main.py @@ -101,6 +101,18 @@ async def require_access_token(request: Request, call_next): status_code=401, ) + # ============ SECURITY HEADERS ============ + # Added after the token check, so it wraps it and the 401 and the redirect get them too. + # The CSP holds only directives that cannot break the dashboard (it runs inline scripts). + @app.middleware("http") + async def security_headers(request: Request, call_next): + response = await call_next(request) + response.headers.setdefault("X-Content-Type-Options", "nosniff") + response.headers.setdefault("X-Frame-Options", "DENY") + response.headers.setdefault("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; object-src 'none'") + response.headers.setdefault("Referrer-Policy", "no-referrer") + return response + # ============ INITIALIZE SERVICES ============ app.state.llm_service = service or LLMService() app.state.memory_service = MemoryService() diff --git a/tests/test_access_token.py b/tests/test_access_token.py index 9ba91e7..81ce495 100644 --- a/tests/test_access_token.py +++ b/tests/test_access_token.py @@ -84,3 +84,14 @@ def test_other_sites_cannot_read_responses_with_the_cookie(make_client, monkeypa response = client.get("/prompts", headers={"Origin": "https://evil.example", "Cookie": f"apollo_access={TOKEN}"}) assert response.headers.get("access-control-allow-origin") != "https://evil.example" assert response.headers.get("access-control-allow-credentials") is None + + +def test_security_headers_also_on_the_401_and_the_redirect(make_client, monkeypatch): + monkeypatch.setenv("APOLLO_ACCESS_TOKEN", TOKEN) + with make_client() as client: + for response in (client.get("/"), client.get(f"/?token={TOKEN}", follow_redirects=False), + client.get("/", headers={"X-Apollo-Token": TOKEN})): + assert response.headers["x-content-type-options"] == "nosniff" + assert response.headers["x-frame-options"] == "DENY" + assert "frame-ancestors 'none'" in response.headers["content-security-policy"] + assert response.headers["referrer-policy"] == "no-referrer"