diff --git a/Dockerfile.worker b/Dockerfile.worker index b4ebae13..f6c41d23 100644 --- a/Dockerfile.worker +++ b/Dockerfile.worker @@ -82,6 +82,8 @@ COPY app/worker_api.py ./app/ COPY app/miner_read.py ./app/ COPY app/orchestrator.py ./app/ COPY app/isolation_check.py ./app/ +# The security layers this worker can give an earner (system_info.layers, runtime_choice). +COPY app/layers.py ./app/ COPY app/socket_policy.py ./app/ # The one-shot cashpilot-migrate service of the compose files runs it. COPY app/owner_migrate.py ./app/ diff --git a/app/layers.py b/app/layers.py new file mode 100644 index 00000000..d5651c21 --- /dev/null +++ b/app/layers.py @@ -0,0 +1,234 @@ +"""The security layers this worker can give an earner, and the runtime each one gets. + +The owner picks, per worker and per earner, whether an earner runs under +Docker's own runtime (runc) or under gVisor. The UI stores the choice and sends +it with the deploy as ``runtime_choice``. This module is the worker's side: + +* ``report()`` says what this host has, for the heartbeat: the runtimes Docker + registered and which of them are gVisor, whether the host has KVM, and which + runtime an environment variable pins. Every value that could not be read is + None, never False or an empty list: an older or blind worker must read as + "unknown", not as "absent". +* ``pick()`` turns the owner's choice into the runtime Docker gets, from what + the daemon registered. A gVisor choice needs a runtime registered with + ``--network=host``, or Docker's DNS fails on our own bridge (gVisor issue + 7469), and an earner that declares NET_RAW (Bitping) needs one with + ``--net-raw`` as well (docs/home-network-security.md, section 7). + +Nothing here picks gVisor by itself. No choice means Docker's default, as before. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import platform +import threading +import time +from pathlib import Path +from typing import Any + +import docker + +from app import gpu + +logger = logging.getLogger(__name__) + +RUNC = "runc" +GVISOR = "gvisor" +CHOICES = (RUNC, GVISOR) + +#: The heartbeat feature that says this worker takes ``runtime_choice`` and +#: reports ``system_info.layers``. +FEATURE = "runtime_choice" + +#: Seconds report() keeps Docker's /info. The heartbeat runs every minute; a +#: gVisor install reloads Docker, and the self-test refreshes this at once. +INFO_TTL = 120.0 +_info: tuple[float, dict[str, Any]] | None = None +_info_lock = threading.Lock() + +#: The last gVisor self-test this worker ran (app/gvisor_check.py), for the heartbeat. +_last_check: dict[str, Any] | None = None + + +class ChoiceRefused(Exception): + """The owner's runtime choice cannot be honoured on this worker. Nothing was touched.""" + + +def _args(spec: dict[str, Any]) -> list[str]: + raw = spec.get("runtimeArgs") or spec.get("args") or [] + return [str(a) for a in raw] if isinstance(raw, list) else [] + + +def _has_flag(args: list[str], flag: str, value: str | None = None) -> bool: + """``--network=host`` and ``--network host`` alike; a bare ``--net-raw`` or ``--net-raw=true``.""" + for i, arg in enumerate(args): + name, sep, val = arg.partition("=") + if name != flag: + continue + if value is None: + return not sep or val.lower() in ("true", "1") + if sep: + return val == value + return i + 1 < len(args) and args[i + 1] == value + return False + + +def runtime_facts(runtimes: Any) -> list[dict[str, Any]]: + """One entry per runtime Docker registered: its name and whether it is gVisor. + + A runtime is gVisor when its binary is runsc. ``hostnet`` is the + ``--network=host`` passthrough Docker's DNS needs on our bridge, and + ``net_raw`` the ``--net-raw`` flag that gives raw sockets back. + """ + if not isinstance(runtimes, dict): + return [] + facts = [] + for name in sorted(runtimes): + spec = runtimes[name] if isinstance(runtimes[name], dict) else {} + path = str(spec.get("path") or "") + args = _args(spec) + gvisor = Path(path).name.startswith("runsc") if path else str(name).startswith("runsc") + facts.append( + { + "name": str(name), + "gvisor": gvisor, + "hostnet": gvisor and _has_flag(args, "--network", "host"), + "net_raw": gvisor and _has_flag(args, "--net-raw"), + } + ) + return facts + + +def kind(runtime: str, facts: list[dict[str, Any]] | None) -> str: + """``gvisor`` or ``runc`` for a runtime name, judged from what the daemon registered.""" + for fact in facts or []: + if fact["name"] == runtime: + return GVISOR if fact["gvisor"] else RUNC + return GVISOR if runtime.startswith("runsc") else RUNC + + +def kvm(sysfs: Path = Path("/sys"), docker_host: str | None = None) -> bool | None: + """Whether the machine Docker runs on has KVM, for the Secure VM layer. + + Read from sysfs, which shows the host's devices from inside a container + with nothing passed in: /dev/kvm exists exactly when the kvm module made + /sys/class/misc/kvm. None when this cannot say anything about that machine: + not Linux, a Docker endpoint on another machine, or sysfs unreadable. + """ + if platform.system() != "Linux": + return None + if not gpu.local_endpoint(os.environ.get("DOCKER_HOST", "") if docker_host is None else docker_host): + return None + misc = sysfs / "class" / "misc" + try: + if not misc.is_dir(): + return None + return (misc / "kvm").exists() + except OSError: + return None + + +def _read_info() -> dict[str, Any] | None: + client = None + try: + client = docker.from_env(timeout=5) + info = client.info() + except Exception as exc: # noqa: BLE001 - unknown is an answer here + logger.debug("Could not read Docker's runtimes: %s", exc) + return None + finally: + if client is not None: + with contextlib.suppress(Exception): + client.close() + return info if isinstance(info, dict) else None + + +def docker_info(fresh: bool = False) -> dict[str, Any] | None: + """Docker's /info, cached for INFO_TTL. None when the daemon cannot be asked.""" + global _info + now = time.monotonic() + with _info_lock: + if not fresh and _info is not None and now - _info[0] < INFO_TTL: + return _info[1] + info = _read_info() + if info is not None: + with _info_lock: + _info = (now, info) + return info + + +def _facts_of(info: dict[str, Any] | None) -> list[dict[str, Any]] | None: + """The runtimes in Docker's /info, or None when /info has no readable runtime list.""" + if info is None or not isinstance(info.get("Runtimes"), dict): + return None + return runtime_facts(info["Runtimes"]) + + +def daemon_runtimes(fresh: bool = False) -> list[dict[str, Any]] | None: + return _facts_of(docker_info(fresh=fresh)) + + +def pick( + choice: str, + slug: str, + facts: list[dict[str, Any]] | None, + *, + net_raw: bool, + allowed: tuple[str, ...] | None, + service: str, +) -> str: + """The runtime Docker gets for the owner's choice, or ChoiceRefused with the reason. + + ``allowed`` is the socket proxy's runtime list when the worker is behind it + (the proxy refuses any other name), None when it is not. + """ + if choice == RUNC: + return RUNC + if choice != GVISOR: + raise ChoiceRefused(f"{choice!r} is not a runtime choice; use one of {', '.join(CHOICES)}.") + if facts is None: + raise ChoiceRefused("Cannot check for gVisor: the Docker daemon is not answering.") + usable = [f for f in facts if f["gvisor"] and f["hostnet"] and (allowed is None or f["name"] in allowed)] + if net_raw: + usable = [f for f in usable if f["net_raw"]] + else: + # A runtime without --net-raw first: an earner that never asked for raw + # sockets does not get them back. + usable.sort(key=lambda f: f["net_raw"]) + if usable: + return usable[0]["name"] + if net_raw: + raise ChoiceRefused( + f"{service} needs raw sockets, and this worker has no gVisor runtime registered with --network=host " + f"and --net-raw (runsc-hostnet-raw). Run the gVisor install command from the Fleet page, " + f"or keep {service} on Standard." + ) + raise ChoiceRefused( + f"This worker has no gVisor runtime registered with --network=host (runsc-hostnet), which Docker's DNS " + f"needs on CashPilot's network. Run the gVisor install command from the Fleet page, or keep {service} " + f"on Standard." + ) + + +def set_last_check(result: dict[str, Any]) -> None: + global _last_check + _last_check = dict(result) + + +def report(pins: dict[str, Any], proxy_runtimes: tuple[str, ...] | None) -> dict[str, Any]: + """``system_info.layers`` for the heartbeat. Reads Docker's cached /info and sysfs; runs no container.""" + info = docker_info() + return { + "runtimes": _facts_of(info), + "default_runtime": (str(info.get("DefaultRuntime") or "") or None) if info is not None else None, + "kvm": kvm(), + # What an environment variable pins on this worker. The UI shows the + # choice locked where one does: the variable wins over the UI. + "pins": pins, + # The runtimes the socket proxy accepts; None when the worker is not behind it. + "proxy_runtimes": list(proxy_runtimes) if proxy_runtimes is not None else None, + "gvisor_check": dict(_last_check) if _last_check is not None else None, + } diff --git a/app/orchestrator.py b/app/orchestrator.py index f11b1e9f..061cca99 100644 --- a/app/orchestrator.py +++ b/app/orchestrator.py @@ -51,7 +51,7 @@ logger = logging.getLogger(__name__) -from app import gpu, route_gate, socket_policy, version # noqa: E402 +from app import gpu, layers, route_gate, socket_policy, version # noqa: E402 from app.constants import ( # noqa: E402 CASHPILOT_DEPLOYED, CONTAINER_PREFIX, @@ -589,6 +589,19 @@ def _shape(container: Any) -> dict[str, Any]: } +def _layer_entry(container: Any) -> dict[str, Any]: + """The layers a container really got, for the UI's per-earner status (app/layers.py). + + ``runtime`` is the runtime Docker started it under (None when Docker does + not say, an older daemon) and ``network`` its network mode, which is the + network's name for a user-defined bridge such as cashpilot-isolated. + Read from the container's own record, so no extra Docker call. + """ + attrs = container.attrs if isinstance(getattr(container, "attrs", None), dict) else {} + host = attrs.get("HostConfig") if isinstance(attrs.get("HostConfig"), dict) else {} + return {"runtime": str(host.get("Runtime") or "") or None, "network": str(host.get("NetworkMode") or "") or None} + + def _shape_entry(container: Any) -> dict[str, Any]: """``{"shape": ...}`` for a container CashPilot's worker made, else nothing. @@ -989,33 +1002,99 @@ def _proxy_allows_runtime(slug: str, runtime: str) -> str: return runtime -def container_runtime(slug: str, network_mode: str | None, requested: str | None) -> str | None: +def runtime_pins() -> dict[str, Any]: + """What CASHPILOT_CONTAINER_RUNTIME and its overrides pin, for the heartbeat (app/layers.py). + + The variables win over the UI's choice, so the UI shows a pinned earner + locked. ``error`` carries a malformed overrides setting, which refuses + every deploy until it is fixed. + """ + try: + overrides = _runtime_overrides() + except ContainerRuntimeError as exc: + return {"default": _CONTAINER_RUNTIME or None, "overrides": {}, "error": str(exc)} + return {"default": _CONTAINER_RUNTIME or None, "overrides": overrides} + + +def _catalog_caps(slug: str) -> set[str]: + if not get_service: + return set() + caps = ((get_service(slug) or {}).get("docker") or {}).get("cap_add") or [] + return {str(c).upper().removeprefix("CAP_") for c in caps} + + +def _check_choice(slug: str, choice: str | None, runtime: str, why: str, facts: list[dict[str, Any]] | None) -> None: + """Refuse a runtime choice that a catalog requirement or an environment variable overrules.""" + if choice and layers.kind(runtime, facts) != choice: + raise ContainerRuntimeError( + f"{service_name(slug)} cannot run under {_CHOICE_NAMES.get(choice, choice)} here: {why} " + f"The running container was not touched." + ) + + +_CHOICE_NAMES = {layers.RUNC: "the standard runtime (runc)", layers.GVISOR: "gVisor"} + + +def container_runtime( + slug: str, network_mode: str | None, requested: str | None, choice: str | None = None +) -> str | None: """The runtime a new container runs under, or None for Docker's default. - A runtime named in the deploy request wins; the worker API has already - checked it against the daemon. A runtime the service's catalog entry - requires wins over both. Otherwise a container on bridge networking takes - the service's override or the worker's default. Host and none networking - keep Docker's default: a sandbox gains little on the host's own network - stack. Mysterium's catalog entry requires runc: a TUN device works under - gVisor, but iptables-nft and kernel WireGuard do not. - - Like container_network, a runtime the daemon does not provide is refused - here, BEFORE the running container is stopped, so a typo in the compose - file cannot take a service down. + A runtime the service's catalog entry requires wins over everything. + Mysterium's requires runc: a TUN device works under gVisor, but + iptables-nft and kernel WireGuard do not. Next a runtime named in the + deploy request (the advanced ``runtime`` field); the worker API has already + checked it against the daemon. Next the environment: the service's + override, or for bridge networking the worker's default. Last the owner's + ``choice`` from the UI (app/layers.py), ``runc`` or ``gvisor``. A choice + that the catalog or the environment overrules is refused with the reason, + never silently swapped, so what the UI shows is what the earner got. + + Like container_network, a runtime that cannot be used is refused here, + BEFORE the running container is stopped, so a typo in the compose file + cannot take a service down. """ + facts = layers.daemon_runtimes(fresh=True) if choice else None + if choice and choice not in layers.CHOICES: + raise ContainerRuntimeError(f"{choice!r} is not a runtime choice; use one of {', '.join(layers.CHOICES)}.", 400) if required := catalog_runtime(slug): # The service's own catalog entry names the one runtime it works under # (Mysterium: runc, since gVisor has no iptables-nft or kernel WireGuard). # Neither the request nor the operator's default can change it. + _check_choice(slug, choice, required, f"its catalog entry requires the {required!r} runtime.", facts) return _proxy_allows_runtime(slug, required) if requested: + # The advanced ``runtime`` field names the runtime outright; a choice that + # disagrees with it is refused, never silently dropped. + _check_choice(slug, choice, requested, f"the deploy names the {requested!r} runtime.", facts) return _proxy_allows_runtime(slug, requested) - if (network_mode or "bridge") not in ("bridge", "default"): - return None - runtime = _runtime_overrides().get(slug, _CONTAINER_RUNTIME) - if not runtime: + # The environment covers bridge networking only: host and none networking + # keep Docker's default unless the owner chooses, since a sandbox gains + # little on the host's own network stack. + bridge = (network_mode or "bridge") in ("bridge", "default") + overrides = _runtime_overrides() if bridge else {} + if slug in overrides: + runtime = overrides[slug] + why = f"CASHPILOT_CONTAINER_RUNTIME_OVERRIDES on this worker sets {slug}={runtime}." + elif bridge and _CONTAINER_RUNTIME: + runtime = _CONTAINER_RUNTIME + why = f"CASHPILOT_CONTAINER_RUNTIME on this worker is {runtime}." + elif choice: + allowed = socket_policy.ALLOWED_RUNTIMES if proxied() else None + try: + return layers.pick( + choice, + slug, + facts, + net_raw="NET_RAW" in _catalog_caps(slug), + allowed=allowed, + service=service_name(slug), + ) + except layers.ChoiceRefused as exc: + raise ContainerRuntimeError(f"{exc} The running container was not touched.") from None + else: return None + _check_choice(slug, choice, runtime, why + " Change or remove it to choose here.", facts) _proxy_allows_runtime(slug, runtime) available = available_runtimes() if available is None: @@ -1202,6 +1281,7 @@ def deploy_raw( resources: Any = None, category: str = "bandwidth", runtime: str | None = None, + runtime_choice: str | None = None, moved_mounts: list[str] | None = None, kept_mounts: list[dict[str, str]] | None = None, keep_targets: set[str] | None = None, @@ -1285,7 +1365,7 @@ def deploy_raw( # cannot be used must fail the deploy while the running service is still running. # The resolvers are checked here for the same reason. network = container_network(network_mode) - runtime = container_runtime(slug, network_mode, runtime) + runtime = container_runtime(slug, network_mode, runtime, runtime_choice) dns = container_dns(network) # The GPU this worker's own catalog gives the service (app/gpu.py), never # the request's choice. A proxied copy gets none. Every container without @@ -5578,6 +5658,7 @@ def get_status() -> list[dict[str, Any]]: "category": c.labels.get(LABEL_CATEGORY, ""), "instance": _instance_of(c), **_shape_entry(c), + **_layer_entry(c), **_stop_facts(c), **_identity_entry(c, slug), **_state_id_entry(c, slug, client), @@ -5651,6 +5732,7 @@ def get_status() -> list[dict[str, Any]]: "created": c.attrs.get("Created", ""), "container_id": c.short_id, "deployed_by": "external", + **_layer_entry(c), "category": "", **_state_id_entry(c, slug, client), **_fatal_entry(c, slug), @@ -5876,6 +5958,7 @@ def get_status_light() -> list[dict[str, Any]]: "category": c.labels.get(LABEL_CATEGORY, ""), "instance": _instance_of(c), **_shape_entry(c), + **_layer_entry(c), **_stop_facts(c), **_fatal_entry(c, slug), **_held_entry(c), @@ -5932,6 +6015,7 @@ def get_status_light() -> list[dict[str, Any]]: "created": c.attrs.get("Created", ""), "container_id": c.short_id, "deployed_by": "external", + **_layer_entry(c), "category": "", **_fatal_entry(c, slug), } diff --git a/app/worker_api.py b/app/worker_api.py index 4d80d312..8332c5bf 100644 --- a/app/worker_api.py +++ b/app/worker_api.py @@ -51,6 +51,7 @@ health_probe, isolation_check, lan_fence, + layers, log_redaction, miner_read, node_read, @@ -58,6 +59,7 @@ payout_read, proxy_tunnel, route_gate, + socket_policy, state_backup, step_up, version, @@ -464,6 +466,11 @@ def _gpu_info() -> dict[str, Any]: return info +def _layers_report() -> dict[str, Any]: + proxy = socket_policy.ALLOWED_RUNTIMES if orchestrator.proxied() else None + return layers.report(orchestrator.runtime_pins(), proxy) + + def _gpu_presence() -> dict[str, Any]: host = gpu.host_gpus() if host["conclusive"]: @@ -851,6 +858,10 @@ async def _send_heartbeat() -> None: # Which isolation mode this worker is in and whether its fence holds. # Cached by the fence check, so no helper container runs per heartbeat. "isolation": lan_fence.status(), + # Which other layers this host can give an earner: the runtimes + # Docker registered (gVisor among them), KVM, and what an + # environment variable pins (app/layers.py). Null fields are unknown. + "layers": await asyncio.to_thread(_layers_report), # Copies of services that leave through a proxy (app/proxy_tunnel.py). # Kept out of "containers": they are on another exit IP and are not # copies of the service, so nothing that counts copies may see them. @@ -895,6 +906,8 @@ async def _send_heartbeat() -> None: payload["system_info"]["features"].append("state_restore") # Gives a catalog service the GPU its own catalog entry declares (docker.gpu, app/gpu.py). payload["system_info"]["features"].append("gpu_grant") + # Takes runtime_choice on a deploy and reports system_info.layers (app/layers.py). + payload["system_info"]["features"].append(layers.FEATURE) payload["system_info"]["gpu_grants"] = { service["slug"]: grant for service in (_catalog_get_services() if _catalog_get_services else []) @@ -1623,6 +1636,10 @@ class DeploySpec(BaseModel): # Advanced and unsupported. Absent means Docker's default runtime, which is # what everything uses and what everything is tested against. runtime: str | None = None + # The owner's runtime choice from the UI, "runc" or "gvisor" (app/layers.py). + # The worker turns it into a runtime Docker registered, and refuses one its + # catalog or its environment overrules. Absent means Docker's default. + runtime_choice: str | None = None # Which copy of the service this is; see constants.LABEL_INSTANCE. instance: int = 1 # The UI's signed note that the owner re-entered their password for this @@ -1868,6 +1885,13 @@ def _catalog_host_network_slugs() -> set[str]: _ALLOWED_NETWORK_MODES = {None, "", "bridge", "none", "host"} +def _validate_runtime_choice(choice: str | None) -> None: + if choice is not None and choice not in layers.CHOICES: + raise HTTPException( + status_code=400, detail=f"runtime_choice is {choice!r}; it takes one of {', '.join(layers.CHOICES)}." + ) + + def _validate_runtime(runtime: str | None) -> None: """Allow only a runtime this daemon actually reports. @@ -2020,6 +2044,7 @@ def _validate_gpu(slug: str | None, spec: DeploySpec) -> None: def _validate_deploy_spec(spec: DeploySpec, slug: str | None = None) -> None: _validate_runtime(spec.runtime) + _validate_runtime_choice(spec.runtime_choice) if blocked_env := sorted(k for k in spec.env if str(k).upper().startswith(gpu.ENV_PREFIX)): # The void stamp and the GPU grant are this worker's (app/gpu.py): a # request that set NVIDIA_VISIBLE_DEVICES could undo the stamp. @@ -2451,6 +2476,15 @@ def _deploy_routed( async def api_proxied_deploy(request: Request, slug: str, proxy_id: int, spec: ProxiedDeploySpec) -> dict[str, Any]: """Run a copy of ``slug`` whose only way out is the given proxy (docs/proxies.md).""" _verify_api_key(request) + if spec.earner.runtime_choice is not None: + # A copy routed through a proxy shares its tunnel's network and runs under + # Docker's default runtime. Refused, not dropped: the owner would see a + # layer the copy does not have. + raise HTTPException( + status_code=400, + detail="A copy routed through a proxy runs under Docker's default runtime. " + "Choosing gVisor for it is not supported yet; deploy it without a runtime choice.", + ) # Counted from now, as a direct deploy's is (api_deploy_container): the UI # holds the ids of a copy deploy it got no answer for, and the hold must # outlast it, however long this one waits for locks or a tunnel pull. @@ -2819,6 +2853,7 @@ async def _deploy_container(request: Request, slug: str, spec: CheckedDeploySpec labels=spec.labels, resources=spec.resources, runtime=spec.runtime, + runtime_choice=spec.runtime_choice, moved_mounts=spec.moved_mounts, kept_mounts=kept_mounts, keep_targets=_catalog_volume_targets(slug), @@ -3419,6 +3454,7 @@ async def api_restore(slug: str, request: Request) -> dict[str, Any]: "labels": spec.labels, "resources": spec.resources, "runtime": spec.runtime, + "runtime_choice": spec.runtime_choice, "keep_targets": _catalog_volume_targets(slug), } try: diff --git a/tests/test_layers.py b/tests/test_layers.py new file mode 100644 index 00000000..5ba39064 --- /dev/null +++ b/tests/test_layers.py @@ -0,0 +1,293 @@ +"""The owner chooses an earner's runtime in the UI; the worker reports what it can give. + +The worker reports the runtimes Docker registered, which of them are gVisor, +whether the host has KVM, and what an environment variable pins +(system_info.layers). A deploy carries the owner's choice as runtime_choice, +"runc" or "gvisor". The worker turns gVisor into the variant Docker's DNS and +the earner's capabilities need, and refuses a choice that its catalog or its +environment overrules, with the reason, before the running container is touched. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest +from fastapi.testclient import TestClient + +from app import layers, orchestrator, worker_api + +RUNTIMES = { + "io.containerd.runc.v2": {"path": "runc"}, + "runc": {"path": "runc"}, + "runsc": {"path": "/usr/local/bin/runsc"}, + "runsc-hostnet": {"path": "/usr/local/bin/runsc", "runtimeArgs": ["--network=host"]}, + "runsc-hostnet-raw": {"path": "/usr/local/bin/runsc", "runtimeArgs": ["--network=host", "--net-raw"]}, +} +FACTS = layers.runtime_facts(RUNTIMES) + + +class TestRuntimeFacts: + def test_gvisor_is_judged_by_its_binary(self): + by_name = {f["name"]: f for f in FACTS} + assert not by_name["runc"]["gvisor"] + assert by_name["runsc"]["gvisor"] and not by_name["runsc"]["hostnet"] + assert by_name["runsc-hostnet"]["hostnet"] and not by_name["runsc-hostnet"]["net_raw"] + assert by_name["runsc-hostnet-raw"]["net_raw"] + + def test_a_runc_binary_under_a_gvisor_name_is_not_gvisor(self): + # The negative control of the self-test: a runtime named runsc-hostnet + # that really points at runc must not count as a layer. + facts = layers.runtime_facts({"runsc-hostnet": {"path": "/usr/bin/runc", "runtimeArgs": ["--network=host"]}}) + assert facts == [{"name": "runsc-hostnet", "gvisor": False, "hostnet": False, "net_raw": False}] + + def test_the_space_separated_flag_form(self): + facts = layers.runtime_facts( + {"g": {"path": "/opt/runsc", "runtimeArgs": ["--network", "host", "--net-raw=true"]}} + ) + assert facts[0]["hostnet"] and facts[0]["net_raw"] + + def test_nothing_readable_is_no_runtimes(self): + assert layers.runtime_facts(None) == [] + + +class TestKvm: + def test_present(self, tmp_path): + (tmp_path / "class" / "misc" / "kvm").mkdir(parents=True) + with patch.object(layers.platform, "system", return_value="Linux"): + assert layers.kvm(tmp_path, docker_host="") is True + + def test_absent(self, tmp_path): + (tmp_path / "class" / "misc" / "tun").mkdir(parents=True) + with patch.object(layers.platform, "system", return_value="Linux"): + assert layers.kvm(tmp_path, docker_host="") is False + + def test_unreadable_sysfs_is_unknown_not_absent(self, tmp_path): + with patch.object(layers.platform, "system", return_value="Linux"): + assert layers.kvm(tmp_path, docker_host="") is None + + def test_a_remote_docker_is_unknown(self, tmp_path): + (tmp_path / "class" / "misc" / "kvm").mkdir(parents=True) + with patch.object(layers.platform, "system", return_value="Linux"): + assert layers.kvm(tmp_path, docker_host="tcp://10.0.0.2:2375") is None + + def test_not_linux_is_unknown(self, tmp_path): + with patch.object(layers.platform, "system", return_value="Darwin"): + assert layers.kvm(tmp_path, docker_host="") is None + + +class TestPick: + def _pick(self, choice, facts=FACTS, net_raw=False, allowed=None): + return layers.pick(choice, "x", facts, net_raw=net_raw, allowed=allowed, service="X") + + def test_runc(self): + assert self._pick("runc") == "runc" + + def test_gvisor_takes_the_dns_safe_variant_without_raw_sockets(self): + assert self._pick("gvisor") == "runsc-hostnet" + + def test_raw_sockets_take_the_net_raw_variant(self): + assert self._pick("gvisor", net_raw=True) == "runsc-hostnet-raw" + + def test_plain_runsc_is_not_enough(self): + facts = layers.runtime_facts({"runc": {"path": "runc"}, "runsc": {"path": "/usr/local/bin/runsc"}}) + with pytest.raises(layers.ChoiceRefused, match="--network=host"): + self._pick("gvisor", facts=facts) + + def test_raw_sockets_without_the_variant_are_refused(self): + facts = layers.runtime_facts({"runsc-hostnet": RUNTIMES["runsc-hostnet"]}) + with pytest.raises(layers.ChoiceRefused, match="raw sockets"): + self._pick("gvisor", facts=facts, net_raw=True) + + def test_a_name_the_proxy_refuses_is_not_used(self): + facts = layers.runtime_facts({"gv": {"path": "/usr/local/bin/runsc", "runtimeArgs": ["--network=host"]}}) + with pytest.raises(layers.ChoiceRefused): + self._pick("gvisor", facts=facts, allowed=("runc", "runsc-hostnet")) + + def test_an_unaskable_daemon(self): + with pytest.raises(layers.ChoiceRefused, match="not answering"): + self._pick("gvisor", facts=None) + + +def _client(old=None): + client = MagicMock() + if old is None: + client.containers.get.side_effect = orchestrator.NotFound("nope") + else: + client.containers.get.return_value = old + created = MagicMock() + created.id = "new" + created.short_id = "new" + client.containers.run.return_value = created + return client + + +def _deploy(client, choice, default="", overrides="", **kwargs): + kwargs.setdefault("slug", "honeygain") + kwargs.setdefault("image", "honeygain/honeygain") + with ( + patch.object(orchestrator, "_CONTAINER_RUNTIME", default), + patch.object(orchestrator, "_CONTAINER_RUNTIME_OVERRIDES", overrides), + patch.object(orchestrator, "_CONTAINER_NETWORK", ""), + patch.object(orchestrator, "available_runtimes", return_value=set(RUNTIMES)), + patch.object(layers, "daemon_runtimes", return_value=FACTS), + patch.object(orchestrator, "_get_client", return_value=client), + ): + orchestrator.deploy_raw(runtime_choice=choice, **kwargs) + return client.containers.run.call_args.kwargs + + +class TestTheChoiceOnADeploy: + def test_no_choice_keeps_dockers_default(self): + assert _deploy(_client(), None)["runtime"] is None + + def test_gvisor(self): + assert _deploy(_client(), "gvisor")["runtime"] == "runsc-hostnet" + + def test_standard(self): + assert _deploy(_client(), "runc")["runtime"] == "runc" + + def test_bitping_gets_raw_sockets_back_from_its_own_catalog(self): + assert _deploy(_client(), "gvisor", slug="bitping", image="bitping/bitpingd")["runtime"] == "runsc-hostnet-raw" + + def test_an_env_pin_that_agrees_is_used(self): + kwargs = _deploy(_client(), "gvisor", overrides="honeygain=runsc-hostnet-raw") + assert kwargs["runtime"] == "runsc-hostnet-raw" + + def test_runc_under_a_catalog_requirement_of_runc(self): + # Mysterium is fence-gated, so its deploy takes another path; the + # runtime is decided here, before either path starts. + with patch.object(layers, "daemon_runtimes", return_value=FACTS): + assert orchestrator.container_runtime("mysterium", None, None, "runc") == "runc" + + +class TestARefusedChoiceTouchesNothing: + def _refused(self, choice, **kwargs): + old = MagicMock() + client = _client(old=old) + with pytest.raises(orchestrator.ContainerRuntimeError) as err: + _deploy(client, choice, **kwargs) + old.stop.assert_not_called() + old.remove.assert_not_called() + client.containers.run.assert_not_called() + return str(err.value) + + def test_mysterium_under_gvisor_names_its_catalog(self): + with ( + patch.object(layers, "daemon_runtimes", return_value=FACTS), + pytest.raises(orchestrator.ContainerRuntimeError) as err, + ): + orchestrator.container_runtime("mysterium", None, None, "gvisor") + assert "catalog entry requires the 'runc' runtime" in str(err.value) + assert err.value.status_code == 409 + + def test_the_worker_default_wins_and_says_so(self): + why = self._refused("runc", default="runsc-hostnet") + assert "CASHPILOT_CONTAINER_RUNTIME on this worker is runsc-hostnet" in why + + def test_an_override_wins_and_says_so(self): + why = self._refused("gvisor", overrides="honeygain=runc") + assert "CASHPILOT_CONTAINER_RUNTIME_OVERRIDES on this worker sets honeygain=runc" in why + + def test_gvisor_without_the_runtime(self): + with patch.object(layers, "daemon_runtimes", return_value=layers.runtime_facts({"runc": {"path": "runc"}})): + old = MagicMock() + client = _client(old=old) + with ( + patch.object(orchestrator, "_CONTAINER_RUNTIME", ""), + patch.object(orchestrator, "_CONTAINER_RUNTIME_OVERRIDES", ""), + patch.object(orchestrator, "_CONTAINER_NETWORK", ""), + patch.object(orchestrator, "_get_client", return_value=client), + pytest.raises(orchestrator.ContainerRuntimeError, match="gVisor install command"), + ): + orchestrator.deploy_raw("honeygain", "honeygain/honeygain", runtime_choice="gvisor") + client.containers.run.assert_not_called() + old.stop.assert_not_called() + + def test_a_choice_that_disagrees_with_the_named_runtime_is_refused(self): + with ( + patch.object(layers, "daemon_runtimes", return_value=FACTS), + pytest.raises(orchestrator.ContainerRuntimeError, match="the deploy names the 'runc' runtime"), + ): + orchestrator.container_runtime("honeygain", None, "runc", "gvisor") + + def test_a_choice_that_agrees_with_the_named_runtime_is_used(self): + with ( + patch.object(layers, "daemon_runtimes", return_value=FACTS), + patch.object(orchestrator, "_proxy_allows_runtime", side_effect=lambda slug, r: r), + ): + assert orchestrator.container_runtime("honeygain", None, "runsc-hostnet", "gvisor") == "runsc-hostnet" + + def test_an_unknown_choice(self): + with pytest.raises(orchestrator.ContainerRuntimeError) as err: + orchestrator.container_runtime("honeygain", None, None, "kata") + assert err.value.status_code == 400 + + +class TestTheWorkerApi: + def test_an_unknown_choice_is_a_400(self): + with patch.object(worker_api, "_verify_api_key"): + resp = TestClient(worker_api.app).post( + "/api/containers/honeygain/deploy", json={"image": "x", "runtime_choice": "kata"} + ) + assert resp.status_code == 400, resp.text + assert "runtime_choice" in resp.json()["detail"] + + def test_the_report_carries_pins_and_unknowns(self): + with ( + patch.object(layers, "docker_info", return_value=None), + patch.object(layers, "kvm", return_value=None), + patch.object(orchestrator, "_CONTAINER_RUNTIME", "runsc-hostnet"), + patch.object(orchestrator, "_CONTAINER_RUNTIME_OVERRIDES", "bitping=runsc-hostnet-raw"), + patch.object(orchestrator, "proxied", return_value=True), + ): + report = worker_api._layers_report() + assert report["runtimes"] is None + assert report["default_runtime"] is None + assert report["kvm"] is None + assert report["pins"] == {"default": "runsc-hostnet", "overrides": {"bitping": "runsc-hostnet-raw"}} + assert "runsc-hostnet" in report["proxy_runtimes"] + + def test_a_malformed_override_is_reported(self): + with patch.object(orchestrator, "_CONTAINER_RUNTIME_OVERRIDES", "bitping"): + pins = orchestrator.runtime_pins() + assert pins["overrides"] == {} + assert "slug=runtime" in pins["error"] + + @pytest.mark.parametrize("runtimes", [None, "runc", ["runc"]]) + def test_an_unreadable_runtime_list_is_unknown_not_empty(self, runtimes): + info = {"DefaultRuntime": "runc"} if runtimes is None else {"Runtimes": runtimes} + with patch.object(layers, "docker_info", return_value=info), patch.object(layers, "kvm", return_value=None): + assert layers.report({"default": None, "overrides": {}}, None)["runtimes"] is None + assert layers.daemon_runtimes() is None + + def test_a_readable_empty_list_is_empty(self): + with patch.object(layers, "docker_info", return_value={"Runtimes": {}}): + assert layers.daemon_runtimes() == [] + + def test_a_routed_copy_refuses_a_runtime_choice(self): + body = { + "earner": {"image": "honeygain/honeygain", "runtime_choice": "gvisor"}, + "proxy": {"kind": "socks5", "host": "203.0.113.9", "port": 1080}, + } + with patch.object(worker_api, "_verify_api_key"): + resp = TestClient(worker_api.app).post("/api/proxied/honeygain/3/deploy", json=body) + assert resp.status_code == 400, resp.text + assert "routed through a proxy" in resp.json()["detail"] + + def test_the_report_lists_the_runtimes(self): + info = {"Runtimes": RUNTIMES, "DefaultRuntime": "runc"} + with patch.object(layers, "docker_info", return_value=info), patch.object(layers, "kvm", return_value=True): + report = layers.report({"default": None, "overrides": {}}, None) + assert [f["name"] for f in report["runtimes"] if f["gvisor"]] == ["runsc", "runsc-hostnet", "runsc-hostnet-raw"] + assert report["default_runtime"] == "runc" + assert report["kvm"] is True + assert report["proxy_runtimes"] is None + + +def test_each_container_says_which_runtime_and_network_it_got(): + container = MagicMock() + container.attrs = {"HostConfig": {"Runtime": "runsc-hostnet", "NetworkMode": "cashpilot-isolated"}} + assert orchestrator._layer_entry(container) == {"runtime": "runsc-hostnet", "network": "cashpilot-isolated"} + container.attrs = {} + assert orchestrator._layer_entry(container) == {"runtime": None, "network": None} diff --git a/tests/test_route_at_deploy.py b/tests/test_route_at_deploy.py index d938bdc5..adc3cb9b 100644 --- a/tests/test_route_at_deploy.py +++ b/tests/test_route_at_deploy.py @@ -966,7 +966,7 @@ def _real_deploy_raw_client(self, monkeypatch): client.images.get.return_value.attrs = {"Config": {}} monkeypatch.setattr(orchestrator, "_get_client", lambda: client) monkeypatch.setattr(orchestrator, "container_network", lambda mode: None) - monkeypatch.setattr(orchestrator, "container_runtime", lambda slug, mode, runtime: None) + monkeypatch.setattr(orchestrator, "container_runtime", lambda slug, mode, runtime, choice=None: None) monkeypatch.setattr(orchestrator, "container_dns", lambda network: None) monkeypatch.setattr(proxy_tunnel, "copy_name", lambda slug, pid: None) monkeypatch.setattr(proxy_tunnel, "routed_copies", lambda slug, marked: [])