"""Restricted OCI runtime controller. This module never builds or runs code on the gateway host.""" import hmac import base64 import json import os import threading import time import uuid import html from datetime import datetime, timezone from fastapi import APIRouter, Header, HTTPException from kubernetes import client from kubernetes.client.rest import ApiException from pydantic import BaseModel, Field from source_runtime import Source, attach_source, source_chunks, source_image router = APIRouter() NAMESPACE = os.environ.get("RUNTIME_NAMESPACE", "platform-runtimes") TOKEN = os.environ.get("RUNTIME_TOKEN", "") RUNTIME = os.environ.get("RUNTIME_CLASS", "gvisor") locks = {} guard = threading.Lock() def auth(authorization): if len(TOKEN) < 32 or not hmac.compare_digest(authorization or "", "Bearer " + TOKEN): raise HTTPException(401, "Unauthorized runtime request") def identifier(value): try: return uuid.UUID(str(value)).hex except ValueError: raise HTTPException(400, "Invalid resource ID") class Service(BaseModel): id: uuid.UUID name: str = Field(pattern=r"^[a-z][a-z0-9-]{0,62}$") image: str = Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9._/:@-]{0,499}$") command: list[str] = Field(max_length=30) environment: dict[str, str] = Field(max_length=100) port: int = Field(ge=1, le=65535) cpu_millis: int = Field(ge=50, le=64000) memory_mb: int = Field(ge=64, le=262144) replicas: int = Field(ge=1, le=20) health_path: str = Field(pattern=r"^/[^\s]{0,499}$|^$") source_managed: bool = False class Deployment(BaseModel): projectId: uuid.UUID deploymentId: uuid.UUID services: list[Service] = Field(min_length=1, max_length=100) branding: dict[str, str] = Field(default_factory=dict) source: Source | None = None class ProjectState(BaseModel): action: str = Field(pattern=r'^(SUSPEND|RESUME)$') operationId: uuid.UUID def blocked(core,project): try: return core.read_namespaced_config_map('control-'+project,NAMESPACE).data.get('state')=='SUSPEND' except ApiException as e: if e.status==404: return False raise def branding_config(port, branding): if branding.get('hostedFooterEnabled') != 'true': return None text = html.escape(branding.get('hostedFooterText', '由 WebUp Cloud 提供服务'), quote=True) url = branding.get('hostedFooterLink', 'https://webup.run') if url and not url.startswith('https://'): raise HTTPException(400, 'Footer link must use HTTPS') label = ('' + text + '') if url else text footer = '