local-web-search/services/orchestrator/app/auth.py
User e6c2cc1e8c Prepare for public release: AGPL license, curl installer, bearer-token auth
- LICENSE: AGPL-3.0
- install.sh: curl-pipeable bootstrap for Linux/macOS (VPS/LXC) — installs
  Docker if missing, clones, generates strong LWSS_API_KEY + SearXNG secret,
  compose up, prints the ready-to-run 'claude mcp add' command; idempotent and
  preserves .env on re-run
- auth: optional bearer token (LWSS_API_KEY) on all orchestrator MCP + REST
  requests via middleware; /health exempt; empty key disables auth (LAN only);
  constant-time compare
- compose: configurable bind address (ORCHESTRATOR_BIND, default 0.0.0.0) so
  the endpoint can stay localhost-only behind a tunnel; API key plumbed through
- docker-compose.override.yml pattern (gitignored) + .example for machine-local
  config like LAN SearXNG extra_hosts
- README: install one-liner, auth + security (SSRF/tunnel) notes, license
- PRD: auth documented in §8; multi-tenant non-goal clarified

Verified: auth rejects unauthenticated REST + MCP (401), passes with a valid
bearer token, /health stays open; full dockerized stack healthy; MCP client
connects only with the Authorization header.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 00:43:04 -07:00

36 lines
1.3 KiB
Python

"""Optional bearer-token auth for public deployments.
If LWSS_API_KEY is set, every request must carry `Authorization: Bearer <key>`
(constant-time compared). /health is always exempt so container healthchecks and
uptime monitors work without the key. If the key is unset, auth is disabled and
a warning is logged — intended only for trusted/LAN use.
"""
import hmac
import logging
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
log = logging.getLogger("orchestrator")
EXEMPT_PATHS = {"/health"}
class BearerAuthMiddleware(BaseHTTPMiddleware):
def __init__(self, app, api_key: str):
super().__init__(app)
self._api_key = api_key
if not api_key:
log.warning("LWSS_API_KEY is empty; authentication DISABLED (trusted networks only)")
async def dispatch(self, request: Request, call_next):
if not self._api_key or request.url.path in EXEMPT_PATHS:
return await call_next(request)
header = request.headers.get("authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer" or not hmac.compare_digest(token, self._api_key):
return JSONResponse({"detail": "missing or invalid bearer token"}, status_code=401)
return await call_next(request)