Repository navigation
feat(sandbox): Kubernetes backend for artex-runner - #780
thecorporatetractor wants to merge 2 commits into
Conversation
9dd0883 to
5fe94b6
Compare
|
@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:
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. |
|
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. |
5fe94b6 to
502e42d
Compare
|
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. |
There was a problem hiding this comment.
The audit on 502e42d fails on isolation and lifecycle. The pod security context and the shared PVC subPath checks pass; these are blocking.
NetworkPolicies
Deleteremoves 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 withdeletePodAndWait, and do not remove the policies when the pod deletion failed.applyPolicyPUTs on 409 withoutmetadata.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 checkingLabelManagedBy/LabelTaskHash, unlike the Service path at:903-905.ARTEX_KUBE_PROXY_DENIED_CIDRSreplacesDefaultProxyDeniedCIDRsinstead 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
DNSPodLabelsmap 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
kubeExecArgvappendsreq.EnvafterworkerBaseEnv(proxyIP)(:1140-1145);ValidateEnvdoes not refuseHTTP_PROXY,HTTPS_PROXY,ALL_PROXY,NO_PROXY,PATHorLD_PRELOAD, so a caller can override the proxy or preload a library ahead of artex-exec-wrap.
Errors and identifiers
kubeAPIErrorforwards up to 4 KiB of the raw API server body to the runner (:346-347,1065), andcontainerExecputsreq.Envandreq.Argvin the WebSocket query string and echoes the dial error (:1035,1067).scopeHashis truncated to 32 bits (:865).
Concurrency and cleanup
Killdoes not taketaskLockand readsb.tasks[taskID]andkt.workerPodoutside the mutex while another Kill writescur.workerPod(:1178-1202): a data race, and a Kill from an Exec cancellation can remove a worker just recreated byensureTask.- An exec timeout (exit 124) does not Kill the worker, unlike the Docker backend (
:1158-1172), so setsid and double-fork descendants survive. - If
waitPodReadyorwaitNetworkReadyfails after objects are created,ensureTaskleaves them orphaned andDeletereturns ErrNotFound (:881-945,1214-1216). b.locks[taskID]is never removed by Delete.
Kubernetes client
- No
SetReadLimiton 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.httpdoes not refuse redirects (:212). workerBaseEnvbuilds the proxy URL withfmt.Sprintfinstead ofnet.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
NewKubernetesBackenddoes not refuseTasksSubPath == AuditSubPathorTasksSubPath == "."(:167-171);ExecandDeletedo not revalidateValidateTaskIDoutside 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).
502e42d to
1c262d3
Compare
|
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 NetworkPolicies
Exec environment
Errors and identifiers
Concurrency and cleanup
Kubernetes client (now
PVC
Also fixed, from our own review
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).
Problem
artex-runneronly 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:
NetworkPolicyfor the worker: no ingress, egress only to the task's proxy on 3128/1080.NetworkPolicyfor the proxy: ingress only from the worker; egress to cluster DNS,0.0.0.0/0minus 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.artex-egress-proxy) with the task's domain/CIDR allowlist and its audit log on the data volume.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 onlytasks/<task>.Behaviour:
pods/execasenv -i -C <workdir> <base env> <request env> artex-exec-wrap <timeout> -- <argv>./procfor uid 10001; if that fails it deletes the worker pod and keeps the workspace.artex.taskannotation hashes to theartex.task_hashlabel.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 requiresresourceVersionon 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:resourceVersionand the label check;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
PATH, proxy and loader variables in exec requests; it also fixes the Docker backend). Please merge it first.NewKubernetesBackend:podPidsLimit, since the pod API has no per-pod PID limit;restricted;ARTEX_KUBE_CLUSTER_CIDRSset to the pod, service and node CIDRs. Without it, scope CIDRs in private ranges are dropped.--pod-max-pidson the kubelet.Part of #781.