Secure, Fast, and Extensible Sandbox runtime for AI agents.
# Copyright 2025 The OpenSandbox Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Application configuration management for sandbox server.
Loads configuration from a TOML file (default: ~/.sandbox.toml) and exposes
helpers to access the parsed settings throughout the application.
"""
from __future__ import annotations
import base64
import ipaddress
import logging
import os
import re
import string
from pathlib import Path
from typing import Any, ClassVar, Dict, Literal, Optional
from urllib.parse import urlparse, urlsplit
from kubernetes.utils.quantity import parse_quantity
from pydantic import (
BaseModel,
ConfigDict,
Field,
SecretStr,
ValidationError,
field_validator,
model_validator,
)
try: # Python 3.11+
import tomllib # type: ignore[attr-defined]
except ModuleNotFoundError: # Python 3.10 fallback
import tomli as tomllib # type: ignore[import]
logger = logging.getLogger(__name__)
CONFIG_ENV_VAR = "SANDBOX_CONFIG_PATH"
DEFAULT_CONFIG_PATH = Path.home() / ".sandbox.toml"
API_KEY_ENV_VAR = "OPENSANDBOX_SERVER_API_KEY"
POSTGRESQL_DSN_ENV_VAR = "OPENSANDBOX_STORE_POSTGRESQL_DSN"
# OSEP-0011 secure-access keys may be injected via environment instead of the
# [ingress.secure_access] TOML block, so key material can come from a Secret
# rather than a plaintext config file.
SECURE_ACCESS_KEYS_ENV_VAR = "OPENSANDBOX_SECURE_ACCESS_KEYS"
SECURE_ACCESS_ACTIVE_KEY_ENV_VAR = "OPENSANDBOX_SECURE_ACCESS_ACTIVE_KEY"
_HOSTNAME_RE = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9-]{1,63}(?:\.(?!-)[A-Za-z0-9-]{1,63})*$")
_WILDCARD_DOMAIN_RE = re.compile(r"^\*\.(?!-)[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})+$")
_IPV4_WITH_PORT_RE = re.compile(r"^(?P<ip>(?:\d{1,3}\.){3}\d{1,3})(?::(?P<port>\d{1,5}))?$")
# ``parse_quantity`` is intentionally permissive (for example, it accepts NaN and the unsupported decimal suffix K), so guard it with Kubernetes' grammar.
_KUBERNETES_QUANTITY_RE = re.compile(
r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)"
r"(?:(?:[eE][+-]?\d+)|(?:[numkMGTPE]|[KMGTPE]i)?)$"
)
_KUBERNETES_STANDARD_CONTAINER_RESOURCES = frozenset(
{"cpu", "memory", "ephemeral-storage"}
)
_KUBERNETES_DNS_LABEL_RE = re.compile(r"^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$")
_KUBERNETES_QUALIFIED_NAME_RE = re.compile(
r"^[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?$"
)
INGRESS_MODE_DIRECT = "direct"
INGRESS_MODE_GATEWAY = "gateway"
GATEWAY_ROUTE_MODE_WILDCARD = "wildcard"
GATEWAY_ROUTE_MODE_HEADER = "header"
GATEWAY_ROUTE_MODE_URI = "uri"
EGRESS_MODE_DNS = "dns"
EGRESS_MODE_DNS_NFT = "dns+nft"
# ASCII characters Go's net/url leaves unescaped in the host slot
# (shouldEscape(c, encodeHost)); the egress component parses
# OPENSANDBOX_EGRESS_UPSTREAM_PROXY with url.Parse, so the server validator
# mirrors that host charset exactly. Non-ASCII stays allowed like Go.
_UPSTREAM_PROXY_HOST_ASCII = frozenset(
string.ascii_letters + string.digits + "-._~!$&'()*+,;=:[]<>\""
)
def _is_valid_kubernetes_container_resource_name(name: str) -> bool:
if name in _KUBERNETES_STANDARD_CONTAINER_RESOURCES:
return True
if name.startswith("hugepages-"):
page_size = name.removeprefix("hugepages-")
try:
parsed = parse_quantity(page_size)
except (TypeError, ValueError):
return False
return bool(
_KUBERNETES_QUANTITY_RE.fullmatch(page_size)
and parsed.is_finite()
and parsed > 0
)
if name.startswith("requests."):
return False
prefix, separator, resource = name.partition("/")
return bool(
separator
and len(prefix) <= 253
and all(
0 < len(label) <= 63 and _KUBERNETES_DNS_LABEL_RE.fullmatch(label)
for label in prefix.split(".")
)
and 0 < len(resource) <= 63
and _KUBERNETES_QUALIFIED_NAME_RE.fullmatch(resource)
)
def _is_valid_ip(host: str) -> bool:
try:
ipaddress.ip_address(host)
return True
except ValueError:
return False
def _is_valid_ip_or_ip_port(address: str) -> bool:
match = _IPV4_WITH_PORT_RE.match(address)
if not match:
return False
ip_str = match.group("ip")
if not _is_valid_ip(ip_str):
return False
port_str = match.group("port")
if port_str is None:
return True
try:
port = int(port_str)
except ValueError:
return False
return 1 <= port <= 65535
def _is_valid_hostname(address: str) -> bool:
host = address
port_str: Optional[str] = None
if ":" in address:
host, _, port_str = address.rpartition(":")
if not host or not port_str:
return False
if not port_str.isdigit():
return False
port = int(port_str)
if not (1 <= port <= 65535):
return False
return bool(_HOSTNAME_RE.match(host))
def _is_wildcard_domain(host: str) -> bool:
return bool(_WILDCARD_DOMAIN_RE.match(host))
class RenewIntentRedisConfig(BaseModel):
"""Redis list consumer for renew-intent queue (ingress gateway path)."""
enabled: bool = Field(
default=False,
description=(
"When true, server workers consume renew intents from Redis "
"(ingress gateway path)."
),
)
dsn: Optional[str] = Field(
default=None,
description=(
'Redis DSN (e.g. "redis://127.0.0.1:6379/0"). '
"Required when redis.enabled is true."
),
)
queue_key: str = Field(
default="opensandbox:renew:intent",
min_length=1,
description="Redis List key for LPUSH/BRPOP renew-intent JSON payloads.",
)
consumer_concurrency: int = Field(
default=8,
ge=1,
description="Number of concurrent BRPOP worker tasks.",
)
@model_validator(mode="after")
def require_dsn_when_redis_enabled(self) -> "RenewIntentRedisConfig":
if self.enabled and (self.dsn is None or not str(self.dsn).strip()):
raise ValueError(
"[renew_intent] redis.dsn must be set when redis.enabled is true."
)
return self
class OtelConfig(BaseModel):
"""Optional OpenTelemetry export for Server and ingested SDK metrics."""
enabled: bool = Field(
default=False,
description=(
"Enable OTLP metrics export. When false, Server and SDK metrics are noops."
),
)
endpoint: Optional[str] = Field(
default=None,
description=(
"OTLP HTTP metrics endpoint. When omitted, OpenTelemetry uses "
"OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_METRICS_ENDPOINT."
),
)
service_name: str = Field(
default="opensandbox-server",
description="service.name resource attribute for exported metrics.",
)
export_interval_millis: int = Field(
default=60000,
ge=1000,
description="Periodic export interval in milliseconds.",
)
class RenewIntentConfig(BaseModel):
"""Renew sandbox expiration when access is observed (proxy and/or Redis queue)."""
enabled: bool = Field(
default=False,
description=(
"Master switch for auto-renew on reverse-proxy access and/or Redis "
"ingress intents. When false, renew-intent logic is off."
),
)
min_interval_seconds: int = Field(
default=60,
ge=1,
description=(
"Minimum seconds between successful renewals for the same sandbox "
"(cooldown)."
),
)
redis: RenewIntentRedisConfig = Field(
default_factory=RenewIntentRedisConfig,
description=(
"Redis queue consumer for ingress gateway renew-intent mode. "
"In TOML, set keys under the same [renew_intent] table as redis.enabled, "
"redis.dsn, redis.queue_key, redis.consumer_concurrency (dotted keys)."
),
)
class IdlePauseRedisConfig(BaseModel):
"""Redis settings for idle-pause activity tracking (OSEP-0024)."""
dsn: Optional[str] = Field(
default=None,
description=(
'Redis DSN (e.g. "redis://127.0.0.1:6379/0"). '
"Required when idle_pause.enabled is true."
),
)
lock_ttl_seconds: int = Field(
default=30,
ge=1,
description="TTL of the per-sandbox pause admission lock (SET NX EX).",
)
class IdlePauseConfig(BaseModel):
"""Auto-pause for opted-in fast sandboxes after X seconds of inactivity.
OSEP-0024. Only sandboxes that declare ``lifecycle.idlePolicy`` at create
time are ever auto-paused or auto-woken; absent the field this feature is
a no-op regardless of these switches.
"""
enabled: bool = Field(
default=False,
description=(
"Master switch: enables the idle sweeper (and server-side activity "
"registry access). Off by default."
),
)
sweep_interval_seconds: int = Field(
default=15,
ge=1,
description="Period between idle sweeps per server replica.",
)
activity_ttl_seconds: int = Field(
default=1800,
ge=30,
description=(
"TTL of per-sandbox activity keys. Must stay >= the largest accepted "
"idlePolicy.idleTimeoutSeconds (30-86400, enforced at create time) so "
"a present-but-stale key always implies idle-by-value. Keep the ingress "
"--activity-ttl-seconds equal to this value."
),
)
redis: IdlePauseRedisConfig = Field(
default_factory=IdlePauseRedisConfig,
description=(
"Redis used for activity keys and pause locks; the sweeper cannot "
"run without it. In TOML, set keys under the same "
"[automation.idle_pause] table as redis.dsn, "
"redis.lock_ttl_seconds (dotted keys)."
),
)
@model_validator(mode="after")
def require_redis_dsn_when_enabled(self) -> "IdlePauseConfig":
if self.enabled and (
self.redis.dsn is None or not str(self.redis.dsn).strip()
):
raise ValueError(
"[automation.idle_pause] redis.dsn must be set when "
"enabled is true."
)
return self
class AutomationConfig(BaseModel):
"""Umbrella for server-side lifecycle automation features.
Today this hosts idle auto-pause (OSEP-0024); future automation features
join as sibling sub-tables.
"""
idle_pause: IdlePauseConfig = Field(
default_factory=IdlePauseConfig,
description=(
"Idle auto-pause / auto-wake for opted-in fast sandboxes "
"(OSEP-0024). Off by default."
),
)
_KEY_ID_RE = re.compile(r"^[0-9a-z]$")
def _try_decode_base64(s: str) -> bytes | None:
"""Accept both padded and unpadded base64."""
try:
return base64.b64decode(s, validate=True)
except Exception:
pass
try:
padded = s + "=" * ((4 - len(s) % 4) % 4)
return base64.b64decode(padded, validate=True)
except Exception:
return None
class SecureAccessKey(BaseModel):
"""A signing key entry for OSEP-0011 signed route verification."""
key_id: str = Field(
...,
min_length=1,
max_length=1,
description="Key identifier, exactly one character in ``[0-9a-z]``.",
)
key: str = Field(
...,
min_length=1,
description="Base64-encoded signing key secret bytes.",
)
@field_validator("key_id")
@classmethod
def validate_key_id_char(cls, v: str) -> str:
if not _KEY_ID_RE.match(v):
raise ValueError(
f"key_id must be exactly one character [0-9a-z], got {v!r}"
)
return v
@field_validator("key")
@classmethod
def validate_key_is_base64(cls, v: str) -> str:
decoded = _try_decode_base64(v)
if decoded is None:
raise ValueError(f"key is not valid base64: {v!r}")
if not decoded:
raise ValueError("key must decode to at least 1 byte")
return v
def get_secret_bytes(self) -> bytes:
decoded = _try_decode_base64(self.key)
assert decoded is not None, "key was validated at construction"
return decoded
class SecureAccessConfig(BaseModel):
"""OSEP-0011 secure access signing configuration."""
active_key: str = Field(
...,
min_length=1,
max_length=1,
description=(
"Identifier of the active signing key. Must reference a ``key_id`` "
"present in ``keys``. Exactly one character ``[0-9a-z]``."
),
)
keys: list[SecureAccessKey] = Field(
...,
min_length=1,
description="List of signing keys available for route signing and verification.",
)
@field_validator("active_key")
@classmethod
def validate_active_key_char(cls, v: str) -> str:
if not _KEY_ID_RE.match(v):
raise ValueError(
f"active_key must be exactly one character [0-9a-z], got {v!r}"
)
return v
@model_validator(mode="after")
def ensure_active_key_exists(self) -> "SecureAccessConfig":
seen = set()
for k in self.keys:
if k.key_id in seen:
raise ValueError(
f"duplicate secure_access key_id {k.key_id!r}; "
"each key_id must be unique"
)
seen.add(k.key_id)
if self.active_key not in seen:
raise ValueError(
f"active_key {self.active_key!r} not found in secure_access.keys; "
f"available keys: {sorted(seen)}"
)
return self
def get_active_secret_bytes(self) -> bytes:
for k in self.keys:
if k.key_id == self.active_key:
return k.get_secret_bytes()
raise RuntimeError(
f"active_key {self.active_key!r} not in keys list"
)
class GatewayRouteModeConfig(BaseModel):
mode: Literal[
GATEWAY_ROUTE_MODE_WILDCARD,
GATEWAY_ROUTE_MODE_HEADER,
GATEWAY_ROUTE_MODE_URI,
] = Field(
...,
description="Routing mode used by the gateway (wildcard, header, uri).",
)
class Config:
populate_by_name = True
class GatewayConfig(BaseModel):
address: str = Field(
...,
description="Gateway host used to expose sandboxes (domain or IP, may include :port; scheme is not allowed).",
min_length=1,
)
route: GatewayRouteModeConfig = Field(
...,
description="Routing mode configuration used by the gateway.",
)
class IngressConfig(BaseModel):
mode: Literal[INGRESS_MODE_DIRECT, INGRESS_MODE_GATEWAY] = Field(
default=INGRESS_MODE_DIRECT,
description="Ingress exposure mode (direct or gateway).",
)
gateway: Optional[GatewayConfig] = Field(
default=None,
description="Gateway configuration required when mode = 'gateway'.",
)
secure_access: Optional[SecureAccessConfig] = Field(
default=None,
description=(
"OSEP-0011 secure access signing configuration. "
"When set, the server can issue signed route tokens and static "
"SecureAccessTokens for sandbox endpoints. "
"Requires ingress.mode = 'gateway'. "
"May also be injected via the OPENSANDBOX_SECURE_ACCESS_KEYS and "
"OPENSANDBOX_SECURE_ACCESS_ACTIVE_KEY environment variables."
),
)
@model_validator(mode="after")
def validate_ingress_mode(self) -> "IngressConfig":
if self.mode == INGRESS_MODE_GATEWAY and self.gateway is None:
raise ValueError("gateway block must be provided when ingress.mode = 'gateway'.")
if self.mode == INGRESS_MODE_DIRECT and self.gateway is not None:
raise ValueError("gateway block must be omitted unless ingress.mode = 'gateway'.")
if self.secure_access is not None and self.mode != INGRESS_MODE_GATEWAY:
raise ValueError(
"secure_access block requires ingress.mode = 'gateway'."
)
if self.mode == INGRESS_MODE_GATEWAY and self.gateway:
route_mode = self.gateway.route.mode
address_raw = self.gateway.address
hostport = address_raw
if "://" in address_raw:
raise ValueError("ingress.gateway.address must not include a scheme; clients choose http/https.")
if route_mode == GATEWAY_ROUTE_MODE_WILDCARD:
if not _is_wildcard_domain(hostport):
raise ValueError(
"ingress.gateway.address must be a wildcard domain (e.g., *.example.com) "
"when gateway.route.mode is wildcard."
)
else:
if "*" in hostport:
raise ValueError(
"ingress.gateway.address must not contain wildcard when gateway.route.mode is not wildcard."
)
if route_mode == GATEWAY_ROUTE_MODE_HEADER:
if not (_is_valid_hostname(hostport) or _is_valid_ip_or_ip_port(hostport)):
raise ValueError(
"ingress.gateway.address must be a valid hostname, hostname:port, IP, or IP:port "
"when gateway.route.mode is header."
)
elif route_mode == GATEWAY_ROUTE_MODE_URI:
if not hostport.strip():
raise ValueError(
"ingress.gateway.address must not be empty when gateway.route.mode is uri."
)
return self
class LogConfig(BaseModel):
level: str = Field(
default="INFO",
description="Python logging level for the server process.",
min_length=3,
)
file_enabled: bool = Field(
default=False,
description=(
"When true, logs are written to rotating files instead of stdout. "
"Uses default paths (/var/log/opensandbox/) unless file_path/access_file_path are set."
),
)
file_path: Optional[str] = Field(
default=None,
description=(
"Path to the main log file. When file_enabled=true and this is unset, "
"defaults to ~/logs/opensandbox/server.log."
),
)
access_file_path: Optional[str] = Field(
default=None,
description=(
"Path to the HTTP access log file. When file_enabled=true, access logs are written "
"to a separate file by default (~/logs/opensandbox/access.log). Set this to override "
"the path. Example: '~/logs/opensandbox/access.log'."
),
)
file_max_bytes: int = Field(
default=100 * 1024 * 1024,
ge=1,
description="Maximum size of each log file in bytes before rotation (default: 100MB).",
)
file_backup_count: int = Field(
default=5,
ge=0,
description="Number of backup log files to keep after rotation (default: 5).",
)
# Default paths when file_enabled=true and user paths are not set.
# Uses ~/logs/opensandbox/ which is writable for non-root users.
DEFAULT_FILE_PATH: ClassVar[str] = str(Path.home() / "logs" / "opensandbox" / "server.log")
DEFAULT_ACCESS_FILE_PATH: ClassVar[str] = str(Path.home() / "logs" / "opensandbox" / "access.log")
def resolved_file_path(self) -> Optional[str]:
"""Return the effective file path, using default if file_enabled and not overridden."""
if not self.file_enabled:
return None
return self.file_path or self.DEFAULT_FILE_PATH
def resolved_access_file_path(self) -> Optional[str]:
"""Return the effective access file path (defaults to separate file when file_enabled)."""
if not self.file_enabled:
return None
return self.access_file_path or self.DEFAULT_ACCESS_FILE_PATH
class ServerConfig(BaseModel):
host: str = Field(
default="0.0.0.0",
description="Interface bound by the lifecycle API server.",
min_length=1,
)
port: int = Field(
default=8080,
ge=1,
le=65535,
description="Port exposed by the lifecycle API server.",
)
timeout_keep_alive: int = Field(
default=30,
ge=1,
description=(
"Idle keep-alive timeout in seconds passed to uvicorn. "
"Connections idle longer than this may be closed by the server."
),
)
limit_concurrency: Optional[int] = Field(
default=1024,
ge=0,
description=(
"Maximum concurrent connections before returning 503. "
"Set to 0 to disable (TOML cannot express null). "
"Provides backpressure protection under burst load."
),
)
@field_validator("limit_concurrency", mode="after")
@classmethod
def _zero_disables_limit_concurrency(cls, value: Optional[int]) -> Optional[int]:
# Translate the TOML-friendly sentinel 0 into None so uvicorn applies
# no concurrency cap. TOML has no null literal, so 0 is the only way
# to disable the limit from the config file.
return None if value == 0 else value
timeout_graceful_shutdown: Optional[int] = Field(
default=5,
ge=1,
description=(
"Seconds uvicorn waits for in-flight requests to finish before "
"forcing shutdown. Ensures Ctrl+C terminates promptly even when "
"a long-running operation (e.g. image pull) is in progress."
),
)
backlog: int = Field(
default=2048,
ge=1,
description="Socket listen backlog passed to uvicorn.",
)
thread_pool_size: int = Field(
default=200,
ge=1,
description=(
"Maximum size of the anyio default threadpool used by FastAPI "
"to run sync route handlers. Default anyio limit is 40, which "
"throttles bursts of blocking sandbox list/get/delete operations "
"under high concurrency."
),
)
loop: Literal["auto", "uvloop", "asyncio"] = Field(
default="auto",
description=(
"Event loop implementation. 'auto' uses uvloop when available and "
"falls back to asyncio. 'asyncio' forces the stdlib loop."
),
)
http: Literal["auto", "httptools", "h11"] = Field(
default="auto",
description=(
"HTTP protocol parser. 'auto' uses httptools when available and "
"falls back to h11."
),
)
api_key: Optional[str] = Field(
default=None,
description="Global API key for authenticating incoming lifecycle API calls.",
)
eip: Optional[str] = Field(
default=None,
description="Bound public IP. When set, used as the host part when returning sandbox endpoints.",
)
max_sandbox_timeout_seconds: Optional[int] = Field(
default=None,
ge=60,
description=(
"Maximum allowed sandbox TTL in seconds for create requests that specify timeout. "
"Does not apply to renew-expiration requests or cap total sandbox lifetime. "
"Omit from config to disable the server-side upper bound."
),
)
class ProxyConfig(BaseModel):
resolve_internal: bool = Field(
default=True,
description=(
"When True (default), the proxy targets the sandbox's internal "
"container IP. When False, the proxy targets the server-local "
"host-mapped port, which is required when the server process "
"cannot route to Docker bridge network container IPs (for example "
"a launchd or systemd user session on macOS). Backward compatible: "
"the default preserves the historical behavior."
),
)
class KubernetesRuntimeConfig(BaseModel):
kubeconfig_path: Optional[str] = Field(
default=None,
description="Absolute path to the kubeconfig file used for API authentication.",
)
insecure_skip_tls_verify: bool = Field(
default=False,
description=(
"Skip TLS certificate verification for the Kubernetes API server. "
"Use only as a temporary workaround when in-cluster ServiceAccount CA "
"does not match the apiserver certificate; disable once cluster CA is fixed."
),
)
informer_resync_seconds: int = Field(
default=300,
ge=1,
description=(
"[Beta] Full resync interval for informer cache (seconds). "
"Shorter intervals refresh the cache more eagerly."
),
)
informer_watch_timeout_seconds: int = Field(
default=60,
ge=1,
description=(
"[Beta] Watch timeout (seconds) before restarting the informer stream."
),
)
read_qps: float = Field(
default=0.0,
ge=0,
description=(
"Maximum read requests per second to the Kubernetes API (get/list). "
"0 means unlimited (no rate limiting)."
),
)
read_burst: int = Field(
default=0,
ge=0,
description=(
"Burst size for the read rate limiter. "
"0 means use read_qps as burst (minimum 1)."
),
)
write_qps: float = Field(
default=0.0,
ge=0,
description=(
"Maximum write requests per second to the Kubernetes API (create/delete/patch). "
"0 means unlimited (no rate limiting)."
),
)
write_burst: int = Field(
default=0,
ge=0,
description=(
"Burst size for the write rate limiter. "
"0 means use write_qps as burst (minimum 1)."
),
)
namespace: Optional[str] = Field(
default=None,
description=(
"Kubernetes / fast-sandbox namespace for workload reads and "
"sandbox creation when no tenant is configured. With [tenants] "
"enabled, each tenant maps to its own namespace."
),
)
# -- fsb (fast-sandbox) backend --------------------------------------
# Shared with the kubernetes runtime, which also serves fsb (fsb-)
# sandboxes side by side; unused fields are harmless per provider.
fastpath_endpoint: str = Field(
default="fast-sandbox-fastpath.opensandbox.svc:9090",
description="fast-sandbox Fast-Path Server gRPC endpoint.",
)
fastpath_timeout_seconds: float = Field(
default=30.0,
ge=1.0,
description="Per-RPC gRPC deadline for FastPath calls.",
)
fastpath_wait_ready_seconds: float = Field(
default=30.0,
ge=1.0,
description="Bounded readiness wait for DataPlaneReady after Create.",
)
fastpath_resource_pool: str = Field(
default="default-pool",
description="Default fast-sandbox SandboxPool when extensions.poolRef is unset.",
)
template_s3_publish_secret: str = Field(
default="sandbox-oss-credentials",
min_length=1,
description=(
"Secret (in the platform namespace) holding the object-store "
"credentials referenced by server-created SandboxTemplates."
),
)
template_oci_publish_secret: Optional[str] = Field(
default=None,
min_length=1,
description=(
"dockerconfigjson Secret used as output.publishSecretRef for "
"format: overlaybd SandboxTemplate builds. Required when "
"creating overlaybd templates."
),
)
template_mitm_ca_secret: Optional[str] = Field(
default=None,
min_length=1,
description=(
"Secret holding the pinned cluster MITM CA certificate "
"(OSEP-0022). When set, server-created SandboxTemplates bake "
"spec.egressMitmCertificate from it (certificate entry only, "
"never the private key); unset keeps templates CA-free. The "
"Secret must exist in each template's namespace (ops-runbook "
"distribution); a missed copy fails the build observably."
),
)
template_mitm_ca_secret_key: str = Field(
default="ca.crt",
min_length=1,
description=(
"Secret entry holding the CA certificate when "
"kubernetes.template_mitm_ca_secret is set."
),
)
workload_provider: Optional[str] = Field(
default=None,
description="Workload provider type. If not specified, uses the first registered provider.",
)
batchsandbox_template_file: Optional[str] = Field(
default=None,
description="Path to BatchSandbox CR YAML template file. Used when workload_provider is 'batchsandbox'.",
)
sandbox_create_timeout_seconds: int = Field(
default=60,
ge=1,
description="Timeout in seconds to wait for a sandbox to become ready (IP assigned) after creation.",
)
pool_acquisition_timeout_seconds: int = Field(
default=30,
ge=1,
description=(
"Maximum cumulative time in seconds to wait while Pool capacity "
"prevents sandbox allocation. The overall sandbox create timeout still applies."
),
)
sandbox_create_poll_interval_seconds: float = Field(
default=1.0,
gt=0,
description="Fallback status-check interval in seconds when no workload change notification arrives during creation.",
)
execd_init_resources: Optional["ExecdInitResources"] = Field(
default=None,
description=(
"Resource requests/limits for the execd init container. "
"If unset, no resource constraints are applied."
),
)
image_pull_policy: Optional[str] = Field(
default="IfNotPresent",
description=(
"Image pull policy for sandbox containers. "
"Values: Always, IfNotPresent, Never. "
"Can be overridden per-sandbox via image.pull_policy in create request."
),
)
class ExecdInitResources(BaseModel):
limits: Optional[Dict[str, str]] = Field(
default=None,
description='Resource limits, e.g. {cpu = "100m", memory = "128Mi"}.',
)
requests: Optional[Dict[str, str]] = Field(
default=None,
description='Resource requests, e.g. {cpu = "50m", memory = "64Mi"}.',
)
class AgentSandboxRuntimeConfig(BaseModel):
template_file: Optional[str] = Field(
default=None,
description="Path to Sandbox CR YAML template file for agent-sandbox.",
)
shutdown_policy: Literal["Delete", "Retain"] = Field(
default="Delete",
description="Shutdown policy applied when a sandbox expires (Delete or Retain).",
)
ingress_enabled: bool = Field(
default=True,
description="Whether ingress routing to agent-sandbox pods is expected to be enabled.",
)
class StorageConfig(BaseModel):
allowed_host_paths: list[str] = Field(
default_factory=list,
description=(
"Allowlist of host path prefixes permitted for host bind mounts. "
"If empty, host bind mounts are rejected. "
"Each entry must be an absolute path (e.g., '/data/opensandbox')."
),
)
volume_default_size: str = Field(
default="1Gi",
description=(
"Default storage size for auto-created PVCs when the caller does "
"not specify a size in the PVC provisioning hints."
),
)
ossfs_mount_root: str = Field(
default="/mnt/ossfs",
description=(
"Host-side root directory where OSSFS mounts are resolved. "
"Resolved OSSFS host paths are built as "
"'ossfs_mount_root/<bucket>/<volume.subPath?>'."
),
)
DEFAULT_EGRESS_DISABLE_IPV6 = True
class EgressUpstreamProxyConfig(BaseModel):
"""Chained upstream CONNECT proxy for the egress sidecar.
Mirrors the egress component's ``parseUpstreamProxy`` validation so an
invalid endpoint fails server startup instead of failing sandbox creation
later. Error messages never echo the configured URL: a userinfo URL would
otherwise leak credentials into logs.
"""
model_config = ConfigDict(hide_input_in_errors=True)
url: str = Field(
...,
description=(
"Upstream proxy endpoint (http://host[:port] or https://host[:port]). "
"Injected into the egress sidecar as OPENSANDBOX_EGRESS_UPSTREAM_PROXY. "
"Credentials, query, fragment, and paths are rejected; use "
"authorization for credentials."
),
min_length=1,
)
authorization: Optional[SecretStr] = Field(
default=None,
description=(
"Complete Proxy-Authorization header value sent on the upstream "
"CONNECT (e.g. 'Basic <base64>'), injected as "
"OPENSANDBOX_EGRESS_UPSTREAM_PROXY_AUTH. Never logged."
),
)
ca_cert_path: Optional[str] = Field(
default=None,
description=(
"Docker only: absolute POSIX path on the Docker daemon host to a "
"PEM CA bundle mounted read-only into the egress sidecar."
),
)
ca_secret_name: Optional[str] = Field(
default=None,
description=(
"Kubernetes only: Secret containing the upstream CA bundle under "
"the fixed ca.crt key; mounted only into the egress sidecar."
),
)
@field_validator("url")
@classmethod
def validate_url(cls, url: str) -> str:
url = url.strip()
if not url:
raise ValueError("egress.upstream_proxy.url: value is empty")
# urlsplit silently strips tab/CR/LF, which Go's parser rejects —
# check the raw string first so both sides agree.
if any(ord(c) < 0x20 or c == "\x7f" for c in url):
raise ValueError(
"egress.upstream_proxy.url: control characters are not allowed"
)
if "://" not in url:
raise ValueError(
"egress.upstream_proxy.url: missing scheme, "
"want http://host:port or https://host:port"
)
try:
parsed = urlsplit(url)
except ValueError:
raise ValueError("egress.upstream_proxy.url: invalid URL") from None
if parsed.scheme not in ("http", "https"):
raise ValueError(
"egress.upstream_proxy.url: unsupported scheme, want http or https"
)
if (
parsed.username is not None
or parsed.password is not None
or "@" in parsed.netloc
):
raise ValueError(
"egress.upstream_proxy.url: userinfo is not allowed, "
"use authorization for credentials"
)
host = parsed.hostname
if not host:
raise ValueError("egress.upstream_proxy.url: missing host")
if "?" in url or "#" in url or parsed.query or parsed.fragment:
raise ValueError(
"egress.upstream_proxy.url: query and fragment are not allowed"
)
if parsed.path not in ("", "/"):
raise ValueError("egress.upstream_proxy.url: path is not allowed")
try:
port = parsed.port
except ValueError:
raise ValueError(
"egress.upstream_proxy.url: invalid port, want 1-65535"
) from None
if port is not None and not 1 <= port <= 65535:
raise ValueError("egress.upstream_proxy.url: invalid port, want 1-65535")
# userinfo is already rejected, so a bracketed netloc means the
# host is an IPv6 literal where "%<zone>" is legitimate.
bracketed = parsed.netloc.startswith("[")
if "%" in host and not bracketed:
raise ValueError("egress.upstream_proxy.url: invalid host")
if any(
ord(c) < 0x80 and c != "%" and c not in _UPSTREAM_PROXY_HOST_ASCII
for c in host
):
raise ValueError("egress.upstream_proxy.url: invalid host")
return url
@field_validator("authorization")
@classmethod
def validate_authorization(
cls, authorization: Optional[SecretStr]
) -> Optional[SecretStr]:
if authorization is None:
return None
secret = authorization.get_secret_value()
if not secret.strip():
return None
if "\r" in secret or "\n" in secret:
raise ValueError(
"egress.upstream_proxy.authorization must not contain newlines"
)
return authorization
@field_validator("ca_cert_path")
@classmethod
def validate_ca_cert_path(cls, path: Optional[str]) -> Optional[str]:
if path is None:
return None
path = path.strip()
if not path:
raise ValueError("egress.upstream_proxy.ca_cert_path: value is empty")
if "\x00" in path:
raise ValueError(
"egress.upstream_proxy.ca_cert_path: NUL is not allowed"
)
# The path lives on the Docker daemon host, which may be remote —
# never stat it here. It must be POSIX-absolute because the bind
# source is resolved by the daemon (typically Linux); Path.is_absolute
# is platform-dependent and would reject "/x/y" when the server itself
# runs on Windows. ":" is rejected because it collides with the
# "src:dst:mode" bind syntax.
if not path.startswith("/") or ":" in path:
raise ValueError(
"egress.upstream_proxy.ca_cert_path must be an absolute POSIX "
"path without ':'"
)
return path
@field_validator("ca_secret_name")
@classmethod
def validate_ca_secret_name(cls, name: Optional[str]) -> Optional[str]:
if name is None:
return None
name = name.strip()
if not name or len(name) > 253:
raise ValueError(
"egress.upstream_proxy.ca_secret_name must be a DNS-1123 subdomain"
)
if not all(
0 < len(label) <= 63 and _KUBERNETES_DNS_LABEL_RE.fullmatch(label)
for label in name.split(".")
):
raise ValueError(
"egress.upstream_proxy.ca_secret_name must be a DNS-1123 subdomain"
)
return name
class EgressConfig(BaseModel):
image: Optional[str] = Field(
default=None,
description="Container image for the egress sidecar (used when network policy is requested).",
min_length=1,
)
mode: Literal[
EGRESS_MODE_DNS,
EGRESS_MODE_DNS_NFT,
] = Field(
default=EGRESS_MODE_DNS,
description="Egress enforcement passed to the sidecar as OPENSANDBOX_EGRESS_MODE (dns or dns+nft).",
)
disable_ipv6: bool = Field(
default=DEFAULT_EGRESS_DISABLE_IPV6,
description=(
"Default true: egress IPv6 support is incomplete, especially on Kubernetes runtime. "
"Set false only if you intentionally leave IPv6 enabled in the sandbox netns "
"(e.g. IPv4-only CNI or experimenting with IPv6 egress despite gaps)."
),
)
otlp_endpoint: Optional[str] = Field(
default=None,
description=(
"OTLP/HTTP endpoint (http:// or https://) where the egress sidecar exports its "
"OpenTelemetry metrics, injected as OTEL_EXPORTER_OTLP_ENDPOINT. "
"Server-side only: the collector address is infrastructure config and cannot be "
"set per request. When unset, sidecar metrics are not exported."
),
)
readiness_timeout_seconds: float = Field(
default=30.0,
gt=0,
description=(
"Maximum time in seconds to wait for the egress sidecar health endpoint "
"to become ready in Docker runtime."
),
)
requests: Optional[Dict[str, str]] = Field(
default=None,
description=(
"Kubernetes resource requests for the egress sidecar. Can be set independently of limits."
),
)
limits: Optional[Dict[str, str]] = Field(
default=None,
description=(
"Kubernetes resource limits for the egress sidecar. Can be set independently of requests. "
"If both are unset, the resources block is omitted (namespace LimitRange defaults may apply)."
),
)
upstream_proxy: Optional[EgressUpstreamProxyConfig] = Field(
default=None,
description=(
"Chained upstream HTTP(S) CONNECT proxy for mitmproxy-handled egress. "
"Server-side only; injected as OPENSANDBOX_EGRESS_UPSTREAM_PROXY[_AUTH] "
"on every egress sidecar. Sandboxes created with networkPolicy must "
"enable transparent MITM (credentialProxy.enabled or env "
"OPENSANDBOX_EGRESS_MITMPROXY_TRANSPARENT=true) or creation is rejected. "
'Requires mode = "dns+nft".'
),
)
@field_validator("otlp_endpoint")
@classmethod
def validate_otlp_endpoint(cls, endpoint: Optional[str]) -> Optional[str]:
if not endpoint:
return None
parsed = urlparse(endpoint)
if parsed.scheme not in ("http", "https") or not parsed.hostname:
raise ValueError(
"otlp_endpoint must be an http(s) URL with a collector host: "
"the egress sidecar telemetry client only supports OTLP over HTTP "
"and rejects endpoints without a hostname"
)
return endpoint
@field_validator("requests", "limits")
@classmethod
def validate_quantities(
cls, resources: Optional[Dict[str, str]]
) -> Optional[Dict[str, str]]:
if not resources:
return None
for resource_name, quantity in resources.items():
if not _is_valid_kubernetes_container_resource_name(resource_name):
raise ValueError(f"invalid Kubernetes container resource name: {resource_name!r}")
try:
parsed = parse_quantity(quantity)
except (TypeError, ValueError):
parsed = None
if (
not _KUBERNETES_QUANTITY_RE.fullmatch(quantity)
or parsed is None
or not parsed.is_finite()
or parsed < 0
):
raise ValueError(f"invalid Kubernetes resource quantity for {resource_name!r}: {quantity!r}")
return resources
@model_validator(mode="after")
def validate_requests_do_not_exceed_limits(self) -> EgressConfig:
requests = self.requests or {}
limits = self.limits or {}
for resource_name in requests.keys() & limits.keys():
request = requests[resource_name]
limit = limits[resource_name]
if parse_quantity(request) > parse_quantity(limit):
raise ValueError(f"resource request for {resource_name!r} ({request!r}) must not exceed limit ({limit!r})")
return self
@model_validator(mode="after")
def validate_upstream_proxy_requires_dns_nft(self) -> EgressConfig:
# The egress sidecar refuses the upstream proxy unless
# OPENSANDBOX_EGRESS_MODE=dns+nft; fail at config load instead of
# crash-looping every sidecar.
if self.upstream_proxy is not None and self.mode != EGRESS_MODE_DNS_NFT:
raise ValueError('egress.upstream_proxy requires egress.mode = "dns+nft"')
return self
class RuntimeConfig(BaseModel):
type: Literal["docker", "kubernetes"] = Field(
...,
description="Active sandbox runtime implementation.",
)
execd_image: str = Field(
...,
description=(
"Container image that contains the execd binary for sandbox "
"initialization. Docker/Kubernetes run it in-sandbox; the fsb "
"runtime injects it into SandboxTemplate golden-image builds "
"(the template builder bakes the runtime files into the guest "
"rootfs)."
),
min_length=1,
)
execd_run_as_init: bool = Field(
default=False,
description=(
"Run execd as the sandbox init (OSEP-0018): sets EXECD_INIT in the "
"sandbox environment so bootstrap.sh execs into execd (--init) and "
"execd becomes PID 1, reaping children and owning the container "
"lifecycle. Defaults to false (classic background-and-wait "
"topology); intended to be flipped on after a few releases once "
"the init mode is validated in production."
),
)
class SecureRuntimeConfig(BaseModel):
type: Literal["", "gvisor", "kata", "firecracker"] = Field(
default="",
description=(
"Secure runtime type. Empty means no secure runtime. "
"gVisor uses runsc OCI runtime. "
"Kata uses kata-runtime (OCI) or kata-qemu (RuntimeClass). "
"Firecracker uses kata-fc (RuntimeClass, Kubernetes only)."
),
)
docker_runtime: Optional[str] = Field(
default=None,
description=(
"OCI runtime name for Docker (e.g., 'runsc' for gVisor, 'kata-runtime' for Kata). "
"When specified, the Docker daemon will use this runtime instead of runc."
),
)
k8s_runtime_class: Optional[str] = Field(
default=None,
description=(
"Kubernetes RuntimeClass name for secure containers. "
"Common values: 'gvisor', 'kata-qemu', 'kata-fc'. "
"When specified, pods will have runtimeClassName set to this value."
),
)
@model_validator(mode="after")
def validate_secure_runtime(self) -> "SecureRuntimeConfig":
if self.type == "":
if self.docker_runtime is not None or self.k8s_runtime_class is not None:
raise ValueError(
"docker_runtime and k8s_runtime_class must be omitted when secure_runtime.type is empty."
)
return self
if self.type == "firecracker":
# Firecracker is Kubernetes-only
if self.k8s_runtime_class is None:
raise ValueError(
"secure_runtime.k8s_runtime_class is required when secure_runtime.type is 'firecracker'."
)
# Optional: also allow docker_runtime for consistency, but Firecracker won't use it
if self.type in ("gvisor", "kata"):
if self.docker_runtime is None and self.k8s_runtime_class is None:
raise ValueError(
f"At least one of secure_runtime.docker_runtime or secure_runtime.k8s_runtime_class "
f"must be specified when secure_runtime.type is '{self.type}'."
)
return self
class DockerConfig(BaseModel):
network_mode: str = Field(
default="host",
description=(
"Network attachment for sandbox containers: 'host', 'bridge', 'none', 'pasta', "
"'slirp4netns', or the name of an existing user-defined network. 'pasta' / "
"'slirp4netns' are container-runtime user-mode networks (podman) that the host "
"reaches through the published ports; egress/networkPolicy still requires 'bridge'."
),
)
api_timeout: Optional[int] = Field(
default=None,
ge=1,
description="Docker API timeout in seconds. If unset, default is 180.",
)
host_ip: Optional[str] = Field(
default=None,
description=(
"Docker host IP or hostname for bridge-mode endpoint URLs when the server runs in a container."
),
)
drop_capabilities: list[str] = Field(
default_factory=lambda: [
"AUDIT_WRITE",
"MKNOD",
"NET_ADMIN",
"NET_RAW",
"SYS_ADMIN",
"SYS_MODULE",
"SYS_PTRACE",
"SYS_TIME",
"SYS_TTY_CONFIG",
],
description=(
"Linux capabilities to drop from sandbox containers. Defaults to a conservative set to reduce host impact."
),
)
apparmor_profile: Optional[str] = Field(
default=None,
description=(
"Optional AppArmor profile name applied to sandbox containers. Leave unset to let Docker choose the default."
),
)
no_new_privileges: bool = Field(
default=True,
description="Enable the kernel no_new_privileges flag to block privilege escalation inside the container.",
)
seccomp_profile: Optional[str] = Field(
default=None,
description=(
"Optional seccomp profile name or path applied to sandbox containers. Leave unset to use Docker's default profile."
),
)
port_range_min: int = Field(
default=40000,
ge=1024,
le=65535,
description=(
"Lower bound of the host port range for bridge-mode sandbox port allocation. "
"Must be less than port_range_max. Narrow the range to match your firewall policy."
),
)
port_range_max: int = Field(
default=60000,
ge=1024,
le=65535,
description=(
"Upper bound of the host port range for bridge-mode sandbox port allocation. "
"Range must span at least 100 ports for reliable allocation. "
"Each sandbox needs 2–3 host ports (2 without egress, 3 with egress sidecar)."
),
)
publish_host: str = Field(
default="0.0.0.0",
description=(
"Host address Docker publishes bridge-mode sandbox ports on (the HostIp of every port "
"binding, the egress sidecar's included). The default 0.0.0.0 publishes on every host "
"interface. Set an IP address to keep sandbox ports off public interfaces: 127.0.0.1 "
"when the server runs on the host, or the Docker bridge gateway (e.g. 172.17.0.1) when "
"the server runs in a container and reaches sandboxes through host-published ports. "
"Must be an IPv4 address (Docker does not resolve names in port bindings, and the port "
"probe is IPv4-only)."
),
)
pids_limit: Optional[int] = Field(
default=4096,
ge=1,
description="Maximum number of processes allowed per sandbox container. Set to null to disable the limit.",
)
sandbox_env: dict[str, str] = Field(
default_factory=dict,
description=(
"Environment variables injected into every sandbox container. Keys from a sandbox "
"creation request override same-named keys. Docker-runtime counterpart of the "
"Kubernetes pod template: useful for fleet-wide settings such as trusting a private "
"CA (e.g. NODE_EXTRA_CA_CERTS) together with sandbox_binds."
),
)
sandbox_binds: list[str] = Field(
default_factory=list,
description=(
"Host bind mounts applied to every sandbox container, in Docker -v syntax "
"(host_path:container_path[:mode]). Prepended to the binds derived from a request's "
"volumes. Useful for mounting a private CA certificate into all sandboxes."
),
)
@field_validator("publish_host")
@classmethod
def validate_publish_host(cls, value: str) -> str:
host = (value or "").strip()
if not host:
return "0.0.0.0"
try:
parsed = ipaddress.ip_address(host)
except ValueError as exc:
raise ValueError(
f"docker.publish_host must be an IP address (got {value!r}): Docker publishes ports "
"on addresses, not names."
) from exc
if not isinstance(parsed, ipaddress.IPv4Address):
# The port allocator probes with an AF_INET socket: an IPv6 literal would pass here and
# then fail every probe (gaierror, not EADDRNOTAVAIL), so say so at config load.
raise ValueError(
f"docker.publish_host must be an IPv4 address (got {value!r}): the port allocator "
"probes with an IPv4 socket."
)
return host
@model_validator(mode="after")
def validate_port_range(self) -> "DockerConfig":
if self.port_range_min >= self.port_range_max:
raise ValueError(
f"docker.port_range_min ({self.port_range_min}) must be less than "
f"docker.port_range_max ({self.port_range_max})."
)
if self.port_range_max - self.port_range_min < 100:
raise ValueError(
f"Port range ({self.port_range_min}-{self.port_range_max}) is too narrow. "
f"Need at least 100 ports for reliable allocation."
)
return self
class PostgreSQLStoreConfig(BaseModel):
dsn: Optional[SecretStr] = Field(
default=None,
description=(
"PostgreSQL connection string. In production, inject it with "
f"{POSTGRESQL_DSN_ENV_VAR} instead of storing credentials in TOML."
),
)
min_pool_size: int = Field(
default=1,
ge=0,
description="Minimum number of PostgreSQL connections retained per server process.",
)
max_pool_size: int = Field(
default=10,
ge=1,
description="Maximum number of PostgreSQL connections per server process.",
)
connect_timeout_seconds: int = Field(
default=5,
ge=1,
description="Maximum time in seconds to establish initial PostgreSQL connections.",
)
pool_timeout_seconds: float = Field(
default=5.0,
gt=0,
description="Maximum time in seconds to wait for a pooled PostgreSQL connection.",
)
snapshot_recovery_interval_seconds: float = Field(
default=15.0,
gt=0,
description=(
"Interval between unfinished snapshot recovery scans when PostgreSQL is paired "
"with the Kubernetes runtime. This controls takeover latency, not correctness."
),
)
@model_validator(mode="after")
def validate_pool_size(self) -> "PostgreSQLStoreConfig":
if self.min_pool_size > self.max_pool_size:
raise ValueError(
"store.postgresql.min_pool_size must be less than or equal to "
"store.postgresql.max_pool_size."
)
return self
class StoreConfig(BaseModel):
type: Literal["sqlite", "postgresql"] = Field(
default="sqlite",
description=(
"Server persistence backend type. SQLite is the default local persistent backend; "
"PostgreSQL provides external persistence."
),
)
path: str = Field(
default=str(Path.home() / ".opensandbox" / "opensandbox.db"),
description="Filesystem path to the SQLite database used for server metadata persistence.",
min_length=1,
)
postgresql: PostgreSQLStoreConfig = Field(
default_factory=PostgreSQLStoreConfig,
description="PostgreSQL settings used when store.type is 'postgresql'.",
)
@model_validator(mode="after")
def require_postgresql_dsn(self) -> "StoreConfig":
if self.type != "postgresql":
return self
dsn = self.postgresql.dsn
if dsn is None or not dsn.get_secret_value().strip():
raise ValueError(
"store.postgresql.dsn or "
f"{POSTGRESQL_DSN_ENV_VAR} must be set when store.type is 'postgresql'."
)
return self
class TenantsConfig(BaseModel):
provider: Literal["file", "http"] = Field(
default="file",
description="Tenant provider type: 'file' (tenants.toml) or 'http' (remote endpoint).",
)
endpoint: Optional[str] = Field(
default=None,
description="HTTP tenant provider endpoint URL. Required when provider='http'.",
)
max_stale_seconds: float = Field(
default=300.0,
ge=0,
description="Maximum seconds to serve stale cache when HTTP endpoint is unreachable.",
)
timeout_seconds: float = Field(
default=5.0,
gt=0,
description="HTTP request timeout in seconds.",
)
auth_header: Optional[str] = Field(
default=None,
description="Optional header name for provider-level authentication to HTTP endpoint.",
)
auth_token: Optional[str] = Field(
default=None,
description="Optional token value for provider-level authentication to HTTP endpoint.",
)
@model_validator(mode="after")
def require_endpoint_for_http(self) -> "TenantsConfig":
if self.provider == "http" and not self.endpoint:
raise ValueError("[tenants] endpoint must be set when provider='http'.")
return self
class AppConfig(BaseModel):
# Config values may be secrets (store dsn, egress upstream proxy
# authorization); never echo raw inputs inside validation errors.
model_config = ConfigDict(hide_input_in_errors=True)
server: ServerConfig = Field(default_factory=ServerConfig)
proxy: ProxyConfig = Field(
default_factory=ProxyConfig,
description="Configuration for the sandbox reverse-proxy routes.",
)
log: LogConfig = Field(
default_factory=LogConfig,
description="Logging configuration (level, file output, rotation).",
)
tenants: Optional[TenantsConfig] = Field(
default=None,
description="Multi-tenant configuration. When present, enables multi-tenant mode.",
)
renew_intent: RenewIntentConfig = Field(
default_factory=RenewIntentConfig,
description="Auto-renew sandbox expiration when reverse-proxy access is observed.",
)
automation: AutomationConfig = Field(
default_factory=AutomationConfig,
description=(
"Lifecycle automation for fast sandboxes: idle auto-pause today "
"(OSEP-0024). Off by default."
),
)
otel: OtelConfig = Field(
default_factory=OtelConfig,
description="OpenTelemetry export for SDK metrics ingestion (Phase 1: create latency).",
)
runtime: RuntimeConfig = Field(..., description="Sandbox runtime configuration.")
kubernetes: Optional[KubernetesRuntimeConfig] = None
agent_sandbox: Optional["AgentSandboxRuntimeConfig"] = None
ingress: Optional[IngressConfig] = None
docker: DockerConfig = Field(default_factory=DockerConfig)
storage: StorageConfig = Field(default_factory=StorageConfig)
store: StoreConfig = Field(
default_factory=StoreConfig,
description="Persistence backend configuration for server-managed resources.",
)
egress: Optional[EgressConfig] = None
secure_runtime: Optional[SecureRuntimeConfig] = Field(
default=None,
description="Secure container runtime configuration (gVisor, Kata, Firecracker).",
)
@model_validator(mode="after")
def validate_runtime_blocks(self) -> "AppConfig":
if self.runtime.type == "docker":
if self.kubernetes is not None:
raise ValueError("Kubernetes block must be omitted when runtime.type = 'docker'.")
if self.agent_sandbox is not None:
raise ValueError("agent_sandbox block must be omitted when runtime.type = 'docker'.")
if self.ingress is not None and self.ingress.mode != INGRESS_MODE_DIRECT:
raise ValueError("ingress.mode must be 'direct' when runtime.type = 'docker'.")
if self.secure_runtime is not None and self.secure_runtime.type == "firecracker":
raise ValueError( "secure_runtime.type 'firecracker' is only compatible with runtime.type='kubernetes'.")
elif self.runtime.type == "kubernetes":
if self.kubernetes is None:
self.kubernetes = KubernetesRuntimeConfig()
provider_type = (self.kubernetes.workload_provider or "").lower()
if provider_type == "agent-sandbox":
if self.agent_sandbox is None:
self.agent_sandbox = AgentSandboxRuntimeConfig()
elif self.agent_sandbox is not None:
raise ValueError(
"agent_sandbox block requires kubernetes.workload_provider = 'agent-sandbox'."
)
else:
raise ValueError(f"Unsupported runtime type '{self.runtime.type}'.")
upstream_proxy = self.egress.upstream_proxy if self.egress else None
if upstream_proxy is not None:
if self.runtime.type == "docker" and upstream_proxy.ca_secret_name is not None:
raise ValueError(
"egress.upstream_proxy.ca_secret_name requires runtime.type = 'kubernetes'"
)
if self.runtime.type == "kubernetes" and upstream_proxy.ca_cert_path is not None:
raise ValueError(
"egress.upstream_proxy.ca_cert_path requires runtime.type = 'docker'"
)
return self
_config: AppConfig | None = None
_config_path: Path | None = None
def _resolve_config_path(path: str | Path | None = None) -> Path:
"""Resolve configuration file path from explicit value, env var, or default."""
if path:
return Path(path).expanduser()
env_path = os.environ.get(CONFIG_ENV_VAR)
if env_path:
return Path(env_path).expanduser()
return DEFAULT_CONFIG_PATH
def _load_toml_data(path: Path) -> dict[str, Any]:
"""Load TOML content from file, returning empty dict if file is missing."""
if not path.exists():
logger.info(f"Config file {path} not found. Using default configuration.")
return {}
try:
with path.open("rb") as fh:
data = tomllib.load(fh)
logger.info(f"Loaded configuration from {path}")
return data
except Exception as exc: # noqa: BLE001
logger.error(f"Failed to read config file {path}: {exc}")
raise
def _apply_raw_env_overrides(raw_data: dict[str, Any]) -> None:
"""Apply environment overrides that must participate in model validation."""
postgresql_dsn = os.environ.get(POSTGRESQL_DSN_ENV_VAR)
if postgresql_dsn is None:
return
store_data = raw_data.setdefault("store", {})
if not isinstance(store_data, dict):
raise ValueError("[store] must be a TOML table.")
postgresql_data = store_data.setdefault("postgresql", {})
if not isinstance(postgresql_data, dict):
raise ValueError("[store.postgresql] must be a TOML table.")
# Wrap before validation so errors from sibling fields cannot expose credentials.
postgresql_data["dsn"] = SecretStr(postgresql_dsn)
def _apply_env_overrides(config: AppConfig) -> None:
"""Apply environment variable overrides to parsed configuration."""
if API_KEY_ENV_VAR in os.environ:
config.server.api_key = os.environ[API_KEY_ENV_VAR]
_apply_secure_access_env_overrides(config)
def _apply_secure_access_env_overrides(config: AppConfig) -> None:
"""Build ingress.secure_access from OPENSANDBOX_SECURE_ACCESS_* env vars.
OPENSANDBOX_SECURE_ACCESS_KEYS is a comma-separated key ring in
"key_id=base64" form; OPENSANDBOX_SECURE_ACCESS_ACTIVE_KEY names the
signing key. Both must be set together, and env wins over any
[ingress.secure_access] block from the config file.
"""
keys_env = os.environ.get(SECURE_ACCESS_KEYS_ENV_VAR)
active_key_env = os.environ.get(SECURE_ACCESS_ACTIVE_KEY_ENV_VAR)
if keys_env is None and active_key_env is None:
return
if not keys_env or not active_key_env:
raise ValueError(
f"{SECURE_ACCESS_KEYS_ENV_VAR} and {SECURE_ACCESS_ACTIVE_KEY_ENV_VAR} "
"must be set together."
)
if config.ingress is None or config.ingress.mode != INGRESS_MODE_GATEWAY:
raise ValueError(
f"{SECURE_ACCESS_KEYS_ENV_VAR} requires ingress.mode = "
f"'{INGRESS_MODE_GATEWAY}' in the config file."
)
keys: list[SecureAccessKey] = []
for pair in keys_env.split(","):
key_id, sep, b64 = pair.partition("=")
if not sep or not key_id:
raise ValueError(
f"{SECURE_ACCESS_KEYS_ENV_VAR} entries must be in "
f"key_id=base64 form, got {pair!r}"
)
keys.append(SecureAccessKey(key_id=key_id, key=b64))
config.ingress.secure_access = SecureAccessConfig(
active_key=active_key_env,
keys=keys,
)
def load_config(path: str | Path | None = None) -> AppConfig:
"""Load configuration from TOML file and store it globally."""
global _config, _config_path
resolved_path = _resolve_config_path(path)
raw_data = _load_toml_data(resolved_path)
_apply_raw_env_overrides(raw_data)
try:
_config = AppConfig(**raw_data)
except ValidationError as exc:
logger.error(f"Invalid configuration in {resolved_path}: {exc}")
raise
_apply_env_overrides(_config)
_config_path = resolved_path
return _config
def get_config() -> AppConfig:
"""Retrieve the currently loaded configuration, loading defaults if necessary."""
global _config
if _config is None:
_config = load_config()
return _config
def get_config_path() -> Path:
global _config_path
if _config_path is None:
_config_path = _resolve_config_path()
return _config_path
__all__ = [
"AppConfig",
"RenewIntentConfig",
"RenewIntentRedisConfig",
"AutomationConfig",
"IdlePauseConfig",
"IdlePauseRedisConfig",
"ServerConfig",
"LogConfig",
"RuntimeConfig",
"IngressConfig",
"GatewayConfig",
"GatewayRouteModeConfig",
"SecureAccessConfig",
"SecureAccessKey",
"INGRESS_MODE_DIRECT",
"INGRESS_MODE_GATEWAY",
"DockerConfig",
"StorageConfig",
"StoreConfig",
"PostgreSQLStoreConfig",
"KubernetesRuntimeConfig",
"EgressConfig",
"EgressUpstreamProxyConfig",
"EGRESS_MODE_DNS",
"EGRESS_MODE_DNS_NFT",
"SecureRuntimeConfig",
"DEFAULT_CONFIG_PATH",
"CONFIG_ENV_VAR",
"POSTGRESQL_DSN_ENV_VAR",
"get_config",
"get_config_path",
"load_config",
]