Skip to content
Merged
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
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

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

Expand Down Expand Up @@ -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
Expand Down
57 changes: 52 additions & 5 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -57,15 +63,56 @@ 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
)

# ============ 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=<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,
)

# ============ 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()
Expand Down
24 changes: 18 additions & 6 deletions launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import atexit
import os
import re
import secrets
import signal
import subprocess
import sys
Expand Down Expand Up @@ -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})")
Expand All @@ -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()


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

Expand Down
97 changes: 97 additions & 0 deletions tests/test_access_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""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"


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


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"
Loading