diff --git a/README.md b/README.md index cbc11bb..8dace82 100644 --- a/README.md +++ b/README.md @@ -1,114 +1,93 @@ # Terminals -> [!WARNING] -> **🚧 Work in Progress** – This project is under active development and is not yet ready for production use. APIs, configuration, and features may change without notice. +> [!NOTE] +> This project is in **alpha**. APIs, configuration, and behavior may change between releases. -> **Alpha** – APIs and configuration may change. +Multi-tenant terminal orchestrator for [Open Terminal](https://github.com/open-webui/open-terminal). Provisions isolated, policy-configured terminal instances per user. -Multi-tenant terminal orchestrator for [Open Terminal](https://github.com/open-webui/open-terminal). Provisions isolated terminal instances per user with automatic lifecycle management. - -## Getting Started - -### Install & Run +## Quick Start ```bash pip install -e . terminals serve ``` -The server starts on `http://0.0.0.0:3000`. An API key is auto-generated and printed to the console. - -### Docker +Or with Docker: ```bash -docker build -t terminals . docker run -p 3000:3000 \ -v /var/run/docker.sock:/var/run/docker.sock \ -v $(pwd)/data:/app/data \ terminals ``` -### Development +## Policies + +Policies define per-environment configuration. Manage via REST API: ```bash -uv sync -./dev.sh # uvicorn with --reload +curl -X PUT http://localhost:3000/api/v1/policies/data-science \ + -H "Authorization: Bearer $API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "image": "ghcr.io/open-webui/open-terminal:python-ds", + "cpu_limit": "2", + "memory_limit": "4Gi", + "env": {"OPENAI_API_KEY": "sk-proj-..."}, + "allowed_domains": ["*.pypi.org", "github.com"], + "idle_timeout_minutes": 30 + }' ``` -Frontend (admin dashboard): +Route requests through a policy via `/p/{policy_id}/`: ```bash -cd terminals/frontend -npm install && npm run dev -``` - -## Usage - -All Open Terminal endpoints are available under `/terminals/`. Include `X-User-Id` to identify the user. - -```bash -export API_KEY="" -export HEADERS=(-H "Authorization: Bearer $API_KEY" -H "X-User-Id: user-123") - -curl -X POST http://localhost:3000/terminals/execute \ - "${HEADERS[@]}" -H "Content-Type: application/json" \ +curl -X POST http://localhost:3000/p/data-science/execute \ + -H "Authorization: Bearer $API_KEY" -H "X-User-Id: user-123" \ + -H "Content-Type: application/json" \ -d '{"command": "echo hello"}' - -curl http://localhost:3000/terminals/files/list "${HEADERS[@]}" - -curl "http://localhost:3000/terminals/files/read?path=README.md" "${HEADERS[@]}" ``` -Interactive terminal sessions connect via WebSocket at `/terminals/api/terminals/{session_id}`. Admins can manage tenants via `/api/v1/tenants/`. +| Field | Type | Description | +|-------|------|-------------| +| `image` | string | Container image | +| `env` | dict | Environment variables | +| `cpu_limit` | string | Max CPU (e.g. `"2"`) | +| `memory_limit` | string | Max memory (e.g. `"4Gi"`) | +| `storage` | string | Persistent volume size (absent = ephemeral) | +| `allowed_domains` | list | `["*"]` = full, `[]` = none, `["*.pypi.org"]` = restricted | +| `idle_timeout_minutes` | int | Idle timeout before cleanup | ## Configuration -Settings are loaded from environment variables prefixed with `TERMINALS_` (or a `.env` file). +Environment variables prefixed with `TERMINALS_` (or `.env` file). | Variable | Default | Description | |----------|---------|-------------| -| `TERMINALS_BACKEND` | `docker` | `docker`, `kubernetes`, `kubernetes-operator`, `local`, `static` | -| `TERMINALS_API_KEY` | *(auto-generated)* | Bearer token for API auth | +| `TERMINALS_BACKEND` | `docker` | `docker`, `kubernetes`, `kubernetes-operator` | +| `TERMINALS_API_KEY` | *(auto)* | Bearer token for API auth | | `TERMINALS_OPEN_WEBUI_URL` | | Open WebUI URL for JWT auth | -| `TERMINALS_DATABASE_URL` | `sqlite+aiosqlite:///./data/terminals.db` | SQLAlchemy async URL | -| `TERMINALS_IMAGE` | `ghcr.io/open-webui/open-terminal:latest` | Docker/K8s container image | -| `TERMINALS_IDLE_TIMEOUT_SECONDS` | `1800` | Stop idle instances (0 = disabled) | -| `TERMINALS_PORT` | `3000` | Server port | +| `TERMINALS_IMAGE` | `ghcr.io/open-webui/open-terminal:latest` | Default container image | +| `TERMINALS_MAX_CPU` | | Hard cap on CPU | +| `TERMINALS_MAX_MEMORY` | | Hard cap on memory | +| `TERMINALS_MAX_STORAGE` | | Hard cap on storage | +| `TERMINALS_ALLOWED_IMAGES` | | Comma-separated image globs | -See [`config.py`](terminals/config.py) for the full list including Kubernetes, static backend, and encryption settings. +See [`config.py`](terminals/config.py) for the full list. ## Authentication -| Mode | Trigger | How it works | -|------|---------|-------------| -| **Open WebUI JWT** | Set `TERMINALS_OPEN_WEBUI_URL` | Validates tokens against Open WebUI | -| **API Key** | Set `TERMINALS_API_KEY` | Static bearer token | -| **Open** | Neither set | No auth (development only) | +| Mode | Trigger | +|------|---------| +| **Open WebUI JWT** | Set `TERMINALS_OPEN_WEBUI_URL` | +| **API Key** | Set `TERMINALS_API_KEY` | +| **Open** | Neither set (dev only) | ## Backends - **`docker`** – One container per user via Docker socket -- **`kubernetes`** – Pod + PVC + Service per user via K8s API -- **`kubernetes-operator`** – Delegates to a Kopf operator watching `Terminal` CRDs -- **`local`** – Spawns `open-terminal` as a subprocess (dev/testing) -- **`static`** – Proxies all users to a single pre-running instance - -## Database - -SQLite works out of the box. For PostgreSQL: - -```bash -pip install asyncpg -export TERMINALS_DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/terminals -``` - -Migrations run automatically on startup. Manual management: - -```bash -terminals db upgrade # run pending migrations -terminals db current # show revision -terminals db revision -m "msg" # create migration -``` +- **`kubernetes`** – Pod + PVC + Service per user +- **`kubernetes-operator`** – Kopf operator watching `Terminal` CRDs ## License diff --git a/terminals/audit.py b/terminals/audit.py deleted file mode 100644 index bd31e0e..0000000 --- a/terminals/audit.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Centralised audit-logging helper. - -Emits structured audit events via: - 1. Database β€” persistent ``audit_logs`` table - 2. Loguru β€” structured log line (always) - 3. SIEM β€” optional webhook forwarding -""" - -import json -from typing import Optional - -import httpx -from loguru import logger - -from terminals.config import settings -from terminals.db.session import async_session - -# Reusable SIEM webhook client (created once, not per-event). -_siem_client: Optional[httpx.AsyncClient] = None - - -async def _get_siem_client() -> httpx.AsyncClient: - global _siem_client - if _siem_client is None: - _siem_client = httpx.AsyncClient(timeout=5.0) - return _siem_client - - -async def log_audit( - *, - action: str, - severity: str = "info", - user_id: Optional[str] = None, - request_id: Optional[str] = None, - resource_type: Optional[str] = None, - resource_id: Optional[str] = None, - detail: Optional[dict] = None, - ip_address: Optional[str] = None, - user_agent: Optional[str] = None, - status_code: Optional[int] = None, -) -> None: - """Emit a structured audit event via DB + loguru + optional SIEM webhook.""" - - event = { - "action": action, - "severity": severity, - "user_id": user_id, - "request_id": request_id, - "resource_type": resource_type, - "resource_id": resource_id, - "detail": detail, - "ip_address": ip_address, - "user_agent": user_agent, - "status_code": status_code, - } - - # ------ 1. Database persistence ------ - try: - from terminals.models.audit import AuditLog - - async with async_session() as session: - session.add(AuditLog(**event)) - await session.commit() - except Exception: - logger.warning("Failed to persist audit event to database") - - # ------ 2. Loguru structured emit ------ - level = {"info": "INFO", "warning": "WARNING", "critical": "ERROR"}.get( - severity, "INFO" - ) - logger.log(level, "AUDIT | {action} | user={user_id} | {detail}", **event) - - # ------ 3. SIEM webhook ------ - if settings.siem_webhook_url: - try: - client = await _get_siem_client() - await client.post( - settings.siem_webhook_url, - json={k: v for k, v in event.items() if v is not None}, - ) - except Exception: - logger.warning("Failed to forward audit event to SIEM webhook") diff --git a/terminals/backends/__init__.py b/terminals/backends/__init__.py index 3aec740..21c5742 100644 --- a/terminals/backends/__init__.py +++ b/terminals/backends/__init__.py @@ -10,14 +10,6 @@ def create_backend() -> Backend: from terminals.backends.docker import DockerBackend return DockerBackend() - elif settings.backend == "local": - from terminals.backends.local import LocalBackend - - return LocalBackend() - elif settings.backend == "static": - from terminals.backends.static import StaticBackend - - return StaticBackend() elif settings.backend == "kubernetes": from terminals.backends.kubernetes import KubernetesBackend diff --git a/terminals/backends/base.py b/terminals/backends/base.py index b79eeef..6cb6df1 100644 --- a/terminals/backends/base.py +++ b/terminals/backends/base.py @@ -8,19 +8,25 @@ class Backend(ABC): """Lifecycle interface for provisioning and managing terminal instances.""" @abstractmethod - async def provision(self, user_id: str) -> dict: + async def provision( + self, + user_id: str, + policy_id: str = "default", + spec: Optional[dict] = None, + ) -> dict: """Create a new terminal instance for *user_id*. + *policy_id* scopes the container (one per user+policy pair). + *spec* is the resolved policy spec dict; if ``None``, the backend + uses ``settings.*`` defaults. + Returns a dict with at least: ``instance_id``, ``instance_name``, ``api_key``, ``host``, ``port``. """ @abstractmethod async def start(self, instance_id: str) -> bool: - """Idempotent start β€” no-op if already running. - - Returns ``True`` if the instance is now running. - """ + """Idempotent start β€” no-op if already running.""" @abstractmethod async def teardown(self, instance_id: str) -> None: @@ -34,36 +40,22 @@ class Backend(ABC): async def close(self) -> None: """Release resources on shutdown.""" - # ------------------------------------------------------------------ - # Optional methods for DB-free operation - # ------------------------------------------------------------------ - - async def ensure_terminal(self, user_id: str) -> Optional[dict]: + async def ensure_terminal( + self, + user_id: str, + policy_id: str = "default", + spec: Optional[dict] = None, + ) -> Optional[dict]: """Get-or-create a terminal for *user_id*. - Returns a dict with ``api_key``, ``host``, ``port`` (and optionally - ``instance_id``, ``instance_name``), or ``None`` if the terminal - could not be resolved. - - The default implementation delegates to :meth:`provision`, which is - already idempotent for most backends. Backends with their own - state store (e.g. Kubernetes CRDs) can override this to avoid - requiring a database. + Returns a dict with ``api_key``, ``host``, ``port``, or ``None``. + Default delegates to :meth:`provision` (already idempotent). """ - return await self.provision(user_id) + return await self.provision(user_id, policy_id=policy_id, spec=spec) async def get_terminal_info(self, user_id: str) -> Optional[dict]: - """Look up an existing terminal without creating one. - - Returns the same dict shape as :meth:`ensure_terminal`, or ``None`` - if no terminal exists for *user_id*. The default returns ``None``; - backends that maintain their own state should override. - """ + """Look up an existing terminal without creating one.""" return None async def touch_activity(self, user_id: str) -> None: - """Record that *user_id*'s terminal is actively being used. - - Backends that track idle time should override this to update the - last-activity timestamp. The default is a no-op. - """ + """Record that *user_id*'s terminal is actively being used.""" diff --git a/terminals/backends/docker.py b/terminals/backends/docker.py index 122465f..cf92e18 100644 --- a/terminals/backends/docker.py +++ b/terminals/backends/docker.py @@ -27,25 +27,50 @@ class DockerBackend(Backend): # Backend interface # ------------------------------------------------------------------ - async def provision(self, user_id: str) -> dict: + async def provision( + self, + user_id: str, + policy_id: str = "default", + spec: dict | None = None, + ) -> dict: docker = await self._get_docker() api_key = secrets.token_urlsafe(24) - instance_name = f"terminals-{user_id}" + instance_name = f"terminals-{user_id}-{policy_id}" host_data_dir = f"{settings.data_dir}/{user_id}" + s = spec or {} + + image = s.get("image", settings.image) + + host_config: dict = { + "Binds": [f"{host_data_dir}:/home/user"], + } + + # Resources + if s.get("memory_limit"): + host_config["Memory"] = self._parse_memory(s["memory_limit"]) + if s.get("cpu_limit"): + host_config["NanoCpus"] = self._parse_cpu_nanos(s["cpu_limit"]) + + # Network + allowed = s.get("allowed_domains") + if allowed is not None and len(allowed) == 0: + host_config["NetworkMode"] = "none" + elif settings.network: + host_config["NetworkMode"] = settings.network + + # Env vars + env = [f"OPEN_TERMINAL_API_KEY={api_key}"] + for k, v in s.get("env", {}).items(): + env.append(f"{k}={v}") config: dict = { - "Image": settings.image, - "Env": [f"OPEN_TERMINAL_API_KEY={api_key}"], - "HostConfig": { - "Binds": [f"{host_data_dir}:/home/user"], - }, + "Image": image, + "Env": env, + "HostConfig": host_config, "ExposedPorts": {"8000/tcp": {}}, } - if settings.network: - config["HostConfig"]["NetworkMode"] = settings.network - - log.info("Provisioning container %s for user %s", instance_name, user_id) + log.info("Provisioning container %s for user %s (policy=%s)", instance_name, user_id, policy_id) try: container = await docker.containers.create_or_replace( @@ -60,9 +85,8 @@ class DockerBackend(Backend): info = await container.show() instance_id = info["Id"] - # Determine the hostname the orchestrator can reach. - host = instance_name # works when on the same Docker network - if not settings.network: + host = instance_name + if not settings.network and (allowed is None or len(allowed) > 0): networks = info.get("NetworkSettings", {}).get("Networks", {}) bridge = networks.get("bridge", {}) host = bridge.get("IPAddress", "127.0.0.1") @@ -75,6 +99,33 @@ class DockerBackend(Backend): "port": 8000, } + # ------------------------------------------------------------------ + # Resource parsing helpers + # ------------------------------------------------------------------ + + @staticmethod + def _parse_memory(value: str) -> int: + """Parse K8s memory string to bytes. '512Mi' -> 536870912.""" + import re + m = re.match(r"^(\d+(?:\.\d+)?)\s*(Ki|Mi|Gi|Ti)?$", str(value).strip()) + if not m: + return int(value) + num, suffix = float(m.group(1)), m.group(2) or "" + mult = {"": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4} + return int(num * mult[suffix]) + + @staticmethod + def _parse_cpu_nanos(value: str) -> int: + """Parse K8s CPU string to nanocpus. '2' -> 2_000_000_000, '500m' -> 500_000_000.""" + import re + m = re.match(r"^(\d+(?:\.\d+)?)\s*(m)?$", str(value).strip()) + if not m: + return int(float(value) * 1_000_000_000) + num, suffix = float(m.group(1)), m.group(2) or "" + if suffix == "m": + return int(num * 1_000_000) + return int(num * 1_000_000_000) + async def start(self, instance_id: str) -> bool: current = await self.status(instance_id) if current == "running": diff --git a/terminals/backends/kubernetes.py b/terminals/backends/kubernetes.py index 918cfc4..af0e57b 100644 --- a/terminals/backends/kubernetes.py +++ b/terminals/backends/kubernetes.py @@ -71,14 +71,29 @@ class KubernetesBackend(Backend): # Backend interface # ------------------------------------------------------------------ - async def provision(self, user_id: str) -> dict: + async def provision( + self, + user_id: str, + policy_id: str = "default", + spec: dict | None = None, + ) -> dict: api_client = await self._ensure_client() core = client.CoreV1Api(api_client) api_key = secrets.token_urlsafe(24) - name = _sanitize_name(user_id) + base_name = _sanitize_name(user_id) + # Include template in resource names for multi-template support + tmpl_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20] + name = f"{base_name}-{tmpl_slug}" if policy_id != "default" else base_name ns = settings.kubernetes_namespace labels = _base_labels(user_id) + labels["openwebui.com/policy"] = tmpl_slug + + # Resolve image and container settings from spec or defaults + container_spec = (spec or {}).get("container", {}) + image = container_spec.get("image", settings.kubernetes_image) + sec_spec = container_spec.get("securityContext", {}) + res_spec = container_spec.get("resources", {}) # ---- Optional PVC ------------------------------------------------ if settings.kubernetes_storage_size: @@ -105,6 +120,29 @@ class KubernetesBackend(Backend): else: raise + # ---- Build K8s objects from spec ---------------------------------- + # Security context + security_context = None + if sec_spec: + security_context = client.V1SecurityContext( + run_as_user=sec_spec.get("runAsUser"), + run_as_group=sec_spec.get("runAsGroup"), + allow_privilege_escalation=sec_spec.get("allowPrivilegeEscalation"), + read_only_root_filesystem=sec_spec.get("readOnlyRootFilesystem"), + capabilities=client.V1Capabilities( + drop=sec_spec.get("capabilities", {}).get("drop"), + add=sec_spec.get("capabilities", {}).get("add"), + ) if sec_spec.get("capabilities") else None, + ) + + # Resource requirements + resource_reqs = None + if res_spec: + resource_reqs = client.V1ResourceRequirements( + requests=res_spec.get("requests"), + limits=res_spec.get("limits"), + ) + # ---- Pod --------------------------------------------------------- volumes = [] volume_mounts = [] @@ -127,7 +165,7 @@ class KubernetesBackend(Backend): containers=[ client.V1Container( name="open-terminal", - image=settings.kubernetes_image, + image=image, ports=[client.V1ContainerPort(container_port=8000)], env=[ client.V1EnvVar( @@ -135,6 +173,8 @@ class KubernetesBackend(Backend): ), ], volume_mounts=volume_mounts or None, + security_context=security_context, + resources=resource_reqs, readiness_probe=client.V1Probe( http_get=client.V1HTTPGetAction( path="/health", port=8000 @@ -151,7 +191,7 @@ class KubernetesBackend(Backend): try: created = await core.create_namespaced_pod(ns, pod) - log.info("Created Pod %s in %s", name, ns) + log.info("Created Pod %s in %s (policy=%s)", name, ns, policy_id) except client.exceptions.ApiException as exc: if exc.status == 409: # Pod exists β€” delete and recreate. @@ -164,11 +204,15 @@ class KubernetesBackend(Backend): instance_id = created.metadata.uid # ---- Service ----------------------------------------------------- + svc_selector = { + "openwebui.com/user-id": user_id, + "openwebui.com/template": tmpl_slug, + } svc = client.V1Service( metadata=client.V1ObjectMeta(name=name, namespace=ns, labels=labels), spec=client.V1ServiceSpec( type=settings.kubernetes_service_type, - selector={"openwebui.com/user-id": user_id}, + selector=svc_selector, ports=[ client.V1ServicePort(port=8000, target_port=8000), ], diff --git a/terminals/backends/local.py b/terminals/backends/local.py deleted file mode 100644 index 732763c..0000000 --- a/terminals/backends/local.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Local backend β€” spawns Open Terminal as a subprocess per user.""" - -import asyncio -import logging -import os -import secrets -import signal -from typing import Optional - -from terminals.backends.base import Backend -from terminals.config import settings - -log = logging.getLogger(__name__) - - -class LocalBackend(Backend): - """Manage terminal instances as local subprocesses.""" - - def __init__(self) -> None: - self._processes: dict[str, asyncio.subprocess.Process] = {} - self._next_port: int = settings.local_port_range_start - - def _allocate_port(self) -> int: - port = self._next_port - self._next_port += 1 - return port - - # ------------------------------------------------------------------ - # Backend interface - # ------------------------------------------------------------------ - - async def provision(self, user_id: str) -> dict: - api_key = secrets.token_urlsafe(24) - port = self._allocate_port() - instance_name = f"terminals-local-{user_id}" - data_dir = os.path.join(settings.data_dir, user_id) - os.makedirs(data_dir, exist_ok=True) - - env = os.environ.copy() - env["OPEN_TERMINAL_API_KEY"] = api_key - env["HOME"] = data_dir - - log.info( - "Spawning local open-terminal for user %s on port %d", - user_id, - port, - ) - - process = await asyncio.create_subprocess_exec( - settings.local_binary, "serve", - "--host", "127.0.0.1", - "--port", str(port), - "--api-key", api_key, - env=env, - stdout=asyncio.subprocess.DEVNULL, - stderr=asyncio.subprocess.DEVNULL, - ) - - instance_id = str(process.pid) - self._processes[instance_id] = process - - # Give the process a moment to start. - await asyncio.sleep(0.5) - - return { - "instance_id": instance_id, - "instance_name": instance_name, - "api_key": api_key, - "host": "127.0.0.1", - "port": port, - } - - async def start(self, instance_id: str) -> bool: - current = await self.status(instance_id) - return current == "running" - - async def teardown(self, instance_id: str) -> None: - process = self._processes.pop(instance_id, None) - if process is None: - return - try: - process.send_signal(signal.SIGTERM) - try: - await asyncio.wait_for(process.wait(), timeout=10) - except asyncio.TimeoutError: - process.kill() - await process.wait() - except ProcessLookupError: - pass - log.info("Terminated local process %s", instance_id) - - async def status(self, instance_id: str) -> str: - process = self._processes.get(instance_id) - if process is None: - return "missing" - if process.returncode is None: - return "running" - return "stopped" - - async def close(self) -> None: - for instance_id in list(self._processes): - await self.teardown(instance_id) diff --git a/terminals/backends/static.py b/terminals/backends/static.py deleted file mode 100644 index 54bd42b..0000000 --- a/terminals/backends/static.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Static backend β€” proxies to a pre-running Open Terminal instance.""" - -import logging - -import httpx - -from terminals.backends.base import Backend -from terminals.config import settings - -log = logging.getLogger(__name__) - - -class StaticBackend(Backend): - """Point at an already-running Open Terminal instance. - - No lifecycle management β€” the admin is responsible for keeping the - target instance alive. - """ - - def __init__(self) -> None: - self._client = httpx.AsyncClient(timeout=5.0) - - # ------------------------------------------------------------------ - # Backend interface - # ------------------------------------------------------------------ - - async def provision(self, user_id: str) -> dict: - return { - "instance_id": "static", - "instance_name": "static", - "api_key": settings.static_api_key, - "host": settings.static_host, - "port": settings.static_port, - } - - async def start(self, instance_id: str) -> bool: - try: - resp = await self._client.get( - f"http://{settings.static_host}:{settings.static_port}/health" - ) - return resp.status_code == 200 - except httpx.HTTPError: - return False - - async def teardown(self, instance_id: str) -> None: - pass # no-op β€” admin manages the instance - - async def status(self, instance_id: str) -> str: - running = await self.start(instance_id) - return "running" if running else "missing" - - async def close(self) -> None: - await self._client.aclose() diff --git a/terminals/config.py b/terminals/config.py index 13b0c43..2f1bc9c 100644 --- a/terminals/config.py +++ b/terminals/config.py @@ -9,7 +9,10 @@ class Settings(BaseSettings): api_key: str = "" open_webui_url: str = "" # if set, validate JWTs against this Open WebUI instance - # Backend selection: "docker", "local", or "static" + # Database + database_url: str = "sqlite+aiosqlite:///./data/terminals.db" + + # Backend selection: "docker", "kubernetes", or "kubernetes-operator" backend: str = "docker" # Docker settings @@ -17,19 +20,10 @@ class Settings(BaseSettings): network: str = "" data_dir: str = "./data/terminals" - # Local settings (process-managed) - local_binary: str = "open-terminal" - local_port_range_start: int = 9000 - - # Static settings (pre-running instance) - static_host: str = "127.0.0.1" - static_port: int = 8000 - static_api_key: str = "" - port: int = 3000 host: str = "0.0.0.0" - # Kubernetes settings (shared by kubernetes and kubernetes-operator backends) + # Kubernetes settings kubernetes_namespace: str = "terminals" kubernetes_image: str = "ghcr.io/open-webui/open-terminal:latest" kubernetes_storage_class: str = "" # empty = cluster default @@ -42,24 +36,11 @@ class Settings(BaseSettings): kubernetes_crd_group: str = "openwebui.com" kubernetes_crd_version: str = "v1alpha1" - # Operator resource defaults (applied to Terminal CRs) - kubernetes_default_cpu_request: str = "100m" - kubernetes_default_cpu_limit: str = "1" - kubernetes_default_memory_request: str = "256Mi" - kubernetes_default_memory_limit: str = "1Gi" - kubernetes_default_idle_timeout_minutes: int = 30 - kubernetes_default_persistence_enabled: bool = True - kubernetes_default_persistence_size: str = "1Gi" - - # Lifecycle management - idle_timeout_seconds: int = 1800 # 30 min β€” stop instances idle this long - cleanup_interval_seconds: int = 60 # how often to check for idle instances - - # Audit logging - siem_webhook_url: str = "" # if set, forward audit events to this URL - - # Encryption - encryption_key: str = "" # if empty, auto-generated and persisted + # Policy hard caps (cannot be exceeded by API) + max_cpu: str = "" # TERMINALS_MAX_CPU + max_memory: str = "" # TERMINALS_MAX_MEMORY + max_storage: str = "" # TERMINALS_MAX_STORAGE + allowed_images: str = "" # TERMINALS_ALLOWED_IMAGES (comma-separated globs) settings = Settings() diff --git a/terminals/crypto.py b/terminals/crypto.py deleted file mode 100644 index 989df56..0000000 --- a/terminals/crypto.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Symmetric encryption utilities for secret storage. - -Uses Fernet (AES-128-CBC + HMAC-SHA256) from the ``cryptography`` -package. The key is derived from ``settings.encryption_key`` via -SHA-256 so any passphrase length is accepted. -""" - -import base64 -import hashlib -import os -from pathlib import Path - -from cryptography.fernet import Fernet - -from terminals.config import settings - -_fernet: Fernet | None = None - -_KEY_FILE = Path(settings.data_dir) / ".encryption_key" - - -def _get_fernet() -> Fernet: - """Return a cached Fernet instance, bootstrapping the key if needed.""" - global _fernet - if _fernet is not None: - return _fernet - - key = settings.encryption_key - if not key: - # Auto-generate and persist a key on first use. - if _KEY_FILE.exists(): - key = _KEY_FILE.read_text().strip() - else: - key = Fernet.generate_key().decode() - _KEY_FILE.parent.mkdir(parents=True, exist_ok=True) - _KEY_FILE.write_text(key) - os.chmod(_KEY_FILE, 0o600) - - settings.encryption_key = key - - # Derive a valid 32-byte Fernet key from an arbitrary passphrase. - raw = hashlib.sha256(key.encode()).digest() - fernet_key = base64.urlsafe_b64encode(raw) - _fernet = Fernet(fernet_key) - return _fernet - - -def encrypt(plaintext: str) -> str: - """Encrypt a plaintext string β†’ URL-safe base64 ciphertext.""" - return _get_fernet().encrypt(plaintext.encode()).decode() - - -def decrypt(ciphertext: str) -> str: - """Decrypt a ciphertext string β†’ original plaintext.""" - return _get_fernet().decrypt(ciphertext.encode()).decode() diff --git a/terminals/lifecycle.py b/terminals/lifecycle.py deleted file mode 100644 index f2f09f9..0000000 --- a/terminals/lifecycle.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Background lifecycle manager β€” cleans up idle terminal instances.""" - -import asyncio -from datetime import datetime, timedelta, timezone - -from loguru import logger -from sqlalchemy import select - -from terminals.audit import log_audit -from terminals.backends.base import Backend -from terminals.config import settings -from terminals.db.session import async_session -from terminals.models.tenants import Tenant, TenantStatus - - -async def _cleanup_idle(backend: Backend) -> int: - """Tear down instances idle longer than the configured timeout. - - Returns the number of instances cleaned up. - """ - if settings.idle_timeout_seconds <= 0: - return 0 # cleanup disabled - - cutoff = datetime.now(timezone.utc) - timedelta( - seconds=settings.idle_timeout_seconds - ) - cleaned = 0 - - async with async_session() as session: - result = await session.execute( - select(Tenant).where( - Tenant.status == TenantStatus.running, - Tenant.last_accessed_at < cutoff, - ) - ) - idle_tenants = result.scalars().all() - - for tenant in idle_tenants: - logger.info( - "Cleaning up idle tenant {} (last access: {})", - tenant.user_id, - tenant.last_accessed_at, - ) - try: - if tenant.instance_id: - await backend.teardown(tenant.instance_id) - tenant.status = TenantStatus.stopped - cleaned += 1 - - await log_audit( - action="idle_cleanup", - severity="info", - user_id=tenant.user_id, - resource_type="tenant", - resource_id=tenant.instance_id, - detail={ - "last_accessed_at": str(tenant.last_accessed_at), - "idle_timeout_seconds": settings.idle_timeout_seconds, - }, - ) - except Exception: - logger.exception( - "Failed to tear down instance for {}", tenant.user_id - ) - tenant.status = TenantStatus.error - - if cleaned: - await session.commit() - - return cleaned - - - - - -async def run_lifecycle_loop(backend: Backend) -> None: - """Periodically sweep for idle instances until cancelled.""" - interval = settings.cleanup_interval_seconds - logger.info( - "Lifecycle manager started (idle_timeout={}s, interval={}s)", - settings.idle_timeout_seconds, - interval, - ) - while True: - try: - cleaned = await _cleanup_idle(backend) - if cleaned: - logger.info("Cleanup sweep: tore down {} idle instance(s)", cleaned) - except Exception: - logger.exception("Error during cleanup sweep") - - await asyncio.sleep(interval) diff --git a/terminals/main.py b/terminals/main.py index 274d63a..6e374d6 100644 --- a/terminals/main.py +++ b/terminals/main.py @@ -9,6 +9,7 @@ from fastapi.staticfiles import StaticFiles from terminals.backends import create_backend from terminals.config import settings +from terminals.db.session import close_db, init_db from terminals.logging import setup_logging from terminals.middleware import RequestIdMiddleware from terminals.routers.proxy import close_proxy_client, router as proxy_router @@ -19,12 +20,16 @@ async def lifespan(app: FastAPI): """Startup / shutdown lifecycle.""" setup_logging() + # Run DB migrations + await init_db() + app.state.backend = create_backend() yield await close_proxy_client() await app.state.backend.close() + await close_db() app = FastAPI( @@ -49,7 +54,12 @@ async def health(): return {"status": True} -# Catch-all proxy router must be last so /health is matched first. +from terminals.routers.policy import router as policy_router + +# Policy CRUD must be before the catch-all proxy. +app.include_router(policy_router) + +# Catch-all proxy router must be last so /health and /api are matched first. app.include_router(proxy_router) diff --git a/terminals/migrations/env.py b/terminals/migrations/env.py index 566734d..6661f49 100644 --- a/terminals/migrations/env.py +++ b/terminals/migrations/env.py @@ -15,8 +15,8 @@ from sqlalchemy.ext.asyncio import async_engine_from_config from terminals.config import settings # Import *all* models so Base.metadata is fully populated. -from terminals.models.tenants import Base # noqa: F401 -from terminals.models.audit import AuditLog # noqa: F401 +from terminals.models.base import Base # noqa: F401 +from terminals.models.policy import Policy # noqa: F401 # Alembic Config object β€” gives access to alembic.ini values. config = context.config diff --git a/terminals/migrations/versions/001_initial.py b/terminals/migrations/versions/001_initial.py new file mode 100644 index 0000000..cc4749f --- /dev/null +++ b/terminals/migrations/versions/001_initial.py @@ -0,0 +1,40 @@ +"""Initial schema β€” policies and audit log. + +Revision ID: 001_initial +Revises: None +""" + +from alembic import op +import sqlalchemy as sa + +revision = "001_initial" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "policies", + sa.Column("id", sa.String(), primary_key=True), + sa.Column("data", sa.JSON(), nullable=False, server_default="{}"), + sa.Column("created_at", sa.DateTime(), server_default=sa.func.now()), + sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now()), + ) + + op.create_table( + "audit_log", + sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), + sa.Column("timestamp", sa.DateTime(), server_default=sa.func.now()), + sa.Column("action", sa.String(), nullable=False), + sa.Column("severity", sa.String(), server_default="info"), + sa.Column("user_id", sa.String(), nullable=True), + sa.Column("resource_type", sa.String(), nullable=True), + sa.Column("resource_id", sa.String(), nullable=True), + sa.Column("detail", sa.JSON(), nullable=True), + ) + + +def downgrade() -> None: + op.drop_table("audit_log") + op.drop_table("policies") diff --git a/terminals/migrations/versions/001_initial_schema.py b/terminals/migrations/versions/001_initial_schema.py deleted file mode 100644 index 262330a..0000000 --- a/terminals/migrations/versions/001_initial_schema.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Initial schema β€” tenants table. - -Revision ID: 001 -Revises: None -Create Date: 2026-03-06 -""" - -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa - -revision: str = "001" -down_revision: Union[str, None] = None -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - op.create_table( - "tenants", - sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), - sa.Column("user_id", sa.String(), nullable=False, unique=True, index=True), - sa.Column("instance_id", sa.String(), nullable=True), - sa.Column("instance_name", sa.String(), nullable=True), - sa.Column("backend_type", sa.String(), nullable=False, server_default="docker"), - sa.Column("api_key", sa.String(), nullable=False), - sa.Column("host", sa.String(), nullable=True), - sa.Column("port", sa.Integer(), server_default="8000"), - sa.Column( - "status", - sa.Enum("provisioning", "running", "stopped", "error", name="tenantstatus"), - server_default="provisioning", - ), - sa.Column("created_at", sa.DateTime(), server_default=sa.func.now()), - sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now()), - sa.Column("last_accessed_at", sa.DateTime(), server_default=sa.func.now()), - ) - - -def downgrade() -> None: - op.drop_table("tenants") diff --git a/terminals/migrations/versions/002_add_audit_log_table.py b/terminals/migrations/versions/002_add_audit_log_table.py deleted file mode 100644 index 64bd438..0000000 --- a/terminals/migrations/versions/002_add_audit_log_table.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Add audit_logs table. - -Revision ID: 002 -Revises: 001 -Create Date: 2026-03-06 -""" - -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa - -revision: str = "002" -down_revision: Union[str, None] = "001" -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - op.create_table( - "audit_logs", - sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), - sa.Column("action", sa.String(), nullable=False, index=True), - sa.Column("severity", sa.String(), nullable=False, server_default="info"), - sa.Column("user_id", sa.String(), nullable=True, index=True), - sa.Column("request_id", sa.String(), nullable=True), - sa.Column("resource_type", sa.String(), nullable=True), - sa.Column("resource_id", sa.String(), nullable=True), - sa.Column("detail", sa.JSON(), nullable=True), - sa.Column("ip_address", sa.String(), nullable=True), - sa.Column("user_agent", sa.String(), nullable=True), - sa.Column("status_code", sa.Integer(), nullable=True), - sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), index=True), - ) - - -def downgrade() -> None: - op.drop_table("audit_logs") diff --git a/terminals/migrations/versions/003_encrypt_api_keys.py b/terminals/migrations/versions/003_encrypt_api_keys.py deleted file mode 100644 index cd44b31..0000000 --- a/terminals/migrations/versions/003_encrypt_api_keys.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Rename api_key to api_key_encrypted on tenants table. - -Revision ID: 003 -Revises: 002 -Create Date: 2026-03-06 -""" - -from typing import Sequence, Union - -from alembic import op - -revision: str = "003" -down_revision: Union[str, None] = "002" -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - with op.batch_alter_table("tenants") as batch_op: - batch_op.alter_column("api_key", new_column_name="api_key_encrypted") - - -def downgrade() -> None: - with op.batch_alter_table("tenants") as batch_op: - batch_op.alter_column("api_key_encrypted", new_column_name="api_key") diff --git a/terminals/models/audit.py b/terminals/models/audit.py deleted file mode 100644 index 193d2ea..0000000 --- a/terminals/models/audit.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Audit log database model.""" - -from sqlalchemy import Column, DateTime, Integer, JSON, String, func - -from terminals.models.tenants import Base - - -class AuditLog(Base): - __tablename__ = "audit_logs" - - id = Column(Integer, primary_key=True, autoincrement=True) - action = Column(String, nullable=False, index=True) - severity = Column(String, nullable=False, server_default="info") - user_id = Column(String, nullable=True, index=True) - request_id = Column(String, nullable=True) - resource_type = Column(String, nullable=True) - resource_id = Column(String, nullable=True) - detail = Column(JSON, nullable=True) - ip_address = Column(String, nullable=True) - user_agent = Column(String, nullable=True) - status_code = Column(Integer, nullable=True) - created_at = Column(DateTime, server_default=func.now(), index=True) diff --git a/terminals/models/base.py b/terminals/models/base.py new file mode 100644 index 0000000..2f92487 --- /dev/null +++ b/terminals/models/base.py @@ -0,0 +1,7 @@ +"""SQLAlchemy declarative base.""" + +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + pass diff --git a/terminals/models/policy.py b/terminals/models/policy.py new file mode 100644 index 0000000..92bc745 --- /dev/null +++ b/terminals/models/policy.py @@ -0,0 +1,18 @@ +"""Policy database model.""" + +from sqlalchemy import Column, DateTime, String, func +from sqlalchemy.types import JSON + +from terminals.models.base import Base + + +class Policy(Base): + __tablename__ = "policies" + + id = Column(String, primary_key=True) + data = Column(JSON, nullable=False, default=dict) + created_at = Column(DateTime, server_default=func.now()) + updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now()) + + def __repr__(self) -> str: + return f"" diff --git a/terminals/models/schemas.py b/terminals/models/schemas.py deleted file mode 100644 index 045335b..0000000 --- a/terminals/models/schemas.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Pydantic response schemas.""" - -import datetime -from typing import Optional - -from pydantic import BaseModel - -from terminals.models.tenants import TenantStatus - - -class TenantResponse(BaseModel): - model_config = {"from_attributes": True} - - id: int - user_id: str - instance_id: Optional[str] = None - instance_name: Optional[str] = None - backend_type: str = "docker" - host: Optional[str] = None - port: int - status: TenantStatus - created_at: Optional[datetime.datetime] = None - updated_at: Optional[datetime.datetime] = None - last_accessed_at: Optional[datetime.datetime] = None - - -class AuditLogResponse(BaseModel): - model_config = {"from_attributes": True} - - id: int - action: str - severity: str - user_id: Optional[str] = None - request_id: Optional[str] = None - resource_type: Optional[str] = None - resource_id: Optional[str] = None - detail: Optional[dict] = None - ip_address: Optional[str] = None - user_agent: Optional[str] = None - status_code: Optional[int] = None - created_at: Optional[datetime.datetime] = None diff --git a/terminals/models/tenants.py b/terminals/models/tenants.py deleted file mode 100644 index 2e7bc44..0000000 --- a/terminals/models/tenants.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Tenant database model and status enum.""" - -import enum - -from sqlalchemy import Column, DateTime, Enum, Integer, String, func -from sqlalchemy.orm import DeclarativeBase - -from terminals.crypto import decrypt, encrypt - - -# --------------------------------------------------------------------------- -# SQLAlchemy -# --------------------------------------------------------------------------- - - -class Base(DeclarativeBase): - pass - - -class TenantStatus(str, enum.Enum): - provisioning = "provisioning" - running = "running" - stopped = "stopped" - error = "error" - - -class Tenant(Base): - __tablename__ = "tenants" - - id = Column(Integer, primary_key=True, autoincrement=True) - user_id = Column(String, unique=True, nullable=False, index=True) - instance_id = Column(String, nullable=True) - instance_name = Column(String, nullable=True) - backend_type = Column(String, nullable=False, default="docker") - api_key_encrypted = Column(String, nullable=False) - host = Column(String, nullable=True) - port = Column(Integer, default=8000) - status = Column(Enum(TenantStatus), default=TenantStatus.provisioning) - created_at = Column(DateTime, server_default=func.now()) - updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now()) - last_accessed_at = Column(DateTime, server_default=func.now()) - - # ---- Transparent encrypt / decrypt property for api_key ---- - - @property - def api_key(self) -> str: - """Decrypt and return the API key.""" - if not self.api_key_encrypted: - return "" - try: - return decrypt(self.api_key_encrypted) - except Exception: - # Backwards compat: if value is not encrypted yet, return as-is. - return self.api_key_encrypted - - @api_key.setter - def api_key(self, value: str) -> None: - """Encrypt and store the API key.""" - self.api_key_encrypted = encrypt(value) if value else "" diff --git a/terminals/routers/policy.py b/terminals/routers/policy.py new file mode 100644 index 0000000..46aa990 --- /dev/null +++ b/terminals/routers/policy.py @@ -0,0 +1,247 @@ +"""Policy CRUD API.""" + +from datetime import datetime, timezone +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel + +from terminals.config import settings +from terminals.db.session import async_session +from terminals.routers.auth import verify_api_key + +router = APIRouter(prefix="/api/v1", tags=["policies"]) + + +# --------------------------------------------------------------------------- +# Pydantic schemas +# --------------------------------------------------------------------------- + + +class PolicyData(BaseModel): + """Policy data β€” all fields optional, merged with defaults.""" + image: Optional[str] = None + env: Optional[dict] = None + cpu_limit: Optional[str] = None + memory_limit: Optional[str] = None + storage: Optional[str] = None # e.g. "5Gi" β€” absent = ephemeral + allowed_domains: Optional[list] = None # ["*"] = full, [] = none + idle_timeout_minutes: Optional[int] = None + + +class PolicyResponse(BaseModel): + id: str + data: dict + created_at: Optional[str] = None + updated_at: Optional[str] = None + + +class PolicyCreate(BaseModel): + id: str + data: PolicyData = PolicyData() + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _parse_size(value: str) -> int: + """Parse K8s-style size string to bytes. '512Mi' -> 536870912.""" + import re + m = re.match(r"^(\d+(?:\.\d+)?)\s*(Ki|Mi|Gi|Ti)?$", str(value).strip()) + if not m: + return int(value) + num, suffix = float(m.group(1)), m.group(2) or "" + mult = {"": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4} + return int(num * mult[suffix]) + + +def _clamp_policy(data: dict) -> dict: + """Clamp policy values against env var hard caps.""" + result = {k: v for k, v in data.items() if v is not None} + + # Clamp CPU + if settings.max_cpu and "cpu_limit" in result: + try: + if float(result["cpu_limit"]) > float(settings.max_cpu): + result["cpu_limit"] = settings.max_cpu + except (ValueError, TypeError): + pass + + # Clamp memory + if settings.max_memory and "memory_limit" in result: + try: + if _parse_size(result["memory_limit"]) > _parse_size(settings.max_memory): + result["memory_limit"] = settings.max_memory + except Exception: + pass + + # Clamp storage + if settings.max_storage and "storage" in result: + try: + if _parse_size(result["storage"]) > _parse_size(settings.max_storage): + result["storage"] = settings.max_storage + except Exception: + pass + + # Validate image against allowlist + if settings.allowed_images and "image" in result: + import fnmatch + patterns = [p.strip() for p in settings.allowed_images.split(",")] + if not any(fnmatch.fnmatch(result["image"], p) for p in patterns): + raise HTTPException( + status_code=400, + detail=f"Image '{result['image']}' not in allowed list", + ) + + return result + + +def _merge_defaults(policy_data: dict) -> dict: + """Merge env var defaults with policy overrides.""" + defaults = {} + if settings.image: + defaults["image"] = settings.image + return {**defaults, **{k: v for k, v in policy_data.items() if v is not None}} + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + + +@router.get("/policies", dependencies=[Depends(verify_api_key)]) +async def list_policies(): + """List all policies.""" + if async_session is None: + raise HTTPException(status_code=503, detail="Database not configured") + + from terminals.models.policy import Policy + + async with async_session() as session: + from sqlalchemy import select + result = await session.execute(select(Policy).order_by(Policy.created_at)) + policies = result.scalars().all() + return [ + PolicyResponse( + id=p.id, + data=p.data or {}, + created_at=str(p.created_at) if p.created_at else None, + updated_at=str(p.updated_at) if p.updated_at else None, + ) + for p in policies + ] + + +@router.post("/policies", dependencies=[Depends(verify_api_key)], status_code=201) +async def create_policy(body: PolicyCreate): + """Create a new policy.""" + if async_session is None: + raise HTTPException(status_code=503, detail="Database not configured") + + from terminals.models.policy import Policy + + clamped = _clamp_policy(body.data.model_dump(exclude_none=True)) + + async with async_session() as session: + from sqlalchemy import select + existing = await session.execute(select(Policy).where(Policy.id == body.id)) + if existing.scalar_one_or_none(): + raise HTTPException(status_code=409, detail=f"Policy '{body.id}' already exists") + + policy = Policy( + id=body.id, + data=clamped, + created_at=datetime.now(timezone.utc), + updated_at=datetime.now(timezone.utc), + ) + session.add(policy) + await session.commit() + + return PolicyResponse( + id=policy.id, + data=policy.data or {}, + created_at=str(policy.created_at), + updated_at=str(policy.updated_at), + ) + + +@router.get("/policies/{policy_id}", dependencies=[Depends(verify_api_key)]) +async def get_policy(policy_id: str): + """Get a single policy.""" + if async_session is None: + raise HTTPException(status_code=503, detail="Database not configured") + + from terminals.models.policy import Policy + + async with async_session() as session: + from sqlalchemy import select + result = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = result.scalar_one_or_none() + if not policy: + raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found") + + return PolicyResponse( + id=policy.id, + data=policy.data or {}, + created_at=str(policy.created_at) if policy.created_at else None, + updated_at=str(policy.updated_at) if policy.updated_at else None, + ) + + +@router.put("/policies/{policy_id}", dependencies=[Depends(verify_api_key)]) +async def upsert_policy(policy_id: str, body: PolicyData): + """Create or update a policy.""" + if async_session is None: + raise HTTPException(status_code=503, detail="Database not configured") + + from terminals.models.policy import Policy + + clamped = _clamp_policy(body.model_dump(exclude_none=True)) + + async with async_session() as session: + from sqlalchemy import select + result = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = result.scalar_one_or_none() + + if policy: + policy.data = clamped + policy.updated_at = datetime.now(timezone.utc) + else: + policy = Policy( + id=policy_id, + data=clamped, + created_at=datetime.now(timezone.utc), + updated_at=datetime.now(timezone.utc), + ) + session.add(policy) + + await session.commit() + + return PolicyResponse( + id=policy.id, + data=policy.data or {}, + created_at=str(policy.created_at), + updated_at=str(policy.updated_at), + ) + + +@router.delete("/policies/{policy_id}", dependencies=[Depends(verify_api_key)]) +async def delete_policy(policy_id: str): + """Delete a policy.""" + if async_session is None: + raise HTTPException(status_code=503, detail="Database not configured") + + from terminals.models.policy import Policy + + async with async_session() as session: + from sqlalchemy import select + result = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = result.scalar_one_or_none() + if not policy: + raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found") + + await session.delete(policy) + await session.commit() + return {"ok": True} diff --git a/terminals/routers/proxy.py b/terminals/routers/proxy.py index 5f03980..fd87807 100644 --- a/terminals/routers/proxy.py +++ b/terminals/routers/proxy.py @@ -1,9 +1,12 @@ -"""Catch-all reverse proxy into tenant instances. +"""Catch-all reverse proxy into terminal instances. Routing is based on the ``X-User-Id`` header β€” the caller (e.g. Open WebUI backend) sets this header and the proxy resolves / provisions the correct instance automatically. The path structure mirrors open-terminal exactly (``/execute``, ``/files/list``, …) so the two are interchangeable. + +Named policy endpoints: + /p/{policy_id}/* β€” provisions using the named policy config """ import asyncio @@ -14,7 +17,7 @@ from typing import Optional import httpx import websockets -from fastapi import APIRouter, BackgroundTasks, Depends, Header, Query, Request, Response, WebSocket +from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Query, Request, Response, WebSocket from fastapi.responses import JSONResponse from loguru import logger @@ -72,31 +75,35 @@ def _request_id(request) -> Optional[str]: # --------------------------------------------------------------------------- -# Resolve tenant +# Resolve instance # --------------------------------------------------------------------------- @dataclass -class TenantInfo: - """Lightweight tenant descriptor resolved from CRDs.""" +class InstanceInfo: + """Resolved terminal instance.""" instance_id: str host: str port: int api_key: str -async def _resolve_tenant(request, user_id: str) -> TenantInfo: - """Return a running tenant, auto-provisioning via CRD if needed.""" +async def _resolve_instance( + request, + user_id: str, + policy_id: str = "default", + spec: Optional[dict] = None, +) -> InstanceInfo: + """Return a running instance, auto-provisioning if needed.""" backend = request.app.state.backend - info = await backend.ensure_terminal(user_id) + info = await backend.ensure_terminal(user_id, policy_id=policy_id, spec=spec) if info is None: raise RuntimeError(f"Failed to provision terminal for user {user_id}") - # Touch activity so the operator knows the terminal is in use. try: await backend.touch_activity(user_id) except Exception: logger.debug("touch_activity failed for user {}", user_id) - return TenantInfo( + return InstanceInfo( instance_id=info["instance_id"], host=info["host"], port=info["port"], @@ -112,17 +119,21 @@ async def _resolve_tenant(request, user_id: str) -> TenantInfo: async def _proxy_request( request: Request, user_id: str, path: str, background_tasks: Optional[BackgroundTasks] = None, + policy_id: str = "default", + spec: Optional[dict] = None, ) -> Response: - """Proxy a request to the user's Open Terminal instance.""" - tenant = await _resolve_tenant(request, user_id) + """Forward an HTTP request to the user's terminal instance.""" + instance = await _resolve_instance( + request, user_id, policy_id=policy_id, spec=spec, + ) - target_url = f"http://{tenant.host}:{tenant.port}/{path}" + target_url = f"http://{instance.host}:{instance.port}/{path}" if request.query_params: target_url += f"?{request.query_params}" headers = dict(request.headers) # Replace auth with the instance's own API key. - headers["authorization"] = f"Bearer {tenant.api_key}" + headers["authorization"] = f"Bearer {instance.api_key}" # Remove hop-by-hop / routing headers. for h in ("host", "transfer-encoding", "connection", "x-user-id"): headers.pop(h, None) @@ -177,14 +188,14 @@ async def get_openapi_spec(request: Request): if _cached_spec is not None and (now - _cached_spec_ts) < _SPEC_CACHE_TTL: return JSONResponse(content=_cached_spec) - # Find any running tenant to fetch the spec from, or provision a system one. - tenant = await _resolve_tenant(request, _SYSTEM_USER_ID) + # Provision a system instance to fetch the spec from. + instance = await _resolve_instance(request, _SYSTEM_USER_ID) client = await _get_proxy_client() try: resp = await client.get( - f"http://{tenant.host}:{tenant.port}/openapi.json", - headers={"Authorization": f"Bearer {tenant.api_key}"}, + f"http://{instance.host}:{instance.port}/openapi.json", + headers={"Authorization": f"Bearer {instance.api_key}"}, ) resp.raise_for_status() spec = resp.json() @@ -212,7 +223,89 @@ async def get_openapi_spec(request: Request): # --------------------------------------------------------------------------- -# Header-based catch-all proxy (primary integration point) +# Named policy proxy β€” /p/{policy_id}/{path} +# --------------------------------------------------------------------------- + + +async def _resolve_policy_spec(policy_id: str) -> tuple[str, dict | None]: + """Look up a policy by ID. Returns (policy_id, merged spec) or raises 404.""" + from terminals.db.session import async_session as db_session + + if db_session is None: + return policy_id, None + + from terminals.models.policy import Policy + from terminals.routers.policy import _merge_defaults + + async with db_session() as session: + from sqlalchemy import select + result = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = result.scalar_one_or_none() + if policy is None: + raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found") + + return policy_id, _merge_defaults(policy.data or {}) + + +@router.get( + "/p/{policy_id}/openapi.json", + dependencies=[Depends(verify_api_key)], +) +async def policy_openapi_spec( + policy_id: str, + request: Request, +): + """Serve the OpenAPI spec via a named policy container.""" + _id, spec = await _resolve_policy_spec(policy_id) + instance = await _resolve_instance(request, _SYSTEM_USER_ID, policy_id=_id, spec=spec) + + client = await _get_proxy_client() + try: + resp = await client.get( + f"http://{instance.host}:{instance.port}/openapi.json", + headers={"Authorization": f"Bearer {instance.api_key}"}, + ) + resp.raise_for_status() + spec_data = resp.json() + except Exception as e: + logger.error("Failed to fetch OpenAPI spec from policy instance: {}", e) + return JSONResponse( + content={"error": "Failed to fetch OpenAPI spec"}, + status_code=502, + ) + + # Strip auth from spec β€” orchestrator handles auth transparently. + spec_data.pop("security", None) + spec_data.get("components", {}).pop("securitySchemes", None) + for _path_methods in spec_data.get("paths", {}).values(): + for _op in _path_methods.values(): + if isinstance(_op, dict): + _op.pop("security", None) + + return JSONResponse(content=spec_data) + + +@router.api_route( + "/p/{policy_id}/{path:path}", + methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"], +) +async def policy_proxy( + policy_id: str, + path: str, + request: Request, + background_tasks: BackgroundTasks, + x_user_id: str = Depends(verify_user_id), +): + """Proxy a request through a named policy endpoint.""" + _id, spec = await _resolve_policy_spec(policy_id) + return await _proxy_request( + request, x_user_id, path, background_tasks, + policy_id=_id, spec=spec, + ) + + +# --------------------------------------------------------------------------- +# Header-based catch-all proxy β€” default endpoint (backward compat) # --------------------------------------------------------------------------- @@ -228,9 +321,7 @@ async def proxy( ): """Reverse-proxy any request into the user's Open Terminal instance. - The target user is identified by the ``X-User-Id`` header. The path - structure mirrors the open-terminal API exactly so the two backends - are fully interchangeable from the caller's perspective. + Uses settings.* defaults β€” no policy lookup. """ return await _proxy_request(request, x_user_id, path, background_tasks) @@ -240,62 +331,64 @@ async def proxy( # --------------------------------------------------------------------------- -@router.websocket("/api/terminals/{session_id}") -async def ws_terminal_proxy( - ws: WebSocket, - session_id: str, - token: str = Query(""), - user_id: str = Query(""), -): - """Proxy a WebSocket terminal session to the user's Open Terminal instance. +async def _validate_ws_auth( + ws: WebSocket, token: str, user_id: str +) -> Optional[str]: + """Validate WS auth, return verified user_id or close the socket. - Authentication is via the ``token`` query parameter (validated against - the orchestrator API key). The ``user_id`` query param identifies the - target tenant (equivalent to the ``X-User-Id`` header used by HTTP routes). + Returns the effective user_id on success, or ``None`` if closed. """ - # Validate token β€” support JWT (Open WebUI) and API key modes. verified_user_id = None if settings.open_webui_url: - # JWT mode β€” validate against Open WebUI and extract verified identity. try: verified_user_id = await validate_token(token) except Exception: await ws.close(code=4001, reason="Invalid token") - return + return None elif settings.api_key and token != settings.api_key: await ws.close(code=4001, reason="Invalid API key") - return + return None if not user_id: await ws.close(code=4002, reason="Missing user_id") - return + return None - # In JWT mode, enforce that user_id matches the verified identity. if verified_user_id is not None and verified_user_id != user_id: await ws.close(code=4003, reason="user_id does not match authenticated identity") - return + return None + return user_id + + +async def _ws_proxy_handler( + ws: WebSocket, + session_id: str, + user_id: str, + policy_id: str = "default", + spec: Optional[dict] = None, +): + """Core WebSocket proxy logic, shared by default and policy routes.""" await ws.accept() global active_ws_connections active_ws_connections += 1 try: - tenant = await _resolve_tenant(ws, user_id) + instance = await _resolve_instance( + ws, user_id, policy_id=policy_id, spec=spec + ) except Exception as e: - logger.error("Failed to resolve tenant for WS: {}", e) + logger.error("Failed to resolve instance for WS: {}", e) await ws.close(code=4003, reason="Failed to resolve terminal instance") return - upstream_url = f"ws://{tenant.host}:{tenant.port}/api/terminals/{session_id}" + upstream_url = f"ws://{instance.host}:{instance.port}/api/terminals/{session_id}" try: async with websockets.connect(upstream_url) as upstream: - # First-message auth to upstream - await upstream.send(json.dumps({"type": "auth", "token": tenant.api_key})) + await upstream.send(json.dumps({"type": "auth", "token": instance.api_key})) async def _client_to_upstream(): - """Forward client WebSocket β†’ upstream.""" try: while True: msg = await ws.receive() @@ -309,7 +402,6 @@ async def ws_terminal_proxy( logger.debug("clientβ†’upstream closed: {}", e) async def _upstream_to_client(): - """Forward upstream β†’ client WebSocket.""" try: async for message in upstream: if isinstance(message, bytes): @@ -332,3 +424,41 @@ async def ws_terminal_proxy( await ws.close() except Exception: pass + + +@router.websocket("/api/terminals/{session_id}") +async def ws_terminal_proxy( + ws: WebSocket, + session_id: str, + token: str = Query(""), + user_id: str = Query(""), +): + """Default WebSocket terminal proxy (no policy).""" + effective_user = await _validate_ws_auth(ws, token, user_id) + if effective_user is None: + return + await _ws_proxy_handler(ws, session_id, effective_user) + + +@router.websocket("/p/{policy_id}/api/terminals/{session_id}") +async def ws_policy_terminal_proxy( + ws: WebSocket, + policy_id: str, + session_id: str, + token: str = Query(""), + user_id: str = Query(""), +): + """Policy-scoped WebSocket terminal proxy.""" + effective_user = await _validate_ws_auth(ws, token, user_id) + if effective_user is None: + return + + try: + _id, spec = await _resolve_policy_spec(policy_id) + except HTTPException: + await ws.close(code=4004, reason=f"Policy '{policy_id}' not found") + return + + await _ws_proxy_handler(ws, session_id, effective_user, policy_id=_id, spec=spec) + + diff --git a/terminals/routers/tenants.py b/terminals/routers/tenants.py deleted file mode 100644 index 5bce149..0000000 --- a/terminals/routers/tenants.py +++ /dev/null @@ -1,392 +0,0 @@ -"""Tenant CRUD API routes.""" - -from typing import Optional - -from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Query, Request -from loguru import logger -from sqlalchemy import select -from sqlalchemy.ext.asyncio import AsyncSession - -from terminals.audit import log_audit -from terminals.config import settings -from terminals.db.session import async_session -from terminals.models.tenants import Tenant, TenantStatus -from terminals.models.audit import AuditLog -from terminals.models.schemas import AuditLogResponse, TenantResponse - -import httpx - -router = APIRouter() - -# --------------------------------------------------------------------------- -# Auth dependency -# --------------------------------------------------------------------------- - -_owui_client: Optional[httpx.AsyncClient] = None - - -async def _get_owui_client() -> httpx.AsyncClient: - global _owui_client - if _owui_client is None: - _owui_client = httpx.AsyncClient(timeout=10.0) - return _owui_client - - -async def validate_token(token: str) -> Optional[str]: - """Validate a bearer token against the Open WebUI instance. - - Returns the verified user ID on success. - Raises ``HTTPException`` on failure. - - Only call when ``settings.open_webui_url`` is set. - """ - client = await _get_owui_client() - url = settings.open_webui_url.rstrip("/") - try: - resp = await client.get( - f"{url}/api/v1/auths/", - headers={"Authorization": f"Bearer {token}"}, - ) - if resp.status_code != 200: - raise HTTPException(status_code=401, detail="Invalid token") - except httpx.HTTPError: - raise HTTPException(status_code=502, detail="Failed to reach Open WebUI") - - data = resp.json() - verified_user_id = data.get("id") - if not verified_user_id: - raise HTTPException(status_code=401, detail="Token response missing user ID") - return verified_user_id - - -async def verify_api_key( - authorization: Optional[str] = Header(None), -) -> Optional[str]: - """Validate the caller's token. - - Supports three modes: - 1. Open WebUI - validates the JWT against the configured Open WebUI instance - 2. API Key - checks against TERMINALS_API_KEY - 3. Open - no auth when neither is configured - - Returns the verified user ID when using Open WebUI JWT validation, - or ``None`` for API-key / open modes (where ``X-User-Id`` is trusted). - """ - # Mode 1: Open WebUI JWT validation - if settings.open_webui_url: - if not authorization: - raise HTTPException(status_code=401, detail="Missing Authorization header") - scheme, _, token = authorization.partition(" ") - if scheme.lower() != "bearer" or not token: - raise HTTPException(status_code=401, detail="Invalid Authorization header") - return await validate_token(token) - - # Mode 2: Static API key - if settings.api_key: - if not authorization: - raise HTTPException(status_code=401, detail="Missing Authorization header") - scheme, _, token = authorization.partition(" ") - if scheme.lower() != "bearer" or token != settings.api_key: - raise HTTPException(status_code=401, detail="Invalid API key") - return None - - # Mode 3: Open access (no key configured) - return None - - -async def verify_user_id( - verified_id: Optional[str] = Depends(verify_api_key), - x_user_id: str = Header(..., alias="X-User-Id"), -) -> str: - """Return the effective user ID after verifying against JWT identity. - - In JWT mode (``open_webui_url`` configured), the user ID extracted from - the validated token **must** match ``X-User-Id``. In API-key or open - modes the header is trusted as-is. - """ - if verified_id is not None and verified_id != x_user_id: - raise HTTPException( - status_code=403, - detail="X-User-Id does not match authenticated identity", - ) - return x_user_id - - -# --------------------------------------------------------------------------- -# DB helpers -# --------------------------------------------------------------------------- - - -async def _get_tenant(session: AsyncSession, user_id: str) -> Optional[Tenant]: - result = await session.execute(select(Tenant).where(Tenant.user_id == user_id)) - return result.scalar_one_or_none() - - -async def _provision_tenant(request: Request, session: AsyncSession, user_id: str) -> Tenant: - """Provision a new instance via the active backend and persist the tenant row.""" - backend = request.app.state.backend - info = await backend.provision(user_id) - tenant = Tenant( - user_id=user_id, - instance_id=info["instance_id"], - instance_name=info["instance_name"], - backend_type=settings.backend, - api_key=info["api_key"], - host=info["host"], - port=info["port"], - status=TenantStatus.running, - ) - session.add(tenant) - await session.commit() - await session.refresh(tenant) - return tenant - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _client_ip(request: Request) -> str: - """Extract client IP, respecting X-Forwarded-For.""" - forwarded = request.headers.get("x-forwarded-for") - if forwarded: - return forwarded.split(",")[0].strip() - return request.client.host if request.client else "" - - -def _user_agent(request: Request) -> str: - return request.headers.get("user-agent", "") - - -def _request_id(request: Request) -> Optional[str]: - return getattr(request.state, "request_id", None) - - -# --------------------------------------------------------------------------- -# Tenant CRUD -# --------------------------------------------------------------------------- - - -@router.post("/tenants/", response_model=TenantResponse) -async def create_tenant( - request: Request, - background_tasks: BackgroundTasks, - x_user_id: str = Depends(verify_user_id), -): - """Provision a terminal for a user (idempotent).""" - backend = request.app.state.backend - async with async_session() as session: - tenant = await _get_tenant(session, x_user_id) - if tenant is not None: - # Ensure existing instance is running. - if tenant.instance_id: - running = await backend.start(tenant.instance_id) - if running and tenant.status != TenantStatus.running: - old_status = tenant.status.value - tenant.status = TenantStatus.running - await session.commit() - await session.refresh(tenant) - background_tasks.add_task( - log_audit, - action="tenant_started", - severity="info", - user_id=x_user_id, - request_id=_request_id(request), - resource_type="tenant", - resource_id=tenant.instance_id, - detail={"before": old_status, "after": "running"}, - ip_address=_client_ip(request), - user_agent=_user_agent(request), - status_code=200, - ) - return tenant - - tenant = await _provision_tenant(request, session, x_user_id) - background_tasks.add_task( - log_audit, - action="tenant_created", - severity="info", - user_id=x_user_id, - request_id=_request_id(request), - resource_type="tenant", - resource_id=tenant.instance_id, - detail={ - "instance_name": tenant.instance_name, - "backend": tenant.backend_type, - "host": tenant.host, - "port": tenant.port, - }, - ip_address=_client_ip(request), - user_agent=_user_agent(request), - status_code=200, - ) - return tenant - - -@router.get("/tenants/", response_model=list[TenantResponse], dependencies=[Depends(verify_api_key)]) -async def list_tenants(): - """List all tenants.""" - async with async_session() as session: - result = await session.execute(select(Tenant)) - return result.scalars().all() - - -@router.get("/tenants/{user_id}", response_model=TenantResponse, dependencies=[Depends(verify_api_key)]) -async def get_tenant(user_id: str): - """Get a single tenant by user ID.""" - async with async_session() as session: - tenant = await _get_tenant(session, user_id) - if tenant is None: - raise HTTPException(status_code=404, detail="Tenant not found") - return tenant - - -@router.delete("/tenants/{user_id}", dependencies=[Depends(verify_api_key)]) -async def delete_tenant(request: Request, background_tasks: BackgroundTasks, user_id: str): - """Stop, remove the instance, and delete the tenant record.""" - backend = request.app.state.backend - async with async_session() as session: - tenant = await _get_tenant(session, user_id) - if tenant is None: - raise HTTPException(status_code=404, detail="Tenant not found") - - instance_id = tenant.instance_id - if instance_id: - await backend.teardown(instance_id) - - await session.delete(tenant) - await session.commit() - - background_tasks.add_task( - log_audit, - action="tenant_deleted", - severity="warning", - user_id=user_id, - request_id=_request_id(request), - resource_type="tenant", - resource_id=instance_id, - ip_address=_client_ip(request), - user_agent=_user_agent(request), - status_code=200, - ) - return {"detail": "deleted"} - - -@router.post("/tenants/{user_id}/start", response_model=TenantResponse, dependencies=[Depends(verify_api_key)]) -async def start_tenant(request: Request, background_tasks: BackgroundTasks, user_id: str): - """Start a stopped tenant instance.""" - backend = request.app.state.backend - async with async_session() as session: - tenant = await _get_tenant(session, user_id) - if tenant is None: - raise HTTPException(status_code=404, detail="Tenant not found") - if not tenant.instance_id: - raise HTTPException(status_code=400, detail="No instance to start") - - running = await backend.start(tenant.instance_id) - if running: - old_status = tenant.status.value - tenant.status = TenantStatus.running - await session.commit() - await session.refresh(tenant) - background_tasks.add_task( - log_audit, action="tenant_started", severity="info", - user_id=user_id, request_id=_request_id(request), - resource_type="tenant", resource_id=tenant.instance_id, - detail={"before": old_status, "after": "running"}, - ip_address=_client_ip(request), - ) - return tenant - - -@router.post("/tenants/{user_id}/stop", response_model=TenantResponse, dependencies=[Depends(verify_api_key)]) -async def stop_tenant(request: Request, background_tasks: BackgroundTasks, user_id: str): - """Stop a tenant instance (keeps DB record).""" - backend = request.app.state.backend - async with async_session() as session: - tenant = await _get_tenant(session, user_id) - if tenant is None: - raise HTTPException(status_code=404, detail="Tenant not found") - if not tenant.instance_id: - raise HTTPException(status_code=400, detail="No instance to stop") - - await backend.teardown(tenant.instance_id) - old_status = tenant.status.value - tenant.status = TenantStatus.stopped - await session.commit() - await session.refresh(tenant) - background_tasks.add_task( - log_audit, action="tenant_stopped", severity="info", - user_id=user_id, request_id=_request_id(request), - resource_type="tenant", resource_id=tenant.instance_id, - detail={"before": old_status, "after": "stopped"}, - ip_address=_client_ip(request), - ) - return tenant - - -@router.get("/config", dependencies=[Depends(verify_api_key)]) -async def get_config(): - """Return sanitized runtime configuration (no secrets).""" - return { - "backend": settings.backend, - "image": settings.image, - "network": settings.network, - "data_dir": settings.data_dir, - "port": settings.port, - "host": settings.host, - "idle_timeout_seconds": settings.idle_timeout_seconds, - "cleanup_interval_seconds": settings.cleanup_interval_seconds, - "kubernetes_namespace": settings.kubernetes_namespace, - "kubernetes_image": settings.kubernetes_image, - "kubernetes_storage_class": settings.kubernetes_storage_class, - "kubernetes_storage_size": settings.kubernetes_storage_size, - "kubernetes_service_type": settings.kubernetes_service_type, - "has_api_key": bool(settings.api_key), - "has_open_webui_url": bool(settings.open_webui_url), - "has_siem_webhook": bool(settings.siem_webhook_url), - } - - -@router.get("/stats", dependencies=[Depends(verify_api_key)]) -async def get_stats(): - """Return aggregate stats for the dashboard.""" - from terminals.routers.proxy import active_ws_connections - - async with async_session() as session: - result = await session.execute(select(Tenant)) - tenants = result.scalars().all() - - total = len(tenants) - running = sum(1 for t in tenants if t.status == TenantStatus.running) - stopped = sum(1 for t in tenants if t.status == TenantStatus.stopped) - error = sum(1 for t in tenants if t.status == TenantStatus.error) - - return { - "total": total, - "running": running, - "stopped": stopped, - "error": error, - "active_ws_connections": active_ws_connections, - } - - -@router.get("/audit-logs", response_model=list[AuditLogResponse], dependencies=[Depends(verify_api_key)]) -async def list_audit_logs( - limit: int = Query(100, ge=1, le=1000), - offset: int = Query(0, ge=0), - action: str | None = Query(None), - user_id: str | None = Query(None), -): - """Query persistent audit logs with optional filters.""" - async with async_session() as session: - stmt = select(AuditLog).order_by(AuditLog.created_at.desc()) - if action: - stmt = stmt.where(AuditLog.action == action) - if user_id: - stmt = stmt.where(AuditLog.user_id == user_id) - stmt = stmt.offset(offset).limit(limit) - result = await session.execute(stmt) - return result.scalars().all() -