Source code for fleetmesh_auth.server

"""Standalone HTTP server for FleetMesh Auth (`python3 -m fleetmesh_auth`).

Two listeners: the public one serves `/api/fauth/*`, the sign-in portal and
`/healthz`; the optional admin one (`--admin-addr` / `FLEETMESH_AUTH_ADMIN_ADDR`)
serves `/healthz`, `/readyz` and Prometheus `/metrics` on a port that is not
meant to be exposed. Every setting has an environment fallback
(`FLEETMESH_AUTH_HOST`, `_PORT`, `_DB`, `_DOMAIN`, `_ADMIN_ADDR`); a flag wins.

Both listeners default to 127.0.0.1 and speak plain HTTP. Binding anywhere
else is allowed (`--host`, `FLEETMESH_AUTH_HOST`) but logs a warning: a
TLS-terminating reverse proxy belongs in front of the service, and the
listener port itself should stay off the public network.

CORS is an allowlist (`FLEETMESH_AUTH_CORS_ORIGINS`, comma-separated). The
server sends no CORS headers at all unless one is configured, and then echoes
only an `Origin` that is on the list (`Vary: Origin` on every response).
"""
from __future__ import annotations

import argparse
import dataclasses
import ipaddress
import json
import logging
import os
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, Optional, Sequence, Tuple
from urllib.parse import parse_qs, urlsplit, urlparse

from fleetmesh_auth.engine import FleetmeshAuthEngine
from fleetmesh_auth.settings import cors_origins_from_env, parse_origins
from fleetmesh_auth.stores import make_store
from fleetmesh_auth.http_routes import handle_fauth_get, handle_fauth_post
from fleetmesh_auth.ui_widget import render_auth_bundle_html

log = logging.getLogger("fleetmesh_auth")

ENV_HOST = "FLEETMESH_AUTH_HOST"
ENV_PORT = "FLEETMESH_AUTH_PORT"
ENV_DB = "FLEETMESH_AUTH_DB"
ENV_STORE_URL = "FLEETMESH_AUTH_STORE_URL"
ENV_DOMAIN = "FLEETMESH_AUTH_DOMAIN"
ENV_ADMIN_ADDR = "FLEETMESH_AUTH_ADMIN_ADDR"

# The loopback address both listeners bind by default: the service speaks
# plain HTTP, so a TLS-terminating proxy on the same host fronts it.
DEFAULT_HOST = "127.0.0.1"

# Headers a cross-origin caller may send: the credentials this API accepts.
CORS_ALLOW_HEADERS = "Content-Type, Authorization, X-Fleetmesh-Auth, X-Admin-Token, X-Session-Token"
CORS_ALLOW_METHODS = "GET, POST, OPTIONS"


# Routes the request counter labels by; anything else is "other", so a
# scanner cannot grow the metric without bound.
KNOWN_ROUTES = frozenset({
    "/", "/login", "/auth", "/healthz",
    "/api/fauth/config", "/api/fauth/providers", "/api/fauth/challenge", "/api/fauth/session",
    "/api/fauth/widget.js", "/api/fauth/login", "/api/fauth/verify", "/api/fauth/register", "/api/fauth/logout",
})


def _package_version() -> str:
    try:
        from importlib.metadata import version

        return version("fleetmesh-auth")
    except Exception:  # noqa: BLE001 - not installed as a distribution (a checkout)
        return "unknown"


def _label_value(text: str) -> str:
    """Escape a Prometheus label value (backslash, double quote, newline)."""
    return str(text).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")


[docs]class RequestMetrics: """Request counters by (method, route, status), rendered as Prometheus text."""
[docs] def __init__(self) -> None: self._lock = threading.Lock() self._requests: Dict[Tuple[str, str, int], int] = {}
[docs] def observe(self, method: str, path: str, status: int) -> None: route = path if path in KNOWN_ROUTES else "other" key = (method.upper(), route, int(status)) with self._lock: self._requests[key] = self._requests.get(key, 0) + 1
[docs] def snapshot(self) -> Dict[Tuple[str, str, int], int]: with self._lock: return dict(self._requests)
[docs]def render_metrics(metrics: Optional[RequestMetrics], engine: Optional[FleetmeshAuthEngine]) -> str: """The admin listener's `/metrics` body (Prometheus text exposition 0.0.4).""" lines = [ "# HELP fleetmesh_auth_build_info The running fleetmesh-auth version.", "# TYPE fleetmesh_auth_build_info gauge", f'fleetmesh_auth_build_info{{version="{_label_value(_package_version())}"}} 1', ] ready = bool(engine is not None and engine.ping()) lines += [ "# HELP fleetmesh_auth_ready 1 when the engine is up and its session store answers.", "# TYPE fleetmesh_auth_ready gauge", f"fleetmesh_auth_ready {1 if ready else 0}", ] if ready and engine is not None: try: active = engine.count_active_sessions() except Exception: # noqa: BLE001 - a metric must not take the listener down active = None if active is not None: lines += [ "# HELP fleetmesh_auth_sessions_active Unexpired sessions in the engine's store.", "# TYPE fleetmesh_auth_sessions_active gauge", f"fleetmesh_auth_sessions_active {active}", ] lines += [ "# HELP fleetmesh_auth_requests_total HTTP requests served by the public listener.", "# TYPE fleetmesh_auth_requests_total counter", ] if metrics is not None: for (method, route, status), count in sorted(metrics.snapshot().items()): lines.append(f'fleetmesh_auth_requests_total{{method="{method}",route="{route}",status="{status}"}} {count}') return "\n".join(lines) + "\n"
def _render_standalone_portal(preset: str) -> str: bundle = render_auth_bundle_html(preset=preset, overrides={"mode": "gate"}) return f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>FleetMesh Identity &amp; Auth Portal</title> <style> body {{ margin: 0; background: #070b14; color: #f8fafc; font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; }} </style> </head> <body> {bundle} </body> </html> """ def _normalize_origin(value: Any) -> str: """`scheme://host[:port]` lowercased, or "" when it is not a usable origin.""" raw = str(value or "").strip() if not raw: return "" parsed = urlsplit(raw) if parsed.scheme.lower() not in ("http", "https") or not parsed.netloc: return "" return f"{parsed.scheme.lower()}://{parsed.netloc.lower()}"
[docs]def is_loopback_host(host: str) -> bool: """True for 127.0.0.0/8, ::1 and `localhost` (what a bind defaults to).""" text = str(host or "").strip().strip("[]") if text.lower() == "localhost": return True try: return ipaddress.ip_address(text).is_loopback except ValueError: return False
[docs]def warn_if_not_loopback(host: str, port: int, listener: str = "listener") -> None: """The service speaks plain HTTP: a non-loopback bind needs TLS in front.""" if is_loopback_host(host): return log.warning( "fleetmesh-auth %s is bound to %s:%s, which is not loopback. It speaks plain HTTP: " "terminate TLS in a reverse proxy in front of it and keep this port off the public network.", listener, host or "0.0.0.0", port, )
[docs]class FleetmeshAuthHTTPHandler(BaseHTTPRequestHandler): engine: FleetmeshAuthEngine metrics: Optional[RequestMetrics] = None # Origins allowed to call this API cross-origin; empty means none (the # response carries no CORS headers at all, i.e. same-origin only). cors_origins: Tuple[str, ...] = ()
[docs] def log_message(self, fmt: str, *args: Any) -> None: return
[docs] def send_response(self, code: int, message: Optional[str] = None) -> None: # noqa: D401 super().send_response(code, message) if self.metrics is not None: self.metrics.observe(self.command or "", urlparse(self.path).path, code)
[docs] def cors_headers(self) -> Dict[str, str]: """The CORS response headers for this request. With no allowlist configured: none, so a browser sees a same-origin service. With one: `Vary: Origin` always (a cache must not hand one origin's grant to another), and `Access-Control-Allow-Origin` echoing the request's Origin only when it is on the list. An origin that is not listed gets no grant, so the browser blocks the cross-origin read even though the request may still be executed. """ if not self.cors_origins: return {} headers: Dict[str, str] = {"Vary": "Origin"} origin = _normalize_origin(self.headers.get("Origin")) if origin and origin in self.cors_origins: headers["Access-Control-Allow-Origin"] = origin return headers
def _send_cors_headers(self) -> None: for name, value in self.cors_headers().items(): self.send_header(name, value) def _send_json(self, status: int, data: Dict[str, Any]) -> None: raw = json.dumps(data).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(raw))) self._send_cors_headers() self.end_headers() self.wfile.write(raw) def _send_html(self, status: int, html: str) -> None: raw = html.encode("utf-8") self.send_response(status) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(raw))) self._send_cors_headers() self.end_headers() self.wfile.write(raw)
[docs] def do_OPTIONS(self) -> None: """A CORS preflight: the grant only when the Origin is on the list.""" headers = self.cors_headers() granted = "Access-Control-Allow-Origin" in headers self.send_response(204) if granted: self.send_header("Access-Control-Allow-Methods", CORS_ALLOW_METHODS) self.send_header("Access-Control-Allow-Headers", CORS_ALLOW_HEADERS) self.send_header("Access-Control-Max-Age", "600") for name, value in headers.items(): self.send_header(name, value) self.end_headers()
[docs] def do_GET(self) -> None: parsed = urlparse(self.path) if handle_fauth_get(self, self.engine, parsed.path, parsed.query): return if parsed.path in ("/", "/login", "/auth"): qs = parse_qs(parsed.query) preset = (qs.get("preset") or ["standard"])[0] self._send_html(200, _render_standalone_portal(preset)) return if parsed.path == "/healthz": self._send_json(200, {"ok": True, "service": "fleetmesh-auth"}) return self._send_json(404, {"ok": False, "error": "not_found", "path": parsed.path})
[docs] def do_POST(self) -> None: parsed = urlparse(self.path) max_body = 65536 try: length = int(self.headers.get("Content-Length", "0") or "0") except ValueError: self._send_json(400, {"ok": False, "error": "invalid_content_length"}) return if length < 0 or length > max_body: self._send_json( 400, {"ok": False, "error": "payload_too_large" if length > max_body else "invalid_content_length"}, ) return raw = self.rfile.read(length) if length > 0 else b"{}" try: payload = json.loads(raw.decode("utf-8") or "{}") except ValueError: self._send_json(400, {"ok": False, "error": "invalid_json"}) return if handle_fauth_post(self, self.engine, parsed.path, payload): return self._send_json(404, {"ok": False, "error": "not_found", "path": parsed.path})
[docs]class AdminHTTPHandler(BaseHTTPRequestHandler): """`/healthz`, `/readyz`, `/metrics`; nothing else, and no public API.""" engine: Optional[FleetmeshAuthEngine] = None metrics: Optional[RequestMetrics] = None
[docs] def log_message(self, fmt: str, *args: Any) -> None: return
def _send(self, status: int, body: bytes, content_type: str) -> None: self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def _send_json(self, status: int, data: Dict[str, Any]) -> None: self._send(status, json.dumps(data).encode("utf-8"), "application/json; charset=utf-8")
[docs] def do_GET(self) -> None: path = urlparse(self.path).path if path == "/healthz": self._send_json(200, {"ok": True, "service": "fleetmesh-auth"}) return if path == "/readyz": ready = self.engine is not None and self.engine.ping() self._send_json(200 if ready else 503, {"ok": bool(ready), "ready": bool(ready)}) return if path == "/metrics": body = render_metrics(self.metrics, self.engine).encode("utf-8") self._send(200, body, "text/plain; version=0.0.4; charset=utf-8") return self._send_json(404, {"ok": False, "error": "not_found", "path": path})
[docs]class AuthHTTPServer(ThreadingHTTPServer): """The public listener; `.engine` and `.metrics` are what its handler uses.""" daemon_threads = True engine: FleetmeshAuthEngine metrics: RequestMetrics
[docs]class AdminHTTPServer(ThreadingHTTPServer): """The admin listener (`/healthz`, `/readyz`, `/metrics`).""" daemon_threads = True engine: Optional[FleetmeshAuthEngine] metrics: Optional[RequestMetrics]
[docs]def create_auth_http_server( host: str = DEFAULT_HOST, port: int = 8099, engine: Optional[FleetmeshAuthEngine] = None, metrics: Optional[RequestMetrics] = None, cors_origins: Optional[Sequence[str]] = None, ) -> AuthHTTPServer: """The public listener. `cors_origins` is the allowlist of origins that may call it cross-origin; None or empty means no CORS headers at all.""" auth_engine = engine or FleetmeshAuthEngine() request_metrics = metrics if metrics is not None else RequestMetrics() warn_if_not_loopback(host, port, "public listener") origins = tuple(_normalize_origin(o) for o in (cors_origins or ())) origins = tuple(o for o in origins if o) class BoundHandler(FleetmeshAuthHTTPHandler): pass BoundHandler.engine = auth_engine BoundHandler.metrics = request_metrics BoundHandler.cors_origins = origins srv = AuthHTTPServer((host, port), BoundHandler) srv.engine = auth_engine srv.metrics = request_metrics return srv
[docs]def create_admin_http_server( host: str, port: int, engine: Optional[FleetmeshAuthEngine], metrics: Optional[RequestMetrics] = None, ) -> AdminHTTPServer: """A listener for probes and metrics. Pass the public server's `.metrics` so `/metrics` counts its requests; `engine` may be None (or not yet working), in which case `/readyz` answers 503.""" warn_if_not_loopback(host, port, "admin listener") class BoundAdminHandler(AdminHTTPHandler): pass BoundAdminHandler.engine = engine BoundAdminHandler.metrics = metrics srv = AdminHTTPServer((host, port), BoundAdminHandler) srv.engine = engine srv.metrics = metrics return srv
[docs]@dataclasses.dataclass class ServerSettings: host: str port: int db: str domain: str admin_addr: Optional[Tuple[str, int]] # None: no admin listener store_url: str = "" # empty: sqlite at `db` cors_origins: Tuple[str, ...] = () # empty: no CORS headers at all @property def effective_store_url(self) -> str: """What `make_store()` gets: `store_url` when set, else the sqlite `db` path.""" return self.store_url or self.db or ":memory:"
[docs]def parse_admin_addr(raw: Optional[str]) -> Optional[Tuple[str, int]]: """`host:port`, `:port` or `port` → (host, port); empty → None. A missing host is loopback, like the public listener's default.""" text = str(raw or "").strip() if not text: return None host, sep, port_text = text.rpartition(":") if not sep: host, port_text = "", text try: port = int(port_text) except ValueError: raise ValueError(f"admin address {text!r} must be host:port") from None if not 0 <= port <= 65535: raise ValueError(f"admin address {text!r}: port out of range") return (host or DEFAULT_HOST, port)
[docs]def resolve_server_settings(argv: Optional[Sequence[str]] = None) -> ServerSettings: """Flags over environment over defaults.""" env = os.environ parser = argparse.ArgumentParser(description="FleetMesh Unified Auth Service") parser.add_argument("--host", default=env.get(ENV_HOST) or DEFAULT_HOST, help=f"bind address (${ENV_HOST})") parser.add_argument("--port", default=env.get(ENV_PORT) or "8099", help=f"public port (${ENV_PORT})") parser.add_argument("--db", default=env.get(ENV_DB) or ":memory:", help=f"sqlite path (${ENV_DB})") parser.add_argument( "--store-url", default=env.get(ENV_STORE_URL, ""), help=f"postgres://... for a shared store, or a sqlite path; beats --db (${ENV_STORE_URL})", ) parser.add_argument("--domain", default=env.get(ENV_DOMAIN) or "fleetmesh.local", help=f"origin domain (${ENV_DOMAIN})") parser.add_argument( "--admin-addr", default=env.get(ENV_ADMIN_ADDR, ""), help=f"host:port for /healthz, /readyz, /metrics; empty disables (${ENV_ADMIN_ADDR})", ) parser.add_argument( "--cors-origin", action="append", default=None, metavar="ORIGIN", help="origin allowed to call the API cross-origin (repeatable; replaces " "FLEETMESH_AUTH_CORS_ORIGINS; default is no cross-origin access)", ) args = parser.parse_args(list(argv) if argv is not None else None) try: port = int(str(args.port).strip()) except ValueError: parser.error(f"--port / {ENV_PORT} must be a number, not {args.port!r}") try: admin_addr = parse_admin_addr(args.admin_addr) except ValueError as exc: parser.error(str(exc)) cors_origins = ( parse_origins(args.cors_origin, "--cors-origin") if args.cors_origin else cors_origins_from_env() ) return ServerSettings( host=args.host, port=port, db=args.db, domain=args.domain, admin_addr=admin_addr, store_url=str(args.store_url or "").strip(), cors_origins=tuple(cors_origins), )
[docs]def main(argv: Optional[Sequence[str]] = None) -> None: settings = resolve_server_settings(argv) store = make_store(settings.effective_store_url) engine = FleetmeshAuthEngine(store=store, domain=settings.domain) srv = create_auth_http_server( settings.host, settings.port, engine=engine, cors_origins=settings.cors_origins, ) if settings.admin_addr is not None: admin = create_admin_http_server(settings.admin_addr[0], settings.admin_addr[1], engine, metrics=srv.metrics) threading.Thread(target=admin.serve_forever, name="fleetmesh-auth-admin", daemon=True).start() print(f"FleetMesh Auth admin listening on http://{admin.server_address[0]}:{admin.server_address[1]}") print(f"FleetMesh Auth listening on http://{srv.server_address[0]}:{srv.server_address[1]}") srv.serve_forever()
if __name__ == "__main__": main()