mirror of
https://github.com/open-webui/terminals.git
synced 2026-11-22 21:50:42 -05:00
init
This commit is contained in:
1 parent
d8d2579468
commit
c9f856256b
60 files changed
+8266
-3
No files matched your search
+24
@@ -0,0 +1,24 @@
|
||||
# -- Stage 1: Build the SvelteKit frontend --
|
||||
FROM node:20-slim AS frontend
|
||||
|
||||
WORKDIR /app/frontend
|
||||
COPY terminals/frontend/package.json terminals/frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY terminals/frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
# -- Stage 2: Python application --
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
# Copy built frontend assets from stage 1
|
||||
COPY --from=frontend /app/frontend/build ./terminals/frontend/build
|
||||
|
||||
RUN pip install --no-cache-dir .
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
ENTRYPOINT ["terminals"]
|
||||
CMD ["serve"]
|
||||
@@ -1,9 +1,380 @@
|
||||
# Terminals
|
||||
|
||||
Multi-tenant terminal orchestrator for [Open Terminal](https://github.com/open-webui/open-terminal).
|
||||
> **Alpha** – This project is under active development. APIs and configuration may change.
|
||||
|
||||
Provisions and manages isolated Open Terminal containers per user, with tenant scoping and a single authenticated API entry point.
|
||||
Multi-tenant terminal orchestrator for [Open Terminal](https://github.com/open-webui/open-terminal). Provisions and manages isolated terminal instances per user with automatic lifecycle management.
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-backend** – Docker, Kubernetes, Kubernetes Operator, local process, or static instance
|
||||
- **Auto-provisioning** – instances created on first request, re-provisioned if missing
|
||||
- **Idle cleanup** – background manager stops instances after configurable idle timeout
|
||||
- **Reverse proxy** – catch-all HTTP and WebSocket proxy routes requests to the correct tenant
|
||||
- **Auth** – Open WebUI JWT validation, static API key, or open access
|
||||
- **Admin dashboard** – SvelteKit static frontend with tenant management, live health, and config view
|
||||
- **Audit logging** – structured events via loguru with optional SIEM webhook forwarding
|
||||
- **Encrypted secrets** – API keys stored encrypted at rest with Fernet (AES-128-CBC + HMAC-SHA256)
|
||||
- **Database migrations** – Alembic migrations run automatically on startup
|
||||
- **PostgreSQL or SQLite** – async SQLAlchemy supports both via connection string
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Python 3.11+**
|
||||
- **Docker** (if using the `docker` backend – the default)
|
||||
- **Node.js 20+** (only if building the admin frontend)
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Install
|
||||
|
||||
```bash
|
||||
# Using pip
|
||||
pip install -e .
|
||||
|
||||
# Using uv (recommended)
|
||||
uv sync
|
||||
```
|
||||
|
||||
### 2. Run
|
||||
|
||||
```bash
|
||||
terminals serve
|
||||
```
|
||||
|
||||
The server starts on `http://0.0.0.0:3000`. An API key is auto-generated on first run and printed to the console:
|
||||
|
||||
```
|
||||
============================================================
|
||||
API Key: <your-generated-key>
|
||||
============================================================
|
||||
```
|
||||
|
||||
### 3. Verify
|
||||
|
||||
```bash
|
||||
curl http://localhost:3000/health
|
||||
# {"status": true}
|
||||
```
|
||||
|
||||
### 4. Provision a terminal for a user
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3000/api/v1/tenants/ \
|
||||
-H "Authorization: Bearer <your-api-key>" \
|
||||
-H "X-User-Id: user-123"
|
||||
```
|
||||
|
||||
### 5. Proxy requests to the user's terminal
|
||||
|
||||
All requests to `/terminals/*` are transparently proxied to the user's Open Terminal instance:
|
||||
|
||||
```bash
|
||||
# List files in the user's terminal
|
||||
curl http://localhost:3000/terminals/files/list \
|
||||
-H "Authorization: Bearer <your-api-key>" \
|
||||
-H "X-User-Id: user-123"
|
||||
|
||||
# Execute a command
|
||||
curl -X POST http://localhost:3000/terminals/execute \
|
||||
-H "Authorization: Bearer <your-api-key>" \
|
||||
-H "X-User-Id: user-123" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"command": "echo hello"}'
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings are loaded from environment variables prefixed with `TERMINALS_`. You can also use a `.env` file in the working directory.
|
||||
|
||||
### Core Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_API_KEY` | *(auto-generated)* | Bearer token for API auth |
|
||||
| `TERMINALS_OPEN_WEBUI_URL` | | Open WebUI instance URL for JWT auth |
|
||||
| `TERMINALS_DATABASE_URL` | `sqlite+aiosqlite:///./data/terminals.db` | SQLAlchemy async connection URL |
|
||||
| `TERMINALS_BACKEND` | `docker` | Backend: `docker`, `kubernetes`, `kubernetes-operator`, `local`, `static` |
|
||||
| `TERMINALS_PORT` | `3000` | Server bind port |
|
||||
| `TERMINALS_HOST` | `0.0.0.0` | Server bind host |
|
||||
| `TERMINALS_ENCRYPTION_KEY` | *(auto-generated)* | Key for encrypting stored API keys |
|
||||
|
||||
### Docker Backend Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_IMAGE` | `ghcr.io/open-webui/open-terminal:latest` | Container image to provision |
|
||||
| `TERMINALS_NETWORK` | | Docker network name (containers use IP if empty) |
|
||||
| `TERMINALS_DATA_DIR` | `./data/terminals` | Host directory for per-user data volumes |
|
||||
|
||||
### Local Backend Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_LOCAL_BINARY` | `open-terminal` | Path to the `open-terminal` binary |
|
||||
| `TERMINALS_LOCAL_PORT_RANGE_START` | `9000` | First port for process allocation |
|
||||
|
||||
### Static Backend Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_STATIC_HOST` | `127.0.0.1` | Pre-running instance host |
|
||||
| `TERMINALS_STATIC_PORT` | `8000` | Pre-running instance port |
|
||||
| `TERMINALS_STATIC_API_KEY` | | API key for the static instance |
|
||||
|
||||
### Kubernetes Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_KUBERNETES_NAMESPACE` | `terminals` | K8s namespace for terminal pods |
|
||||
| `TERMINALS_KUBERNETES_IMAGE` | `ghcr.io/open-webui/open-terminal:latest` | Container image |
|
||||
| `TERMINALS_KUBERNETES_STORAGE_CLASS` | *(cluster default)* | PVC storage class |
|
||||
| `TERMINALS_KUBERNETES_STORAGE_SIZE` | `1Gi` | PVC size per user |
|
||||
| `TERMINALS_KUBERNETES_SERVICE_TYPE` | `ClusterIP` | Service type |
|
||||
| `TERMINALS_KUBERNETES_KUBECONFIG` | *(in-cluster)* | Path to kubeconfig file |
|
||||
| `TERMINALS_KUBERNETES_LABELS` | | Extra labels as `k=v,k2=v2` |
|
||||
|
||||
### Kubernetes Operator Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_KUBERNETES_CRD_GROUP` | `openwebui.com` | CRD API group |
|
||||
| `TERMINALS_KUBERNETES_CRD_VERSION` | `v1alpha1` | CRD API version |
|
||||
|
||||
### Lifecycle & Observability
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `TERMINALS_IDLE_TIMEOUT_SECONDS` | `1800` | Stop instances idle longer than this (0 = disabled) |
|
||||
| `TERMINALS_CLEANUP_INTERVAL_SECONDS` | `60` | How often to sweep for idle instances |
|
||||
| `TERMINALS_SIEM_WEBHOOK_URL` | | Forward audit events to this URL |
|
||||
|
||||
## Authentication
|
||||
|
||||
Terminals supports three authentication modes, determined by which environment variables are set:
|
||||
|
||||
### 1. Open WebUI JWT (recommended)
|
||||
|
||||
```bash
|
||||
export TERMINALS_OPEN_WEBUI_URL=https://your-openwebui.example.com
|
||||
```
|
||||
|
||||
Tokens are validated against the Open WebUI `/api/v1/auths/` endpoint. The verified user ID must match the `X-User-Id` header.
|
||||
|
||||
### 2. Static API Key
|
||||
|
||||
```bash
|
||||
export TERMINALS_API_KEY=my-secret-key
|
||||
```
|
||||
|
||||
Clients pass `Authorization: Bearer my-secret-key`. If no key is set, one is auto-generated on startup.
|
||||
|
||||
### 3. Open Access
|
||||
|
||||
If neither `TERMINALS_OPEN_WEBUI_URL` nor `TERMINALS_API_KEY` is set, all requests are accepted without authentication.
|
||||
|
||||
## Backends
|
||||
|
||||
### Docker (default)
|
||||
|
||||
Provisions one container per user via the Docker socket:
|
||||
|
||||
```bash
|
||||
export TERMINALS_BACKEND=docker
|
||||
# Ensure Docker socket is accessible
|
||||
```
|
||||
|
||||
Each user gets an isolated container with their data mounted at `/home/user`. Containers are named `terminals-<user-id>`.
|
||||
|
||||
### Kubernetes
|
||||
|
||||
Creates a Pod + PVC + Service per user via the Kubernetes API:
|
||||
|
||||
```bash
|
||||
export TERMINALS_BACKEND=kubernetes
|
||||
export TERMINALS_KUBERNETES_NAMESPACE=terminals
|
||||
# If running outside the cluster:
|
||||
export TERMINALS_KUBERNETES_KUBECONFIG=~/.kube/config
|
||||
```
|
||||
|
||||
### Kubernetes Operator
|
||||
|
||||
Delegates to a Kopf-based operator that watches `Terminal` CRDs:
|
||||
|
||||
```bash
|
||||
export TERMINALS_BACKEND=kubernetes-operator
|
||||
```
|
||||
|
||||
Deploy the operator and CRD first:
|
||||
|
||||
```bash
|
||||
kubectl apply -f manifests/terminal-crd.yaml
|
||||
kubectl apply -f manifests/operator-deployment.yaml
|
||||
```
|
||||
|
||||
### Local
|
||||
|
||||
Spawns `open-terminal` as a child process per user (useful for development):
|
||||
|
||||
```bash
|
||||
export TERMINALS_BACKEND=local
|
||||
export TERMINALS_LOCAL_BINARY=open-terminal # must be on PATH
|
||||
```
|
||||
|
||||
### Static
|
||||
|
||||
Proxies all users to a single pre-running Open Terminal instance (no lifecycle management):
|
||||
|
||||
```bash
|
||||
export TERMINALS_BACKEND=static
|
||||
export TERMINALS_STATIC_HOST=127.0.0.1
|
||||
export TERMINALS_STATIC_PORT=8000
|
||||
export TERMINALS_STATIC_API_KEY=your-instance-api-key
|
||||
```
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
docker build -t terminals .
|
||||
```
|
||||
|
||||
### Run
|
||||
|
||||
```bash
|
||||
docker run -p 3000:3000 \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v $(pwd)/data:/app/data \
|
||||
terminals
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```yaml
|
||||
services:
|
||||
terminals:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- terminals-data:/app/data
|
||||
environment:
|
||||
TERMINALS_API_KEY: "your-secret-key"
|
||||
# TERMINALS_OPEN_WEBUI_URL: "http://open-webui:8080"
|
||||
|
||||
volumes:
|
||||
terminals-data:
|
||||
```
|
||||
|
||||
## Database
|
||||
|
||||
### SQLite (default)
|
||||
|
||||
No setup required. The database file is created automatically at `./data/terminals.db`.
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
```bash
|
||||
export TERMINALS_DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/terminals
|
||||
```
|
||||
|
||||
> **Note:** When using PostgreSQL, add `asyncpg` to your dependencies:
|
||||
> ```bash
|
||||
> pip install asyncpg
|
||||
> ```
|
||||
|
||||
### Migrations
|
||||
|
||||
Migrations run automatically on startup. You can also manage them manually via the CLI:
|
||||
|
||||
```bash
|
||||
# Run pending migrations
|
||||
terminals db upgrade
|
||||
|
||||
# Show current revision
|
||||
terminals db current
|
||||
|
||||
# Create a new migration
|
||||
terminals db revision -m "add new column"
|
||||
|
||||
# Stamp DB without running migrations
|
||||
terminals db stamp head
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
# Clone and install
|
||||
git clone https://github.com/open-webui/terminals.git
|
||||
cd terminals
|
||||
uv sync
|
||||
|
||||
# Start the backend in development mode
|
||||
./dev.sh
|
||||
# or equivalently:
|
||||
uv run uvicorn terminals.main:app --reload
|
||||
```
|
||||
|
||||
### Frontend
|
||||
|
||||
The admin dashboard is a SvelteKit static app:
|
||||
|
||||
```bash
|
||||
cd terminals/frontend
|
||||
npm install
|
||||
npm run dev # dev server on :5173
|
||||
npm run build # production build → build/
|
||||
```
|
||||
|
||||
The production build is served by FastAPI at `/` when present.
|
||||
|
||||
### CLI Reference
|
||||
|
||||
```bash
|
||||
terminals serve # start the API server
|
||||
terminals serve --host 0.0.0.0 --port 8080 --api-key my-key
|
||||
terminals db upgrade # run migrations
|
||||
terminals db current # show DB revision
|
||||
terminals db revision -m "description"
|
||||
terminals db stamp head
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Admin Endpoints (`/api/v1`)
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| `POST` | `/api/v1/tenants/` | Provision a terminal (idempotent) |
|
||||
| `GET` | `/api/v1/tenants/` | List all tenants |
|
||||
| `GET` | `/api/v1/tenants/{user_id}` | Get a single tenant |
|
||||
| `DELETE` | `/api/v1/tenants/{user_id}` | Delete tenant and instance |
|
||||
| `POST` | `/api/v1/tenants/{user_id}/start` | Start a stopped tenant |
|
||||
| `POST` | `/api/v1/tenants/{user_id}/stop` | Stop a tenant (keeps DB record) |
|
||||
| `GET` | `/api/v1/config` | Sanitized runtime config |
|
||||
| `GET` | `/api/v1/stats` | Aggregate stats for dashboard |
|
||||
| `GET` | `/api/v1/audit-logs` | Query audit log history |
|
||||
|
||||
### Proxy Endpoints (`/terminals`)
|
||||
|
||||
All requests to `/terminals/{path}` are reverse-proxied to the user's Open Terminal instance. The `X-User-Id` header identifies the target tenant. Includes full support for:
|
||||
|
||||
- **File operations** – list, read, write, delete, move, replace, grep, glob, upload
|
||||
- **Process management** – execute, status, input, kill
|
||||
- **Interactive terminal** – create, list, delete sessions (WebSocket at `/terminals/api/terminals/{session_id}`)
|
||||
- **Notebooks** – create, execute cells, manage sessions
|
||||
- **Port proxy** – access services started within the terminal
|
||||
|
||||
### Other Endpoints
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| `GET` | `/health` | Health check |
|
||||
| `GET` | `/terminals/openapi.json` | Open Terminal OpenAPI spec |
|
||||
|
||||
## License
|
||||
|
||||
[Open WebUI Enterprise License](LICENSE) — see LICENSE for details.
|
||||
[Open WebUI Enterprise License](LICENSE) – see LICENSE for details.
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
uv run uvicorn terminals.main:app --reload
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: terminals
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: open-terminal-operator
|
||||
namespace: terminals
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRole
|
||||
metadata:
|
||||
name: open-terminal-operator
|
||||
rules:
|
||||
# Terminal CRDs
|
||||
- apiGroups: ["openwebui.com"]
|
||||
resources: ["terminals", "terminals/status"]
|
||||
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
|
||||
# Pods, Services, PVCs managed by the operator
|
||||
- apiGroups: [""]
|
||||
resources: ["pods", "services", "persistentvolumeclaims"]
|
||||
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
|
||||
# Events (Kopf posts events for status)
|
||||
- apiGroups: [""]
|
||||
resources: ["events"]
|
||||
verbs: ["create"]
|
||||
# Kopf needs these for leader election and state tracking
|
||||
- apiGroups: [""]
|
||||
resources: ["configmaps"]
|
||||
verbs: ["get", "list", "watch", "create", "update", "patch"]
|
||||
- apiGroups: ["coordination.k8s.io"]
|
||||
resources: ["leases"]
|
||||
verbs: ["get", "list", "watch", "create", "update", "patch"]
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRoleBinding
|
||||
metadata:
|
||||
name: open-terminal-operator
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: open-terminal-operator
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: open-terminal-operator
|
||||
namespace: terminals
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: open-terminal-operator
|
||||
namespace: terminals
|
||||
labels:
|
||||
app.kubernetes.io/name: open-terminal-operator
|
||||
app.kubernetes.io/part-of: open-terminal
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: open-terminal-operator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: open-terminal-operator
|
||||
spec:
|
||||
serviceAccountName: open-terminal-operator
|
||||
containers:
|
||||
- name: operator
|
||||
image: ghcr.io/open-webui/open-terminal-operator:latest
|
||||
resources:
|
||||
requests:
|
||||
memory: "64Mi"
|
||||
cpu: "50m"
|
||||
limits:
|
||||
memory: "256Mi"
|
||||
cpu: "200m"
|
||||
@@ -0,0 +1,93 @@
|
||||
apiVersion: apiextensions.k8s.io/v1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: terminals.openwebui.com
|
||||
spec:
|
||||
group: openwebui.com
|
||||
scope: Namespaced
|
||||
names:
|
||||
plural: terminals
|
||||
singular: terminal
|
||||
kind: Terminal
|
||||
shortNames:
|
||||
- term
|
||||
versions:
|
||||
- name: v1alpha1
|
||||
served: true
|
||||
storage: true
|
||||
schema:
|
||||
openAPIV3Schema:
|
||||
type: object
|
||||
properties:
|
||||
spec:
|
||||
type: object
|
||||
required:
|
||||
- userId
|
||||
- apiKey
|
||||
properties:
|
||||
userId:
|
||||
type: string
|
||||
description: Open WebUI user ID.
|
||||
image:
|
||||
type: string
|
||||
default: "ghcr.io/open-webui/open-terminal:latest"
|
||||
description: Container image for the terminal.
|
||||
apiKey:
|
||||
type: string
|
||||
description: API key for the terminal instance.
|
||||
replicas:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 1
|
||||
default: 1
|
||||
description: Set to 0 to stop, 1 to run.
|
||||
storage:
|
||||
type: object
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
default: false
|
||||
size:
|
||||
type: string
|
||||
default: "1Gi"
|
||||
storageClass:
|
||||
type: string
|
||||
nullable: true
|
||||
status:
|
||||
type: object
|
||||
properties:
|
||||
phase:
|
||||
type: string
|
||||
enum:
|
||||
- Provisioning
|
||||
- Running
|
||||
- Stopped
|
||||
- Error
|
||||
podName:
|
||||
type: string
|
||||
serviceName:
|
||||
type: string
|
||||
host:
|
||||
type: string
|
||||
description: Service FQDN reachable within the cluster.
|
||||
port:
|
||||
type: integer
|
||||
default: 8000
|
||||
message:
|
||||
type: string
|
||||
description: Human-readable status message.
|
||||
subresources:
|
||||
status: {}
|
||||
additionalPrinterColumns:
|
||||
- name: User
|
||||
type: string
|
||||
jsonPath: .spec.userId
|
||||
- name: Phase
|
||||
type: string
|
||||
jsonPath: .status.phase
|
||||
- name: Host
|
||||
type: string
|
||||
jsonPath: .status.host
|
||||
- name: Age
|
||||
type: date
|
||||
jsonPath: .metadata.creationTimestamp
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install --no-cache-dir \
|
||||
kopf>=1.37.0 \
|
||||
kubernetes-asyncio>=31.0.0
|
||||
|
||||
COPY handler.py /app/handler.py
|
||||
|
||||
ENTRYPOINT ["kopf", "run", "/app/handler.py", "--verbose"]
|
||||
@@ -0,0 +1,318 @@
|
||||
"""Open Terminal Operator — Kopf handlers for the Terminal CRD.
|
||||
|
||||
Watches ``Terminal`` custom resources (``terminals.openwebui.com/v1alpha1``)
|
||||
and reconciles the underlying Kubernetes resources:
|
||||
|
||||
- **Pod** running the open-terminal container
|
||||
- **Service** (ClusterIP) exposing port 8000
|
||||
- **PVC** (optional) for persistent ``/home/user`` storage
|
||||
|
||||
The orchestrator creates/deletes Terminal CRs; this operator does the rest.
|
||||
"""
|
||||
|
||||
import kopf
|
||||
import kubernetes_asyncio as k8s
|
||||
from kubernetes_asyncio import client, config
|
||||
|
||||
GROUP = "openwebui.com"
|
||||
VERSION = "v1alpha1"
|
||||
PLURAL = "terminals"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Startup
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@kopf.on.startup()
|
||||
async def configure(settings: kopf.OperatorSettings, **_):
|
||||
"""Load K8s config at startup."""
|
||||
try:
|
||||
config.load_incluster_config()
|
||||
except config.ConfigException:
|
||||
await config.load_kube_config()
|
||||
settings.posting.level = kopf.INFO
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _owner_ref(body: dict) -> list[dict]:
|
||||
"""Build an ownerReferences list so child resources are garbage-collected."""
|
||||
return [
|
||||
{
|
||||
"apiVersion": f"{GROUP}/{VERSION}",
|
||||
"kind": "Terminal",
|
||||
"name": body["metadata"]["name"],
|
||||
"uid": body["metadata"]["uid"],
|
||||
"controller": True,
|
||||
"blockOwnerDeletion": True,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _labels(spec: dict) -> dict[str, str]:
|
||||
return {
|
||||
"app.kubernetes.io/managed-by": "open-terminal-operator",
|
||||
"app.kubernetes.io/part-of": "open-terminal",
|
||||
"openwebui.com/user-id": spec["userId"],
|
||||
}
|
||||
|
||||
|
||||
async def _patch_status(name: str, namespace: str, status: dict):
|
||||
"""Patch the Terminal CR status subresource."""
|
||||
async with k8s.client.ApiClient() as api:
|
||||
custom = client.CustomObjectsApi(api)
|
||||
await custom.patch_namespaced_custom_object_status(
|
||||
group=GROUP,
|
||||
version=VERSION,
|
||||
namespace=namespace,
|
||||
plural=PLURAL,
|
||||
name=name,
|
||||
body={"status": status},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Create handler
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@kopf.on.create(GROUP, VERSION, PLURAL)
|
||||
async def on_create(spec, name, namespace, body, **_):
|
||||
"""Provision a Pod + Service (+ optional PVC) for a new Terminal CR."""
|
||||
labels = _labels(spec)
|
||||
owner = _owner_ref(body)
|
||||
image = spec.get("image", "ghcr.io/open-webui/open-terminal:latest")
|
||||
api_key = spec["apiKey"]
|
||||
storage = spec.get("storage", {})
|
||||
|
||||
await _patch_status(name, namespace, {"phase": "Provisioning"})
|
||||
|
||||
async with k8s.client.ApiClient() as api:
|
||||
core = client.CoreV1Api(api)
|
||||
|
||||
# ---- PVC (optional) ----------------------------------------------
|
||||
volumes = []
|
||||
volume_mounts = []
|
||||
|
||||
if storage.get("enabled"):
|
||||
pvc = client.V1PersistentVolumeClaim(
|
||||
metadata=client.V1ObjectMeta(
|
||||
name=name,
|
||||
namespace=namespace,
|
||||
labels=labels,
|
||||
owner_references=owner,
|
||||
),
|
||||
spec=client.V1PersistentVolumeClaimSpec(
|
||||
access_modes=["ReadWriteOnce"],
|
||||
resources=client.V1VolumeResourceRequirements(
|
||||
requests={"storage": storage.get("size", "1Gi")},
|
||||
),
|
||||
**(
|
||||
{"storage_class_name": storage["storageClass"]}
|
||||
if storage.get("storageClass")
|
||||
else {}
|
||||
),
|
||||
),
|
||||
)
|
||||
try:
|
||||
await core.create_namespaced_persistent_volume_claim(namespace, pvc)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status != 409:
|
||||
raise
|
||||
|
||||
volumes.append(
|
||||
client.V1Volume(
|
||||
name="home",
|
||||
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
|
||||
claim_name=name,
|
||||
),
|
||||
)
|
||||
)
|
||||
volume_mounts.append(
|
||||
client.V1VolumeMount(name="home", mount_path="/home/user"),
|
||||
)
|
||||
|
||||
# ---- Pod ---------------------------------------------------------
|
||||
pod = client.V1Pod(
|
||||
metadata=client.V1ObjectMeta(
|
||||
name=name,
|
||||
namespace=namespace,
|
||||
labels=labels,
|
||||
owner_references=owner,
|
||||
),
|
||||
spec=client.V1PodSpec(
|
||||
containers=[
|
||||
client.V1Container(
|
||||
name="open-terminal",
|
||||
image=image,
|
||||
ports=[client.V1ContainerPort(container_port=8000)],
|
||||
env=[
|
||||
client.V1EnvVar(
|
||||
name="OPEN_TERMINAL_API_KEY", value=api_key
|
||||
),
|
||||
],
|
||||
volume_mounts=volume_mounts or None,
|
||||
readiness_probe=client.V1Probe(
|
||||
http_get=client.V1HTTPGetAction(
|
||||
path="/health", port=8000
|
||||
),
|
||||
initial_delay_seconds=3,
|
||||
period_seconds=5,
|
||||
),
|
||||
)
|
||||
],
|
||||
volumes=volumes or None,
|
||||
restart_policy="Always",
|
||||
),
|
||||
)
|
||||
try:
|
||||
await core.create_namespaced_pod(namespace, pod)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status != 409:
|
||||
await _patch_status(
|
||||
name, namespace, {"phase": "Error", "message": str(exc)}
|
||||
)
|
||||
raise
|
||||
|
||||
# ---- Service -----------------------------------------------------
|
||||
svc = client.V1Service(
|
||||
metadata=client.V1ObjectMeta(
|
||||
name=name,
|
||||
namespace=namespace,
|
||||
labels=labels,
|
||||
owner_references=owner,
|
||||
),
|
||||
spec=client.V1ServiceSpec(
|
||||
type="ClusterIP",
|
||||
selector={"openwebui.com/user-id": spec["userId"]},
|
||||
ports=[client.V1ServicePort(port=8000, target_port=8000)],
|
||||
),
|
||||
)
|
||||
try:
|
||||
await core.create_namespaced_service(namespace, svc)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status != 409:
|
||||
raise
|
||||
|
||||
host = f"{name}.{namespace}.svc.cluster.local"
|
||||
await _patch_status(
|
||||
name,
|
||||
namespace,
|
||||
{
|
||||
"phase": "Running",
|
||||
"podName": name,
|
||||
"serviceName": name,
|
||||
"host": host,
|
||||
"port": 8000,
|
||||
},
|
||||
)
|
||||
|
||||
return {"message": f"Terminal {name} provisioned at {host}:8000"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Replicas field change (start / stop)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@kopf.on.field(GROUP, VERSION, PLURAL, field="spec.replicas")
|
||||
async def on_replicas_change(spec, name, namespace, old, new, **_):
|
||||
"""Handle spec.replicas changes for start/stop."""
|
||||
replicas = new or spec.get("replicas", 1)
|
||||
|
||||
async with k8s.client.ApiClient() as api:
|
||||
core = client.CoreV1Api(api)
|
||||
|
||||
if replicas == 0:
|
||||
# Stop — delete the Pod (Service stays for quick restart).
|
||||
try:
|
||||
await core.delete_namespaced_pod(name, namespace)
|
||||
except client.exceptions.ApiException:
|
||||
pass
|
||||
await _patch_status(name, namespace, {"phase": "Stopped"})
|
||||
|
||||
elif replicas == 1:
|
||||
# Start — need to check if Pod exists, recreate if not.
|
||||
try:
|
||||
await core.read_namespaced_pod(name, namespace)
|
||||
# Pod exists, nothing to do.
|
||||
await _patch_status(name, namespace, {"phase": "Running"})
|
||||
except client.exceptions.ApiException:
|
||||
# Pod is gone — trigger a full re-provision by raising a
|
||||
# temporary error so Kopf retries via the create handler.
|
||||
# For simplicity, we recreate inline.
|
||||
labels = _labels(spec)
|
||||
image = spec.get("image", "ghcr.io/open-webui/open-terminal:latest")
|
||||
api_key = spec["apiKey"]
|
||||
storage = spec.get("storage", {})
|
||||
|
||||
volumes = []
|
||||
volume_mounts = []
|
||||
if storage.get("enabled"):
|
||||
volumes.append(
|
||||
client.V1Volume(
|
||||
name="home",
|
||||
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
|
||||
claim_name=name,
|
||||
),
|
||||
)
|
||||
)
|
||||
volume_mounts.append(
|
||||
client.V1VolumeMount(name="home", mount_path="/home/user"),
|
||||
)
|
||||
|
||||
pod = client.V1Pod(
|
||||
metadata=client.V1ObjectMeta(
|
||||
name=name,
|
||||
namespace=namespace,
|
||||
labels=labels,
|
||||
),
|
||||
spec=client.V1PodSpec(
|
||||
containers=[
|
||||
client.V1Container(
|
||||
name="open-terminal",
|
||||
image=image,
|
||||
ports=[
|
||||
client.V1ContainerPort(container_port=8000)
|
||||
],
|
||||
env=[
|
||||
client.V1EnvVar(
|
||||
name="OPEN_TERMINAL_API_KEY",
|
||||
value=api_key,
|
||||
),
|
||||
],
|
||||
volume_mounts=volume_mounts or None,
|
||||
readiness_probe=client.V1Probe(
|
||||
http_get=client.V1HTTPGetAction(
|
||||
path="/health", port=8000
|
||||
),
|
||||
initial_delay_seconds=3,
|
||||
period_seconds=5,
|
||||
),
|
||||
)
|
||||
],
|
||||
volumes=volumes or None,
|
||||
restart_policy="Always",
|
||||
),
|
||||
)
|
||||
await core.create_namespaced_pod(namespace, pod)
|
||||
await _patch_status(name, namespace, {"phase": "Running"})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Delete handler (cleanup is automatic via ownerReferences, but log it)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@kopf.on.delete(GROUP, VERSION, PLURAL)
|
||||
async def on_delete(name, namespace, **_):
|
||||
"""Log deletion — K8s garbage-collects child resources via ownerReferences."""
|
||||
kopf.info(
|
||||
{"metadata": {"name": name, "namespace": namespace}},
|
||||
reason="Deleted",
|
||||
message=f"Terminal {name} deleted, child resources will be garbage-collected.",
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
[project]
|
||||
name = "terminals"
|
||||
version = "0.1.0"
|
||||
description = "Multi-tenant terminal orchestrator for Open Terminal."
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{ name = "Timothy Jaeryang Baek", email = "tim@openwebui.com" }
|
||||
]
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"fastapi>=0.115.0",
|
||||
"uvicorn[standard]>=0.34.0",
|
||||
"click>=8.1.0",
|
||||
"httpx>=0.27.0",
|
||||
"aiodocker>=0.23.0",
|
||||
"sqlalchemy[asyncio]>=2.0.0",
|
||||
"aiosqlite>=0.21.0",
|
||||
"alembic>=1.15.0",
|
||||
"pydantic-settings>=2.0.0",
|
||||
"websockets>=13.0",
|
||||
"loguru>=0.7.3",
|
||||
"kubernetes-asyncio>=31.0.0",
|
||||
"cryptography>=44.0.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
terminals = "terminals.cli:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["terminals"]
|
||||
@@ -0,0 +1,37 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
# sqlalchemy.url is set programmatically in migrations/env.py
|
||||
sqlalchemy.url =
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Backend factory — returns the configured Backend implementation."""
|
||||
|
||||
from terminals.backends.base import Backend
|
||||
from terminals.config import settings
|
||||
|
||||
|
||||
def create_backend() -> Backend:
|
||||
"""Instantiate the backend selected by ``TERMINALS_BACKEND``."""
|
||||
if settings.backend == "docker":
|
||||
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
|
||||
|
||||
return KubernetesBackend()
|
||||
elif settings.backend == "kubernetes-operator":
|
||||
from terminals.backends.kubernetes_operator import KubernetesOperatorBackend
|
||||
|
||||
return KubernetesOperatorBackend()
|
||||
raise ValueError(f"Unknown backend: {settings.backend!r}")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Abstract base class for terminal backends."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Backend(ABC):
|
||||
"""Lifecycle interface for provisioning and managing terminal instances."""
|
||||
|
||||
@abstractmethod
|
||||
async def provision(self, user_id: str) -> dict:
|
||||
"""Create a new terminal instance for *user_id*.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
async def teardown(self, instance_id: str) -> None:
|
||||
"""Stop and remove the instance."""
|
||||
|
||||
@abstractmethod
|
||||
async def status(self, instance_id: str) -> str:
|
||||
"""Return ``'running'``, ``'stopped'``, or ``'missing'``."""
|
||||
|
||||
@abstractmethod
|
||||
async def close(self) -> None:
|
||||
"""Release resources on shutdown."""
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Docker backend — provisions Open Terminal inside containers via aiodocker."""
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
import aiodocker
|
||||
|
||||
from terminals.backends.base import Backend
|
||||
from terminals.config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DockerBackend(Backend):
|
||||
"""Manage terminal instances as Docker containers."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._docker: Optional[aiodocker.Docker] = None
|
||||
|
||||
async def _get_docker(self) -> aiodocker.Docker:
|
||||
if self._docker is None:
|
||||
self._docker = aiodocker.Docker()
|
||||
return self._docker
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Backend interface
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def provision(self, user_id: str) -> dict:
|
||||
docker = await self._get_docker()
|
||||
api_key = secrets.token_urlsafe(24)
|
||||
instance_name = f"terminals-{user_id}"
|
||||
host_data_dir = f"{settings.data_dir}/{user_id}"
|
||||
|
||||
config: dict = {
|
||||
"Image": settings.image,
|
||||
"Env": [f"OPEN_TERMINAL_API_KEY={api_key}"],
|
||||
"HostConfig": {
|
||||
"Binds": [f"{host_data_dir}:/home/user"],
|
||||
},
|
||||
"ExposedPorts": {"8000/tcp": {}},
|
||||
}
|
||||
|
||||
if settings.network:
|
||||
config["HostConfig"]["NetworkMode"] = settings.network
|
||||
|
||||
log.info("Provisioning container %s for user %s", instance_name, user_id)
|
||||
|
||||
try:
|
||||
container = await docker.containers.create_or_replace(
|
||||
name=instance_name,
|
||||
config=config,
|
||||
)
|
||||
await container.start()
|
||||
except aiodocker.exceptions.DockerError as exc:
|
||||
log.error("Failed to provision container for %s: %s", user_id, exc)
|
||||
raise
|
||||
|
||||
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:
|
||||
networks = info.get("NetworkSettings", {}).get("Networks", {})
|
||||
bridge = networks.get("bridge", {})
|
||||
host = bridge.get("IPAddress", "127.0.0.1")
|
||||
|
||||
return {
|
||||
"instance_id": instance_id,
|
||||
"instance_name": instance_name,
|
||||
"api_key": api_key,
|
||||
"host": host,
|
||||
"port": 8000,
|
||||
}
|
||||
|
||||
async def start(self, instance_id: str) -> bool:
|
||||
current = await self.status(instance_id)
|
||||
if current == "running":
|
||||
return True
|
||||
if current == "stopped":
|
||||
docker = await self._get_docker()
|
||||
try:
|
||||
container = await docker.containers.get(instance_id)
|
||||
await container.start()
|
||||
return True
|
||||
except aiodocker.exceptions.DockerError as exc:
|
||||
log.error("Failed to restart container %s: %s", instance_id, exc)
|
||||
return False
|
||||
return False # missing
|
||||
|
||||
async def teardown(self, instance_id: str) -> None:
|
||||
docker = await self._get_docker()
|
||||
try:
|
||||
container = await docker.containers.get(instance_id)
|
||||
await container.stop(t=10)
|
||||
except aiodocker.exceptions.DockerError:
|
||||
pass
|
||||
try:
|
||||
container = await docker.containers.get(instance_id)
|
||||
await container.delete(force=True)
|
||||
except aiodocker.exceptions.DockerError:
|
||||
log.warning("Could not remove container %s (may already be gone)", instance_id)
|
||||
|
||||
async def status(self, instance_id: str) -> str:
|
||||
docker = await self._get_docker()
|
||||
try:
|
||||
container = await docker.containers.get(instance_id)
|
||||
info = await container.show()
|
||||
state = info.get("State", {})
|
||||
if state.get("Running"):
|
||||
return "running"
|
||||
return "stopped"
|
||||
except aiodocker.exceptions.DockerError:
|
||||
return "missing"
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._docker is not None:
|
||||
await self._docker.close()
|
||||
self._docker = None
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Kubernetes backend — provisions Open Terminal as Pods via the K8s API."""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from kubernetes_asyncio import client, config
|
||||
from kubernetes_asyncio.client import ApiClient
|
||||
|
||||
from terminals.backends.base import Backend
|
||||
from terminals.config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DNS_SAFE = re.compile(r"[^a-z0-9-]")
|
||||
|
||||
|
||||
def _sanitize_name(user_id: str) -> str:
|
||||
"""Convert a user ID to a DNS-safe K8s resource name."""
|
||||
name = _DNS_SAFE.sub("-", user_id.lower()).strip("-")[:53]
|
||||
return f"terminal-{name}"
|
||||
|
||||
|
||||
def _parse_labels() -> dict[str, str]:
|
||||
"""Parse ``TERMINALS_KUBERNETES_LABELS`` into a dict."""
|
||||
labels: dict[str, str] = {}
|
||||
if not settings.kubernetes_labels:
|
||||
return labels
|
||||
for pair in settings.kubernetes_labels.split(","):
|
||||
pair = pair.strip()
|
||||
if "=" in pair:
|
||||
k, v = pair.split("=", 1)
|
||||
labels[k.strip()] = v.strip()
|
||||
return labels
|
||||
|
||||
|
||||
def _base_labels(user_id: str) -> dict[str, str]:
|
||||
"""Standard labels applied to every resource we create."""
|
||||
labels = {
|
||||
"app.kubernetes.io/managed-by": "terminals",
|
||||
"app.kubernetes.io/part-of": "open-terminal",
|
||||
"openwebui.com/user-id": user_id,
|
||||
}
|
||||
labels.update(_parse_labels())
|
||||
return labels
|
||||
|
||||
|
||||
class KubernetesBackend(Backend):
|
||||
"""Manage terminal instances as Kubernetes Pods + Services."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._api_client: Optional[ApiClient] = None
|
||||
|
||||
async def _ensure_client(self) -> ApiClient:
|
||||
if self._api_client is None:
|
||||
if settings.kubernetes_kubeconfig:
|
||||
await config.load_kube_config(
|
||||
config_file=settings.kubernetes_kubeconfig
|
||||
)
|
||||
else:
|
||||
config.load_incluster_config()
|
||||
self._api_client = ApiClient()
|
||||
return self._api_client
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Backend interface
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def provision(self, user_id: str) -> dict:
|
||||
api_client = await self._ensure_client()
|
||||
core = client.CoreV1Api(api_client)
|
||||
|
||||
api_key = secrets.token_urlsafe(24)
|
||||
name = _sanitize_name(user_id)
|
||||
ns = settings.kubernetes_namespace
|
||||
labels = _base_labels(user_id)
|
||||
|
||||
# ---- Optional PVC ------------------------------------------------
|
||||
if settings.kubernetes_storage_size:
|
||||
pvc = client.V1PersistentVolumeClaim(
|
||||
metadata=client.V1ObjectMeta(name=name, namespace=ns, labels=labels),
|
||||
spec=client.V1PersistentVolumeClaimSpec(
|
||||
access_modes=["ReadWriteOnce"],
|
||||
resources=client.V1VolumeResourceRequirements(
|
||||
requests={"storage": settings.kubernetes_storage_size},
|
||||
),
|
||||
**(
|
||||
{"storage_class_name": settings.kubernetes_storage_class}
|
||||
if settings.kubernetes_storage_class
|
||||
else {}
|
||||
),
|
||||
),
|
||||
)
|
||||
try:
|
||||
await core.create_namespaced_persistent_volume_claim(ns, pvc)
|
||||
log.info("Created PVC %s in %s", name, ns)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status == 409:
|
||||
log.debug("PVC %s already exists", name)
|
||||
else:
|
||||
raise
|
||||
|
||||
# ---- Pod ---------------------------------------------------------
|
||||
volumes = []
|
||||
volume_mounts = []
|
||||
if settings.kubernetes_storage_size:
|
||||
volumes.append(
|
||||
client.V1Volume(
|
||||
name="home",
|
||||
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
|
||||
claim_name=name,
|
||||
),
|
||||
)
|
||||
)
|
||||
volume_mounts.append(
|
||||
client.V1VolumeMount(name="home", mount_path="/home/user"),
|
||||
)
|
||||
|
||||
pod = client.V1Pod(
|
||||
metadata=client.V1ObjectMeta(name=name, namespace=ns, labels=labels),
|
||||
spec=client.V1PodSpec(
|
||||
containers=[
|
||||
client.V1Container(
|
||||
name="open-terminal",
|
||||
image=settings.kubernetes_image,
|
||||
ports=[client.V1ContainerPort(container_port=8000)],
|
||||
env=[
|
||||
client.V1EnvVar(
|
||||
name="OPEN_TERMINAL_API_KEY", value=api_key
|
||||
),
|
||||
],
|
||||
volume_mounts=volume_mounts or None,
|
||||
readiness_probe=client.V1Probe(
|
||||
http_get=client.V1HTTPGetAction(
|
||||
path="/health", port=8000
|
||||
),
|
||||
initial_delay_seconds=3,
|
||||
period_seconds=5,
|
||||
),
|
||||
)
|
||||
],
|
||||
volumes=volumes or None,
|
||||
restart_policy="Always",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
created = await core.create_namespaced_pod(ns, pod)
|
||||
log.info("Created Pod %s in %s", name, ns)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status == 409:
|
||||
# Pod exists — delete and recreate.
|
||||
log.info("Pod %s already exists, replacing", name)
|
||||
await core.delete_namespaced_pod(name, ns)
|
||||
created = await core.create_namespaced_pod(ns, pod)
|
||||
else:
|
||||
raise
|
||||
|
||||
instance_id = created.metadata.uid
|
||||
|
||||
# ---- Service -----------------------------------------------------
|
||||
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},
|
||||
ports=[
|
||||
client.V1ServicePort(port=8000, target_port=8000),
|
||||
],
|
||||
),
|
||||
)
|
||||
try:
|
||||
await core.create_namespaced_service(ns, svc)
|
||||
log.info("Created Service %s in %s", name, ns)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status == 409:
|
||||
log.debug("Service %s already exists", name)
|
||||
else:
|
||||
raise
|
||||
|
||||
host = f"{name}.{ns}.svc.cluster.local"
|
||||
|
||||
return {
|
||||
"instance_id": instance_id,
|
||||
"instance_name": name,
|
||||
"api_key": api_key,
|
||||
"host": host,
|
||||
"port": 8000,
|
||||
}
|
||||
|
||||
async def start(self, instance_id: str) -> bool:
|
||||
current = await self.status(instance_id)
|
||||
if current == "running":
|
||||
return True
|
||||
# Pods can't be restarted — caller should re-provision.
|
||||
return False
|
||||
|
||||
async def teardown(self, instance_id: str) -> None:
|
||||
api_client = await self._ensure_client()
|
||||
core = client.CoreV1Api(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
# Find the pod by UID to get the name.
|
||||
name = await self._name_from_uid(instance_id)
|
||||
if name is None:
|
||||
log.warning("No pod found for UID %s", instance_id)
|
||||
return
|
||||
|
||||
# Delete Pod.
|
||||
try:
|
||||
await core.delete_namespaced_pod(name, ns)
|
||||
log.info("Deleted Pod %s", name)
|
||||
except client.exceptions.ApiException:
|
||||
log.warning("Could not delete Pod %s (may already be gone)", name)
|
||||
|
||||
# Delete Service.
|
||||
try:
|
||||
await core.delete_namespaced_service(name, ns)
|
||||
log.info("Deleted Service %s", name)
|
||||
except client.exceptions.ApiException:
|
||||
log.warning("Could not delete Service %s", name)
|
||||
|
||||
# Note: PVC is intentionally kept for data persistence.
|
||||
|
||||
async def status(self, instance_id: str) -> str:
|
||||
api_client = await self._ensure_client()
|
||||
core = client.CoreV1Api(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
name = await self._name_from_uid(instance_id)
|
||||
if name is None:
|
||||
return "missing"
|
||||
|
||||
try:
|
||||
pod = await core.read_namespaced_pod(name, ns)
|
||||
phase = pod.status.phase # Pending, Running, Succeeded, Failed, Unknown
|
||||
if phase == "Running":
|
||||
return "running"
|
||||
if phase in ("Pending",):
|
||||
return "running" # still starting up
|
||||
return "stopped"
|
||||
except client.exceptions.ApiException:
|
||||
return "missing"
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._api_client is not None:
|
||||
await self._api_client.close()
|
||||
self._api_client = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _name_from_uid(self, uid: str) -> Optional[str]:
|
||||
"""Look up a Pod name by its UID."""
|
||||
api_client = await self._ensure_client()
|
||||
core = client.CoreV1Api(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
try:
|
||||
pods = await core.list_namespaced_pod(
|
||||
ns, label_selector="app.kubernetes.io/managed-by=terminals"
|
||||
)
|
||||
for pod in pods.items:
|
||||
if pod.metadata.uid == uid:
|
||||
return pod.metadata.name
|
||||
except client.exceptions.ApiException:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,283 @@
|
||||
"""Kubernetes Operator backend — manages Terminals via CRDs.
|
||||
|
||||
Instead of creating Pods/Services directly, this backend creates and manages
|
||||
``Terminal`` custom resources. A separate Kopf-based operator watches these
|
||||
CRs and reconciles the underlying Pods, Services, and PVCs.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from kubernetes_asyncio import client, config
|
||||
from kubernetes_asyncio.client import ApiClient
|
||||
|
||||
from terminals.backends.base import Backend
|
||||
from terminals.config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DNS_SAFE = re.compile(r"[^a-z0-9-]")
|
||||
|
||||
|
||||
def _sanitize_name(user_id: str) -> str:
|
||||
"""Convert a user ID to a DNS-safe K8s resource name."""
|
||||
name = _DNS_SAFE.sub("-", user_id.lower()).strip("-")[:53]
|
||||
return f"terminal-{name}"
|
||||
|
||||
|
||||
class KubernetesOperatorBackend(Backend):
|
||||
"""Manage terminal instances via Terminal CRDs.
|
||||
|
||||
The backend creates/deletes ``Terminal`` custom resources in the
|
||||
configured namespace. A Kopf operator running in the cluster watches
|
||||
these resources and manages the actual Pods, Services, and PVCs.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._api_client: Optional[ApiClient] = None
|
||||
|
||||
async def _ensure_client(self) -> ApiClient:
|
||||
if self._api_client is None:
|
||||
if settings.kubernetes_kubeconfig:
|
||||
await config.load_kube_config(
|
||||
config_file=settings.kubernetes_kubeconfig
|
||||
)
|
||||
else:
|
||||
config.load_incluster_config()
|
||||
self._api_client = ApiClient()
|
||||
return self._api_client
|
||||
|
||||
@property
|
||||
def _group(self) -> str:
|
||||
return settings.kubernetes_crd_group
|
||||
|
||||
@property
|
||||
def _version(self) -> str:
|
||||
return settings.kubernetes_crd_version
|
||||
|
||||
@property
|
||||
def _plural(self) -> str:
|
||||
return "terminals"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Backend interface
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def provision(self, user_id: str) -> dict:
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
|
||||
api_key = secrets.token_urlsafe(24)
|
||||
name = _sanitize_name(user_id)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
cr = {
|
||||
"apiVersion": f"{self._group}/{self._version}",
|
||||
"kind": "Terminal",
|
||||
"metadata": {
|
||||
"name": name,
|
||||
"namespace": ns,
|
||||
"labels": {
|
||||
"app.kubernetes.io/managed-by": "terminals",
|
||||
"app.kubernetes.io/part-of": "open-terminal",
|
||||
"openwebui.com/user-id": user_id,
|
||||
},
|
||||
},
|
||||
"spec": {
|
||||
"userId": user_id,
|
||||
"image": settings.kubernetes_image,
|
||||
"apiKey": api_key,
|
||||
"storage": {
|
||||
"enabled": bool(settings.kubernetes_storage_size),
|
||||
"size": settings.kubernetes_storage_size,
|
||||
"storageClass": settings.kubernetes_storage_class or None,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
created = await custom.create_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
body=cr,
|
||||
)
|
||||
log.info("Created Terminal CR %s in %s", name, ns)
|
||||
except client.exceptions.ApiException as exc:
|
||||
if exc.status == 409:
|
||||
# Already exists — fetch it.
|
||||
log.debug("Terminal CR %s already exists", name)
|
||||
created = await custom.get_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
name=name,
|
||||
)
|
||||
else:
|
||||
raise
|
||||
|
||||
instance_id = created["metadata"]["uid"]
|
||||
|
||||
# Wait for the operator to set status.phase = Running.
|
||||
host = await self._wait_for_ready(name, ns, timeout=60)
|
||||
|
||||
return {
|
||||
"instance_id": instance_id,
|
||||
"instance_name": name,
|
||||
"api_key": api_key,
|
||||
"host": host,
|
||||
"port": 8000,
|
||||
}
|
||||
|
||||
async def start(self, instance_id: str) -> bool:
|
||||
"""Signal the operator to bring the terminal back up.
|
||||
|
||||
The operator watches for ``spec.replicas`` changes and
|
||||
creates/deletes the Pod accordingly.
|
||||
"""
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
name = await self._name_from_uid(instance_id)
|
||||
if name is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
await custom.patch_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
name=name,
|
||||
body={"spec": {"replicas": 1}},
|
||||
)
|
||||
return True
|
||||
except client.exceptions.ApiException:
|
||||
return False
|
||||
|
||||
async def teardown(self, instance_id: str) -> None:
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
name = await self._name_from_uid(instance_id)
|
||||
if name is None:
|
||||
log.warning("No Terminal CR found for UID %s", instance_id)
|
||||
return
|
||||
|
||||
try:
|
||||
await custom.delete_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
name=name,
|
||||
)
|
||||
log.info("Deleted Terminal CR %s", name)
|
||||
except client.exceptions.ApiException:
|
||||
log.warning(
|
||||
"Could not delete Terminal CR %s (may already be gone)", name
|
||||
)
|
||||
|
||||
async def status(self, instance_id: str) -> str:
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
name = await self._name_from_uid(instance_id)
|
||||
if name is None:
|
||||
return "missing"
|
||||
|
||||
try:
|
||||
cr = await custom.get_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
name=name,
|
||||
)
|
||||
phase = cr.get("status", {}).get("phase", "Unknown")
|
||||
if phase == "Running":
|
||||
return "running"
|
||||
if phase in ("Provisioning", "Pending"):
|
||||
return "running" # still coming up
|
||||
if phase == "Stopped":
|
||||
return "stopped"
|
||||
return "stopped"
|
||||
except client.exceptions.ApiException:
|
||||
return "missing"
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._api_client is not None:
|
||||
await self._api_client.close()
|
||||
self._api_client = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _name_from_uid(self, uid: str) -> Optional[str]:
|
||||
"""Look up a Terminal CR name by its UID."""
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
ns = settings.kubernetes_namespace
|
||||
|
||||
try:
|
||||
result = await custom.list_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=ns,
|
||||
plural=self._plural,
|
||||
label_selector="app.kubernetes.io/managed-by=terminals",
|
||||
)
|
||||
for item in result.get("items", []):
|
||||
if item["metadata"]["uid"] == uid:
|
||||
return item["metadata"]["name"]
|
||||
except client.exceptions.ApiException:
|
||||
pass
|
||||
return None
|
||||
|
||||
async def _wait_for_ready(
|
||||
self, name: str, namespace: str, timeout: int = 60
|
||||
) -> str:
|
||||
"""Poll the CR status until the operator reports it as Running.
|
||||
|
||||
Returns the service hostname set by the operator.
|
||||
"""
|
||||
api_client = await self._ensure_client()
|
||||
custom = client.CustomObjectsApi(api_client)
|
||||
|
||||
deadline = asyncio.get_event_loop().time() + timeout
|
||||
while asyncio.get_event_loop().time() < deadline:
|
||||
try:
|
||||
cr = await custom.get_namespaced_custom_object(
|
||||
group=self._group,
|
||||
version=self._version,
|
||||
namespace=namespace,
|
||||
plural=self._plural,
|
||||
name=name,
|
||||
)
|
||||
status = cr.get("status", {})
|
||||
if status.get("phase") == "Running" and status.get("host"):
|
||||
return status["host"]
|
||||
except client.exceptions.ApiException:
|
||||
pass
|
||||
await asyncio.sleep(2)
|
||||
|
||||
# Timed out — return the expected FQDN anyway; proxy will retry.
|
||||
log.warning(
|
||||
"Terminal CR %s did not reach Running in %ds, returning expected host",
|
||||
name,
|
||||
timeout,
|
||||
)
|
||||
return f"{name}.{namespace}.svc.cluster.local"
|
||||
@@ -0,0 +1,102 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,136 @@
|
||||
"""CLI entry point for the Terminals orchestrator."""
|
||||
|
||||
import click
|
||||
import uvicorn
|
||||
|
||||
|
||||
@click.group()
|
||||
def main():
|
||||
"""terminals — multi-tenant terminal orchestrator"""
|
||||
pass
|
||||
|
||||
|
||||
BANNER = r"""
|
||||
_____ _ _
|
||||
|_ _| (_) | |
|
||||
| | ___ _ __ _ __ ___ _ _ __ __ _| |___
|
||||
| |/ _ | '__| '_ ` _ \| | '_ \ / _` | / __|
|
||||
| | __| | | | | | | | | | | | (_| | \__ \
|
||||
\_/\___|_| |_| |_| |_|_|_| |_|\__,_|_|___/
|
||||
"""
|
||||
|
||||
|
||||
@main.command()
|
||||
@click.option("--host", default=None, help="Bind host (overrides TERMINALS_HOST)")
|
||||
@click.option("--port", default=None, type=int, help="Bind port (overrides TERMINALS_PORT)")
|
||||
@click.option(
|
||||
"--api-key",
|
||||
default=None,
|
||||
help="Bearer API key (overrides TERMINALS_API_KEY)",
|
||||
)
|
||||
def serve(host: str | None, port: int | None, api_key: str | None):
|
||||
"""Start the orchestrator API server."""
|
||||
import os
|
||||
import secrets
|
||||
|
||||
from terminals.config import settings
|
||||
|
||||
# CLI flags take precedence over env/config.
|
||||
effective_host = host or settings.host
|
||||
effective_port = port or settings.port
|
||||
|
||||
if api_key is not None:
|
||||
os.environ["TERMINALS_API_KEY"] = api_key
|
||||
settings.api_key = api_key
|
||||
|
||||
generated = not settings.api_key
|
||||
if generated:
|
||||
key = secrets.token_urlsafe(24)
|
||||
os.environ["TERMINALS_API_KEY"] = key
|
||||
settings.api_key = key
|
||||
|
||||
click.echo(BANNER)
|
||||
if generated:
|
||||
click.echo("=" * 60)
|
||||
click.echo(f" API Key: {settings.api_key}")
|
||||
click.echo("=" * 60)
|
||||
click.echo()
|
||||
|
||||
uvicorn.run("terminals.main:app", host=effective_host, port=effective_port)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database / migration commands
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@main.group()
|
||||
def db():
|
||||
"""Database migration commands (Alembic)."""
|
||||
pass
|
||||
|
||||
|
||||
def _alembic_cfg():
|
||||
"""Build an Alembic Config pointing at the right ini and script dir."""
|
||||
from pathlib import Path
|
||||
|
||||
from alembic.config import Config
|
||||
|
||||
ini_path = Path(__file__).resolve().parent / "alembic.ini"
|
||||
if ini_path.exists():
|
||||
cfg = Config(str(ini_path))
|
||||
else:
|
||||
cfg = Config()
|
||||
cfg.set_main_option(
|
||||
"script_location",
|
||||
str(Path(__file__).resolve().parent / "migrations"),
|
||||
)
|
||||
|
||||
from terminals.config import settings
|
||||
|
||||
cfg.set_main_option("sqlalchemy.url", settings.database_url)
|
||||
return cfg
|
||||
|
||||
|
||||
@db.command()
|
||||
@click.option("--revision", default="head", help="Target revision (default: head)")
|
||||
def upgrade(revision: str):
|
||||
"""Run pending migrations."""
|
||||
from alembic import command
|
||||
|
||||
click.echo(f"Upgrading database to {revision}…")
|
||||
command.upgrade(_alembic_cfg(), revision)
|
||||
click.echo("Done.")
|
||||
|
||||
|
||||
@db.command()
|
||||
@click.option("-m", "--message", required=True, help="Migration message")
|
||||
@click.option("--autogenerate/--no-autogenerate", default=True, help="Auto-detect changes")
|
||||
def revision(message: str, autogenerate: bool):
|
||||
"""Create a new migration revision."""
|
||||
from alembic import command
|
||||
|
||||
command.revision(_alembic_cfg(), message=message, autogenerate=autogenerate)
|
||||
click.echo("Revision created.")
|
||||
|
||||
|
||||
@db.command()
|
||||
def current():
|
||||
"""Show current migration revision."""
|
||||
from alembic import command
|
||||
|
||||
command.current(_alembic_cfg())
|
||||
|
||||
|
||||
@db.command()
|
||||
@click.argument("revision", default="head")
|
||||
def stamp(revision: str):
|
||||
"""Stamp the database as a given revision without running migrations."""
|
||||
from alembic import command
|
||||
|
||||
command.stamp(_alembic_cfg(), revision)
|
||||
click.echo(f"Stamped as {revision}.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Application settings loaded from environment variables."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_prefix="TERMINALS_", env_file=".env")
|
||||
|
||||
api_key: str = ""
|
||||
open_webui_url: str = "" # if set, validate JWTs against this Open WebUI instance
|
||||
database_url: str = "sqlite+aiosqlite:///./data/terminals.db"
|
||||
|
||||
# Backend selection: "docker", "local", or "static"
|
||||
backend: str = "docker"
|
||||
|
||||
# Docker settings
|
||||
image: str = "ghcr.io/open-webui/open-terminal:latest"
|
||||
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_namespace: str = "terminals"
|
||||
kubernetes_image: str = "ghcr.io/open-webui/open-terminal:latest"
|
||||
kubernetes_storage_class: str = "" # empty = cluster default
|
||||
kubernetes_storage_size: str = "1Gi"
|
||||
kubernetes_service_type: str = "ClusterIP"
|
||||
kubernetes_kubeconfig: str = "" # empty = in-cluster config
|
||||
kubernetes_labels: str = "" # extra labels as "k=v,k2=v2"
|
||||
|
||||
# Operator-specific settings
|
||||
kubernetes_crd_group: str = "openwebui.com"
|
||||
kubernetes_crd_version: str = "v1alpha1"
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Async SQLAlchemy engine and session factory."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from terminals.config import settings
|
||||
|
||||
# Ensure the directory for the SQLite file exists.
|
||||
_db_url = settings.database_url
|
||||
if _db_url.startswith("sqlite"):
|
||||
# Extract path from sqlite+aiosqlite:///path/to/db
|
||||
_db_path = _db_url.split("///", 1)[-1]
|
||||
if _db_path:
|
||||
os.makedirs(os.path.dirname(_db_path) or ".", exist_ok=True)
|
||||
|
||||
engine = create_async_engine(settings.database_url, echo=False)
|
||||
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
async def init_db():
|
||||
"""Run Alembic migrations to bring the database up to date."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
alembic_cfg = Config()
|
||||
# Locate the alembic.ini relative to the package.
|
||||
ini_path = Path(__file__).resolve().parent.parent / "alembic.ini"
|
||||
if ini_path.exists():
|
||||
alembic_cfg = Config(str(ini_path))
|
||||
else:
|
||||
# Fallback: configure programmatically.
|
||||
alembic_cfg.set_main_option(
|
||||
"script_location",
|
||||
str(Path(__file__).resolve().parent.parent / "migrations"),
|
||||
)
|
||||
alembic_cfg.set_main_option("sqlalchemy.url", settings.database_url)
|
||||
|
||||
# Run upgrade synchronously (Alembic handles async internally via env.py).
|
||||
command.upgrade(alembic_cfg, "head")
|
||||
|
||||
|
||||
async def close_db():
|
||||
"""Dispose of the engine's connection pool."""
|
||||
await engine.dispose()
|
||||
@@ -0,0 +1,23 @@
|
||||
node_modules
|
||||
|
||||
# Output
|
||||
.output
|
||||
.vercel
|
||||
.netlify
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
|
||||
# Vite
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
@@ -0,0 +1 @@
|
||||
engine-strict=true
|
||||
@@ -0,0 +1,42 @@
|
||||
# sv
|
||||
|
||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
||||
|
||||
## Creating a project
|
||||
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
```sh
|
||||
# create a new project
|
||||
npx sv create my-app
|
||||
```
|
||||
|
||||
To recreate this project with the same configuration:
|
||||
|
||||
```sh
|
||||
# recreate this project
|
||||
npx sv@0.12.5 create --template minimal --no-types --install npm frontend
|
||||
```
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To create a production version of your app:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": false,
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
|
||||
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
|
||||
//
|
||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||
}
|
||||
Generated
+1998
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"prepare": "svelte-kit sync || echo ''"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-auto": "^7.0.0",
|
||||
"@sveltejs/kit": "^2.50.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.2.4",
|
||||
"svelte": "^5.51.0",
|
||||
"vite": "^7.3.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sveltejs/adapter-static": "^3.0.10",
|
||||
"@tailwindcss/vite": "^4.2.1",
|
||||
"tailwindcss": "^4.2.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--color-surface: #000000;
|
||||
--color-panel: #0a0a0a;
|
||||
--color-subtle: #141414;
|
||||
--color-border: #1a1a1a;
|
||||
--color-muted: #666666;
|
||||
--color-accent: #ffffff;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-surface text-white font-sans antialiased;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Terminals - Admin Dashboard</title>
|
||||
<meta name="description" content="Multi-tenant terminal orchestrator admin dashboard" />
|
||||
<link rel="icon"
|
||||
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⬛</text></svg>" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,9 @@
|
||||
import { request } from './index.js';
|
||||
|
||||
export async function fetchConfig() {
|
||||
return request('/api/v1/config');
|
||||
}
|
||||
|
||||
export async function fetchStats() {
|
||||
return request('/api/v1/stats');
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { request, ORIGIN } from './index.js';
|
||||
|
||||
export async function healthCheck() {
|
||||
return request('/health');
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Shared API request helper.
|
||||
*
|
||||
* In dev mode, routes directly to the backend at localhost:3000.
|
||||
* In production, uses relative URLs (same origin, served by FastAPI).
|
||||
*/
|
||||
|
||||
import { getToken } from '$lib/auth.js';
|
||||
|
||||
export const ORIGIN = import.meta.env.DEV ? 'http://localhost:3000' : '';
|
||||
|
||||
export async function request(path, options = {}) {
|
||||
const url = `${ORIGIN}${path}`;
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
};
|
||||
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(url, { ...options, headers });
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new Error(body.detail || `Request failed: ${res.status}`);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Open WebUI auth API client.
|
||||
*
|
||||
* Signs in against a user-provided Open WebUI instance to get a JWT,
|
||||
* then validates that JWT to retrieve user info.
|
||||
*/
|
||||
|
||||
export async function signinOpenWebUI(baseUrl, email, password) {
|
||||
const res = await fetch(`${baseUrl}/api/v1/auths/signin`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new Error(body.detail || 'Sign in failed');
|
||||
}
|
||||
|
||||
return res.json(); // { token, token_type, id, email, name, role, ... }
|
||||
}
|
||||
|
||||
export async function verifyOpenWebUI(baseUrl, token) {
|
||||
const res = await fetch(`${baseUrl}/api/v1/auths/`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error('Token validation failed');
|
||||
}
|
||||
|
||||
return res.json(); // { id, email, name, role, profile_image_url, ... }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { request } from './index.js';
|
||||
|
||||
const BASE = '/api/v1/tenants';
|
||||
|
||||
export async function fetchTenants() {
|
||||
return request(`${BASE}/`);
|
||||
}
|
||||
|
||||
export async function fetchTenant(userId) {
|
||||
return request(`${BASE}/${encodeURIComponent(userId)}`);
|
||||
}
|
||||
|
||||
export async function createTenant(userId) {
|
||||
return request(`${BASE}/`, {
|
||||
method: 'POST',
|
||||
headers: { 'X-User-Id': userId }
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteTenant(userId) {
|
||||
return request(`${BASE}/${encodeURIComponent(userId)}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
}
|
||||
|
||||
export async function startTenant(userId) {
|
||||
return request(`${BASE}/${encodeURIComponent(userId)}/start`, {
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
|
||||
export async function stopTenant(userId) {
|
||||
return request(`${BASE}/${encodeURIComponent(userId)}/stop`, {
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Auth store - persists connection settings and user session.
|
||||
*
|
||||
* Supports two auth modes:
|
||||
* 1. Open WebUI - signs in via an Open WebUI instance, gets a JWT
|
||||
* 2. API Key - direct TERMINALS_API_KEY (no user info)
|
||||
* 3. None - no auth configured (open access)
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'terminals_auth';
|
||||
|
||||
function load() {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function save(data) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
export function getAuth() {
|
||||
return load();
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
const auth = load();
|
||||
return auth?.token || '';
|
||||
}
|
||||
|
||||
export function getOpenWebUIUrl() {
|
||||
const auth = load();
|
||||
return auth?.openWebUIUrl || '';
|
||||
}
|
||||
|
||||
export function getUser() {
|
||||
const auth = load();
|
||||
return auth?.user || null;
|
||||
}
|
||||
|
||||
export function isAuthenticated() {
|
||||
const auth = load();
|
||||
if (!auth) return false;
|
||||
if (auth.mode === 'open-webui') return !!auth.token;
|
||||
if (auth.mode === 'api-key') return !!auth.token;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function getAuthMode() {
|
||||
const auth = load();
|
||||
return auth?.mode || null;
|
||||
}
|
||||
|
||||
export function saveOpenWebUIAuth(openWebUIUrl, token, user) {
|
||||
save({ mode: 'open-webui', openWebUIUrl, token, user });
|
||||
}
|
||||
|
||||
export function saveApiKeyAuth(token) {
|
||||
save({ mode: 'api-key', token, user: null });
|
||||
}
|
||||
|
||||
export function clearAuth() {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
// place files you want to import through the `$lib` alias in this folder.
|
||||
@@ -0,0 +1,2 @@
|
||||
export const prerender = true;
|
||||
export const ssr = false;
|
||||
@@ -0,0 +1,99 @@
|
||||
<script>
|
||||
import '../app.css';
|
||||
import { isAuthenticated, getUser, getAuthMode, clearAuth } from '$lib/auth.js';
|
||||
import { healthCheck } from '$lib/apis/health.js';
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
|
||||
let { children } = $props();
|
||||
let ready = $state(false);
|
||||
let user = $state(null);
|
||||
let authMode = $state(null);
|
||||
let healthy = $state(null);
|
||||
|
||||
onMount(() => {
|
||||
const path = window.location.pathname;
|
||||
const authed = isAuthenticated();
|
||||
|
||||
if (!authed && path !== '/login') {
|
||||
goto('/login');
|
||||
} else if (authed && path === '/login') {
|
||||
goto('/');
|
||||
}
|
||||
|
||||
user = getUser();
|
||||
authMode = getAuthMode();
|
||||
ready = true;
|
||||
|
||||
if (authed) {
|
||||
checkHealth();
|
||||
const interval = setInterval(checkHealth, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
});
|
||||
|
||||
async function checkHealth() {
|
||||
try {
|
||||
const res = await healthCheck();
|
||||
healthy = res.status === true;
|
||||
} catch {
|
||||
healthy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
clearAuth();
|
||||
goto('/login');
|
||||
}
|
||||
|
||||
function isActive(path) {
|
||||
return $page.url.pathname === path;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !ready}
|
||||
<div class="min-h-screen"></div>
|
||||
{:else if $page.url.pathname === '/login'}
|
||||
{@render children()}
|
||||
{:else}
|
||||
<div class="flex h-screen">
|
||||
<aside class="w-52 shrink-0 border-r border-border flex flex-col">
|
||||
<div class="p-5">
|
||||
<h1 class="text-sm font-semibold tracking-tight">Terminals</h1>
|
||||
</div>
|
||||
<nav class="flex-1 px-3 space-y-0.5">
|
||||
<a href="/" class="flex items-center gap-2 px-3 py-1.5 text-[13px] rounded-md transition-colors {isActive('/') ? 'text-white bg-white/[0.06]' : 'text-muted hover:text-white'}">
|
||||
Dashboard
|
||||
</a>
|
||||
<a href="/settings" class="flex items-center gap-2 px-3 py-1.5 text-[13px] rounded-md transition-colors {isActive('/settings') ? 'text-white bg-white/[0.06]' : 'text-muted hover:text-white'}">
|
||||
Settings
|
||||
</a>
|
||||
</nav>
|
||||
<div class="px-4 py-3 border-t border-border space-y-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
{#if healthy === null}
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-muted"></span>
|
||||
<span class="text-[11px] text-muted">Checking...</span>
|
||||
{:else if healthy}
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-green-400"></span>
|
||||
<span class="text-[11px] text-muted">Online</span>
|
||||
{:else}
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-red-400"></span>
|
||||
<span class="text-[11px] text-muted">Offline</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if user}
|
||||
<div class="text-[12px] text-white truncate">{user.name}</div>
|
||||
<div class="text-[11px] text-muted truncate">{user.email}</div>
|
||||
{:else if authMode === 'api-key'}
|
||||
<div class="text-[11px] text-muted">API Key</div>
|
||||
{/if}
|
||||
<button onclick={logout} class="text-[11px] text-muted hover:text-white transition-colors">Sign out</button>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="flex-1 overflow-y-auto">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,309 @@
|
||||
<script>
|
||||
import { fetchTenants, createTenant, deleteTenant, startTenant, stopTenant } from '$lib/apis/tenants.js';
|
||||
import { fetchStats } from '$lib/apis/config.js';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let tenants = $state([]);
|
||||
let stats = $state({ total: 0, running: 0, stopped: 0, error: 0, active_ws_connections: 0 });
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let showModal = $state(false);
|
||||
let userId = $state('');
|
||||
let provisioning = $state(false);
|
||||
let provisionError = $state('');
|
||||
let actionId = $state(null); // user_id currently being acted on
|
||||
let search = $state('');
|
||||
let statusFilter = $state('all');
|
||||
let expandedId = $state(null);
|
||||
let idleTimeout = $state(0);
|
||||
|
||||
let filtered = $derived(() => {
|
||||
let list = tenants;
|
||||
if (statusFilter !== 'all') {
|
||||
list = list.filter(t => t.status === statusFilter);
|
||||
}
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase();
|
||||
list = list.filter(t => t.user_id.toLowerCase().includes(q) || (t.instance_name || '').toLowerCase().includes(q));
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
[tenants, stats] = await Promise.all([fetchTenants(), fetchStats()]);
|
||||
error = '';
|
||||
} catch (e) {
|
||||
error = e.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function provision() {
|
||||
if (!userId.trim()) return;
|
||||
provisioning = true; provisionError = '';
|
||||
try { await createTenant(userId.trim()); showModal = false; userId = ''; await load(); }
|
||||
catch (e) { provisionError = e.message; }
|
||||
finally { provisioning = false; }
|
||||
}
|
||||
|
||||
async function remove(id) {
|
||||
actionId = id;
|
||||
try { await deleteTenant(id); await load(); }
|
||||
catch (e) { error = e.message; }
|
||||
finally { actionId = null; }
|
||||
}
|
||||
|
||||
async function start(id) {
|
||||
actionId = id;
|
||||
try { await startTenant(id); await load(); }
|
||||
catch (e) { error = e.message; }
|
||||
finally { actionId = null; }
|
||||
}
|
||||
|
||||
async function stop(id) {
|
||||
actionId = id;
|
||||
try { await stopTenant(id); await load(); }
|
||||
catch (e) { error = e.message; }
|
||||
finally { actionId = null; }
|
||||
}
|
||||
|
||||
function ago(ts) {
|
||||
if (!ts) return '-';
|
||||
const d = Date.now() - new Date(ts).getTime();
|
||||
if (d < 60000) return 'now';
|
||||
if (d < 3600000) return `${Math.floor(d / 60000)}m`;
|
||||
if (d < 86400000) return `${Math.floor(d / 3600000)}h`;
|
||||
return new Date(ts).toLocaleDateString('en', { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
function idlePercent(ts) {
|
||||
if (!ts || !idleTimeout) return 0;
|
||||
const elapsed = (Date.now() - new Date(ts).getTime()) / 1000;
|
||||
return Math.min(100, Math.round((elapsed / idleTimeout) * 100));
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
await load();
|
||||
// Fetch idle timeout from config
|
||||
try {
|
||||
const { fetchConfig } = await import('$lib/apis/config.js');
|
||||
const cfg = await fetchConfig();
|
||||
idleTimeout = cfg.idle_timeout_seconds || 0;
|
||||
} catch {}
|
||||
const interval = setInterval(load, 15000);
|
||||
return () => clearInterval(interval);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="p-10 max-w-6xl">
|
||||
<!-- Header -->
|
||||
<div class="flex items-center justify-between mb-10">
|
||||
<h1 class="text-xl font-semibold tracking-tight">Dashboard</h1>
|
||||
<button onclick={() => (showModal = true)} class="text-[13px] px-4 py-2 bg-white text-black rounded-lg font-medium hover:bg-white/90 transition-colors">
|
||||
New Tenant
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Stats -->
|
||||
<div class="grid grid-cols-5 gap-px bg-border rounded-xl overflow-hidden mb-8">
|
||||
{#each [
|
||||
{ label: 'Total', value: stats.total },
|
||||
{ label: 'Running', value: stats.running },
|
||||
{ label: 'Stopped', value: stats.stopped },
|
||||
{ label: 'Errors', value: stats.error },
|
||||
{ label: 'WS Connections', value: stats.active_ws_connections }
|
||||
] as s}
|
||||
<div class="bg-panel p-5">
|
||||
<div class="text-2xl font-semibold tracking-tight">{s.value}</div>
|
||||
<div class="text-[11px] text-muted mt-1 uppercase tracking-widest">{s.label}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Error -->
|
||||
{#if error}
|
||||
<div class="mb-6 text-[13px] text-red-400 bg-red-400/5 border border-red-400/10 rounded-lg px-4 py-3 flex justify-between items-center">
|
||||
{error}
|
||||
<button onclick={() => (error = '')} class="text-red-400/40 hover:text-red-400 ml-4">x</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Table -->
|
||||
<div class="rounded-xl border border-border overflow-hidden">
|
||||
<div class="flex items-center justify-between px-5 py-3 border-b border-border">
|
||||
<!-- Status filter chips -->
|
||||
<div class="flex gap-1">
|
||||
{#each [
|
||||
{ key: 'all', label: 'All' },
|
||||
{ key: 'running', label: 'Running' },
|
||||
{ key: 'stopped', label: 'Stopped' },
|
||||
{ key: 'error', label: 'Error' }
|
||||
] as f}
|
||||
<button
|
||||
onclick={() => (statusFilter = f.key)}
|
||||
class="text-[12px] px-2.5 py-1 rounded-md transition-colors {statusFilter === f.key ? 'bg-white/[0.08] text-white' : 'text-muted hover:text-white'}"
|
||||
>{f.label}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search"
|
||||
bind:value={search}
|
||||
class="text-[13px] bg-transparent border-none outline-none text-white placeholder:text-muted/40 w-40"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="py-20 text-center text-[13px] text-muted">Loading...</div>
|
||||
{:else if filtered().length === 0}
|
||||
<div class="py-20 text-center">
|
||||
{#if search || statusFilter !== 'all'}
|
||||
<p class="text-[13px] text-muted">No results</p>
|
||||
{:else}
|
||||
<p class="text-[13px] text-muted mb-4">No tenants</p>
|
||||
<button onclick={() => (showModal = true)} class="text-[13px] px-4 py-2 bg-white text-black rounded-lg font-medium hover:bg-white/90 transition-colors">New Tenant</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<table class="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr class="border-b border-border text-left text-muted">
|
||||
<th class="px-5 py-2.5 font-normal">User</th>
|
||||
<th class="px-5 py-2.5 font-normal">Status</th>
|
||||
<th class="px-5 py-2.5 font-normal">Backend</th>
|
||||
<th class="px-5 py-2.5 font-normal">Host</th>
|
||||
<th class="px-5 py-2.5 font-normal">Created</th>
|
||||
<th class="px-5 py-2.5 font-normal"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each filtered() as t (t.id)}
|
||||
<!-- Main row -->
|
||||
<tr
|
||||
class="border-b border-border hover:bg-white/[0.02] transition-colors cursor-pointer {expandedId === t.id ? 'bg-white/[0.02]' : ''}"
|
||||
onclick={() => (expandedId = expandedId === t.id ? null : t.id)}
|
||||
>
|
||||
<td class="px-5 py-3 font-medium">{t.user_id}</td>
|
||||
<td class="px-5 py-3">
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<span class="w-1.5 h-1.5 rounded-full {t.status === 'running' ? 'bg-green-400' : t.status === 'error' ? 'bg-red-400' : 'bg-yellow-400'}"></span>
|
||||
{t.status}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-3 text-muted">{t.backend_type}</td>
|
||||
<td class="px-5 py-3 text-muted font-mono text-xs">{t.host || '-'}:{t.port}</td>
|
||||
<td class="px-5 py-3 text-muted">{ago(t.created_at)}</td>
|
||||
<td class="px-5 py-3 text-right">
|
||||
<div class="inline-flex gap-2">
|
||||
{#if t.status === 'running'}
|
||||
<button
|
||||
onclick={(e) => { e.stopPropagation(); stop(t.user_id); }}
|
||||
disabled={actionId === t.user_id}
|
||||
class="text-muted hover:text-yellow-400 transition-colors disabled:opacity-30"
|
||||
>Stop</button>
|
||||
{:else if t.status === 'stopped'}
|
||||
<button
|
||||
onclick={(e) => { e.stopPropagation(); start(t.user_id); }}
|
||||
disabled={actionId === t.user_id}
|
||||
class="text-muted hover:text-green-400 transition-colors disabled:opacity-30"
|
||||
>Start</button>
|
||||
{/if}
|
||||
<button
|
||||
onclick={(e) => { e.stopPropagation(); remove(t.user_id); }}
|
||||
disabled={actionId === t.user_id}
|
||||
class="text-muted hover:text-red-400 transition-colors disabled:opacity-30"
|
||||
>Delete</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<!-- Expanded detail row -->
|
||||
{#if expandedId === t.id}
|
||||
<tr class="border-b border-border bg-white/[0.01]">
|
||||
<td colspan="6" class="px-5 py-4">
|
||||
<div class="grid grid-cols-3 gap-4 text-[12px]">
|
||||
<div>
|
||||
<span class="text-muted">Instance ID</span>
|
||||
<div class="font-mono mt-0.5">{t.instance_id || '-'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">Instance Name</span>
|
||||
<div class="font-mono mt-0.5">{t.instance_name || '-'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">Port</span>
|
||||
<div class="mt-0.5">{t.port}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">Created</span>
|
||||
<div class="mt-0.5">{t.created_at ? new Date(t.created_at).toLocaleString() : '-'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">Updated</span>
|
||||
<div class="mt-0.5">{t.updated_at ? new Date(t.updated_at).toLocaleString() : '-'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-muted">Last Accessed</span>
|
||||
<div class="mt-0.5">
|
||||
{t.last_accessed_at ? new Date(t.last_accessed_at).toLocaleString() : '-'}
|
||||
{#if t.status === 'running' && idleTimeout > 0 && t.last_accessed_at}
|
||||
{@const pct = idlePercent(t.last_accessed_at)}
|
||||
<div class="mt-1.5 flex items-center gap-2">
|
||||
<div class="flex-1 h-1 bg-border rounded-full overflow-hidden">
|
||||
<div class="h-full rounded-full transition-all {pct > 80 ? 'bg-red-400' : pct > 50 ? 'bg-yellow-400' : 'bg-green-400'}" style="width: {pct}%"></div>
|
||||
</div>
|
||||
<span class="text-[10px] text-muted">{pct}% idle</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/if}
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
{#if showModal}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 bg-black/70 flex items-center justify-center z-50"
|
||||
onclick={(e) => { if (e.target === e.currentTarget) showModal = false; }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape') showModal = false; }}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="bg-panel border border-border rounded-2xl p-7 w-full max-w-sm">
|
||||
<h2 class="text-base font-semibold mb-1">New Tenant</h2>
|
||||
<p class="text-[13px] text-muted mb-6">Provision a terminal instance for a user.</p>
|
||||
|
||||
{#if provisionError}
|
||||
<div class="mb-4 text-[13px] text-red-400">{provisionError}</div>
|
||||
{/if}
|
||||
|
||||
<form onsubmit={(e) => { e.preventDefault(); provision(); }}>
|
||||
<label for="uid" class="block text-[12px] text-muted mb-1.5">User ID</label>
|
||||
<input
|
||||
id="uid"
|
||||
type="text"
|
||||
bind:value={userId}
|
||||
placeholder="user-123"
|
||||
class="w-full px-3 py-2 text-[13px] bg-surface border border-border rounded-lg text-white placeholder:text-muted/40 focus:outline-none focus:border-white/20 transition-colors"
|
||||
/>
|
||||
<div class="flex justify-end gap-2 mt-6">
|
||||
<button type="button" onclick={() => (showModal = false)} class="px-4 py-2 text-[13px] text-muted hover:text-white transition-colors">Cancel</button>
|
||||
<button type="submit" disabled={provisioning || !userId.trim()} class="px-4 py-2 text-[13px] font-medium bg-white text-black rounded-lg hover:bg-white/90 transition-colors disabled:opacity-30">
|
||||
{provisioning ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,98 @@
|
||||
<script>
|
||||
import { signinOpenWebUI } from '$lib/apis/openwebui.js';
|
||||
import { saveOpenWebUIAuth, saveApiKeyAuth } from '$lib/auth.js';
|
||||
|
||||
let mode = $state('open-webui'); // 'open-webui' | 'api-key'
|
||||
let openWebUIUrl = $state('');
|
||||
let email = $state('');
|
||||
let password = $state('');
|
||||
let apiKey = $state('');
|
||||
let loading = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
async function handleOpenWebUI(e) {
|
||||
e.preventDefault();
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
const url = openWebUIUrl.replace(/\/+$/, '');
|
||||
const res = await signinOpenWebUI(url, email, password);
|
||||
saveOpenWebUIAuth(url, res.token, {
|
||||
id: res.id,
|
||||
email: res.email,
|
||||
name: res.name,
|
||||
role: res.role,
|
||||
profile_image_url: res.profile_image_url
|
||||
});
|
||||
window.location.href = '/';
|
||||
} catch (e) {
|
||||
error = e.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleApiKey(e) {
|
||||
e.preventDefault();
|
||||
if (!apiKey.trim()) return;
|
||||
saveApiKeyAuth(apiKey.trim());
|
||||
window.location.href = '/';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen flex items-center justify-center">
|
||||
<div class="w-full max-w-sm">
|
||||
<h1 class="text-lg font-semibold tracking-tight mb-1">Terminals</h1>
|
||||
<p class="text-[13px] text-muted mb-8">Connect to manage terminal instances.</p>
|
||||
|
||||
<!-- Mode selector -->
|
||||
<div class="flex gap-1 mb-6 bg-subtle rounded-lg p-1">
|
||||
<button
|
||||
class="flex-1 text-[13px] py-1.5 rounded-md transition-colors {mode === 'open-webui' ? 'bg-panel text-white' : 'text-muted hover:text-white'}"
|
||||
onclick={() => (mode = 'open-webui')}
|
||||
>Open WebUI</button>
|
||||
<button
|
||||
class="flex-1 text-[13px] py-1.5 rounded-md transition-colors {mode === 'api-key' ? 'bg-panel text-white' : 'text-muted hover:text-white'}"
|
||||
onclick={() => (mode = 'api-key')}
|
||||
>API Key</button>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<div class="mb-4 text-[13px] text-red-400">{error}</div>
|
||||
{/if}
|
||||
|
||||
{#if mode === 'open-webui'}
|
||||
<form onsubmit={handleOpenWebUI} class="space-y-3">
|
||||
<div>
|
||||
<label for="url" class="block text-[12px] text-muted mb-1">Open WebUI URL</label>
|
||||
<input id="url" type="url" bind:value={openWebUIUrl} placeholder="https://your-openwebui.com" required
|
||||
class="w-full px-3 py-2 text-[13px] bg-surface border border-border rounded-lg text-white placeholder:text-muted/40 focus:outline-none focus:border-white/20 transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="email" class="block text-[12px] text-muted mb-1">Email</label>
|
||||
<input id="email" type="email" bind:value={email} placeholder="you@example.com" required
|
||||
class="w-full px-3 py-2 text-[13px] bg-surface border border-border rounded-lg text-white placeholder:text-muted/40 focus:outline-none focus:border-white/20 transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="password" class="block text-[12px] text-muted mb-1">Password</label>
|
||||
<input id="password" type="password" bind:value={password} required
|
||||
class="w-full px-3 py-2 text-[13px] bg-surface border border-border rounded-lg text-white placeholder:text-muted/40 focus:outline-none focus:border-white/20 transition-colors" />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} class="w-full mt-2 px-4 py-2 text-[13px] font-medium bg-white text-black rounded-lg hover:bg-white/90 transition-colors disabled:opacity-30">
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
{:else}
|
||||
<form onsubmit={handleApiKey} class="space-y-3">
|
||||
<div>
|
||||
<label for="key" class="block text-[12px] text-muted mb-1">API Key</label>
|
||||
<input id="key" type="password" bind:value={apiKey} placeholder="TERMINALS_API_KEY" required
|
||||
class="w-full px-3 py-2 text-[13px] bg-surface border border-border rounded-lg text-white placeholder:text-muted/40 focus:outline-none focus:border-white/20 transition-colors" />
|
||||
</div>
|
||||
<button type="submit" class="w-full mt-2 px-4 py-2 text-[13px] font-medium bg-white text-black rounded-lg hover:bg-white/90 transition-colors">
|
||||
Connect
|
||||
</button>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,121 @@
|
||||
<script>
|
||||
import { fetchConfig } from '$lib/apis/config.js';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let config = $state(null);
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
config = await fetchConfig();
|
||||
} catch (e) {
|
||||
error = e.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="p-10 max-w-4xl">
|
||||
<h1 class="text-xl font-semibold tracking-tight mb-1">Settings</h1>
|
||||
<p class="text-[13px] text-muted mb-8">Runtime configuration (read-only)</p>
|
||||
|
||||
{#if loading}
|
||||
<p class="text-[13px] text-muted">Loading...</p>
|
||||
{:else if error}
|
||||
<p class="text-[13px] text-red-400">{error}</p>
|
||||
{:else if config}
|
||||
<div class="space-y-6">
|
||||
<!-- General -->
|
||||
<section>
|
||||
<h2 class="text-[12px] text-muted uppercase tracking-widest mb-3">General</h2>
|
||||
<div class="rounded-xl border border-border overflow-hidden divide-y divide-border">
|
||||
{#each [
|
||||
{ label: 'Backend', value: config.backend },
|
||||
{ label: 'Host', value: config.host },
|
||||
{ label: 'Port', value: config.port },
|
||||
{ label: 'Data Directory', value: config.data_dir },
|
||||
] as row}
|
||||
<div class="flex justify-between px-5 py-3 text-[13px]">
|
||||
<span class="text-muted">{row.label}</span>
|
||||
<span class="font-mono">{row.value}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Docker -->
|
||||
{#if config.backend === 'docker'}
|
||||
<section>
|
||||
<h2 class="text-[12px] text-muted uppercase tracking-widest mb-3">Docker</h2>
|
||||
<div class="rounded-xl border border-border overflow-hidden divide-y divide-border">
|
||||
{#each [
|
||||
{ label: 'Image', value: config.image },
|
||||
{ label: 'Network', value: config.network || 'default' },
|
||||
] as row}
|
||||
<div class="flex justify-between px-5 py-3 text-[13px]">
|
||||
<span class="text-muted">{row.label}</span>
|
||||
<span class="font-mono">{row.value}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- Kubernetes -->
|
||||
{#if config.backend === 'kubernetes' || config.backend === 'kubernetes-operator'}
|
||||
<section>
|
||||
<h2 class="text-[12px] text-muted uppercase tracking-widest mb-3">Kubernetes</h2>
|
||||
<div class="rounded-xl border border-border overflow-hidden divide-y divide-border">
|
||||
{#each [
|
||||
{ label: 'Namespace', value: config.kubernetes_namespace },
|
||||
{ label: 'Image', value: config.kubernetes_image },
|
||||
{ label: 'Storage Class', value: config.kubernetes_storage_class || 'default' },
|
||||
{ label: 'Storage Size', value: config.kubernetes_storage_size },
|
||||
{ label: 'Service Type', value: config.kubernetes_service_type },
|
||||
] as row}
|
||||
<div class="flex justify-between px-5 py-3 text-[13px]">
|
||||
<span class="text-muted">{row.label}</span>
|
||||
<span class="font-mono">{row.value}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- Lifecycle -->
|
||||
<section>
|
||||
<h2 class="text-[12px] text-muted uppercase tracking-widest mb-3">Lifecycle</h2>
|
||||
<div class="rounded-xl border border-border overflow-hidden divide-y divide-border">
|
||||
{#each [
|
||||
{ label: 'Idle Timeout', value: `${config.idle_timeout_seconds}s (${Math.round(config.idle_timeout_seconds / 60)}min)` },
|
||||
{ label: 'Cleanup Interval', value: `${config.cleanup_interval_seconds}s` },
|
||||
] as row}
|
||||
<div class="flex justify-between px-5 py-3 text-[13px]">
|
||||
<span class="text-muted">{row.label}</span>
|
||||
<span class="font-mono">{row.value}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Auth -->
|
||||
<section>
|
||||
<h2 class="text-[12px] text-muted uppercase tracking-widest mb-3">Auth & Integrations</h2>
|
||||
<div class="rounded-xl border border-border overflow-hidden divide-y divide-border">
|
||||
{#each [
|
||||
{ label: 'API Key', value: config.has_api_key ? 'Configured' : 'Not set' },
|
||||
{ label: 'Open WebUI', value: config.has_open_webui_url ? 'Configured' : 'Not set' },
|
||||
{ label: 'SIEM Webhook', value: config.has_siem_webhook ? 'Configured' : 'Not set' },
|
||||
] as row}
|
||||
<div class="flex justify-between px-5 py-3 text-[13px]">
|
||||
<span class="text-muted">{row.label}</span>
|
||||
<span class="{row.value === 'Configured' ? 'text-green-400' : 'text-muted'}">{row.value}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,3 @@
|
||||
# allow crawling everything by default
|
||||
User-agent: *
|
||||
Disallow:
|
||||
@@ -0,0 +1,16 @@
|
||||
import adapter from '@sveltejs/adapter-static';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
kit: {
|
||||
adapter: adapter({
|
||||
pages: 'build',
|
||||
assets: 'build',
|
||||
fallback: 'index.html',
|
||||
precompress: false,
|
||||
strict: true
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true
|
||||
},
|
||||
'/health': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true
|
||||
},
|
||||
'/terminals': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
ws: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Loguru configuration — replaces stdlib logging across the project."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class _InterceptHandler(logging.Handler):
|
||||
"""Route stdlib logging messages into loguru."""
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
# Find caller from where the logged message originated.
|
||||
try:
|
||||
level = logger.level(record.levelname).name
|
||||
except ValueError:
|
||||
level = record.levelno
|
||||
|
||||
frame, depth = logging.currentframe(), 2
|
||||
while frame and frame.f_code.co_filename == logging.__file__:
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(
|
||||
level, record.getMessage()
|
||||
)
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
"""Call once at startup to configure loguru and intercept stdlib logging."""
|
||||
|
||||
# Remove default loguru handler and add our own.
|
||||
logger.remove()
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
format=(
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
|
||||
"<level>{level: <8}</level> | "
|
||||
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
|
||||
"<level>{message}</level>"
|
||||
),
|
||||
level="DEBUG",
|
||||
colorize=True,
|
||||
)
|
||||
|
||||
# Intercept stdlib logging (uvicorn, sqlalchemy, etc.).
|
||||
logging.basicConfig(handlers=[_InterceptHandler()], level=0, force=True)
|
||||
for name in ("uvicorn", "uvicorn.error", "uvicorn.access", "sqlalchemy"):
|
||||
logging.getLogger(name).handlers = [_InterceptHandler()]
|
||||
@@ -0,0 +1,77 @@
|
||||
"""FastAPI application assembly."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from terminals.backends import create_backend
|
||||
from terminals.db.session import close_db, init_db
|
||||
from terminals.lifecycle import run_lifecycle_loop
|
||||
from terminals.logging import setup_logging
|
||||
from terminals.middleware import RequestIdMiddleware
|
||||
from terminals.routers.proxy import close_proxy_client, router as proxy_router
|
||||
from terminals.routers.tenants import router as tenants_router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Startup / shutdown lifecycle."""
|
||||
setup_logging()
|
||||
await init_db()
|
||||
app.state.backend = create_backend()
|
||||
|
||||
# Start background lifecycle manager.
|
||||
lifecycle_task = asyncio.create_task(
|
||||
run_lifecycle_loop(app.state.backend)
|
||||
)
|
||||
|
||||
yield
|
||||
|
||||
# Cancel lifecycle manager on shutdown.
|
||||
lifecycle_task.cancel()
|
||||
try:
|
||||
await lifecycle_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
await close_proxy_client()
|
||||
await app.state.backend.close()
|
||||
await close_db()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Terminals",
|
||||
description="Multi-tenant terminal orchestrator for Open Terminal.",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(tenants_router, prefix="/api/v1")
|
||||
app.include_router(proxy_router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": True}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Serve the SvelteKit static frontend (must be last — catch-all mount)
|
||||
# ---------------------------------------------------------------------------
|
||||
_FRONTEND_DIR = Path(__file__).resolve().parent / "frontend" / "build"
|
||||
if _FRONTEND_DIR.is_dir():
|
||||
app.mount("/", StaticFiles(directory=str(_FRONTEND_DIR), html=True), name="frontend")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Request middleware for correlation IDs."""
|
||||
|
||||
import uuid
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
"""Attach a unique ``request_id`` to every request.
|
||||
|
||||
The ID is stored in ``request.state.request_id`` for downstream use
|
||||
and returned as an ``X-Request-Id`` response header.
|
||||
"""
|
||||
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Alembic async environment configuration.
|
||||
|
||||
Reads the database URL from ``terminals.config.settings`` so the
|
||||
connection string is never hardcoded in ``alembic.ini``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
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
|
||||
|
||||
# Alembic Config object — gives access to alembic.ini values.
|
||||
config = context.config
|
||||
|
||||
# Set up Python logging from the INI file.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Target metadata for autogenerate support.
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def _get_url() -> str:
|
||||
"""Return the DB URL, converting async drivers for offline mode."""
|
||||
return settings.database_url
|
||||
|
||||
|
||||
def _sync_url(url: str) -> str:
|
||||
"""Convert an async URL to a sync one for offline migrations."""
|
||||
return (
|
||||
url.replace("sqlite+aiosqlite", "sqlite")
|
||||
.replace("postgresql+asyncpg", "postgresql")
|
||||
)
|
||||
|
||||
|
||||
def _ensure_sqlite_dir(url: str) -> None:
|
||||
"""Create parent directories for SQLite database files."""
|
||||
if url.startswith("sqlite"):
|
||||
db_path = url.split("///", 1)[-1]
|
||||
if db_path:
|
||||
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode (emit SQL without connecting)."""
|
||||
url = _sync_url(_get_url())
|
||||
_ensure_sqlite_dir(url)
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection):
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""Run migrations in 'online' mode with an async engine."""
|
||||
url = _get_url()
|
||||
_ensure_sqlite_dir(url)
|
||||
|
||||
configuration = config.get_section(config.config_ini_section, {})
|
||||
configuration["sqlalchemy.url"] = url
|
||||
|
||||
connectable = async_engine_from_config(
|
||||
configuration,
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Entry point for online migrations — delegates to async runner."""
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,38 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,22 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""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
|
||||
@@ -0,0 +1,59 @@
|
||||
"""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 ""
|
||||
@@ -0,0 +1,420 @@
|
||||
"""Catch-all reverse proxy into tenant 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.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Header, Query, Request, Response, WebSocket
|
||||
from fastapi.responses import JSONResponse
|
||||
from loguru import logger
|
||||
from sqlalchemy import func
|
||||
|
||||
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.routers.tenants import _get_tenant, _provision_tenant, validate_token, verify_api_key, verify_user_id
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Proxy client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_proxy_client: Optional[httpx.AsyncClient] = None
|
||||
|
||||
# Active WebSocket connection counter (for stats endpoint)
|
||||
active_ws_connections: int = 0
|
||||
|
||||
|
||||
async def _get_proxy_client() -> httpx.AsyncClient:
|
||||
global _proxy_client
|
||||
if _proxy_client is None:
|
||||
_proxy_client = httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0))
|
||||
return _proxy_client
|
||||
|
||||
|
||||
async def close_proxy_client() -> None:
|
||||
global _proxy_client
|
||||
if _proxy_client is not None:
|
||||
await _proxy_client.aclose()
|
||||
_proxy_client = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _client_ip(request) -> str:
|
||||
"""Extract client IP, respecting X-Forwarded-For."""
|
||||
headers = getattr(request, "headers", {})
|
||||
forwarded = headers.get("x-forwarded-for") if hasattr(headers, "get") else None
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
client = getattr(request, "client", None)
|
||||
return client.host if client else ""
|
||||
|
||||
|
||||
def _user_agent(request) -> str:
|
||||
headers = getattr(request, "headers", {})
|
||||
return headers.get("user-agent", "") if hasattr(headers, "get") else ""
|
||||
|
||||
|
||||
def _request_id(request) -> Optional[str]:
|
||||
return getattr(getattr(request, "state", None), "request_id", None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resolve tenant
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _resolve_tenant(request, user_id: str) -> Tenant:
|
||||
"""Return a running tenant, auto-provisioning if needed."""
|
||||
backend = request.app.state.backend
|
||||
async with async_session() as session:
|
||||
tenant = await _get_tenant(session, user_id)
|
||||
|
||||
if tenant is None:
|
||||
tenant = await _provision_tenant(request, session, user_id)
|
||||
return tenant
|
||||
|
||||
# Ensure the instance is alive.
|
||||
if tenant.instance_id:
|
||||
running = await backend.start(tenant.instance_id)
|
||||
if not running:
|
||||
# Re-provision.
|
||||
old_instance_id = tenant.instance_id
|
||||
await backend.teardown(tenant.instance_id)
|
||||
info = await backend.provision(user_id)
|
||||
tenant.instance_id = info["instance_id"]
|
||||
tenant.instance_name = info["instance_name"]
|
||||
tenant.api_key = info["api_key"]
|
||||
tenant.host = info["host"]
|
||||
tenant.port = info["port"]
|
||||
tenant.status = TenantStatus.running
|
||||
|
||||
# Audit re-provision (fire-and-forget since we're not in a route).
|
||||
try:
|
||||
await log_audit(
|
||||
action="tenant_reprovisioned",
|
||||
severity="warning",
|
||||
user_id=user_id,
|
||||
request_id=_request_id(request),
|
||||
resource_type="tenant",
|
||||
resource_id=tenant.instance_id,
|
||||
detail={
|
||||
"old_instance_id": old_instance_id,
|
||||
"new_instance_id": info["instance_id"],
|
||||
},
|
||||
ip_address=_client_ip(request),
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Failed to audit tenant re-provision")
|
||||
|
||||
# Touch the access timestamp for idle tracking.
|
||||
tenant.last_accessed_at = func.now()
|
||||
await session.commit()
|
||||
await session.refresh(tenant)
|
||||
|
||||
return tenant
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal proxy helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _proxy_request(
|
||||
request: Request, user_id: str, path: str,
|
||||
background_tasks: Optional[BackgroundTasks] = None,
|
||||
) -> Response:
|
||||
"""Proxy a request to the user's Open Terminal instance."""
|
||||
tenant = await _resolve_tenant(request, user_id)
|
||||
|
||||
target_url = f"http://{tenant.host}:{tenant.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}"
|
||||
# Remove hop-by-hop / routing headers.
|
||||
for h in ("host", "transfer-encoding", "connection", "x-user-id"):
|
||||
headers.pop(h, None)
|
||||
|
||||
body = await request.body()
|
||||
|
||||
client = await _get_proxy_client()
|
||||
upstream = await client.request(
|
||||
method=request.method,
|
||||
url=target_url,
|
||||
headers=headers,
|
||||
content=body,
|
||||
)
|
||||
|
||||
# Strip hop-by-hop from response too.
|
||||
response_headers = dict(upstream.headers)
|
||||
for h in ("transfer-encoding", "connection", "content-encoding", "content-length"):
|
||||
response_headers.pop(h, None)
|
||||
|
||||
# Audit the proxied request.
|
||||
severity = "warning" if upstream.status_code >= 500 else "info"
|
||||
if background_tasks:
|
||||
background_tasks.add_task(
|
||||
log_audit,
|
||||
action="proxy_request",
|
||||
severity=severity,
|
||||
user_id=user_id,
|
||||
request_id=_request_id(request),
|
||||
resource_type="proxy",
|
||||
resource_id=tenant.instance_id,
|
||||
detail={"method": request.method, "path": path},
|
||||
ip_address=_client_ip(request),
|
||||
user_agent=_user_agent(request),
|
||||
status_code=upstream.status_code,
|
||||
)
|
||||
|
||||
return Response(
|
||||
content=upstream.content,
|
||||
status_code=upstream.status_code,
|
||||
headers=response_headers,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenAPI spec passthrough (tool discovery — no X-User-Id required)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SPEC_CACHE_TTL = 300 # seconds
|
||||
_cached_spec: Optional[dict] = None
|
||||
_cached_spec_ts: float = 0.0
|
||||
|
||||
_SYSTEM_USER_ID = "__system__"
|
||||
|
||||
|
||||
@router.get(
|
||||
"/terminals/openapi.json",
|
||||
dependencies=[Depends(verify_api_key)],
|
||||
)
|
||||
async def get_openapi_spec(request: Request):
|
||||
"""Return the open-terminal OpenAPI spec.
|
||||
|
||||
The spec is fetched from a running instance and cached for 5 minutes.
|
||||
This endpoint does **not** require ``X-User-Id`` — it is used by
|
||||
Open WebUI for tool discovery before any user context exists.
|
||||
"""
|
||||
global _cached_spec, _cached_spec_ts
|
||||
|
||||
now = time.monotonic()
|
||||
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)
|
||||
|
||||
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}"},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
spec = resp.json()
|
||||
except Exception as e:
|
||||
logger.error("Failed to fetch OpenAPI spec from instance: {}", e)
|
||||
return JSONResponse(
|
||||
content={"error": "Failed to fetch OpenAPI spec from terminal instance"},
|
||||
status_code=502,
|
||||
)
|
||||
|
||||
_cached_spec = spec
|
||||
_cached_spec_ts = now
|
||||
|
||||
return JSONResponse(content=spec)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Header-based catch-all proxy (primary integration point)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/terminals/{path:path}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
||||
)
|
||||
async def proxy(
|
||||
path: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
x_user_id: str = Depends(verify_user_id),
|
||||
):
|
||||
"""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.
|
||||
"""
|
||||
return await _proxy_request(request, x_user_id, path, background_tasks)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WebSocket proxy for interactive terminal sessions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.websocket("/terminals/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.
|
||||
|
||||
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).
|
||||
"""
|
||||
# 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")
|
||||
await log_audit(
|
||||
action="auth_failed",
|
||||
severity="critical",
|
||||
user_id=user_id or None,
|
||||
resource_type="websocket",
|
||||
detail={"reason": "JWT validation failed", "session_id": session_id},
|
||||
ip_address=_client_ip(ws),
|
||||
)
|
||||
return
|
||||
elif settings.api_key and token != settings.api_key:
|
||||
await ws.close(code=4001, reason="Invalid API key")
|
||||
await log_audit(
|
||||
action="auth_failed",
|
||||
severity="critical",
|
||||
user_id=user_id or None,
|
||||
resource_type="websocket",
|
||||
detail={"reason": "Invalid API key", "session_id": session_id},
|
||||
ip_address=_client_ip(ws),
|
||||
)
|
||||
return
|
||||
|
||||
if not user_id:
|
||||
await ws.close(code=4002, reason="Missing user_id")
|
||||
return
|
||||
|
||||
# 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")
|
||||
await log_audit(
|
||||
action="auth_failed",
|
||||
severity="critical",
|
||||
user_id=user_id,
|
||||
resource_type="websocket",
|
||||
detail={
|
||||
"reason": "user_id mismatch",
|
||||
"claimed": user_id,
|
||||
"verified": verified_user_id,
|
||||
"session_id": session_id,
|
||||
},
|
||||
ip_address=_client_ip(ws),
|
||||
)
|
||||
return
|
||||
|
||||
await ws.accept()
|
||||
|
||||
global active_ws_connections
|
||||
active_ws_connections += 1
|
||||
|
||||
# Audit WS connect.
|
||||
await log_audit(
|
||||
action="ws_connect",
|
||||
severity="info",
|
||||
user_id=user_id,
|
||||
resource_type="websocket",
|
||||
resource_id=session_id,
|
||||
ip_address=_client_ip(ws),
|
||||
user_agent=_user_agent(ws),
|
||||
)
|
||||
|
||||
try:
|
||||
tenant = await _resolve_tenant(ws, user_id)
|
||||
except Exception as e:
|
||||
logger.error("Failed to resolve tenant 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}"
|
||||
|
||||
import websockets
|
||||
|
||||
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}))
|
||||
|
||||
async def _client_to_upstream():
|
||||
"""Forward client WebSocket → upstream."""
|
||||
try:
|
||||
while True:
|
||||
msg = await ws.receive()
|
||||
if msg["type"] == "websocket.disconnect":
|
||||
break
|
||||
elif "bytes" in msg and msg["bytes"]:
|
||||
await upstream.send(msg["bytes"])
|
||||
elif "text" in msg and msg["text"]:
|
||||
await upstream.send(msg["text"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def _upstream_to_client():
|
||||
"""Forward upstream → client WebSocket."""
|
||||
try:
|
||||
async for message in upstream:
|
||||
if isinstance(message, bytes):
|
||||
await ws.send_bytes(message)
|
||||
else:
|
||||
await ws.send_text(message)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await asyncio.gather(
|
||||
_client_to_upstream(),
|
||||
_upstream_to_client(),
|
||||
return_exceptions=True,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("WebSocket terminal proxy error: {}", e)
|
||||
finally:
|
||||
active_ws_connections -= 1
|
||||
# Audit WS disconnect.
|
||||
try:
|
||||
await log_audit(
|
||||
action="ws_disconnect",
|
||||
severity="info",
|
||||
user_id=user_id,
|
||||
resource_type="websocket",
|
||||
resource_id=session_id,
|
||||
ip_address=_client_ip(ws),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,392 @@
|
||||
"""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()
|
||||
|
||||
Reference in new issue
Block a user