Skip to content

config_schema

config_schema

Pydantic schema for the sandbox-owned slice of the shared config.yml.

The ecosystem uses one ~/.config/terok/config.yml file shared across every package (Podman model — see terok_sandbox.paths for the prior decision around umbrella roots). Each package owns the schema for the sub-sections it consumes; higher-level packages compose the full file by importing from their dependencies.

This module is sandbox's contribution: the nine top-level sections sandbox actually reads (paths, credentials, vault, gate_server, services, shield, network, ssh, run), each strict on its own keys (extra="forbid"), wrapped in SandboxConfigView whose top level is tolerant (extra="allow") so unknown sections — those owned by terok-executor or terok — pass through silently when sandbox is run standalone.

Validation strategy:

  • Owned sub-sections are strict. A typo inside paths.rooot is rejected at load time with a clear pydantic error.
  • Unknown top-level sections are tolerated. Sandbox doesn't know about terok's tui: or executor's image:; rejecting them would make the standalone python -m terok_sandbox flow crash on any complete ecosystem config.

Higher-level packages inherit from SandboxConfigView and add their own sections. The topmost layer (terok) flips back to extra="forbid" because it knows every section in the v0 ecosystem.

GPU_VENDORS = ('nvidia', 'amd', 'intel') module-attribute

Recognised run.gpus vendor tokens, in canonical (emission) order.

ServicesMode = Literal['tcp', 'socket'] module-attribute

Type alias for the services.mode Literal; re-exported from RawServicesSection.model_fields['mode'] so downstream modules (sandbox's SandboxConfig, terok's make_sandbox_config) can annotate without re-declaring the shape.

ClearanceMode = Literal['prompt', 'mute', 'off'] module-attribute

Type alias for the services.clearance Literal — who is asked about a refusal.

Re-exported so downstream modules (sandbox's SandboxConfig and sidecar, terok's project schema and make_sandbox_config) annotate the knob without re-declaring its values. What each value does is documented on RawServicesSection.

SERVICES_TCP_OPTOUT_YAML = 'services: {mode: tcp}' module-attribute

User-facing opt-out snippet shown in SELinux hints — keep in one place so setup, sickbay, tests and docs stay in sync.

__all__ = ['SERVICES_TCP_OPTOUT_YAML', 'ClearanceMode', 'RawCredentialsSection', 'RawGateServerSection', 'RawNetworkSection', 'RawPathsSection', 'RawSSHSection', 'RawServicesSection', 'RawShieldSection', 'RawVaultSection', 'SandboxConfigView', 'ServicesMode', 'gate_use_personal_ssh_default'] module-attribute

GpuVendor = Literal['nvidia', 'amd', 'intel']

GpuGrant = tuple[GpuVendor, int | None]

One normalized selector token: a vendor and an optional device index.

("amd", None) grants every AMD device; ("amd", 1) grants the host's second AMD device (PCI-bus-address order — see terok_sandbox.runtime.gpu for the ordering contract per passthrough tier).

GpuSelector = tuple[GpuGrant, ...] | Literal['all'] | None

Normalized run.gpus value: explicit grants, auto-detect, or off.

The vocabulary lives here, next to the field it types; the host-probing and podman-arg side of the story is terok_sandbox.runtime.gpu.

RawCredentialsSection

Bases: BaseModel

The credentials: section — vault routing for proxy DB and agent mounts.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

dir = Field(default=None, description='Shared credentials directory (proxy DB, agent config mounts)') class-attribute instance-attribute

passphrase = Field(default=None, description="Rejected when set: sandbox reads no plaintext passphrase from config. The validator below refuses any value with migration directions; the field exists so the error names the replacement instead of pydantic's generic extra-key refusal.") class-attribute instance-attribute

use_desktop_keyring = Field(default=True, description="The desktop keyring tier of the passphrase resolution chain. On by default — an empty desktop keyring simply doesn't resolve; set ``false`` to keep the chain away from Secret Service entirely (its ACLs are per-collection, not per-item).") class-attribute instance-attribute

passphrase_command = Field(default=None, description='Operator-supplied shell command (e.g. ``pass show terok-sandbox/vault-passphrase``) that prints the SQLCipher passphrase on stdout. Tokenised with ``shlex.split``; resolver tier slots below the desktop keyring. Canonical headless option for hosts without systemd ≥ 257 — covers a plain secret file (``cat /path/to/file``), ``pass``, ``bw``, ``op``, HashiCorp ``vault``, and the cloud secret-manager CLIs (AWS, GCP, Azure).') class-attribute instance-attribute

RawPathsSection

Bases: BaseModel

The paths: section — umbrella state root and per-purpose overrides.

root is the namespace state root read by every ecosystem package (Podman model — see also terok_sandbox.paths.umbrella_state_dir).

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

root = Field(default=None, description='Namespace state root shared by all ecosystem packages (Podman model — one config, multiple readers)') class-attribute instance-attribute

build_dir = Field(default=None, description='Build artifacts directory (generated Dockerfiles)') class-attribute instance-attribute

sandbox_live_dir = Field(default=None, description='Container-writable runtime data (tasks, agent mounts). For hardened installs, mount the target with ``noexec,nosuid,nodev``') class-attribute instance-attribute

user_projects_dir = Field(default=None, description='User projects directory (per-user project configs)') class-attribute instance-attribute

user_presets_dir = Field(default=None, description='User presets directory (per-user preset configs)') class-attribute instance-attribute

port_registry_dir = Field(default=None, description='Shared port registry directory for multi-user isolation') class-attribute instance-attribute

RawShieldSection

Bases: BaseModel

The shield: section — egress firewall policy + audit + task lifecycle defaults.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

disable_firewall_no_protection = Field(default=False, description='**Dangerous**: disable egress firewall entirely') class-attribute instance-attribute

audit = Field(default=True, description='Enable shield audit logging') class-attribute instance-attribute

dnsmasq_path = Field(default=None, description='dnsmasq binary to run; found on the host PATH when unset') class-attribute instance-attribute

bypass_duration = Field(default=_DEFAULT_BYPASS_DURATION, description=f'How long the timed bypass window stays open when no duration is named: a non-zero count and one unit, such as ``30s``, ``5m`` or ``2h``. An unusable value warns and falls back to ``{_DEFAULT_BYPASS_DURATION}``') class-attribute instance-attribute

down_on_task_run = Field(default=True, description='Take the shield down when a task container is created') class-attribute instance-attribute

on_task_restart = Field(default='retain', description='Shield policy on container restart: ``retain`` or ``up``') class-attribute instance-attribute

RawServicesSection

Bases: BaseModel

The services: section — the per-container services and how a task reaches them.

mode picks the host ↔ container IPC transport. clearance picks who is asked about a connection the shield refused:

  • prompt (the default) — the operator, live. The container's supervisor runs the clearance hub, which turns each refusal into a desktop prompt (or a row in a clearance UI), and the verdict server that applies an operator's allow or deny.
  • mute — nobody, from the container's first moment. Both children still run, but the hub starts with the container muted, so not even the first refusal is put to anyone. The shield still refuses every blocked connection, and an operator can unmute the running task.
  • off — nobody, and nothing listening. The supervisor starts neither child: refusals stay enforced, no prompt is raised, and no verdict path exists that could widen the firewall. The task costs two fewer processes.

Under mute and off the audit log is the only record a refusal leaves: the shield records each refused target there while shield.audit is on (the default), repeats folded into one line per target for a short while. With audit off, a refusal nobody is asked about leaves no record at all.

A change applies at the next start of the task: create, recreate, or a terok restart. The value travels to the supervisor in the container's sidecar, which every start re-reads; creation writes it, and a restart rewrites that one field from current config before the start (Sandbox.clearance_refresh). A running task keeps the mode it started with, and a bare podman start replays whatever the sidecar last recorded.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

mode = Field(default='socket', description='Transport for host↔container IPC. Default ``socket``; set to ``tcp`` to opt out. See ``docs/selinux.md``') class-attribute instance-attribute

clearance = Field(default=_DEFAULT_CLEARANCE, description=f"Who is asked about a connection the shield refused. ``prompt``: the operator, live, through the clearance hub. ``mute``: nobody — the hub starts with the task muted; the shield still refuses every blocked connection, and the operator can unmute the running task. ``off``: no clearance hub or verdict server runs — refusals stay enforced, nobody is asked, and nothing can allow a destination from a prompt. Under ``mute`` and ``off`` the audit log is a refusal's only record, kept while ``shield.audit`` is on (the default); with audit off, nothing records it. A change applies at the next start of the task: create, recreate, or a terok restart. An unknown value warns and falls back to ``{_DEFAULT_CLEARANCE}``.") class-attribute instance-attribute

RawVaultSection

Bases: BaseModel

The vault: section — token broker and SSH signer ports.

The container-side transport was previously configured via vault.transport; since 0.7.4 it is derived from services.mode so the two knobs stay in lockstep (tcp listener ↔ direct routing, socket listener ↔ socket routing). Any prior vault.transport: line in config.yml must be removed.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

bypass_no_secret_protection = Field(default=False, description='**Dangerous**: mount real API keys and OAuth tokens in task containers instead of going through the vault') class-attribute instance-attribute

port = Field(default=None, ge=1, le=65535, description='Token broker listen port; allocated automatically when unset') class-attribute instance-attribute

ssh_signer_port = Field(default=None, ge=1, le=65535, description='SSH signer listen port; allocated automatically when unset') class-attribute instance-attribute

RawGateServerSection

Bases: BaseModel

The gate_server: section — host-side gate listen port + repo dir.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

port = Field(default=None, ge=1, le=65535, description='Gate server listen port') class-attribute instance-attribute

repos_dir = Field(default=None, description='Override gate repo directory (default: ``state_dir/gate``)') class-attribute instance-attribute

suppress_systemd_warning = Field(default=False, description='Suppress the systemd unit installation suggestion') class-attribute instance-attribute

RawNetworkSection

Bases: BaseModel

The network: section — port range for service / container ports.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

port_range_start = Field(default=18700, ge=1024, le=65535, description='First port of the range that service and container ports come from') class-attribute instance-attribute

port_range_end = Field(default=32700, ge=1024, le=65535, description='Last port of the range that service and container ports come from') class-attribute instance-attribute

RawSSHSection

Bases: BaseModel

The ssh: section — auth strategy for the host-side gate.

Default is None (not False) so model_dump(exclude_none=True) can distinguish unset from explicitly false. Higher layers may layer this with a project.yml ssh: section of the same shape; the None sentinel keeps the project layer from stomping the global value when the user omits it. The effective False default happens at the consumer end.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

use_personal = Field(default=None, description="Opt in to the user's ``~/.ssh`` keys for host-side ``gate-sync``. Default ``false`` — terok uses only its vault-managed key. Resolves through ConfigStack: ``terok-global config.yml`` → ``project.yml`` → CLI ``--use-personal-ssh`` (highest).") class-attribute instance-attribute

RawHooksSection

Bases: BaseModel

Task lifecycle hook commands.

Run on the host (not inside the container) around container lifecycle events. Sandbox owns them because the lifecycle events themselves are sandbox-mediated — the orchestrator just opts into being notified. The four hook points map to sandbox-internal transitions:

  • pre_start: before the container exists (host-side prep).
  • post_start: after the container is created but possibly not ready.
  • post_ready: after the readiness marker has been observed.
  • post_stop: after the container has stopped (cleanup hook).

Each value is a shell command string, run by the host shell with the orchestrator's environment. None means no hook.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

pre_start = Field(default=None, description='Host shell command to run before the container exists') class-attribute instance-attribute

post_start = Field(default=None, description='Host shell command to run after the container is created, maybe not ready') class-attribute instance-attribute

post_ready = Field(default=None, description='Host shell command to run after the container reports ready') class-attribute instance-attribute

post_stop = Field(default=None, description='Host shell command to run after the container has stopped') class-attribute instance-attribute

RawRunSection

Bases: BaseModel

The run: section — "how the container runs".

Covers OCI-runtime selection, container resource limits, capability toggles, environment, and lifecycle hooks. Sandbox owns this because every field translates to a podman/runtime flag or annotation sandbox emits at launch time.

Inheritable in both directions:

  • At the global level, defaults apply to every project (e.g. set runtime: krun once to opt the whole installation into microVM isolation).
  • At the project level, fields override the global default one-by-one via the orchestrator's merge logic.

model_config = ConfigDict(extra='forbid') class-attribute instance-attribute

shutdown_timeout = Field(default=10, description='Seconds to wait before SIGKILL on container stop') class-attribute instance-attribute

gpus = Field(default=None, description='GPU passthrough: ``"all"``/``true`` (every vendor detected on the host), a vendor name (``"nvidia"``, ``"amd"``, ``"intel"``), or a list of vendor names; omit to disable') class-attribute instance-attribute

memory = Field(default=None, description='Podman ``--memory`` value (e.g. ``"4g"``, ``"512m"``, ``"4gib"``, plain ``"1024"`` for bytes); ``None`` = unlimited. Format mirrors what podman accepts — see ``man podman-run(1)`` --memory.') class-attribute instance-attribute

cpus = Field(default=None, description='Podman ``--cpus`` value (e.g. ``"2.0"``, ``"0.5"``); ``None`` = unlimited. Non-negative decimal.') class-attribute instance-attribute

nested_containers = Field(default=False, description='Declares that the project runs podman/docker inside its container. When true, the outer container is launched with ``--security-opt label=nested`` and ``--device /dev/fuse`` so rootless nested containers work under SELinux without disabling labels wholesale.') class-attribute instance-attribute

perf = Field(default=False, description="Grant the container the ``perfmon`` capability and explicitly allow ``perf_event_open`` in its seccomp profile so ``perf`` can sample inside it. Rootless scope: the task samples its **own** processes, user-space only — and only if the host's ``kernel.perf_event_paranoid`` sysctl is ≤ 2 (hardened kernels ship 4, which disables unprivileged perf entirely).") class-attribute instance-attribute

aslr_control = Field(default=False, description='Allow processes to disable their own ASLR through narrowly filtered personality calls, for ThreadSanitizer and debugging. Extends the host Podman seccomp profile without changing other syscall rules. Weakens exploit mitigation; opt in only for development containers.') class-attribute instance-attribute

hosts_file = Field(default='none', description="Podman ``--hosts-file`` value, the base of the container's ``/etc/hosts``: ``none``, ``image``, or an absolute host path. Set ``/etc/hosts`` to copy the host's names into the container. Podman older than 5.4 has no such flag and always copies them.") class-attribute instance-attribute

podman_args = Field(default_factory=list, description='Freeform extra ``podman run`` flags, appended verbatim (expert escape hatch — you own the pieces). Sandbox-managed flags (``--network``, ``--cap-add``, …), mounts shadowing sandbox targets, and isolation-weakening flags (``--privileged``, ``--security-opt``) are rejected at parse time.') class-attribute instance-attribute

runtime = Field(default=None, description="OCI runtime override: ``crun`` for conventional containers, or ``krun`` for KVM-microVM isolation (experimental). ``None`` inherits Podman's configured default. Explicit ``krun`` requires the global ``experimental: true`` flag at task launch.") class-attribute instance-attribute

timezone = Field(default=None, description="IANA timezone for the task container (e.g. ``Europe/Prague``, ``UTC``). Propagated as ``TZ`` — resolved against the image's ``tzdata``. Unset (default) means follow the host's timezone.") class-attribute instance-attribute

hooks = Field(default_factory=RawHooksSection) class-attribute instance-attribute

SandboxConfigView

Bases: BaseModel

The slice of config.yml sandbox owns and validates.

extra="allow" at the top level so unknown sections (executor's image:, terok's tui: / logs: / tasks: / git: / hooks:) pass through silently when sandbox is run standalone — the ecosystem's shared config file is expected to contain every package's keys, and rejecting them would make python -m terok_sandbox crash on any complete config.

Higher layers compose by inheriting from this class and adding their own typed fields:

  • terok_executor.config_schema.ExecutorConfigView inherits and adds the image: section.
  • terok's RawGlobalConfig inherits and adds the terok-owned sections, then flips to extra="forbid" — the topmost layer knows every section, so a typo at the top level is caught there.

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

credentials = Field(default_factory=RawCredentialsSection) class-attribute instance-attribute

paths = Field(default_factory=RawPathsSection) class-attribute instance-attribute

shield = Field(default_factory=RawShieldSection) class-attribute instance-attribute

services = Field(default_factory=RawServicesSection) class-attribute instance-attribute

vault = Field(default_factory=RawVaultSection) class-attribute instance-attribute

gate_server = Field(default_factory=RawGateServerSection) class-attribute instance-attribute

network = Field(default_factory=RawNetworkSection) class-attribute instance-attribute

ssh = Field(default_factory=RawSSHSection) class-attribute instance-attribute

run = Field(default_factory=RawRunSection) class-attribute instance-attribute

experimental = Field(default=False, description="Cross-package opt-in for experimental features. Gates terok's krun runtime and sandbox's krun-only host-binary prereq probes (``ip``). Lives on the top level rather than in any one section because it's shared between sandbox, executor, and terok — the topmost layer (terok) inherits this declaration.") class-attribute instance-attribute

normalize_gpus(value)

Normalize a raw run.gpus value into a GpuSelector.

Accepts the shapes a YAML config or CLI flag produces: booleans, a single token ("all", "nvidia", "nvidia:0", …), a comma-separated token string, or a list of tokens. A :N suffix grants one device of that vendor instead of all of them; repeat the vendor to grant several ("nvidia:0,nvidia:1"). A whole-vendor token absorbs that vendor's indexed ones. Raises ValueError on an unknown vendor or malformed index so misconfiguration surfaces at parse time, not at launch.

Source code in src/terok_sandbox/config_schema.py
def normalize_gpus(value: bool | str | Sequence[str] | None) -> GpuSelector:
    """Normalize a raw ``run.gpus`` value into a [`GpuSelector`][terok_sandbox.config_schema.GpuSelector].

    Accepts the shapes a YAML config or CLI flag produces: booleans,
    a single token (``"all"``, ``"nvidia"``, ``"nvidia:0"``, …), a
    comma-separated token string, or a list of tokens.  A ``:N`` suffix
    grants one device of that vendor instead of all of them; repeat the
    vendor to grant several (``"nvidia:0,nvidia:1"``).  A whole-vendor
    token absorbs that vendor's indexed ones.  Raises ``ValueError`` on
    an unknown vendor or malformed index so misconfiguration surfaces
    at parse time, not at launch.
    """
    if value is None or value is False:
        return None
    if value is True:
        return "all"
    parts = [value] if isinstance(value, str) else list(value)
    tokens = [tok for part in parts for raw in part.split(",") if (tok := raw.strip().lower())]
    if not tokens:
        return None
    # dict.fromkeys deduplicates while keeping first-seen order; the
    # grants themselves are the (vendor, index) tuple keys.
    grants = list(dict.fromkeys(_parse_gpu_token(tok) for tok in tokens if tok != "all"))
    if "all" in tokens:
        return "all"
    whole_vendors = {vendor for vendor, index in grants if index is None}
    return tuple(
        (vendor, index)
        for vendor, index in sorted(
            grants, key=lambda g: (GPU_VENDORS.index(g[0]), g[1] if g[1] is not None else -1)
        )
        if index is None or vendor not in whole_vendors
    )

gate_use_personal_ssh_default()

Resolve the host gate's ssh.use_personal global default.

Reads the ssh: section from the shared config.yml, validates via RawSSHSection, and returns the bool. An unset section, a missing key, or a malformed value collapses to False — the safe historical default ("terok never touches your real keys").

Higher layers compose this with project-level and per-invocation overrides; the resolution chain ends up:

CLI ``--use-personal-ssh``     (highest)
project ``project.yml`` ssh
global ``config.yml`` ssh      ← THIS function
False                          (default)

Lives in sandbox because the consumer (_git_env_with_ssh) is here too — same package owns the schema and the reader.

Source code in src/terok_sandbox/config_schema.py
def gate_use_personal_ssh_default() -> bool:
    """Resolve the host gate's ``ssh.use_personal`` global default.

    Reads the ``ssh:`` section from the shared ``config.yml``, validates
    via [`RawSSHSection`][terok_sandbox.config_schema.RawSSHSection], and returns the bool.  An unset section,
    a missing key, or a malformed value collapses to ``False`` — the
    safe historical default ("terok never touches your real keys").

    Higher layers compose this with project-level and per-invocation
    overrides; the resolution chain ends up:

        CLI ``--use-personal-ssh``     (highest)
        project ``project.yml`` ssh
        global ``config.yml`` ssh      ← THIS function
        False                          (default)

    Lives in sandbox because the consumer
    (`_git_env_with_ssh`) is here too —
    same package owns the schema and the reader.
    """
    from .paths import read_config_section

    raw = read_config_section("ssh")
    if not raw:
        return False
    try:
        section = RawSSHSection.model_validate(raw)
    except Exception:  # noqa: BLE001 - malformed config falls back to safe default
        return False
    return bool(section.use_personal)