Source code for fleetmesh_auth.http_routes

"""Mountable HTTP route handlers for `/api/fauth/*` across FleetMesh web services."""
from __future__ import annotations

from typing import Any, Dict, Optional
from urllib.parse import parse_qs

from fleetmesh_auth.engine import FleetmeshAuthEngine
from fleetmesh_auth.errors import refusal
from fleetmesh_auth.principal import resolve_widget_config
from fleetmesh_auth.ui_widget import render_auth_widget_js

# Registration refusals that mean "fix the form", answered 400; the rest
# (a provider or method switched off, a provider bug) are answered 401.
REGISTER_VALIDATION_ERRORS = frozenset({
    "handle_taken", "invalid_handle", "weak_password", "invalid_email",
    "provider_required", "unknown_provider", "registration_unsupported",
})
# Handle-check refusals that mean "fix the request", answered 400; the rest
# (provider switched off, a provider bug or its store down) are answered 401.
HANDLE_CHECK_VALIDATION_ERRORS = frozenset({
    "provider_required", "unknown_provider", "handle_check_unsupported", "registration_unsupported",
})


[docs]def apply_cors_headers(handler: Any) -> None: """Send the handler's CORS headers, when it has any. The standalone server's handler exposes `cors_headers()`; a host app that mounts these routes with its own handler simply has none, which keeps this a no-op there.""" cors = getattr(handler, "cors_headers", None) if not callable(cors): return headers = cors() or {} if not isinstance(headers, dict): return for name, value in headers.items(): handler.send_header(name, value)
[docs]def extract_request_token(handler: Any, payload: Optional[Dict[str, Any]] = None) -> str: """Extract a session/auth token from HTTP headers, query string, or JSON body.""" headers = getattr(handler, "headers", {}) or {} for hdr in ( "X-Fleetmesh-Auth", "Authorization", "X-Admin-Token", "X-Session-Token", "X-FleetMesh-Key", ): val = str(headers.get(hdr) or "").strip() if val: if val.lower().startswith("bearer "): val = val[7:].strip() if val: return val if payload: for key in ("token", "session_token", "api_key"): val = str(payload.get(key) or "").strip() if val: return val return ""
[docs]def handle_fauth_get( handler: Any, engine: FleetmeshAuthEngine, path: str, query_string: str = "", ) -> bool: """Handle `GET /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler. Returns ``True`` if the path matched `/api/fauth/*` and a response was sent. """ if not path.startswith("/api/fauth/"): return False qs = parse_qs(query_string or "") preset = (qs.get("preset") or ["standard"])[0] if path == "/api/fauth/config": cfg = engine.get_widget_config(preset=preset) handler._send_json(200, {"ok": True, "config": cfg}) return True if path == "/api/fauth/providers": handler._send_json(200, {"ok": True, "providers": engine.list_providers()}) return True if path == "/api/fauth/challenge": domain = (qs.get("domain") or [engine.domain])[0] res = engine.issue_challenge(domain=domain) handler._send_json(200, res) return True if path == "/api/fauth/session": token = (qs.get("token") or [""])[0] or extract_request_token(handler) req_role = (qs.get("required_role") or [None])[0] res = engine.verify_session(token, required_role=req_role) handler._send_json(200 if res.get("ok") else 401, res) return True if path == "/api/fauth/register/check": provider_id = (qs.get("provider") or qs.get("provider_id") or [""])[0] handle = (qs.get("handle") or qs.get("username") or [""])[0] res = engine.check_handle(provider_id, handle, app_preset=preset) if res.get("ok"): status = 200 elif res.get("error") in HANDLE_CHECK_VALIDATION_ERRORS: status = 400 else: status = 401 handler._send_json(status, res) return True if path == "/api/fauth/widget.js": cfg = resolve_widget_config(preset) js_body = render_auth_widget_js(cfg).encode("utf-8") handler.send_response(200) handler.send_header("Content-Type", "application/javascript; charset=utf-8") handler.send_header("Content-Length", str(len(js_body))) handler.send_header("Cache-Control", "no-store") apply_cors_headers(handler) handler.end_headers() handler.wfile.write(js_body) return True handler._send_json(404, refusal("unknown_fauth_endpoint", path=path)) return True
[docs]def handle_fauth_post( handler: Any, engine: FleetmeshAuthEngine, path: str, payload: Dict[str, Any], ) -> bool: """Handle `POST /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler. Returns ``True`` if the path matched `/api/fauth/*` and a response was sent. """ if not path.startswith("/api/fauth/"): return False body = payload or {} if path == "/api/fauth/challenge": domain = str(body.get("domain") or engine.domain) res = engine.issue_challenge(domain=domain) handler._send_json(200, res) return True if path in ("/api/fauth/login", "/api/fauth/verify"): preset = str(body.get("app_preset") or body.get("preset") or "standard") req_role = body.get("required_role") res = engine.authenticate( body, app_preset=preset, required_role=str(req_role) if req_role else None, ) status = 200 if res.get("ok") else 401 handler._send_json(status, res) return True if path == "/api/fauth/register": preset = str(body.get("app_preset") or body.get("preset") or "standard") res = engine.register(body, app_preset=preset) if res.get("ok"): status = 200 elif res.get("error") in REGISTER_VALIDATION_ERRORS: status = 400 else: status = 401 handler._send_json(status, res) return True if path == "/api/fauth/logout": token = extract_request_token(handler, body) res = engine.revoke_session(token) handler._send_json(200, res) return True handler._send_json(404, refusal("unknown_fauth_endpoint", path=path)) return True