Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ venv
node_modules
docs/
scripts/
# The UI image carries the host helpers it pins (app/layer_scripts.py).
!scripts/cashpilot-gvisor
*.md
!requirements.txt
.DS_Store
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ jobs:
- name: Currency formatting behaviour
run: node scripts/currency_check.mjs

# The browser's message formatter (app/static/js/i18n.js) on the cases
# tests/test_i18n.py runs through the server's (app/i18n), so a plural or
# a quoted brace cannot read differently on the two sides.
- name: Message formatting behaviour (i18n)
run: node scripts/i18n_format_check.mjs

- name: Catalog patterns reach the deploy form
run: node scripts/deploy_field_check.mjs

Expand Down
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ COPY --from=builder /build/.venv ./.venv

COPY app/ ./app/
COPY services/ ./services/
# The host helpers the Fleet page offers as one pinned command (app/layer_scripts.py).
COPY scripts/cashpilot-gvisor ./scripts/
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

Expand Down
3 changes: 3 additions & 0 deletions Dockerfile.worker
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ 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/gvisor_check.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/
Expand Down
3 changes: 3 additions & 0 deletions app/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,9 @@ def _validate_network_shape(docker: dict[str, Any], name: str) -> list[str]:
runtime = docker.get("runtime")
if runtime is not None and (not isinstance(runtime, str) or not runtime.strip()):
errors.append(f"{name}: docker.runtime must be a runtime name")
reason = docker.get("runtime_reason")
if reason is not None and (runtime is None or not isinstance(reason, str) or not reason.strip()):
errors.append(f"{name}: docker.runtime_reason must be a sentence, next to docker.runtime")
caps = {str(c).upper().removeprefix("CAP_") for c in docker.get("cap_add") or []}
if held := sorted(caps & NETNS_CAPABILITIES):
# The threat class this rule closes: a container with these in the host's
Expand Down
17 changes: 14 additions & 3 deletions app/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,9 @@ def decrypt_value(value: str) -> str:
-- An id from app/themes.json. NULL = never chosen, so the default applies.
-- Nullable with no default so fresh and upgraded match.
theme TEXT,
-- A locale from app/i18n (NAMES). NULL = never chosen, or set back to
-- automatic, so the browser's language applies.
language TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
Expand Down Expand Up @@ -1316,6 +1319,11 @@ async def init_db() -> None:
if "theme" not in pref_cols:
applied.append("user_preferences.theme")
await db.execute("ALTER TABLE user_preferences ADD COLUMN theme TEXT")
# The language choice, per user. NULL means "never chosen": the
# browser's Accept-Language decides, as it did before this column.
if "language" not in pref_cols:
applied.append("user_preferences.language")
await db.execute("ALTER TABLE user_preferences ADD COLUMN language TEXT")

# Migrate earnings table: add fx_rate_usd so a non-USD balance's value at the
# time it was recorded stays reconstructable (rates are only cached live).
Expand Down Expand Up @@ -3313,30 +3321,33 @@ async def save_user_preferences(
timezone: str | None = None,
setup_completed: bool | None = None,
theme: str | None = None,
language: str | None = None,
) -> None:
"""Upsert the fields that were passed; a None field keeps its stored value.

One statement, no read first: a theme click and the wizard's step-4 POST can
land together, and a read-modify-write would let one undo the other.
``language="auto"`` clears the choice, so the browser's language applies again.
"""
done = None if setup_completed is None else int(setup_completed)
db = await _get_db()
try:
await db.execute(
"""
INSERT INTO user_preferences
(user_id, setup_mode, selected_categories, timezone, setup_completed, theme, updated_at)
(user_id, setup_mode, selected_categories, timezone, setup_completed, theme, language, updated_at)
VALUES (?1, COALESCE(?2, 'fresh'), COALESCE(?3, '[]'), COALESCE(?4, 'UTC'), COALESCE(?5, 0), ?6,
datetime('now'))
NULLIF(?7, 'auto'), datetime('now'))
ON CONFLICT(user_id) DO UPDATE SET
setup_mode = COALESCE(?2, setup_mode),
selected_categories = COALESCE(?3, selected_categories),
timezone = COALESCE(?4, timezone),
setup_completed = COALESCE(?5, setup_completed),
theme = COALESCE(?6, theme),
language = CASE WHEN ?7 IS NULL THEN language ELSE NULLIF(?7, 'auto') END,
updated_at = datetime('now')
""",
(user_id, setup_mode, selected_categories, timezone, done, theme),
(user_id, setup_mode, selected_categories, timezone, done, theme, language),
)
await db.commit()
finally:
Expand Down
10 changes: 9 additions & 1 deletion app/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates

from app import auth, database, login_rate_limit, setup_token, themes, version
from app import auth, database, i18n, login_rate_limit, setup_token, themes, version

__all__ = [
"templates",
Expand Down Expand Up @@ -67,6 +67,14 @@ def _csp_nonce(request) -> str:
templates.env.globals["themes"] = themes.THEME_LIST
templates.env.globals["theme_default"] = themes.DEFAULT_THEME
templates.env.globals["theme_config"] = themes.CONFIG
# The page's language (app/i18n): t() looks a key up in it, lang() and
# lang_dir() go on <html>, languages() fills the picker. All of them read the
# request's current locale, which app.i18n.LocaleMiddleware sets from the
# cookie and Accept-Language and a signed-in page replaces with the saved choice.
templates.env.globals["t"] = i18n.t
templates.env.globals["lang"] = i18n.current
templates.env.globals["lang_dir"] = i18n.direction
templates.env.globals["languages"] = i18n.languages


def _login_redirect() -> RedirectResponse:
Expand Down
200 changes: 200 additions & 0 deletions app/gvisor_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
"""Does gVisor really protect the earners on this host? A red/green self-test.

The owner installs gVisor with one command on the host (scripts/cashpilot-gvisor),
because that needs root and the worker has none. The worker cannot see what the
command did, only what Docker reports afterwards, and a runtime's name proves
nothing: a ``runsc-hostnet`` entry can point at runc. So this starts one short
probe container per gVisor runtime the earners would use, on the network they
are on, and checks two things from inside it:

* **gVisor's kernel.** The probe reads its kernel release and /proc/version.
gVisor answers with its own (``4.19.0-gvisor``, measured on release
20261123.1), never the host's. The worker runs under runc, so its own
release is the host's, unless it runs under gVisor itself (Docker's default
runtime inside a Secure VM), so only gVisor's own answer counts.
* **DNS on the earners' network.** Plain runsc cannot resolve names on a
user-defined bridge (gVisor issue 7469), which is why the install registers
the ``--network=host`` passthrough. The probe resolves a public name.

Green needs both, for every runtime checked. No gVisor runtime at all is
"not installed", which the UI shows as such, never as a failure of the earners.
The probes run from the worker's own image with no capabilities, as nobody, on
a read-only root, and are removed on every path, as in app/isolation_check.py.
"""

from __future__ import annotations

import contextlib
import json
import logging
import threading
from datetime import UTC, datetime
from typing import Any

import docker
from docker.errors import DockerException, NotFound

from app import lan_fence, layers, orchestrator, socket_policy

logger = logging.getLogger(__name__)

PROBE_NAME = "cashpilot-gvisor-probe"
PROBE_LABEL = lan_fence.PROBE_LABEL
PROBE_TIMEOUT = 60
DOCKER_TIMEOUT = 30
#: A public name whose lookup must work from the earners' network.
DNS_NAME = "cloudflare.com"

_lock = threading.Lock()

PROBE_SCRIPT = r"""
import json, platform, socket, sys
out = {"release": platform.release()}
try:
with open("/proc/version") as fh:
out["version"] = fh.read().strip()
except OSError as exc:
out["version_error"] = str(exc)
try:
socket.setdefaulttimeout(10)
out["dns"] = sorted({a[4][0] for a in socket.getaddrinfo(sys.argv[1], 443, proto=socket.IPPROTO_TCP)})[:4]
except Exception as exc:
out["dns_error"] = f"{type(exc).__name__}: {exc}"
print(json.dumps(out))
"""


class CheckBusy(Exception):
pass


def judge(probe: dict[str, Any]) -> dict[str, Any]:
"""Whether one probe saw gVisor's kernel and could resolve names, with the reason for each."""
release = str(probe.get("release") or "")
seen = f"{release} {probe.get('version') or ''}".lower()
# Not "differs from the worker's own release": inside a Secure VM the
# worker itself may run under gVisor, as Docker's default runtime there.
kernel = "gvisor" in seen
if kernel:
kernel_why = f"gVisor's kernel answered ({release})"
elif release:
kernel_why = f"the probe ran on a real Linux kernel ({release}), so this runtime is not gVisor"
else:
kernel_why = "the probe saw no sign of gVisor's kernel"
dns = bool(probe.get("dns"))
dns_why = (
f"{DNS_NAME} resolved"
if dns
else f"{DNS_NAME} did not resolve ({probe.get('dns_error') or 'no answer'}); "
"gVisor needs the --network=host passthrough for Docker's DNS on this network"
)
return {"kernel": kernel, "kernel_why": kernel_why, "dns": dns, "dns_why": dns_why}


def _client() -> Any:
try:
client = docker.from_env(timeout=DOCKER_TIMEOUT)
client.ping()
except Exception as exc:
raise RuntimeError(f"Docker socket not available: {exc}") from exc
return client


def _remove(client: Any, leftovers: list[str]) -> None:
try:
client.containers.get(PROBE_NAME).remove(force=True, v=True)
except NotFound:
pass
except Exception as exc: # noqa: BLE001 - reported, never raised
logger.warning("Could not remove the gVisor probe: %s", exc)
leftovers.append(PROBE_NAME)


def _probe(client: Any, image: str, runtime: str, network: str, leftovers: list[str]) -> dict[str, Any]:
_remove(client, [])
try:
container = client.containers.run(
image=image,
name=PROBE_NAME,
entrypoint=["python", "-c", PROBE_SCRIPT],
command=[DNS_NAME],
runtime=runtime,
network=network or None,
user="65534:65534",
read_only=True,
cap_drop=["ALL"],
security_opt=["no-new-privileges:true"],
privileged=False,
pids_limit=64,
mem_limit="128m",
healthcheck={"test": ["NONE"]},
labels={PROBE_LABEL: "gvisor-check"},
detach=True,
)
status = container.wait(timeout=PROBE_TIMEOUT)
logs = container.logs(stdout=True, stderr=False)
if (status or {}).get("StatusCode") != 0:
return {"error": f"the probe exited with status {(status or {}).get('StatusCode')}"}
return json.loads(logs)
except (DockerException, ValueError) as exc:
# Docker's own answer can name paths; the runtime and a short reason are enough.
logger.warning("gVisor probe under %s failed: %s", runtime, exc)
return {"error": f"Docker could not run the probe under {runtime}: {str(exc)[:200]}"}
finally:
_remove(client, leftovers)


def run() -> dict[str, Any]:
"""Run the self-test. Raises CheckBusy when one runs already, RuntimeError without Docker."""
if not _lock.acquire(blocking=False):
raise CheckBusy("A gVisor check is already running on this worker.")
try:
client = _client()
try:
result = _run(client)
finally:
with contextlib.suppress(Exception):
client.close()
layers.set_last_check(result)
return result
finally:
_lock.release()


def _run(client: Any) -> dict[str, Any]:
facts = layers.daemon_runtimes(fresh=True) or []
allowed = socket_policy.ALLOWED_RUNTIMES if orchestrator.proxied() else None
gvisor = [f for f in facts if f["gvisor"]]
# The runtimes an earner would get (layers.pick): the passthrough ones the proxy accepts.
targets = [f["name"] for f in gvisor if f["hostnet"] and (allowed is None or f["name"] in allowed)]
_mode, network = lan_fence.effective_network(client)
checked_at = datetime.now(UTC).isoformat(timespec="seconds")
base: dict[str, Any] = {"checked_at": checked_at, "network": network or "bridge", "runtimes": []}
if not targets:
why = (
"Docker has gVisor registered, but not with --network=host, which Docker's DNS needs on this network."
if gvisor
else "Docker on this host has no gVisor runtime registered."
)
return {**base, "state": "not_installed", "message": why}
image = orchestrator._self_container(client)
image = ((image.attrs or {}).get("Image") or None) if image is not None else None
if not image:
return {**base, "state": "red", "message": "The worker could not find its own image to run the probe from."}
leftovers: list[str] = []
for name in targets:
probe = _probe(client, image, name, network, leftovers)
if "error" in probe:
base["runtimes"].append({"name": name, "kernel": False, "dns": False, "error": probe["error"]})
continue
base["runtimes"].append({"name": name, **judge(probe)})
green = all(r["kernel"] and r["dns"] for r in base["runtimes"])
base["state"] = "green" if green else "red"
base["message"] = (
"Every earner that runs under gVisor here gets gVisor's kernel, and its name lookups work."
if green
else "gVisor is not protecting the earners correctly on this host; see each runtime below."
)
if leftovers:
base["leftovers"] = leftovers
return base
Loading