Skip to content

feat(sandbox): Kubernetes backend for artex-runner - #780

Open
thecorporatetractor wants to merge 2 commits into
BaaRai:mainfrom
thecorporatetractor:feat/k8s-sandbox-backend
Open

thecorporatetractor wants to merge 2 commits into
BaaRai:mainfrom
thecorporatetractor:feat/k8s-sandbox-backend

Conversation

@thecorporatetractor

@thecorporatetractor thecorporatetractor commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

artex-runner only has a Docker backend. On Kubernetes that means mounting a container runtime socket into a pod, which gives it control of the node. There is no way to run ARTEX's per-task sandbox natively on a cluster (see #620).

Change

New backend ARTEX_RUNNER_BACKEND=kubernetes (sandbox/kube.go). It talks to the API server with the pod's service-account token. No runtime socket.

For each task the runner creates:

  • NetworkPolicy for the worker: no ingress, egress only to the task's proxy on 3128/1080.
  • NetworkPolicy for the proxy: ingress only from the worker; egress to cluster DNS, 0.0.0.0/0 minus private, CGNAT, loopback, link-local, metadata and multicast ranges, plus the task's scope CIDRs.
  • Service (ClusterIP) for the proxy. The worker uses the IP, not DNS.
  • Proxy pod (artex-egress-proxy) with the task's domain/CIDR allowlist and its audit log on the data volume.
  • Worker pod (artex-worker): uid/gid 10001, runAsNonRoot, read-only root filesystem, all capabilities dropped, no privilege escalation, seccomp: RuntimeDefault, no service-account token, no service links, dnsPolicy: None. It mounts only tasks/<task>.

Behaviour:

  • Policies are created before the pods and deleted after them.
  • After pods start, the runner probes worker → proxy and proxy → DNS before running a command. CNIs program NetworkPolicy a few seconds after a pod is Ready (k3s does), and the first command would otherwise fail or run before the policy applies.
  • Commands run through pods/exec as env -i -C <workdir> <base env> <request env> artex-exec-wrap <timeout> -- <argv>.
  • Kill scans /proc for uid 10001; if that fails it deletes the worker pod and keeps the workspace.
  • A scope change replaces the proxy and its policy.
  • After a restart the runner re-adopts task pods by label. It adopts a pod only when the artex.task annotation hashes to the artex.task_hash label.
  • Object names use the first 32 hex characters (128 bits) of the SHA-256 of the task ID, because task IDs can contain characters Kubernetes rejects.
  • Configuration is through ARTEX_KUBE_* variables (namespace, data claim and sub-paths, images, runtime class, DNS selector, denied CIDRs, ready timeout, node pinning for ReadWriteOnce volumes, worker limits).

The Docker backend is unchanged.

Tests

  • Unit tests run against a fake API server (sandbox/kube_fake_test.go). The fake requires resourceVersion on PUT, keeps a deleted pod visible for a while, checks UID preconditions and refuses force deletes. This PR keeps the tests for the review items:

    • deletion ordering;
    • the 409 update with resourceVersion and the label check;
    • the denied-CIDR merge;
    • scope that cannot open cluster ranges;
    • the isolation checks;
    • the client: redirects, http://, error bodies, and the exec stream read limit, subprotocol and CLOSE.

    The other 12 unit tests (create and exec, scope change, recover, kill races, timeout, failed setup, queued exec after delete, stream errors) move to the follow-up PR with the live test.

  • go test -race ./sandbox/ ./cmd/...: pass. With the follow-up unit tests they pass once fix(sandbox): refuse exec env names that override the proxy, PATH or the loader #895 is merged.

  • Live test on k3d v5.9.0 (k3s, kube-router), 10/10 on this head: identity and hardening, workdir and env, exit codes, timeout and truncation, cluster objects, network isolation, in-scope egress through the proxy, kill, runner restart, delete.

Notes

  • Depends on fix(sandbox): refuse exec env names that override the proxy, PATH or the loader #895 (refuse PATH, proxy and loader variables in exec requests; it also fixes the Docker backend). Please merge it first.
  • Deployment requirements, also documented on NewKubernetesBackend:
    • the kubelet podPidsLimit, since the pod API has no per-pod PID limit;
    • a dedicated task namespace with Pod Security Admission restricted;
    • a ResourceQuota and LimitRange, plus a cap on concurrent tasks (the Helm and scaling PRs add these);
    • ARTEX_KUBE_CLUSTER_CIDRS set to the pod, service and node CIDRs. Without it, scope CIDRs in private ranges are dropped.
  • Size: 2,489 lines across 11 files. The other unit tests, the live test, the Helm chart and the k3d CI job follow as separate PRs, in the order listed in We need Kubernetes: run ARTEX and its sandbox natively on clusters #781.
  • NetworkPolicy enforcement is required. Without it a worker can reach the cluster directly. The runner refuses to run a command until it sees the policies in effect.
  • Kubernetes has no per-pod PID limit in the pod API; set --pod-max-pids on the kubelet.

Part of #781.

@thecorporatetractor

Copy link
Copy Markdown
Contributor Author

Rebased onto main after #775 merged. The only conflict was in CHANGELOG (CRLF kept). All checks pass on 5fe94b6. #783 (Helm chart) builds on this PR, and its kubernetes CI job runs this backend live on k3d.

@thecorporatetractor

Copy link
Copy Markdown
Contributor Author

@BaaRai This PR starts a short series that brings Kubernetes support to ARTEX (tracking issue #781, which has screenshots).

The whole stack has been tested end to end: the runner on k3d, the Helm chart with the panel (the #620 self-test failure is gone), a real ARTEX task running its commands in a worker pod, and cluster-autoscaler on a multi-node cluster. Following CONTRIBUTING, I split it into focused PRs that each do one thing and build on the previous one:

  1. feat(sandbox): Kubernetes backend for artex-runner #780: Kubernetes backend for artex-runner (this PR)
  2. feat(deploy): Helm chart with the Kubernetes sandbox #783: Helm chart, k3d e2e script and CI job. Its kubernetes job already runs this backend on the GitHub runner.
  3. Next: the Sandbox page with scale-to-zero and a capacity cap
  4. Next: scope-restricted panel egress for sandbox.mode=off

All checks pass on #780 and #783. Review in this order works best. I'll rebase and address comments as they come. Happy to change the split if you prefer another shape.

@BaaRai

BaaRai commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Thanks for the work. This PR is 2,733 lines across 7 files, above the review threshold we can apply line by line (2,500 lines or 15 files). I am parking it for the current wave rather than closing it: the PR stays open and the work is kept.

To get it reviewed, please split it by subsystem into PRs under that threshold. For this one, a natural split is: backend interface, Docker versus Kubernetes, tests.

If the feature is already on the roadmap, link the tracking issue and we will pick it up there.

@thecorporatetractor

Copy link
Copy Markdown
Contributor Author

Trimmed to 2,430 lines across 6 files: backend and unit tests only. The live test moves to its own PR. Full split plan in #781.

@BaaRai BaaRai left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The audit on 502e42d fails on isolation and lifecycle. The pod security context and the shared PVC subPath checks pass; these are blocking.

NetworkPolicies

  • Delete removes the per-task policies right after issuing background pod deletions (sandbox/kube.go:1218-1236): deleteObj(..., &zero) returns before the pods are gone, so a still-running pod loses its isolation. Wait with deletePodAndWait, and do not remove the policies when the pod deletion failed.
  • applyPolicy PUTs on 409 without metadata.resourceVersion (:745-752), which a real API server rejects with 422; the fake API does not check it. It also overwrites an existing policy without checking LabelManagedBy/LabelTaskHash, unlike the Service path at :903-905.
  • ARTEX_KUBE_PROXY_DENIED_CIDRS replaces DefaultProxyDeniedCIDRs instead of extending it (:178-180,253-261): one extra CIDR silently drops IMDS, RFC1918, CGNAT, loopback and multicast from the proxy policy.
  • An empty non-nil DNSPodLabels map opens port 53 to every pod in kube-system (:184,708).
  • The runner assumes an external default-deny policy that is not in this repository.

Exec environment

  • kubeExecArgv appends req.Env after workerBaseEnv(proxyIP) (:1140-1145); ValidateEnv does not refuse HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY, PATH or LD_PRELOAD, so a caller can override the proxy or preload a library ahead of artex-exec-wrap.

Errors and identifiers

  • kubeAPIError forwards up to 4 KiB of the raw API server body to the runner (:346-347,1065), and containerExec puts req.Env and req.Argv in the WebSocket query string and echoes the dial error (:1035,1067).
  • scopeHash is truncated to 32 bits (:865).

Concurrency and cleanup

  • Kill does not take taskLock and reads b.tasks[taskID] and kt.workerPod outside the mutex while another Kill writes cur.workerPod (:1178-1202): a data race, and a Kill from an Exec cancellation can remove a worker just recreated by ensureTask.
  • An exec timeout (exit 124) does not Kill the worker, unlike the Docker backend (:1158-1172), so setsid and double-fork descendants survive.
  • If waitPodReady or waitNetworkReady fails after objects are created, ensureTask leaves them orphaned and Delete returns ErrNotFound (:881-945,1214-1216).
  • b.locks[taskID] is never removed by Delete.

Kubernetes client

  • No SetReadLimit on the exec WebSocket (:1057-1099): a compromised worker can send an unbounded frame and OOM the runner.
  • The v5/v4 subprotocol is not verified and the v5 CLOSE channel is not handled (:1053-1057); b.http does not refuse redirects (:212).
  • workerBaseEnv builds the proxy URL with fmt.Sprintf instead of net.JoinHostPort, so an IPv6 ClusterIP gives an invalid URL (:606-607).
  • An http:// API server is accepted without a test-only guard, which would send the service-account token in clear (:198).

PVC

  • NewKubernetesBackend does not refuse TasksSubPath == AuditSubPath or TasksSubPath == "." (:167-171); Exec and Delete do not revalidate ValidateTaskID outside RunnerServer.

Please fix these on a new head and add tests for the deletion ordering, the 409 PUT, the denied-CIDR merge and the WebSocket read limit. The delta will be re-audited.

ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own
egress-proxy pod, created through the Kubernetes API (kube_client.go) with no
container runtime socket. Per-task NetworkPolicies are applied before the pods
and removed after them; the runner proves they are in effect before the first
command, runs commands through pods/exec under env -i and artex-exec-wrap, and
re-adopts task pods after a restart. Unit tests run against a fake API
server; this commit keeps the tests for the review items, and the other
unit tests and the live cluster test follow in a separate PR.

Changes since the first review (502e42d):

NetworkPolicies and scope:
- Delete and failed setups delete the task's pods and wait until they are
  gone before removing the service and, last, the policies. If a pod
  cannot be deleted, the policies stay and the task stays tracked. Pods
  get a 1s grace, not 0: a zero grace removes the API object before the
  kubelet has stopped the containers.
- applyPolicy replaces an existing policy only when it carries the
  runner's labels for the same task, and sends its resourceVersion.
- ARTEX_KUBE_PROXY_DENIED_CIDRS adds to DefaultProxyDeniedCIDRs instead
  of replacing it. An empty DNSPodLabels map falls back to k8s-app=kube-dns.
- No scope opens the cluster: ARTEX_KUBE_CLUSTER_CIDRS (pod, service and
  node CIDRs) plus metadata, loopback, link-local and the API server
  address form a never-reachable list. Each scope ipBlock gets them as
  except (a block inside one is dropped), the public rule excepts them,
  and the proxy refuses them through ARTEX_NEVER_CIDRS (new
  EgressPolicy.Never; Docker does not set it). Without
  ARTEX_KUBE_CLUSTER_CIDRS, scope CIDRs overlapping private, loopback or
  link-local ranges are dropped (logged), so the scope fails closed.
- Isolation does not rely on an outside default-deny policy: every task
  pod has its own Ingress+Egress policy, adopted tasks get theirs applied
  again, and before the first command the runner checks that the worker
  reaches neither the API server nor a public address directly and that
  the proxy cannot reach the API server; setup fails otherwise. A scope
  change replaces the worker too, so the checks run in a worker no
  command has used.
- The proxy pod uses ndots 1, so scope names are not first looked up as
  cluster names.

Exec:
- The worker base env comes after the request env in the env(1) argv.
  Refusing PATH, proxy and loader variables (LD_*, BASH_ENV, ...) in a
  request is a separate change to the shared ValidateEnv, which also
  covers the Docker backend.
- Any exec error after the stream started (cancel, broken stream, read
  limit) kills the worker's processes, and so does a wrapper timeout
  (exit 124 after at least timeout_ms, the Docker rule).
- Exec, Kill and Delete validate the task ID; Exec validates the request.

Concurrency and cleanup:
- Kill takes the task lock; stored tasks are copied, never changed in
  place. A Kill caused by an exec acts only on the worker pod UID that
  ran it; pod deletes carry a UID precondition.
- An exec queued behind a Delete returns ErrNotFound instead of creating
  the task again. Per-task locks are reference counted and removed.
- A failed setup removes what it created, found by label (a foreign
  object with the same name stays). Delete returns ErrNotFound only when
  no object of the task exists.
- Recover adopts only pods named artex-w-/artex-p-<hash> and services
  with a real ClusterIP; adopted tasks are re-checked on first use.
- Scope hash: full SHA-256; task object names use 128 bits.

Config: http:// API servers are refused, the tasks and audit sub paths
must not be ".", equal or nested, and NewKubernetesBackend documents what
the deployment must provide (PID limits, restricted namespace, quotas,
shared volume, shared Kill).
@thecorporatetractor

thecorporatetractor commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the audit. All points are fixed in this PR except the env names, which need #895 (below). The main commit is 1c262d3: one squashed commit, so git diff 502e42d 1c262d3 shows the delta, and the commit message lists every change. d92a02f on top closes IPv4-mapped scope entries and adds 0.0.0.0/8, ::, ::ffff:0:0/96 and NAT64 link-local to the never-reachable list.

NetworkPolicies

  • Delete ordering: Delete deletes the pods, waits with deletePodAndWait until they are gone, then removes the Service and, last, the policies. A failed pod deletion keeps the policies and keeps the task tracked. Pods get a 1s grace instead of 0, because a zero grace removes the API object before the kubelet stops the containers. Test: TestKubeDeleteRemovesPoliciesOnlyAfterPodsAreGone.
  • 409 → PUT: applyPolicy GETs the existing policy, refuses one without our LabelManagedBy/LabelTaskHash, and sends its resourceVersion. The fake API now answers 422 without it. Test: TestKubeApplyPolicyUpdatesWithResourceVersionOnlyOwnPolicy.
  • Denied CIDRs: ARTEX_KUBE_PROXY_DENIED_CIDRS now adds to DefaultProxyDeniedCIDRs instead of replacing it. An empty DNSPodLabels falls back to k8s-app=kube-dns. Test: TestKubeDeniedCIDRsExtendDefaults.
  • External default-deny: isolation no longer depends on it.
    • Every task pod is selected by its own policy with Ingress and Egress.
    • Before the first command, the runner checks that the worker reaches neither the API server nor a public address directly, and that the proxy cannot reach the API server. Setup fails otherwise.
    • A scope change replaces the worker too. A worker re-adopted after a runner restart, or kept when only the proxy died, is re-checked in place.
    • Test: TestKubeIsolationProbesMustFailToConnect.

Exec environment

Errors and identifiers

  • API errors: kubeAPIError returns only the status code and a validated reason. The body is logged, cut to 512 bytes and never for exec.
  • Exec errors: dial and status errors are generic. pods/exec needs the command in the query string, so the URL is never put in an error or a log line.
  • Hashes: scopeHash is the full SHA-256. Task object names now use 128 bits.

Concurrency and cleanup

  • Kill race: Kill takes the task lock, and stored tasks are copied, never changed in place. A Kill caused by an exec acts only on the worker pod UID that ran the command, and the deletes Kill makes carry a UID precondition.
  • Exit 124: any exec error after the stream started (cancel, broken stream, read limit) runs the uid kill. So does a wrapper timeout, using the Docker rule: 124 after at least timeout_ms.
  • Failed setup: it removes what it created, found by label; a foreign object with the same name is left alone. Delete returns ErrNotFound only when no object of the task exists.
  • Locks: they are reference counted and removed. An exec queued behind a Delete returns ErrNotFound instead of recreating the task.

Kubernetes client (now kube_client.go)

  • SetReadLimit is 4 MiB.
  • The subprotocol must be v5.channel.k8s.io or v4.channel.k8s.io.
  • The v5 CLOSE channel is handled.
  • Redirects are refused.
  • Proxy URLs use net.JoinHostPort.
  • http:// API servers are refused unless a test-only field is set.
  • Test: TestKubeClientExecStream (an oversized frame fails without buffering it), plus the client tests for each of these.

PVC

  • The sub paths are cleaned, and may not be ., absolute, equal or nested.
  • Exec, Kill and Delete validate the task ID, and Exec validates the request.

Also fixed, from our own review

  • Cluster ranges: a task scope like 10.0.0.0/8 could open the cluster's pod and service networks. ARTEX_KUBE_CLUSTER_CIDRS, metadata, loopback, link-local and the API server address now form a list no scope can override. It is applied in the policy (except) and in the proxy (ARTEX_NEVER_CIDRS). Without the setting, scope CIDRs in private ranges are dropped. Test: TestKubeScopeCannotOpenClusterRanges.
  • Adoption after restart: Recover adopts only expected pod names and Services with a real ClusterIP.
  • Proxy DNS: the proxy pod uses ndots: 1.
  • Deployment requirements: the PID limit, the namespace and quotas are listed on NewKubernetesBackend and in the PR description.

Size

…tes scope

From a second review of the backend:
- Scope CIDRs written as IPv4-mapped IPv6 (::ffff:10.0.0.0/104) are read
  as the IPv4 range they map, so the private-range filter and the
  never-reachable excepts apply to them. netip treats the two families as
  distinct, so such an entry skipped both.
- The never-reachable list adds 0.0.0.0/8 and :: (they reach the proxy's
  own host), ::ffff:0:0/96 and link-local through NAT64
  (64:ff9b::a9fe:0/112).
- ARTEX_KUBE_CLUSTER_CIDRS and ARTEX_KUBE_PROXY_DENIED_CIDRS refuse /0
  (an except equal to its block is rejected by the API server) and
  IPv4-mapped prefixes (they would never match).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants