Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

19.6 KB
Raw Blame
#!/usr/bin/env python3
"""Network exposure contract checks for bundled services."""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
SERVICES = ROOT / "extensions" / "services"
POLICY = ROOT / "config" / "network-exposure-policy.json"


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace")


def manifest_value(text: str, key: str) -> str | None:
    match = re.search(rf"(?m)^\s+{re.escape(key)}:\s*(.+?)\s*$", text)
    return match.group(1).strip() if match else None


def manifest_bool(text: str, key: str) -> bool:
    value = manifest_value(text, key)
    return bool(value and value.lower() == "true")


def caddy_block_body(text: str, opener: str) -> str:
    """Return the body of the Caddy block whose opening line equals `opener`.

    `opener` is the literal site line ending in the block's opening brace, e.g.
    ``http://chat.{$ODS_DEVICE_NAME:ods}.local {``. Depth counting starts at that
    brace; inline placeholders like ``{scheme}`` or ``{$ENV}`` are brace-balanced,
    so they net to zero and do not disturb the match. This keeps assertions scoped
    to the intended host block rather than the file as a whole.
    """
    idx = text.index(opener)
    brace = idx + len(opener) - 1  # opener ends with the block's opening "{"
    depth = 0
    for i in range(brace, len(text)):
        if text[i] == "{":
            depth += 1
        elif text[i] == "}":
            depth -= 1
            if depth == 0:
                return text[brace + 1 : i]
    raise AssertionError(f"unbalanced braces after Caddy block opener {opener!r}")


def exposed_service_ids() -> set[str]:
    exposed: set[str] = set()
    for manifest in SERVICES.glob("*/manifest.yaml"):
        text = read(manifest)
        service_id = manifest_value(text, "id") or manifest.parent.name
        has_external_port = manifest_value(text, "external_port_default") is not None
        if has_external_port or manifest_bool(text, "host_network"):
            exposed.add(service_id)
    return exposed


def assert_true(condition: bool, message: str) -> None:
    if not condition:
        raise AssertionError(message)


def test_exposed_services_are_policy_labeled() -> None:
    policy = json.loads(read(POLICY))
    policy_services = set(policy["services"])
    exposed = exposed_service_ids()
    assert_true(exposed <= policy_services, f"missing exposure policy entries: {sorted(exposed - policy_services)}")
    assert_true(policy_services <= exposed, f"stale exposure policy entries: {sorted(policy_services - exposed)}")
    for service_id, entry in policy["services"].items():
        assert_true(entry.get("risk"), f"{service_id} missing risk label")
        assert_true(entry.get("lan_exposure"), f"{service_id} missing lan_exposure label")
        assert_true(isinstance(entry.get("auth_required"), bool), f"{service_id} auth_required must be boolean")
        assert_true(entry.get("notes"), f"{service_id} missing notes")


def test_hermes_is_internal_only_with_optional_proxy_gate() -> None:
    hermes_compose = read(SERVICES / "hermes" / "compose.yaml")
    hermes_manifest = read(SERVICES / "hermes" / "manifest.yaml")
    proxy_caddyfile = read(SERVICES / "hermes-proxy" / "Caddyfile")
    policy = json.loads(read(POLICY))["services"]

    assert_true(not re.search(r"(?m)^\s{4}ports:\s*$", hermes_compose), "hermes compose must not bind host ports")
    assert_true(re.search(r"(?m)^\s{4}expose:\s*$", hermes_compose) is not None, "hermes compose should expose only internally")
    assert_true(manifest_value(hermes_manifest, "external_port_default") == "0", "hermes manifest external port must be 0")
    assert_true(policy["hermes"]["lan_exposure"] == "none", "hermes policy must mark no LAN exposure")
    assert_true("@owner_card_required expression {$HERMES_REQUIRE_OWNER_CARD:false}" in proxy_caddyfile, "Hermes owner-card gate must default off")
    assert_true("route @owner_card_required" in proxy_caddyfile, "session verification must be conditional")
    assert_true(policy["hermes-proxy"]["auth_required"] is False, "default proxy policy must reflect direct access")
    assert_true("forward_auth" in proxy_caddyfile, "opt-in Hermes gate must retain forward_auth")
    assert_true("/api/auth/verify-session" in proxy_caddyfile, "hermes-proxy must call dashboard auth verification")
    assert_true("reverse_proxy {$HERMES_PROXY_UPSTREAM:ods-hermes:9119}" in proxy_caddyfile, "hermes-proxy must forward to internal Hermes")
    lan = caddy_block_body(read(SERVICES / "ods-proxy" / "Caddyfile"), "http://hermes.{$ODS_DEVICE_NAME:ods}.local {")
    assert_true("forward_auth dashboard-api:3002" in lan and "/api/auth/verify-session" in lan,
                "Hermes LAN entrypoint must authenticate even when local gating is disabled")
    assert_true("HERMES_REQUIRE_OWNER_CARD" not in lan, "LAN authentication must not be optional")


def test_pixel_edge_is_internal_only_and_token_gated() -> None:
    compose = read(SERVICES / "pixel-edge" / "compose.yaml.disabled")
    manifest = read(SERVICES / "pixel-edge" / "manifest.yaml")
    policy = json.loads(read(POLICY))["services"]["pixel-edge"]

    assert_true(not re.search(r"(?m)^\s{4}ports:\s*$", compose), "pixel-edge must not bind a host port")
    assert_true(manifest_value(manifest, "external_port_default") == "0", "pixel-edge external port must be 0")
    assert_true("PIXEL_OPENWEBUI_KEY=${PIXEL_OPENWEBUI_KEY:?" in compose, "pixel-edge must require scoped bearer auth")
    assert_true(policy["lan_exposure"] == "none", "pixel-edge policy must mark no LAN exposure")
    assert_true(policy["auth_required"] is True, "pixel-edge policy must require auth")


def test_model_router_is_internal_only() -> None:
    base_compose = read(ROOT / "docker-compose.base.yml")
    manifest = read(SERVICES / "model-router" / "manifest.yaml")
    policy = json.loads(read(POLICY))["services"]["model-router"]
    service_block = re.search(
        r"(?ms)^  model-router:\s*\n(?P<body>.*?)(?=^  [A-Za-z0-9_.-]+:\s*\n|\Z)",
        base_compose,
    )

    assert_true(service_block is not None, "model-router compose service must exist")
    assert_true(
        "\n    ports:" not in f"\n{service_block.group('body')}",
        "model-router must not bind a host port",
    )
    assert_true(
        manifest_value(manifest, "external_port_default") == "0",
        "model-router external port must be 0",
    )
    assert_true(
        manifest_value(manifest, "health_source") == "container",
        "model-router health must come from its Docker healthcheck",
    )
    assert_true(policy["lan_exposure"] == "none", "model-router policy must mark no LAN exposure")


def test_hermes_whatsapp_bridge_avoids_open_webui_port() -> None:
    hermes_compose = read(SERVICES / "hermes" / "compose.yaml")
    hermes_config = read(SERVICES / "hermes" / "cli-config.yaml.template")

    assert_true("whatsapp:" in hermes_config, "Hermes config should pre-seed WhatsApp settings")
    assert_true("enabled: false" in hermes_config, "WhatsApp must remain disabled by default")
    assert_true(
        re.search(r"(?m)^\s+bridge_port:\s*3010\s*$", hermes_config) is not None,
        "WhatsApp bridge must default away from Open WebUI port 3000",
    )
    assert_true(
        re.search(r"(?m)^\s+bridge_port:\s*3000\s*$", hermes_config) is None,
        "WhatsApp bridge must not use upstream's port 3000 default",
    )
    assert_true(
        re.search(r"(?m)^\s+-\s+WHATSAPP_ENABLED\s*$", hermes_compose) is not None,
        "Hermes compose should pass intentional WhatsApp enables without blank defaults",
    )
    assert_true("3010:3010" not in hermes_compose, "WhatsApp bridge must not be host-bound")


def test_hermes_local_provider_has_generous_timeouts() -> None:
    base_compose = read(ROOT / "docker-compose.base.yml")
    hermes_compose = read(SERVICES / "hermes" / "compose.yaml")
    hermes_config = read(SERVICES / "hermes" / "cli-config.yaml.template")

    assert_true("providers:" in hermes_config, "Hermes config should declare provider overrides")
    assert_true(
        re.search(
            r"(?ms)^providers:\s*\n\s+custom:\s*\n(?:\s{4}.+\n)*?\s{4}request_timeout_seconds:\s*180\s*$",
            hermes_config,
        )
        is not None,
        "Hermes custom provider must allow slow local-model first-token latency",
    )
    assert_true(
        re.search(r"(?m)^\s+-\s+HERMES_STREAM_STALE_TIMEOUT=900\s*$", hermes_compose) is not None,
        "Hermes streaming paths must allow slow local-model first-token latency",
    )
    assert_true(
        "ODS_TALK_HERMES_TIMEOUT=${ODS_TALK_HERMES_TIMEOUT:-900}" in base_compose,
        "dashboard-api must give ODS Talk the same long local-model timeout on the base stack",
    )


def test_ods_proxy_routes_talk_portal() -> None:
    caddyfile = read(SERVICES / "ods-proxy" / "Caddyfile")

    assert_true("talk.{$ODS_DEVICE_NAME:ods}.local" in caddyfile, "ods-proxy must route talk.<device>.local")
    for host in ("talk", "dashboard"):
        body = caddy_block_body(caddyfile, "http://%s.{$ODS_DEVICE_NAME:ods}.local {" % host)
        assert_true(
            "reverse_proxy dashboard:3011" in body and "dashboard:3001" not in body,
            f"ods-proxy must send {host}.<device>.local to the dashboard's sign-in-required network listener",
        )


def test_dashboard_admin_api_requires_sign_in_off_the_machine() -> None:
    nginx_conf = read(SERVICES / "dashboard" / "nginx.conf")
    entrypoint = read(SERVICES / "dashboard" / "entrypoint.sh")
    compose = read(ROOT / "docker-compose.base.yml")
    summary = read(ROOT / "installers" / "phases" / "13-summary.sh")

    blocks = re.findall(r"(?ms)^    location [^\n]*\{\n.*?^    \}", nginx_conf)
    keyed = [block for block in blocks if 'Authorization "Bearer ${DASHBOARD_API_KEY}"' in block]
    assert_true(len(keyed) >= 8, "expected the dashboard's API-key locations")
    for block in keyed:
        assert_true(
            "auth_request /_ods_dashboard_gate;" in block,
            "every location that adds the dashboard API key must pass the sign-in gate: " + block.splitlines()[0],
        )
    enable = next(block for block in blocks if block.startswith(
        "    location ~ ^/api/extensions/[a-z0-9_-]+/enable$"))
    assert_true(
        "proxy_read_timeout 720s;" in enable and "proxy_send_timeout 720s;" in enable,
        "cold Library enables must outlast the host agent's 660-second request budget",
    )
    webui = next(block for block in blocks if block.startswith("    location = /api/webui/selection "))
    assert_true(
        "auth_request /_ods_dashboard_gate;" in webui
        and "proxy_read_timeout 960s;" in webui and "proxy_send_timeout 960s;" in webui,
        "adding Open WebUI must pass the sign-in gate and outlast the Dashboard API's 900-second host request",
    )
    talk = next(block for block in blocks if block.startswith("    location ^~ /api/talk/"))
    assert_true("DASHBOARD_API_KEY" not in talk, "ODS Talk must not receive the dashboard admin key")
    assert_true(
        "listen 3011;" in nginx_conf and '"__ODS_LOCAL_LISTENER__:1:0" 1;' in nginx_conf,
        "only the loopback-published listener may skip sign-in, and only for loopback hosts without forwarding",
    )
    assert_true(
        "- ODS_DASHBOARD_BIND=127.0.0.1" in compose
        and '"127.0.0.1:${DASHBOARD_PORT:-3001}:3001"' in compose
        and '"${BIND_ADDRESS:-127.0.0.1}:${DASHBOARD_REMOTE_PORT:-3011}:3011"' in compose,
        "the unauthenticated dashboard listener must be host-loopback only; the network listener needs sign-in",
    )
    assert_true(
        "LOCAL_LISTENER=off" in entrypoint and 's|__ODS_LOCAL_LISTENER__|${LOCAL_LISTENER}|g' in entrypoint,
        "an unknown dashboard bind must disable the local no-sign-in listener",
    )
    assert_true(
        'http://${LOCAL_IP}:${DASHBOARD_REMOTE_PORT}' in summary,
        "the installer must show the signed-in network port, not the loopback dashboard port",
    )


def test_dashboard_csp_allows_ods_talk_tts_blob_audio() -> None:
    nginx_conf = read(SERVICES / "dashboard" / "nginx.conf")

    assert_true("Content-Security-Policy" in nginx_conf, "dashboard must keep a CSP header")
    assert_true("media-src 'self' blob:" in nginx_conf, "ODS Talk TTS playback uses blob: audio URLs")


def test_dashboard_csp_allows_only_verified_pixel_preview_routes() -> None:
    nginx_conf = read(SERVICES / "dashboard" / "nginx.conf")
    connect = re.search(r"connect-src ([^;]+);", nginx_conf)
    assert_true(
        connect is not None
        and connect.group(1).split() == ["'self'", "http://*.localhost:__PIXEL_PREVIEW_PORT__"],
        "preview identity probes may reach only the configured isolated preview port, not arbitrary hosts or ports",
    )
    entrypoint = read(SERVICES / "dashboard" / "entrypoint.sh")
    dockerfile = read(SERVICES / "dashboard" / "Dockerfile")
    compose = read(ROOT / "docker-compose.base.yml")

    assert_true(
        "frame-src 'self' http://localhost:__PIXEL_PREVIEW_PORT__ "
        "http://127.0.0.1:__PIXEL_PREVIEW_PORT__ "
        "http://*.localhost:__PIXEL_PREVIEW_PORT__;" in nginx_conf,
        "dashboard CSP must permit same-route remote previews and per-artifact loopback origins",
    )
    assert_true(
        "location ^~ /pixel-preview/" in nginx_conf
        and "rewrite ^/pixel-preview/(.*)$ /preview/$1 break;" in nginx_conf
        and 'proxy_set_header Authorization "Bearer ${DASHBOARD_API_KEY}";' in nginx_conf,
        "remote Pixel previews must use the authenticated internal edge route",
    )
    assert_true(
        "PIXEL_PREVIEW_PORT=${PIXEL_PREVIEW_PORT:-9437}" in compose,
        "dashboard container must receive the configured Pixel preview port",
    )
    assert_true(
        "*[!0-9]*" in entrypoint and '"$PREVIEW_PORT" -gt 65535' in entrypoint,
        "dashboard must reject a non-numeric or out-of-range preview port",
    )
    assert_true(
        's|__PIXEL_PREVIEW_PORT__|${PREVIEW_PORT}|g' in entrypoint,
        "dashboard must substitute only the validated preview port into its CSP",
    )
    assert_true(
        "COPY nginx.conf /etc/nginx/conf.d/default.conf.template" in dockerfile,
        "dashboard image must retain an immutable nginx template for restarts",
    )
    assert_true(
        "pid /tmp/nginx.pid" in dockerfile,
        "non-root dashboard nginx must keep its restartable PID file in a writable directory",
    )
    assert_true(
        'grep -qF \'__PIXEL_PREVIEW_PORT__\' "$NGINX_TEMPLATE"' in entrypoint
        and 'cp "$NGINX_TEMPLATE" "$NGINX_CONF"' in entrypoint,
        "dashboard must render its active nginx config from the template on every start",
    )
    assert_true(
        "^[A-Za-z0-9._~+/=-]+$" in entrypoint,
        "dashboard must reject API keys containing sed or nginx control characters",
    )


def test_dashboard_csp_allows_huggingface_author_avatars_only_as_images() -> None:
    nginx_conf = read(SERVICES / "dashboard" / "nginx.conf")

    assert_true(
        "img-src 'self' data: https://huggingface.co https://cdn-avatars.huggingface.co;" in nginx_conf,
        "the Models library renders Hugging Face author avatars",
    )
    assert_true(
        "connect-src 'self' http://*.localhost:__PIXEL_PREVIEW_PORT__;" in nginx_conf,
        "Hub API access must remain server-side instead of exposing HF_TOKEN to the browser",
    )


def test_ods_proxy_caps_request_body_sizes() -> None:
    caddyfile = read(SERVICES / "ods-proxy" / "Caddyfile")

    chat_block = caddy_block_body(caddyfile, "http://chat.{$ODS_DEVICE_NAME:ods}.local {")
    assert_true(
        re.search(r"request_body\s*\{\s*max_size\s+200MB\s*\}", chat_block) is not None,
        "ods-proxy chat host must cap request body at 200MB (Open WebUI document uploads)",
    )

    api_block = caddy_block_body(caddyfile, "http://api.{$ODS_DEVICE_NAME:ods}.local {")
    assert_true(
        re.search(r"request_body\s*\{\s*max_size\s+50MB\s*\}", api_block) is not None,
        "ods-proxy api host must cap request body at 50MB (admin surface)",
    )


def test_hermes_proxy_caps_request_body() -> None:
    caddyfile = read(SERVICES / "hermes-proxy" / "Caddyfile")

    site_block = caddy_block_body(caddyfile, ":9120 {")
    assert_true(
        re.search(r"request_body\s*\{\s*max_size\s+50MB\s*\}", site_block) is not None,
        "hermes-proxy must cap request body at 50MB (agent prompt attachments)",
    )


def test_dashboard_pre_stages_hsts() -> None:
    nginx_conf = read(SERVICES / "dashboard" / "nginx.conf")

    # HSTS is pre-staged so it activates once TLS lands via Caddy/Tailscale.
    # Browsers ignore the header over plain HTTP, so it is inert until then.
    assert_true(
        re.search(
            r'add_header\s+Strict-Transport-Security\s+"max-age=\d+;[^"]*includeSubDomains',
            nginx_conf,
        )
        is not None,
        "dashboard nginx must pre-stage a Strict-Transport-Security header with includeSubDomains",
    )


def test_legacy_openclaw_extension_stays_removed() -> None:
    """The removed legacy OpenClaw container must not come back.

    Pixel's host OpenClaw runtime is separate and is not covered here.
    """
    assert_true(not (SERVICES / "openclaw").exists(), "legacy OpenClaw extension must stay removed")
    policy = json.loads(read(POLICY))["services"]
    assert_true("openclaw" not in policy, "removed legacy OpenClaw extension must not keep an exposure policy")
    ports = json.loads(read(ROOT / "config" / "ports.json"))["ports"]
    assert_true(
        all(entry.get("service_id") != "openclaw" for entry in ports),
        "removed legacy OpenClaw extension must not keep a port contract",
    )
    compose_files = [*sorted(ROOT.glob("docker-compose*.yml")), *sorted(SERVICES.glob("*/compose*.yaml"))]
    for compose_path in compose_files:
        assert_true(
            "ghcr.io/openclaw/openclaw" not in read(compose_path),
            f"{compose_path.relative_to(ROOT)} must not run the legacy OpenClaw image",
        )


def test_litellm_gateway_auth_is_enforced() -> None:
    compose = read(SERVICES / "litellm" / "compose.yaml")
    host_native_compose = read(ROOT / "docker-compose.host-native-llm.yml")
    policy = json.loads(read(POLICY))["services"]["litellm"]

    assert_true("LITELLM_MASTER_KEY=${LITELLM_KEY:-}" in compose, "LiteLLM must keep master-key auth")
    # A host-native llama-server is reachable only through LiteLLM, so Open
    # WebUI presents the gateway key there.
    assert_true(
        'OPENAI_API_KEY: "${LITELLM_KEY}"' in host_native_compose,
        "host-native Open WebUI must present LITELLM_KEY",
    )
    assert_true(policy["auth_required"] is True, "LiteLLM policy must require auth")


def main() -> int:
    tests = [
        test_exposed_services_are_policy_labeled,
        test_hermes_is_internal_only_with_optional_proxy_gate,
        test_pixel_edge_is_internal_only_and_token_gated,
        test_model_router_is_internal_only,
        test_hermes_whatsapp_bridge_avoids_open_webui_port,
        test_hermes_local_provider_has_generous_timeouts,
        test_ods_proxy_routes_talk_portal,
        test_dashboard_admin_api_requires_sign_in_off_the_machine,
        test_dashboard_csp_allows_ods_talk_tts_blob_audio,
        test_dashboard_csp_allows_only_verified_pixel_preview_routes,
        test_ods_proxy_caps_request_body_sizes,
        test_hermes_proxy_caps_request_body,
        test_dashboard_pre_stages_hsts,
        test_legacy_openclaw_extension_stays_removed,
        test_litellm_gateway_auth_is_enforced,
    ]
    for test in tests:
        test()
        print(f"[PASS] {test.__name__}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except AssertionError as exc:
        print(f"[FAIL] {exc}", file=sys.stderr)
        raise SystemExit(1)