""" Admin-endpoint access control. Every request to /api/admin/* must present an X-Admin-Token header whose value matches the ADMIN_TOKEN environment variable. The token is bootstrapped at application startup: if .env does not contain ADMIN_TOKEN, one is generated deterministically from the current UTC time (SHA-256 hexdigest) and appended to the .env file, and the value is loaded into os.environ for the running process. Why the token exists: OpenCode agent containers share a docker network with the backend, so any unauthenticated /api/admin/* route (test-deploy, status, scm_model, ...) is directly reachable and has been observed to be exploited as a budget-bypass oracle. Gating the router closes that surface. """ from __future__ import annotations import hashlib import logging import os import secrets from datetime import datetime, timezone from pathlib import Path from typing import Optional from fastapi import Header, HTTPException, status logger = logging.getLogger(__name__) ADMIN_TOKEN_VAR = "ADMIN_TOKEN" def _find_repo_root() -> Path: """Return the directory that should host .env (the repo root).""" # api/security.py -> api/ -> repo root return Path(__file__).resolve().parent.parent def _generate_token() -> str: """ SHA-256 hex digest of (current UTC time as ISO-8601 + 32 random bytes). The random suffix ensures uniqueness even if two processes call this within the same wall-clock second. The timestamp is included so a human reading the .env can see roughly when the token was minted. """ ts = datetime.now(timezone.utc).isoformat(timespec="microseconds") entropy = secrets.token_hex(32) return hashlib.sha256(f"{ts}|{entropy}".encode("utf-8")).hexdigest() def _append_to_env_file(env_path: Path, key: str, value: str) -> None: """Append `KEY=value` to `.env`, preceded by a blank line if the file is non-empty.""" prefix = "" if env_path.exists() and env_path.stat().st_size > 0: # Ensure we start on a fresh line. with env_path.open("rb") as f: f.seek(-1, os.SEEK_END) last = f.read(1) if last not in (b"\n", b""): prefix = "\n" with env_path.open("a", encoding="utf-8") as f: f.write( f"{prefix}\n# Auto-generated by api/security.py on " f"{datetime.now(timezone.utc).isoformat(timespec='seconds')}.\n" f"# Rotate by deleting this line and restarting the backend.\n" f"{key}={value}\n" ) def ensure_admin_token_in_env() -> str: """ Guarantee that os.environ[ADMIN_TOKEN] is set. Order of resolution: 1. If os.environ already has ADMIN_TOKEN → keep it. 2. Else generate a fresh token, append it to /.env, and export it into os.environ so subsequent requests can validate against it. Returns the token value (for convenience — callers should not need it). """ existing = os.environ.get(ADMIN_TOKEN_VAR) if existing: return existing token = _generate_token() env_path = _find_repo_root() / ".env" try: _append_to_env_file(env_path, ADMIN_TOKEN_VAR, token) logger.info( "Bootstrapped %s and appended it to %s (fingerprint=%s...)", ADMIN_TOKEN_VAR, env_path, token[:8], ) except OSError as e: # Read-only filesystem etc. — still export to os.environ so the # running process can operate; operator will need to persist manually. logger.warning( "Could not write %s to %s (%s); token exists only for this process.", ADMIN_TOKEN_VAR, env_path, e, ) os.environ[ADMIN_TOKEN_VAR] = token return token async def require_admin_token( x_admin_token: Optional[str] = Header(None, alias="X-Admin-Token"), ) -> None: """ FastAPI dependency: reject the request unless X-Admin-Token matches the ADMIN_TOKEN environment variable. Applied at router level (see api/admin/endpoints.py) so every /api/admin/* route inherits the check without per-endpoint boilerplate. """ expected = os.environ.get(ADMIN_TOKEN_VAR) if not expected: # ensure_admin_token_in_env() should have set this at startup; if we # reach here, the operator has misconfigured the deployment. raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Admin token not initialized on server.", ) if not x_admin_token or not secrets.compare_digest(x_admin_token, expected): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Missing or invalid X-Admin-Token header.", )