diff --git a/CHANGELOG.md b/CHANGELOG.md index fba02828..bd283bde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ All notable changes to this project are documented in this file. The format is b ### Added +- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. No scope opens the cluster's own ranges, the API server or cloud metadata: set `ARTEX_KUBE_CLUSTER_CIDRS` to the pod, service and node CIDRs, plus the API server endpoint addresses when they lie outside them as on managed clusters (without it, private scope CIDRs are dropped). The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart. - **Slack notification channel**: System → Notifications can push findings to Slack by pasting an Incoming Webhook URL; each URL posts to the channel, or the installer's own direct messages, chosen when it was created in Slack. Only `https://hooks.slack.com/services/…` (and the GovSlack host) is accepted, and the URL is stored sealed and masked like other channel credentials. Finding text is escaped (`&`, `<`, `>`) so it cannot mention `@channel` or hide a link, digests are packed under 3,900 characters and link unfurling is off. The form explains the Slack setup steps in every console language. - **The task target gate has a UI.** `target_gate` was API-only (`POST /api/tasks`, `PATCH /api/tasks/{id}`), so an operator could neither see nor change it: a task-level block rule added to a task whose gate was off never reached a network target, because `CheckTargets` returns before any rule is matched. The create-task sheet now carries a `Network target gate` selector (auto / on / off; auto leaves the backend default of on for scoped tasks) and warns when block rules would be stored unenforced, and the task overview's task-level rule card carries a switch with the live state, an explicit warning while enabled block rules exist with the gate off, and a retry when the state cannot be read. The switch writes through `PATCH /api/tasks/{id}` and takes effect on the next tool call. The gate governs the targets a tool call declares, not a sandboxed worker's sockets (the sandbox egress list decides those), turning it on also attaches the panel-hosted shared browser in sandbox mode, an unpinned target waits out the 300 s bound before the call is refused, task allow rules do not affect the gate, and each flip is recorded in the task's activity history with the operator, the client address, and the previous and new setting; the chat side's `target_gate` still has no UI. diff --git a/cmd/artex-egress-proxy/main.go b/cmd/artex-egress-proxy/main.go index e0f45555..c95e4e68 100644 --- a/cmd/artex-egress-proxy/main.go +++ b/cmd/artex-egress-proxy/main.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "net/netip" "os" "os/signal" "strconv" @@ -40,6 +41,15 @@ func main() { if err != nil { log.Fatalf("[egress-proxy] invalid scope policy: %v", err) } + // Ranges no scope may open (set by the Kubernetes backend: cluster networks, + // API server, metadata). + for _, c := range sandbox.ParseCSV(os.Getenv("ARTEX_NEVER_CIDRS")) { + pfx, err := netip.ParsePrefix(c) + if err != nil { + log.Fatalf("[egress-proxy] invalid ARTEX_NEVER_CIDRS entry %q: %v", c, err) + } + policy.Never = append(policy.Never, pfx.Masked()) + } proxy := sandbox.NewEgressProxy(policy) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go index 83031312..9f3a77ad 100644 --- a/cmd/artex-runner/main.go +++ b/cmd/artex-runner/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "log" "net/http" "os" @@ -22,33 +23,61 @@ func envOr(k, def string) string { return def } +// buildBackend selects the container backend from ARTEX_RUNNER_BACKEND +// ("docker", the default, or "kubernetes"). +func buildBackend() (sandbox.Backend, error) { + wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) + auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) + workerImage := envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage) + proxyImage := envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage) + + switch kind := strings.ToLower(envOr(sandbox.EnvRunnerBackend, sandbox.BackendDocker)); kind { + case sandbox.BackendDocker: + sock := envOr("DOCKER_SOCK", "/var/run/docker.sock") + if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") { + sock = strings.TrimPrefix(dh, "unix://") + } + log.Printf("[runner] backend=docker socket=%s", sock) + return sandbox.NewDockerBackend(sandbox.DockerConfig{ + SocketPath: sock, + WorkerImage: workerImage, + ProxyImage: proxyImage, + WorkspaceRoot: wsRoot, + HostWorkspaceRoot: envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot), + AuditRoot: auditRoot, + HostAuditRoot: envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot), + TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix), + EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet), + }), nil + case sandbox.BackendKubernetes: + cfg, err := sandbox.KubeConfigFromEnv() + if err != nil { + return nil, err + } + cfg.WorkerImage, cfg.ProxyImage = workerImage, proxyImage + cfg.WorkspaceRoot, cfg.AuditRoot = wsRoot, auditRoot + b, err := sandbox.NewKubernetesBackend(cfg) + if err != nil { + return nil, err + } + log.Printf("[runner] backend=kubernetes namespace=%s claim=%s", b.Namespace(), cfg.DataClaim) + return b, nil + default: + return nil, fmt.Errorf("invalid %s=%q (want %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes) + } +} + func main() { token := strings.TrimSpace(os.Getenv(sandbox.EnvRunnerToken)) if token == "" { log.Fatalf("[runner] %s is required (refusing to start unauthenticated)", sandbox.EnvRunnerToken) } addr := envOr("ARTEX_RUNNER_ADDR", sandbox.DefaultRunnerAddr) - sock := envOr("DOCKER_SOCK", "/var/run/docker.sock") - if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") { - sock = strings.TrimPrefix(dh, "unix://") + backend, err := buildBackend() + if err != nil { + log.Fatalf("[runner] %v", err) } - wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) - hostWSRoot := envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot) - auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) - hostAuditRoot := envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot) - backend := sandbox.NewDockerBackend(sandbox.DockerConfig{ - SocketPath: sock, - WorkerImage: envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage), - ProxyImage: envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage), - WorkspaceRoot: wsRoot, - HostWorkspaceRoot: hostWSRoot, - AuditRoot: auditRoot, - HostAuditRoot: hostAuditRoot, - TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix), - EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet), - }) - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/sandbox/kube.go b/sandbox/kube.go new file mode 100644 index 00000000..2f344d03 --- /dev/null +++ b/sandbox/kube.go @@ -0,0 +1,1331 @@ +package sandbox + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "log" + "net" + "net/http" + "net/netip" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// Kubernetes-specific labels and annotations. Task IDs may contain characters or +// lengths that Kubernetes names and label values reject, so objects are keyed by a +// short hash of the task ID (LabelTaskHash) and carry the real ID in an annotation. +const ( + LabelTaskHash = "artex.task_hash" + AnnotationTaskID = "artex.task" + AnnotationScope = "artex.scope_hash" + kubeSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" + kubeSACAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" + kubeSANSPath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" + kubeDefaultTimeout = 2 * time.Minute +) + +// KubeConfig configures the KubernetesBackend for artex-runner. +type KubeConfig struct { + APIServer string // default https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT + TokenPath string // default service-account token path (re-read on every request: bound tokens rotate) + CAPath string // default service-account CA path + Namespace string // default: the runner's own namespace + + WorkerImage string + ProxyImage string + ImagePullPolicy string // IfNotPresent by default + RuntimeClassName string // optional, e.g. gvisor or kata + ServiceAccount string // service account for worker/proxy pods (token is never mounted) + + // DataClaim is the PersistentVolumeClaim shared with the panel and the runner. + // Workers mount / at /workspace; proxies mount + // / at /audit. + DataClaim string + TasksSubPath string // default "tasks" + AuditSubPath string // default "egress-audit" + + // WorkspaceRoot and AuditRoot are where the runner itself mounts the same two + // directories, so it can create and chown per-task directories before a pod + // mounts them (kubelet would otherwise create them root:root 0755). + WorkspaceRoot string + AuditRoot string + + // ProxyDeniedCIDRs are added to DefaultProxyDeniedCIDRs, the egress "except" + // list on the proxy's per-task NetworkPolicy (defence in depth below the proxy's + // own allowlist). Scope CIDRs of the task are added back as explicit allow rules. + ProxyDeniedCIDRs []string + // DNSNamespace/DNSPodLabels select the cluster DNS pods the proxy may query. + // Empty labels fall back to k8s-app=kube-dns (never every pod in the namespace). + DNSNamespace string + DNSPodLabels map[string]string + // ClusterCIDRs are the cluster's pod, service and node CIDRs. No task scope + // can open them (NetworkPolicy except + proxy deny). Without them, scope + // CIDRs that overlap private, loopback or link-local ranges are refused. + // Where the API server endpoints (default/kubernetes) lie outside them, as + // on managed clusters, list their addresses too: only the Service IP is added. + ClusterCIDRs []string + + PodReadyTimeout time.Duration + + // PinNode, when set, schedules task pods onto that node (nodeAffinity on + // metadata.name). Needed when DataClaim is ReadWriteOnce: every pod mounting it + // must share a node. + PinNode string + + // Worker resources; defaults mirror DockerBackend (2 CPU, 2Gi). + WorkerCPULimit string + WorkerMemoryLimit string + + // allowPlainHTTP lets tests use an http:// fake API server. Never set in + // production: the service-account token would travel in clear. + allowPlainHTTP bool +} + +// kubeTask is never modified once stored in KubernetesBackend.tasks: updates +// store a new copy under mu, so readers holding a pointer never race. +type kubeTask struct { + taskID string + hash string + scopeHash string + workerPod string // pod names are unique per generation (kubePodName) + workerUID string + proxyPod string + proxyUID string + proxyIP string // ClusterIP of the per-task proxy Service + // verified is set once this process has applied the task's policies and + // probed its network; adopted tasks (Recover) are re-checked on first use. + verified bool +} + +type kubeTaskLock struct { + sync.Mutex + refs int + deletes int // Deletes done under this lock, so a queued exec does not resurrect the task +} + +// KubernetesBackend implements Backend by creating per-task worker and egress-proxy +// pods through the Kubernetes API. It needs no container runtime socket: isolation +// comes from pod security settings and per-task NetworkPolicies. +type KubernetesBackend struct { + *kubeClient + cfg KubeConfig + mu sync.Mutex + tasks map[string]*kubeTask + // locks serialises ensureTask, Kill and Delete per task so they never race to + // delete and recreate each other's pods. Entries are reference counted and + // removed when unused. + locks map[string]*kubeTaskLock + // never: prefixes no task scope may open (kubeNeverCIDRs, ClusterCIDRs, API server). + never []netip.Prefix +} + +// DefaultProxyDeniedCIDRs mirrors the proxy's default-denied IPv4 prefixes that a +// NetworkPolicy ipBlock can express inside 0.0.0.0/0. +var DefaultProxyDeniedCIDRs = []string{ + "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "100.100.100.200/32", "127.0.0.0/8", + "168.63.129.16/32", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", + "224.0.0.0/4", "240.0.0.0/4", +} + +// kubeNeverCIDRs are never reachable through a task's proxy, whatever its scope. +// It includes the unspecified addresses (0.0.0.0/8, ::), which reach the proxy's +// own host, IPv4-mapped IPv6, and link-local reached through NAT64. +var kubeNeverCIDRs = []string{"0.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "168.63.129.16/32", "100.100.100.200/32", + "::/128", "::1/128", "::ffff:0:0/96", "fe80::/10", "fd00:ec2::254/128", "fd20:ce::254/128", "64:ff9b::a9fe:0/112"} + +// kubeProbePublicAddr is dialled from the worker to prove it has no direct egress. +// A deny probe passes only when it prints kubeProbeBlocked. +const ( + kubeProbePublicAddr = "1.1.1.1/443" + kubeProbeBlocked = "artex-probe:blocked" +) + +// NewKubernetesBackend builds a backend from cfg, filling defaults from the +// in-cluster environment. +// +// Deployment requirements the runner cannot enforce through the pod API: +// - kubelet podPidsLimit: pods have no per-pod PID limit field, so a fork bomb +// in a worker is bounded only by the node setting. +// - a dedicated task namespace with Pod Security Admission "restricted". +// - ResourceQuota/LimitRange and a cap on concurrent tasks for that namespace. +// - /tmp in the worker is a memory emptyDir without noexec. +// - the shared data volume has no per-task quota: one task can fill it. +// - commands of one task run concurrently in one worker and share Kill. +func NewKubernetesBackend(cfg KubeConfig) (*KubernetesBackend, error) { + if cfg.APIServer == "" { + host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") + if host == "" || port == "" { + return nil, errors.New("kubernetes backend: KUBERNETES_SERVICE_HOST/PORT unset and no API server configured") + } + cfg.APIServer = "https://" + net.JoinHostPort(host, port) + } + cfg.APIServer = strings.TrimRight(cfg.APIServer, "/") + if cfg.TokenPath == "" { + cfg.TokenPath = kubeSATokenPath + } + if cfg.CAPath == "" { + cfg.CAPath = kubeSACAPath + } + if cfg.Namespace == "" { + raw, err := os.ReadFile(kubeSANSPath) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: namespace not set and %s unreadable: %w", kubeSANSPath, err) + } + cfg.Namespace = strings.TrimSpace(string(raw)) + } + if cfg.WorkerImage == "" { + cfg.WorkerImage = DefaultWorkerImage + } + if cfg.ProxyImage == "" { + cfg.ProxyImage = DefaultProxyImage + } + if cfg.ImagePullPolicy == "" { + cfg.ImagePullPolicy = "IfNotPresent" + } + if cfg.DataClaim == "" { + return nil, errors.New("kubernetes backend: data PersistentVolumeClaim name is required") + } + if cfg.TasksSubPath == "" { + cfg.TasksSubPath = "tasks" + } + if cfg.AuditSubPath == "" { + cfg.AuditSubPath = "egress-audit" + } + // Workers mount /, proxies /: the two trees must be + // distinct and not nested, or a task ID could name the other tree. + sub := []string{path.Clean(cfg.TasksSubPath), path.Clean(cfg.AuditSubPath)} + for _, p := range sub { + if path.IsAbs(p) || p == "." || p == ".." || strings.HasPrefix(p, "../") { + return nil, fmt.Errorf("kubernetes backend: sub path %q must be a relative directory without ..", p) + } + } + if strings.HasPrefix(sub[0]+"/", sub[1]+"/") || strings.HasPrefix(sub[1]+"/", sub[0]+"/") { + return nil, fmt.Errorf("kubernetes backend: tasks sub path %q and audit sub path %q overlap", sub[0], sub[1]) + } + cfg.TasksSubPath, cfg.AuditSubPath = sub[0], sub[1] + if cfg.WorkspaceRoot == "" { + cfg.WorkspaceRoot = DefaultWorkspaceRoot + } + if cfg.AuditRoot == "" { + cfg.AuditRoot = DefaultAuditRoot + } + never := mustParsePrefixes(kubeNeverCIDRs) + for _, c := range cfg.ClusterCIDRs { + p, err := configPrefix(c) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: cluster CIDR %q: %v", c, err) + } + never = append(never, p.Masked()) + } + apiURL, err := url.Parse(cfg.APIServer) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: API server %q: %v", cfg.APIServer, err) + } + for _, h := range []string{os.Getenv("KUBERNETES_SERVICE_HOST"), apiURL.Hostname()} { + if a, err := netip.ParseAddr(h); err == nil && !slices.ContainsFunc(never, func(p netip.Prefix) bool { return p.Contains(a.Unmap()) }) { + never = append(never, netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())) + } + } + // The proxy's public rule excepts the defaults, the configured extras and the + // IPv4 never-reachable ranges, skipping any already covered. + extra := slices.Clone(never) + for _, c := range cfg.ProxyDeniedCIDRs { + p, err := configPrefix(c) + if err != nil || !p.Addr().Is4() { + return nil, fmt.Errorf("kubernetes backend: denied CIDR %q is not an IPv4 CIDR", c) + } + extra = append(extra, p.Masked()) + } + denied := mustParsePrefixes(DefaultProxyDeniedCIDRs) + for _, p := range extra { + if p.Addr().Is4() && !slices.ContainsFunc(denied, func(d netip.Prefix) bool { return d.Bits() <= p.Bits() && d.Contains(p.Addr()) }) { + denied = append(denied, p) + } + } + cfg.ProxyDeniedCIDRs = nil + for _, p := range denied { + cfg.ProxyDeniedCIDRs = append(cfg.ProxyDeniedCIDRs, p.String()) + } + if cfg.DNSNamespace == "" { + cfg.DNSNamespace = "kube-system" + } + if len(cfg.DNSPodLabels) == 0 { + cfg.DNSPodLabels = map[string]string{"k8s-app": "kube-dns"} + } + if cfg.WorkerCPULimit == "" { + cfg.WorkerCPULimit = "2" + } + if cfg.WorkerMemoryLimit == "" { + cfg.WorkerMemoryLimit = "2Gi" + } + if cfg.PodReadyTimeout <= 0 { + cfg.PodReadyTimeout = kubeDefaultTimeout + } + + client, err := newKubeClient(cfg.APIServer, cfg.TokenPath, cfg.CAPath, cfg.Namespace, cfg.allowPlainHTTP) + if err != nil { + return nil, err + } + return &KubernetesBackend{ + kubeClient: client, + cfg: cfg, + tasks: map[string]*kubeTask{}, + locks: map[string]*kubeTaskLock{}, + never: never, + }, nil +} + +// Namespace returns the namespace task pods are created in. +func (b *KubernetesBackend) Namespace() string { return b.cfg.Namespace } + +// KubeConfigFromEnv reads the Kubernetes backend settings: +// +// ARTEX_KUBE_NAMESPACE namespace for task pods (default: the runner's own) +// ARTEX_KUBE_DATA_CLAIM shared data PersistentVolumeClaim (required) +// ARTEX_KUBE_TASKS_SUBPATH default "tasks" +// ARTEX_KUBE_AUDIT_SUBPATH default "egress-audit" +// ARTEX_KUBE_IMAGE_PULL_POLICY default IfNotPresent +// ARTEX_KUBE_RUNTIME_CLASS optional RuntimeClass (gvisor, kata, ...) +// ARTEX_KUBE_SERVICE_ACCOUNT service account for task pods (token never mounted) +// ARTEX_KUBE_PROXY_DENIED_CIDRS comma list added to DefaultProxyDeniedCIDRs +// ARTEX_KUBE_CLUSTER_CIDRS pod, service and node CIDRs no scope may open, and +// the API server endpoint addresses when outside them +// ARTEX_KUBE_DNS_NAMESPACE default kube-system +// ARTEX_KUBE_DNS_LABELS comma list of k=v; default k8s-app=kube-dns +// ARTEX_KUBE_POD_READY_TIMEOUT Go duration; default 2m +// ARTEX_KUBE_PIN_NODE node name task pods must run on (ReadWriteOnce data volume) +// ARTEX_KUBE_WORKER_CPU_LIMIT default "2" +// ARTEX_KUBE_WORKER_MEMORY_LIMIT default "2Gi" +func KubeConfigFromEnv() (KubeConfig, error) { + get := func(k string) string { return strings.TrimSpace(os.Getenv(k)) } + cfg := KubeConfig{ + Namespace: get("ARTEX_KUBE_NAMESPACE"), + DataClaim: get("ARTEX_KUBE_DATA_CLAIM"), + TasksSubPath: get("ARTEX_KUBE_TASKS_SUBPATH"), + AuditSubPath: get("ARTEX_KUBE_AUDIT_SUBPATH"), + ImagePullPolicy: get("ARTEX_KUBE_IMAGE_PULL_POLICY"), + RuntimeClassName: get("ARTEX_KUBE_RUNTIME_CLASS"), + ServiceAccount: get("ARTEX_KUBE_SERVICE_ACCOUNT"), + DNSNamespace: get("ARTEX_KUBE_DNS_NAMESPACE"), + PinNode: get("ARTEX_KUBE_PIN_NODE"), + ClusterCIDRs: ParseCSV(get("ARTEX_KUBE_CLUSTER_CIDRS")), + + WorkerCPULimit: get("ARTEX_KUBE_WORKER_CPU_LIMIT"), + WorkerMemoryLimit: get("ARTEX_KUBE_WORKER_MEMORY_LIMIT"), + } + if v := get("ARTEX_KUBE_PROXY_DENIED_CIDRS"); v != "" { + for _, c := range ParseCSV(v) { + p, err := netip.ParsePrefix(c) + if err != nil || !p.Addr().Is4() { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_PROXY_DENIED_CIDRS: %q is not an IPv4 CIDR", c) + } + cfg.ProxyDeniedCIDRs = append(cfg.ProxyDeniedCIDRs, p.Masked().String()) + } + } + if v := get("ARTEX_KUBE_DNS_LABELS"); v != "" { + cfg.DNSPodLabels = map[string]string{} + for _, kv := range ParseCSV(v) { + k, val, ok := strings.Cut(kv, "=") + if !ok || k == "" { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_DNS_LABELS: %q is not key=value", kv) + } + cfg.DNSPodLabels[k] = val + } + } + if v := get("ARTEX_KUBE_POD_READY_TIMEOUT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d <= 0 { + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_POD_READY_TIMEOUT: %q is not a positive duration", v) + } + cfg.PodReadyTimeout = d + } + switch cfg.ImagePullPolicy { + case "", "Always", "IfNotPresent", "Never": + default: + return KubeConfig{}, fmt.Errorf("ARTEX_KUBE_IMAGE_PULL_POLICY: %q (want Always, IfNotPresent or Never)", cfg.ImagePullPolicy) + } + return cfg, nil +} + +func sha256Hex(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +// kubeTaskHash keys a task's objects: 128 bits, short enough for names and labels. +func kubeTaskHash(taskID string) string { return sha256Hex(taskID)[:32] } + +// kubeTaskID validates a task ID as given: ValidateTaskID trims, but here the +// raw ID names directories and annotations. +func kubeTaskID(id string) error { + if id != strings.TrimSpace(id) { + return fmt.Errorf("%w: task id has surrounding whitespace", ErrBadRequest) + } + return ValidateTaskID(id) +} + +// kubePodNameRE matches task pod names: artex---. +var kubePodNameRE = regexp.MustCompile(`^artex-([wp])-([0-9a-f]{32})-[0-9a-f]{6}$`) + +// kubePodName returns a new pod name for the task, never old. Each pod gets a +// fresh name, so an exec still on its way to a replaced pod fails (404) instead +// of landing in its replacement before that one is verified. +func kubePodName(prefix, hash, old string) string { + for { + var r [3]byte + _, _ = rand.Read(r[:]) + if n := prefix + hash + "-" + hex.EncodeToString(r[:]); n != old { + return n + } + } +} + +func taskSelector(hash string) string { + return "?labelSelector=" + url.QueryEscape(LabelManagedBy+"="+ManagedByRunner+","+LabelTaskHash+"="+hash) +} + +// owned reports whether an object carries the runner's labels for this task. +func owned(m kubeObjectMeta, hash string) bool { + return m.Labels[LabelManagedBy] == ManagedByRunner && m.Labels[LabelTaskHash] == hash +} + +// Ping verifies the API server is reachable and the runner may list pods. +func (b *KubernetesBackend) Ping(ctx context.Context) error { + err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"?limit=1&labelSelector="+url.QueryEscape(LabelManagedBy+"="+ManagedByRunner), nil, nil) + if err != nil && !errors.Is(err, ErrDockerUnavailable) { + return fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + return err +} + +// WorkerCount returns the number of tracked tasks. +func (b *KubernetesBackend) WorkerCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return len(b.tasks) +} + +// Recover rebuilds task state from pods carrying artex.managed_by=artex-runner. +// Only pods named by kubePodName, a valid task annotation whose hash matches +// their label, and services with a real ClusterIP are adopted. Adopted tasks are +// unverified: their first exec re-applies the policies and re-runs the probes. +func (b *KubernetesBackend) Recover(ctx context.Context) (int, error) { + var list struct { + Items []kubePod `json:"items"` + } + sel := url.QueryEscape(LabelManagedBy + "=" + ManagedByRunner) + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"?labelSelector="+sel, nil, &list); err != nil { + return 0, err + } + var svcs struct { + Items []struct { + Metadata kubeObjectMeta `json:"metadata"` + Spec struct { + ClusterIP string `json:"clusterIP"` + } `json:"spec"` + } `json:"items"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("services")+"?labelSelector="+sel, nil, &svcs); err != nil { + return 0, err + } + svcIP := map[string]string{} + for _, s := range svcs.Items { + if h := s.Metadata.Labels[LabelTaskHash]; s.Metadata.Name == "artex-p-"+h && net.ParseIP(s.Spec.ClusterIP) != nil { + svcIP[h] = s.Spec.ClusterIP + } + } + b.mu.Lock() + defer b.mu.Unlock() + for _, p := range list.Items { + if p.Metadata.Deletion != nil || p.Metadata.Labels[LabelManagedBy] != ManagedByRunner { + continue + } + tid := p.Metadata.Annotations[AnnotationTaskID] + m := kubePodNameRE.FindStringSubmatch(p.Metadata.Name) + if kubeTaskID(tid) != nil || kubeTaskHash(tid) != p.Metadata.Labels[LabelTaskHash] || m == nil || m[2] != kubeTaskHash(tid) || + map[string]string{"w": ComponentWorker, "p": ComponentProxy}[m[1]] != p.Metadata.Labels[LabelComponent] { + continue + } + kt := &kubeTask{taskID: tid, hash: kubeTaskHash(tid), proxyIP: svcIP[kubeTaskHash(tid)]} + if cur := b.tasks[tid]; cur != nil { + cp := *cur + kt = &cp + } + b.tasks[tid] = kt + switch p.Metadata.Labels[LabelComponent] { + case ComponentWorker: + kt.workerPod, kt.workerUID = p.Metadata.Name, p.Metadata.UID + case ComponentProxy: + kt.proxyPod, kt.proxyUID = p.Metadata.Name, p.Metadata.UID + kt.scopeHash = p.Metadata.Annotations[AnnotationScope] + } + } + return len(b.tasks), nil +} + +func (b *KubernetesBackend) taskLabels(kt *kubeTask, component string) map[string]string { + return map[string]string{ + LabelManagedBy: ManagedByRunner, + LabelTaskHash: kt.hash, + LabelComponent: component, + } +} + +func (b *KubernetesBackend) meta(name string, kt *kubeTask, component string, extra map[string]string) map[string]any { + ann := map[string]string{AnnotationTaskID: kt.taskID} + for k, v := range extra { + ann[k] = v + } + m := map[string]any{"name": name, "annotations": ann} + labels := map[string]string{LabelManagedBy: ManagedByRunner, LabelTaskHash: kt.hash} + if component != "" { + labels[LabelComponent] = component + } + m["labels"] = labels + return m +} + +// prepareDirs creates the per-task workspace and audit directories owned by the +// worker uid, mirroring DockerBackend (best effort: the runner may lack CAP_CHOWN +// when the volume is already owned by 10001). +func (b *KubernetesBackend) prepareDirs(taskID string) { + for _, dir := range []string{filepath.Join(b.cfg.WorkspaceRoot, taskID), filepath.Join(b.cfg.AuditRoot, taskID)} { + if err := os.MkdirAll(dir, 0o775); err != nil { + log.Printf("[runner] mkdir %s: %v", dir, err) + continue + } + _ = os.Chown(dir, WorkerUID, WorkerGID) + } +} + +func (b *KubernetesBackend) podSecurity() (map[string]any, map[string]any) { + pod := map[string]any{ + "runAsUser": WorkerUID, + "runAsGroup": WorkerGID, + "runAsNonRoot": true, + "seccompProfile": map[string]any{ + "type": "RuntimeDefault", + }, + } + ctr := map[string]any{ + "allowPrivilegeEscalation": false, + "readOnlyRootFilesystem": true, + "privileged": false, + "capabilities": map[string]any{"drop": []string{"ALL"}}, + } + return pod, ctr +} + +func (b *KubernetesBackend) basePodSpec() map[string]any { + podSec, _ := b.podSecurity() + spec := map[string]any{ + "restartPolicy": "Always", + "automountServiceAccountToken": false, + "enableServiceLinks": false, + "hostNetwork": false, + "hostPID": false, + "hostIPC": false, + "shareProcessNamespace": false, + "terminationGracePeriodSeconds": 5, + "securityContext": podSec, + } + if b.cfg.ServiceAccount != "" { + spec["serviceAccountName"] = b.cfg.ServiceAccount + } + if b.cfg.RuntimeClassName != "" { + spec["runtimeClassName"] = b.cfg.RuntimeClassName + } + if b.cfg.PinNode != "" { + spec["affinity"] = map[string]any{"nodeAffinity": map[string]any{ + "requiredDuringSchedulingIgnoredDuringExecution": map[string]any{ + "nodeSelectorTerms": []any{map[string]any{"matchFields": []any{map[string]any{ + "key": "metadata.name", "operator": "In", "values": []string{b.cfg.PinNode}, + }}}}, + }, + }} + } + return spec +} + +func (b *KubernetesBackend) neverList() string { + out := make([]string, len(b.never)) + for i, p := range b.never { + out[i] = p.String() + } + return strings.Join(out, ",") +} + +func (b *KubernetesBackend) proxyPodObj(name string, kt *kubeTask, scopeDomains, scopeCIDRs []string) map[string]any { + _, ctrSec := b.podSecurity() + spec := b.basePodSpec() + // ndots 1: scope names are looked up as given, not first as *.svc.cluster.local. + spec["dnsConfig"] = map[string]any{"options": []any{map[string]any{"name": "ndots", "value": "1"}}} + spec["containers"] = []any{map[string]any{ + "name": kubeProxyName, + "image": b.cfg.ProxyImage, + "imagePullPolicy": b.cfg.ImagePullPolicy, + "env": []any{ + map[string]any{"name": "ARTEX_TASK_ID", "value": kt.taskID}, + map[string]any{"name": "ARTEX_SCOPE_DOMAINS", "value": strings.Join(scopeDomains, ",")}, + map[string]any{"name": "ARTEX_SCOPE_CIDRS", "value": strings.Join(scopeCIDRs, ",")}, + map[string]any{"name": "ARTEX_PROXY_PORT", "value": strconv.Itoa(DefaultProxyPort)}, + map[string]any{"name": "ARTEX_SOCKS_PORT", "value": strconv.Itoa(DefaultSocksPort)}, + map[string]any{"name": "ARTEX_EGRESS_LOG_PATH", "value": "/audit/egress.jsonl"}, + map[string]any{"name": "ARTEX_NEVER_CIDRS", "value": b.neverList()}, + }, + "ports": []any{ + map[string]any{"name": "http-proxy", "containerPort": DefaultProxyPort, "protocol": "TCP"}, + map[string]any{"name": "socks", "containerPort": DefaultSocksPort, "protocol": "TCP"}, + }, + "readinessProbe": map[string]any{ + "tcpSocket": map[string]any{"port": DefaultProxyPort}, + "periodSeconds": 2, + }, + "securityContext": ctrSec, + "resources": map[string]any{ + "requests": map[string]string{"cpu": "50m", "memory": "32Mi"}, + "limits": map[string]string{"cpu": "500m", "memory": "256Mi"}, + }, + "volumeMounts": []any{map[string]any{ + "name": "data", "mountPath": "/audit", "subPath": path.Join(b.cfg.AuditSubPath, kt.taskID), + }}, + }} + spec["volumes"] = []any{map[string]any{ + "name": "data", "persistentVolumeClaim": map[string]any{"claimName": b.cfg.DataClaim}, + }} + return map[string]any{ + "apiVersion": "v1", + "kind": "Pod", + "metadata": b.meta(name, kt, ComponentProxy, map[string]string{AnnotationScope: kt.scopeHash}), + "spec": spec, + } +} + +// workerBaseEnv is the environment every worker command runs with, matching the +// DockerBackend worker container. +func workerBaseEnv(proxyIP string) [][2]string { + proxyURL := "http://" + net.JoinHostPort(proxyIP, strconv.Itoa(DefaultProxyPort)) + socksURL := "socks5h://" + net.JoinHostPort(proxyIP, strconv.Itoa(DefaultSocksPort)) + return [][2]string{ + {"PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, + {"HOME", "/home/exec"}, {"LANG", "C.UTF-8"}, {"TERM", "xterm"}, + {"HTTP_PROXY", proxyURL}, {"HTTPS_PROXY", proxyURL}, {"ALL_PROXY", socksURL}, {"NO_PROXY", "localhost,127.0.0.1"}, + {"http_proxy", proxyURL}, {"https_proxy", proxyURL}, {"all_proxy", socksURL}, {"no_proxy", "localhost,127.0.0.1"}, + } +} + +func (b *KubernetesBackend) workerPodObj(name string, kt *kubeTask) map[string]any { + _, ctrSec := b.podSecurity() + env := []any{} + for _, kv := range workerBaseEnv(kt.proxyIP) { + env = append(env, map[string]any{"name": kv[0], "value": kv[1]}) + } + spec := b.basePodSpec() + // The worker never talks to cluster DNS (its NetworkPolicy only reaches the + // proxy ClusterIP); a resolver pointing nowhere keeps lookups from leaking. + spec["dnsPolicy"] = "None" + spec["dnsConfig"] = map[string]any{"nameservers": []string{"127.0.0.1"}} + spec["containers"] = []any{map[string]any{ + "name": kubeWorkerName, + "image": b.cfg.WorkerImage, + "imagePullPolicy": b.cfg.ImagePullPolicy, + "command": []string{"/usr/local/bin/artex-exec-wrap", "--init"}, + "workingDir": "/workspace", + "env": env, + "securityContext": ctrSec, + "resources": map[string]any{ + "requests": map[string]string{"cpu": "100m", "memory": "128Mi"}, + "limits": map[string]string{"cpu": b.cfg.WorkerCPULimit, "memory": b.cfg.WorkerMemoryLimit, "ephemeral-storage": "1Gi"}, + }, + "volumeMounts": []any{ + map[string]any{"name": "data", "mountPath": "/workspace", "subPath": path.Join(b.cfg.TasksSubPath, kt.taskID)}, + map[string]any{"name": "tmp", "mountPath": "/tmp"}, + map[string]any{"name": "home", "mountPath": "/home/exec"}, + }, + }} + spec["volumes"] = []any{ + map[string]any{"name": "data", "persistentVolumeClaim": map[string]any{"claimName": b.cfg.DataClaim}}, + map[string]any{"name": "tmp", "emptyDir": map[string]any{"medium": "Memory", "sizeLimit": "512Mi"}}, + map[string]any{"name": "home", "emptyDir": map[string]any{"medium": "Memory", "sizeLimit": "128Mi"}}, + } + return map[string]any{ + "apiVersion": "v1", + "kind": "Pod", + "metadata": b.meta(name, kt, ComponentWorker, nil), + "spec": spec, + } +} + +func (b *KubernetesBackend) proxyServiceObj(name string, kt *kubeTask) map[string]any { + return map[string]any{ + "apiVersion": "v1", + "kind": "Service", + "metadata": b.meta(name, kt, ComponentProxy, nil), + "spec": map[string]any{ + "type": "ClusterIP", + "selector": b.taskLabels(kt, ComponentProxy), + "ports": []any{ + map[string]any{"name": "http-proxy", "port": DefaultProxyPort, "targetPort": DefaultProxyPort, "protocol": "TCP"}, + map[string]any{"name": "socks", "port": DefaultSocksPort, "targetPort": DefaultSocksPort, "protocol": "TCP"}, + }, + }, + } +} + +func proxyPorts() []any { + return []any{ + map[string]any{"protocol": "TCP", "port": DefaultProxyPort}, + map[string]any{"protocol": "TCP", "port": DefaultSocksPort}, + } +} + +// Isolation does not depend on any NetworkPolicy outside this file. Each task pod +// is selected by its own per-task policy covering both Ingress and Egress, so +// everything not listed is denied for it. The runner creates both policies +// before any pod, removes them only once the pods are gone (Delete, +// cleanupTask), re-applies them for adopted tasks, and waitNetworkReady proves +// the worker's egress deny is in effect before the first command runs. A +// namespace default-deny (the Helm chart ships one) is extra defence in depth. +// +// workerPolicyObj lets the task's worker reach only its own proxy. +func (b *KubernetesBackend) workerPolicyObj(name string, kt *kubeTask) map[string]any { + return map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": b.meta(name, kt, ComponentWorker, nil), + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentWorker)}, + "policyTypes": []string{"Ingress", "Egress"}, + "ingress": []any{}, + "egress": []any{map[string]any{ + "to": []any{map[string]any{"podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentProxy)}}}, + "ports": proxyPorts(), + }}, + }, + } +} + +// proxyPolicyObj admits only the task's worker and lets the proxy reach cluster DNS, +// public addresses, and the task's scope CIDRs. +func (b *KubernetesBackend) proxyPolicyObj(name string, kt *kubeTask, scopeCIDRs []string) map[string]any { + egress := []any{ + map[string]any{ + "to": []any{map[string]any{ + "namespaceSelector": map[string]any{"matchLabels": map[string]string{"kubernetes.io/metadata.name": b.cfg.DNSNamespace}}, + "podSelector": map[string]any{"matchLabels": b.cfg.DNSPodLabels}, + }}, + "ports": []any{ + map[string]any{"protocol": "UDP", "port": 53}, + map[string]any{"protocol": "TCP", "port": 53}, + }, + }, + map[string]any{"to": []any{map[string]any{"ipBlock": map[string]any{"cidr": "0.0.0.0/0", "except": b.cfg.ProxyDeniedCIDRs}}}}, + } + // NetworkPolicy rules add up, so each scope block carries the never-reachable + // prefixes inside it as except, and a block inside one of them is dropped. + var scopeBlocks []any +scope: + for _, sp := range scopePrefixes(scopeCIDRs) { + blk := map[string]any{"cidr": sp.String()} + var except []string + for _, n := range b.never { + if n.Bits() <= sp.Bits() && n.Contains(sp.Addr()) { + continue scope + } + if sp.Bits() < n.Bits() && sp.Contains(n.Addr()) { + except = append(except, n.String()) + } + } + if len(except) > 0 { + blk["except"] = except + } + scopeBlocks = append(scopeBlocks, map[string]any{"ipBlock": blk}) + } + if len(scopeBlocks) > 0 { + egress = append(egress, map[string]any{"to": scopeBlocks}) + } + return map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": b.meta(name, kt, ComponentProxy, nil), + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentProxy)}, + "policyTypes": []string{"Ingress", "Egress"}, + "ingress": []any{map[string]any{ + "from": []any{map[string]any{"podSelector": map[string]any{"matchLabels": b.taskLabels(kt, ComponentWorker)}}}, + "ports": proxyPorts(), + }}, + "egress": egress, + }, + } +} + +// configPrefix parses a configured CIDR. A /0 would make an except equal to its +// block, which the API server rejects; an IPv4-mapped prefix would never match. +func configPrefix(c string) (netip.Prefix, error) { + p, err := netip.ParsePrefix(strings.TrimSpace(c)) + if err != nil { + return p, err + } + if p.Bits() == 0 || p.Addr().Is4In6() { + return p, fmt.Errorf("must not be /0 or IPv4-mapped") + } + return p.Masked(), nil +} + +// scopePrefixes parses scope CIDRs and IPs; ValidateExecRequest +// (sandbox/validate.go) checks and canonicalizes entries. +// An IPv4-mapped prefix is read as the IPv4 range it maps, so the private-range +// filter and the never-reachable excepts apply to it. +func scopePrefixes(cidrs []string) []netip.Prefix { + var out []netip.Prefix + for _, c := range cidrs { + if p, err := netip.ParsePrefix(c); err == nil { + if p.Addr().Is4In6() && p.Bits() >= 96 { + p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96) + } + out = append(out, p.Masked()) + } else if a, err := netip.ParseAddr(c); err == nil { + out = append(out, netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())) + } + } + return out +} + +// scopeForCluster drops, when ClusterCIDRs is not configured, scope CIDRs that +// overlap private, loopback or link-local ranges: they could cover the cluster's +// own pods, services or nodes. Like the invalid entries ValidateExecRequest +// (sandbox/validate.go) drops, they are dropped rather than failing every +// command: the narrower scope fails closed. +func (b *KubernetesBackend) scopeForCluster(cidrs []string) []string { + if len(b.cfg.ClusterCIDRs) > 0 { + return cidrs + } + out := cidrs[:0:0] + for _, c := range cidrs { + if ps := scopePrefixes([]string{c}); len(ps) == 1 && !slices.ContainsFunc(defaultDeniedPrefixes, ps[0].Overlaps) { + out = append(out, c) + } + } + if n := len(cidrs) - len(out); n > 0 { + log.Printf("[runner] dropped %d scope CIDRs overlapping private ranges (set ARTEX_KUBE_CLUSTER_CIDRS to allow them)", n) + } + return out +} + +// applyPolicy creates a NetworkPolicy or replaces an existing one carrying the +// runner's labels for the same task (with its resourceVersion, as the API server +// requires). A policy someone else created under that name is never overwritten. +func (b *KubernetesBackend) applyPolicy(ctx context.Context, obj map[string]any) error { + meta := obj["metadata"].(map[string]any) + name, hash := meta["name"].(string), meta["labels"].(map[string]string)[LabelTaskHash] + err := b.create(ctx, "networkpolicies", obj, nil) + if !isKubeStatus(err, http.StatusConflict) { + return err + } + p := b.nsPath("networkpolicies") + "/" + url.PathEscape(name) + var cur struct { + Metadata kubeObjectMeta `json:"metadata"` + } + if err := b.do(ctx, http.MethodGet, p, nil, &cur); err != nil { + return err + } + if !owned(cur.Metadata, hash) { + return fmt.Errorf("existing network policy %s is not managed by the runner for this task (refusing to replace it)", name) + } + meta["resourceVersion"] = cur.Metadata.ResourceVersion + return b.do(ctx, http.MethodPut, p, obj, nil) +} + +// waitPodReady polls until every container of the pod is ready. It fails fast on +// image pull and container creation errors, crash loops and exited containers. +func (b *KubernetesBackend) waitPodReady(ctx context.Context, name string) error { + ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) + defer cancel() + for { + p, err := b.getPod(ctx, name) + if err != nil && !isKubeStatus(err, http.StatusNotFound) { + return err + } + if p != nil { + if p.Status.Phase == "Failed" || p.Status.Phase == "Succeeded" { + return fmt.Errorf("pod %s ended in phase %s", name, p.Status.Phase) + } + ready := p.Status.Phase == "Running" && len(p.Status.ContainerStatuses) > 0 + for _, cs := range p.Status.ContainerStatuses { + if w := cs.State.Waiting; w != nil { + switch w.Reason { + case "ErrImagePull", "ImagePullBackOff", "InvalidImageName", "CreateContainerConfigError", "CreateContainerError", "CrashLoopBackOff": + log.Printf("[runner] pod %s: %s: %.512s", name, w.Reason, w.Message) + return fmt.Errorf("pod %s: %s", name, w.Reason) + } + } + if t := cs.State.Terminated; t != nil { + return fmt.Errorf("pod %s: container exited (%.64s)", name, t.Reason) + } + if !cs.Ready { + ready = false + } + } + if ready { + return nil + } + } + select { + case <-ctx.Done(): + return fmt.Errorf("pod %s not ready after %s: %w", name, b.cfg.PodReadyTimeout, ctx.Err()) + case <-time.After(500 * time.Millisecond): + } + } +} + +// podAlive reports whether the pod is running and ready and, when uid is set, is +// still the exact pod the runner created. Any other API error (a cancelled +// request too) is returned: it says nothing about the pod. +func (b *KubernetesBackend) podAlive(ctx context.Context, name, uid string) (bool, error) { + if name == "" { + return false, nil + } + p, err := b.getPod(ctx, name) + if err != nil || p.Metadata.Deletion != nil || (uid != "" && p.Metadata.UID != uid) || p.Status.Phase != "Running" { + if isKubeStatus(err, http.StatusNotFound) { + err = nil + } + return false, err + } + for _, cs := range p.Status.ContainerStatuses { + if !cs.Ready { + return false, nil + } + } + return true, nil +} + +// deletePodAndWait removes a pod immediately and waits until it is gone, so its +// processes are stopped and a pod with the same name can be created again. With +// uid set, a different pod reusing the name is left alone. +func (b *KubernetesBackend) deletePodAndWait(ctx context.Context, name, uid string) (bool, error) { + found, err := b.deleteObj(ctx, "pods", name, uid) + if err != nil || !found { + return found, err + } + wctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + for { + p, err := b.getPod(wctx, name) + if isKubeStatus(err, http.StatusNotFound) || (err == nil && uid != "" && p.Metadata.UID != uid) { + return true, nil + } + select { + case <-wctx.Done(): + return true, fmt.Errorf("pod %s still present after delete: %w", name, wctx.Err()) + case <-time.After(300 * time.Millisecond): + } + } +} + +// lockTask takes the per-task lock and returns its unlock function, and whether +// a Delete completed while this caller waited. +func (b *KubernetesBackend) lockTask(taskID string) (func(), bool) { + b.mu.Lock() + l := b.locks[taskID] + if l == nil { + l = &kubeTaskLock{} + b.locks[taskID] = l + } + l.refs++ + gen := l.deletes + b.mu.Unlock() + l.Lock() + b.mu.Lock() + deleted := l.deletes != gen + b.mu.Unlock() + return func() { + l.Unlock() + b.mu.Lock() + if l.refs--; l.refs == 0 { + delete(b.locks, taskID) + } + b.mu.Unlock() + }, deleted +} + +func (b *KubernetesBackend) getTask(taskID string) *kubeTask { + b.mu.Lock() + defer b.mu.Unlock() + return b.tasks[taskID] +} + +func (b *KubernetesBackend) setTask(taskID string, kt *kubeTask) { + b.mu.Lock() + defer b.mu.Unlock() + if kt == nil { + delete(b.tasks, taskID) + } else { + b.tasks[taskID] = kt + } +} + +// cleanupTask deletes every object labelled for the task: pods first, waiting +// until they are gone, then the service and, last, the network policies. When a +// pod cannot be removed the policies stay so it never runs without isolation. +// found reports whether anything existed. Must be called with the task lock. +func (b *KubernetesBackend) cleanupTask(ctx context.Context, hash string) (found bool, err error) { + for _, kind := range []string{"pods", "services", "networkpolicies"} { + var list struct { + Items []struct { + Metadata kubeObjectMeta `json:"metadata"` + } `json:"items"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath(kind)+taskSelector(hash), nil, &list); err != nil { + return found, err + } + var errs []error + for _, it := range list.Items { + var ok bool + var err error + if kind == "pods" { + ok, err = b.deletePodAndWait(ctx, it.Metadata.Name, it.Metadata.UID) + } else { + ok, err = b.deleteObj(ctx, kind, it.Metadata.Name, it.Metadata.UID) + } + found = found || ok + errs = append(errs, err) + } + if err := errors.Join(errs...); err != nil { + return found, fmt.Errorf("delete task %s: %w", kind, err) + } + } + return found, nil +} + +func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*kubeTask, error) { + unlock, deleted := b.lockTask(taskID) + defer unlock() + if deleted { + return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID) + } + + kt := &kubeTask{taskID: taskID, hash: kubeTaskHash(taskID)} + if cur := b.getTask(taskID); cur != nil { + cp := *cur + kt = &cp + } + sh := sha256Hex(scopeFingerprint(scopeDomains, scopeCIDRs)) + proxyOK, err := b.podAlive(ctx, kt.proxyPod, kt.proxyUID) + workerOK := false + if err == nil { + workerOK, err = b.podAlive(ctx, kt.workerPod, kt.workerUID) + } + if err != nil { + return nil, err // the pods may be fine: fail this exec only + } + if kt.verified && kt.scopeHash == sh && kt.proxyIP != "" && proxyOK && workerOK { + return kt, nil + } + kt.verified = false + // A scope change replaces both pods, so the probes run in a worker no command + // has touched (a hostile process in a used worker could fake them). + keep := kt.scopeHash == sh + if err := b.setupTask(ctx, kt, sh, keep && proxyOK, keep && workerOK, scopeDomains, scopeCIDRs); err != nil { + // Leave nothing half-built behind, even when ctx was cancelled. + cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute) + defer cancel() + if _, cerr := b.cleanupTask(cctx, kt.hash); cerr != nil { + log.Printf("[runner] cleanup after failed setup of task %s: %v", taskID, cerr) + err = errors.Join(err, cerr) + } + b.setTask(taskID, nil) + return nil, err + } + kt.verified = true + b.setTask(taskID, kt) + return kt, nil +} + +func (b *KubernetesBackend) setupTask(ctx context.Context, kt *kubeTask, sh string, keepProxy, keepWorker bool, scopeDomains, scopeCIDRs []string) error { + b.prepareDirs(kt.taskID) + name := func(prefix string) string { return prefix + kt.hash } + + // Policies first: a pod must never run before its isolation exists. + if err := b.applyPolicy(ctx, b.workerPolicyObj(name("artex-w-"), kt)); err != nil { + return fmt.Errorf("worker network policy: %w", err) + } + if err := b.applyPolicy(ctx, b.proxyPolicyObj(name("artex-p-"), kt, scopeCIDRs)); err != nil { + return fmt.Errorf("proxy network policy: %w", err) + } + + if kt.proxyIP == "" { + svcName := name("artex-p-") + err := b.create(ctx, "services", b.proxyServiceObj(svcName, kt), nil) + if err != nil && !isKubeStatus(err, http.StatusConflict) { + return fmt.Errorf("proxy service: %w", err) + } + var svc struct { + Metadata kubeObjectMeta `json:"metadata"` + Spec struct { + ClusterIP string `json:"clusterIP"` + } `json:"spec"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("services")+"/"+url.PathEscape(svcName), nil, &svc); err != nil { + return fmt.Errorf("proxy service: %w", err) + } + if !owned(svc.Metadata, kt.hash) { + return fmt.Errorf("existing service %s has untrusted labels (refusing to route worker through it)", svcName) + } + if ip := net.ParseIP(svc.Spec.ClusterIP); ip == nil { + return fmt.Errorf("proxy service %s has no ClusterIP", svcName) + } + kt.proxyIP = svc.Spec.ClusterIP + } + + // Every task pod except the kept ones goes first (found by label, deleted + // by UID), so the Service and the policies only ever match current pods. + var pods struct { + Items []kubePod `json:"items"` + } + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+taskSelector(kt.hash), nil, &pods); err != nil { + return err + } + for _, p := range pods.Items { + m := p.Metadata + if !(keepProxy && m.Name == kt.proxyPod) && !(keepWorker && m.Name == kt.workerPod) { + if _, err := b.deletePodAndWait(ctx, m.Name, m.UID); err != nil { + return err + } + } + } + var created kubePod + if !keepProxy { + kt.scopeHash = sh + n := kubePodName("artex-p-", kt.hash, kt.proxyPod) + if err := b.create(ctx, "pods", b.proxyPodObj(n, kt, scopeDomains, scopeCIDRs), &created); err != nil { + return fmt.Errorf("create proxy pod: %w", err) + } + kt.proxyPod, kt.proxyUID = n, created.Metadata.UID + } + if !keepWorker { + n := kubePodName("artex-w-", kt.hash, kt.workerPod) + if err := b.create(ctx, "pods", b.workerPodObj(n, kt), &created); err != nil { + return fmt.Errorf("create worker pod: %w", err) + } + kt.workerPod, kt.workerUID = n, created.Metadata.UID + } + if err := b.waitPodReady(ctx, kt.proxyPod); err != nil { + return err + } + if err := b.waitPodReady(ctx, kt.workerPod); err != nil { + return err + } + return b.waitNetworkReady(ctx, kt) +} + +// waitNetworkReady blocks until the task's NetworkPolicies are in effect for its +// current pods. A pod becomes Ready before the CNI has programmed policy for its +// new IP (seconds on k3s/kube-router), and until then the worker cannot reach its +// proxy and the proxy cannot reach DNS, while the denies may not hold yet. So +// probe both allowed paths, then prove the worker reaches neither the API server +// nor a public address directly, and the proxy cannot reach the API server +// (a never-reachable range). A deny probe passes only when every connection +// timed out or was refused or unroutable; it prints a token per outcome, and an +// error (no timeout binary, failed fork, ...) fails setup. The worker probes are +// trustworthy in a fresh worker (new task, dead worker, scope change); in an +// adopted one they only re-check. The proxy probe is out of the worker's reach. +func (b *KubernetesBackend) waitNetworkReady(ctx context.Context, kt *kubeTask) error { + ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) + defer cancel() + wrap := []string{"/usr/local/bin/artex-exec-wrap", "8000", "--", "bash", "-c"} + workerProbe := append(slices.Clone(wrap), fmt.Sprintf("exec 3<>/dev/tcp/%s/%d", kt.proxyIP, DefaultProxyPort)) + proxyProbe := []string{"getent", "hosts", "kubernetes.default.svc"} + deny := func(targets string) string { + return `[ -n "$KUBERNETES_SERVICE_HOST" ] || { echo artex-probe:noenv; exit; } +for t in "$KUBERNETES_SERVICE_HOST/$KUBERNETES_SERVICE_PORT" ` + targets + `; do e=$(timeout 2 bash -c "exec 3<>/dev/tcp/$t" 2>&1); case $?:$e in +124:*|1:*"Connection refused"*|1:*"No route to host"*|1:*"Network is unreachable"*) ;; 0:*) echo artex-probe:open; exit;; *) echo artex-probe:error; exit;; +esac; done; echo ` + kubeProbeBlocked + } + for _, p := range []struct { + pod, container string + argv []string + what string + }{ + {kt.workerPod, kubeWorkerName, workerProbe, "worker to proxy"}, + {kt.proxyPod, kubeProxyName, proxyProbe, "proxy to cluster DNS"}, + {kt.workerPod, kubeWorkerName, append(slices.Clone(wrap), deny(kubeProbePublicAddr)), "worker egress deny"}, + {kt.proxyPod, kubeProxyName, []string{"bash", "-c", deny("")}, "proxy deny of the API server"}, + } { + isDeny := strings.Contains(p.what, "deny") + for { + pctx, pcancel := context.WithTimeout(ctx, 10*time.Second) + out, serr, _, code, err := b.containerExec(pctx, p.pod, p.container, p.argv, 4096) + pcancel() + out = strings.TrimSpace(out) + if err == nil && code == 0 && (!isDeny || out == kubeProbeBlocked) { + break + } + last := fmt.Sprintf("task %s probe %s: exit %d err %v out %.64q stderr %.256q", kt.taskID, p.what, code, err, out, serr) + if isDeny && err == nil && out != "artex-probe:open" { + log.Printf("[runner] %s", last) + return fmt.Errorf("network probe %s failed (see runner log)", p.what) // details stay out of the panel + } + select { + case <-ctx.Done(): + log.Printf("[runner] %s", last) + return fmt.Errorf("network path %s not in effect after %s (network policy not applied?)", p.what, b.cfg.PodReadyTimeout) + case <-time.After(500 * time.Millisecond): + } + } + } + return nil +} + +// kubeExecArgv builds the exec argv. Kubernetes exec has no working-directory or +// environment options, so env(1) applies both before handing off to +// artex-exec-wrap. It starts from an empty environment (-i): kubelet injects +// KUBERNETES_SERVICE_* into every container whatever enableServiceLinks says, and +// the command must see exactly what DockerBackend gives it: the request's +// variables plus the worker base env. The base env comes last so it wins even +// if a reserved name ever got past ValidateEnv. Env names are validated by +// ValidateEnv (no '='), workdir by ValidateExecRequest (inside /workspace), and +// nothing passes through a shell. +func kubeExecArgv(req ExecRequest, proxyIP string) []string { + envList := make([]string, 0, len(req.Env)) + for k, v := range req.Env { + envList = append(envList, k+"="+v) + } + sort.Strings(envList) + workdir := req.Workdir + if workdir == "" { + workdir = "/workspace" + } + out := append([]string{"/usr/bin/env", "-i", "-C", workdir}, envList...) + for _, kv := range workerBaseEnv(proxyIP) { + out = append(out, kv[0]+"="+kv[1]) + } + out = append(out, "/usr/local/bin/artex-exec-wrap", strconv.Itoa(req.TimeoutMS), "--") + return append(out, req.Argv...) +} + +// Exec runs req.Argv inside the task's worker pod through artex-exec-wrap. +func (b *KubernetesBackend) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) { + if err := kubeTaskID(taskID); err != nil { + return ExecResponse{}, err + } + if err := ValidateExecRequest(&req); err != nil { + return ExecResponse{}, err + } + req.ScopeCIDRs = b.scopeForCluster(req.ScopeCIDRs) + start := time.Now() + kt, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs) + if err != nil { + return ExecResponse{}, err + } + timeout := time.Duration(req.TimeoutMS) * time.Millisecond + execCtx, cancel := context.WithTimeout(ctx, timeout+12*time.Second) + defer cancel() + execStart := time.Now() + stdout, stderr, truncated, code, err := b.podExec(execCtx, kt.workerPod, kubeExecArgv(req, kt.proxyIP), MaxOutputBytes) + if err != nil { + // The command may still run (cancelled, stream broken, read limit hit). + return ExecResponse{}, errors.Join(err, b.killWorker(context.WithoutCancel(ctx), taskID, kt.workerUID)) + } + // Same rule as DockerBackend: artex-exec-wrap exits 124 when it enforces + // timeout_ms, but the command can exit 124 itself. Only the wrapper's timeout + // takes timeout_ms or longer. Its process-group kill misses setsid and + // double-fork descendants, so kill every worker-uid process (or the pod). + timedOut := code == 124 && time.Since(execStart) >= timeout + if timedOut { + if err := b.killWorker(context.WithoutCancel(ctx), taskID, kt.workerUID); err != nil { + return ExecResponse{}, err + } + } + return ExecResponse{ + ExitCode: code, + Stdout: stdout, + Stderr: stderr, + Truncated: truncated, + TimedOut: timedOut, + DurationMS: time.Since(start).Milliseconds(), + }, nil +} + +// Kill terminates every worker-uid process in the task's worker pod (PID 1 excluded) +// with artex-exec-wrap --kill-uid. If that fails, the worker pod is deleted so no +// process survives; /workspace stays on the volume for the next exec. +func (b *KubernetesBackend) Kill(ctx context.Context, taskID string) error { + if err := kubeTaskID(taskID); err != nil { + return err + } + return b.killWorker(ctx, taskID, "") +} + +// killWorker kills the task's current worker under the task lock. A non-empty +// uid limits it to that exact pod: when the worker was replaced meanwhile (an +// exec cancelled while another exec recreated the pod), it does nothing. +func (b *KubernetesBackend) killWorker(ctx context.Context, taskID, uid string) error { + unlock, _ := b.lockTask(taskID) + defer unlock() + kt := b.getTask(taskID) + if kt == nil || kt.workerPod == "" { + if uid != "" { + return nil + } + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + if uid != "" && kt.workerUID != uid { + return nil + } + kctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + _, _, _, code, err := b.podExec(kctx, kt.workerPod, []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)}, 4096) + if err == nil && code == 0 { + return nil + } + log.Printf("[runner] kill-uid for task %s failed (code=%d err=%v); deleting worker pod", taskID, code, err) + dctx, dcancel := context.WithTimeout(context.WithoutCancel(ctx), 90*time.Second) + defer dcancel() + if _, derr := b.deletePodAndWait(dctx, kt.workerPod, kt.workerUID); derr != nil && !isKubeStatus(derr, http.StatusConflict) { + return derr + } + cp := *kt + cp.workerPod, cp.workerUID = "", "" + b.setTask(taskID, &cp) + return nil +} + +// Delete removes the task's pods, proxy service and network policies, keeping the +// workspace directory on the volume. Objects are found by label, so a task this +// process does not track (failed setup, lost state) is still cleaned up. Policies +// go only after the pods are gone; on failure everything else stays for a retry. +func (b *KubernetesBackend) Delete(ctx context.Context, taskID string) error { + if err := kubeTaskID(taskID); err != nil { + return err + } + unlock, _ := b.lockTask(taskID) + defer unlock() + tracked := b.getTask(taskID) != nil + found, err := b.cleanupTask(ctx, kubeTaskHash(taskID)) + if err != nil { + return err + } + b.setTask(taskID, nil) + b.mu.Lock() + b.locks[taskID].deletes++ // this call holds a reference: the entry exists + b.mu.Unlock() + if !found && !tracked { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + return nil +} diff --git a/sandbox/kube_client.go b/sandbox/kube_client.go new file mode 100644 index 00000000..2e700962 --- /dev/null +++ b/sandbox/kube_client.go @@ -0,0 +1,385 @@ +package sandbox + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "regexp" + "strconv" + "strings" + "time" + + "github.com/gorilla/websocket" +) + +// Container names in the task pods of the Kubernetes backend. +const ( + kubeWorkerName = "worker" + kubeProxyName = "egress-proxy" +) + +// kubeClient is the minimal Kubernetes API client of the Kubernetes sandbox +// backend: JSON requests on one namespace and pods/exec over WebSocket, with the +// in-cluster service-account token (re-read on every request: bound tokens +// rotate). +type kubeClient struct { + apiServer string + tokenPath string + namespace string + plainHTTP bool // tests only: http:// API server + http *http.Client + tls *tls.Config +} + +// newKubeClient builds a client for apiServer. An https:// server is verified +// against the CA in caPath. An http:// server is refused unless allowPlainHTTP +// (set only by tests): the token would travel in clear. +func newKubeClient(apiServer, tokenPath, caPath, namespace string, allowPlainHTTP bool) (*kubeClient, error) { + apiServer = strings.TrimRight(apiServer, "/") + tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} + if !strings.HasPrefix(apiServer, "https://") && !allowPlainHTTP { + return nil, fmt.Errorf("kubernetes backend: API server %q must use https:// (the service-account token would be sent in clear)", apiServer) + } + if strings.HasPrefix(apiServer, "https://") { + ca, err := os.ReadFile(caPath) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", caPath, err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(ca) { + return nil, fmt.Errorf("kubernetes backend: no certificates in %s", caPath) + } + tlsCfg.RootCAs = pool + } + return &kubeClient{ + apiServer: apiServer, + tokenPath: tokenPath, + namespace: namespace, + plainHTTP: allowPlainHTTP && strings.HasPrefix(apiServer, "http://"), + tls: tlsCfg, + http: &http.Client{ + Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg}, + Timeout: 30 * time.Second, + // Never follow a redirect: it could carry the bearer token elsewhere. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, + }, nil +} + +func (c *kubeClient) token() (string, error) { + raw, err := os.ReadFile(c.tokenPath) + if err != nil { + return "", fmt.Errorf("%w: read service account token: %v", ErrDockerUnavailable, err) + } + return strings.TrimSpace(string(raw)), nil +} + +// kubeAPIError carries the HTTP status and the metav1.Status reason of a failed +// API call. The response body is never forwarded: it can echo object specs or +// exec commands. +type kubeAPIError struct { + Code int + Reason string +} + +func (e *kubeAPIError) Error() string { + return fmt.Sprintf("kubernetes API HTTP %d %s", e.Code, e.Reason) +} + +var kubeReasonRE = regexp.MustCompile(`^[A-Za-z]{1,64}$`) + +func newKubeAPIError(code int, body io.Reader) (*kubeAPIError, string) { + raw, _ := io.ReadAll(io.LimitReader(body, 4096)) + var st struct { + Reason string `json:"reason"` + } + _ = json.Unmarshal(raw, &st) + if !kubeReasonRE.MatchString(st.Reason) { + st.Reason = "" + } + return &kubeAPIError{Code: code, Reason: st.Reason}, string(raw) +} + +func isKubeStatus(err error, code int) bool { + var ae *kubeAPIError + return errors.As(err, &ae) && ae.Code == code +} + +func (c *kubeClient) do(ctx context.Context, method, apiPath string, body, out any) error { + var r io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return err + } + r = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, c.apiServer+apiPath, r) + if err != nil { + return err + } + tok, err := c.token() + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + // The error holds the API URL and namespace: log it, return a generic one. + if ctx.Err() != nil { + return fmt.Errorf("kubernetes API request cancelled: %w", ctx.Err()) + } + log.Printf("[runner] kubernetes API %s %s: %v", method, apiPath, err) + return fmt.Errorf("%w: kubernetes API request failed", ErrDockerUnavailable) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + ae, raw := newKubeAPIError(resp.StatusCode, resp.Body) + if ae.Code != http.StatusNotFound && ae.Code != http.StatusConflict { + log.Printf("[runner] kubernetes API %s %s: HTTP %d: %.512s", method, apiPath, ae.Code, raw) + } + return ae + } + if out != nil { + return json.NewDecoder(resp.Body).Decode(out) + } + _, _ = io.Copy(io.Discard, resp.Body) + return nil +} + +func (c *kubeClient) nsPath(kind string) string { + switch kind { + case "networkpolicies": + return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(c.namespace) + "/networkpolicies" + default: + return "/api/v1/namespaces/" + url.PathEscape(c.namespace) + "/" + kind + } +} + +func (c *kubeClient) create(ctx context.Context, kind string, obj, out any) error { + return c.do(ctx, http.MethodPost, c.nsPath(kind), obj, out) +} + +// deleteObj deletes an object and reports whether it existed. Pods get a 1s +// grace, not 0: a zero grace force-removes the API object before the kubelet has +// stopped the containers, while with a grace the pod stays (terminating) until +// they are dead, so waiting for 404 proves its processes are gone. A non-empty +// uid makes the API server refuse (409) to delete a different object reusing the name. +func (c *kubeClient) deleteObj(ctx context.Context, kind, name, uid string) (bool, error) { + body := map[string]any{"propagationPolicy": "Background"} + if kind == "pods" { + body["gracePeriodSeconds"] = 1 + } + if uid != "" { + body["preconditions"] = map[string]any{"uid": uid} + } + err := c.do(ctx, http.MethodDelete, c.nsPath(kind)+"/"+url.PathEscape(name), body, nil) + if isKubeStatus(err, http.StatusNotFound) { + return false, nil + } + return err == nil, err +} + +type kubeObjectMeta struct { + Name string `json:"name"` + UID string `json:"uid,omitempty"` + ResourceVersion string `json:"resourceVersion,omitempty"` + Labels map[string]string `json:"labels"` + Annotations map[string]string `json:"annotations"` + Deletion *string `json:"deletionTimestamp,omitempty"` +} + +type kubePod struct { + Metadata kubeObjectMeta `json:"metadata"` + Status struct { + Phase string `json:"phase"` + ContainerStatuses []struct { + Ready bool `json:"ready"` + State struct { + Waiting *struct { + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"waiting"` + Terminated *struct { + Reason string `json:"reason"` + } `json:"terminated"` + } `json:"state"` + } `json:"containerStatuses"` + } `json:"status"` +} + +func (c *kubeClient) getPod(ctx context.Context, name string) (*kubePod, error) { + var p kubePod + if err := c.do(ctx, http.MethodGet, c.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// kubeExecStatus is the metav1.Status sent on the exec error channel. +type kubeExecStatus struct { + Status string `json:"status"` + Reason string `json:"reason"` + Details struct { + Causes []struct { + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"causes"` + } `json:"details"` +} + +// cappedBuffer keeps the first max bytes written and records truncation. +type cappedBuffer struct { + buf bytes.Buffer + max int + truncated bool +} + +func (c *cappedBuffer) Write(p []byte) { + rem := c.max - c.buf.Len() + if rem <= 0 { + if len(p) > 0 { + c.truncated = true + } + return + } + if len(p) > rem { + p = p[:rem] + c.truncated = true + } + c.buf.Write(p) +} + +// kubeExecReadLimit caps one exec WebSocket message. The API server forwards +// output in frames of at most a few tens of KiB; a larger frame means a broken or +// hostile peer and fails the exec before its payload is read into memory. +const kubeExecReadLimit = 4 << 20 + +// podExec runs argv in the pod's worker container over the Kubernetes exec +// WebSocket (channel.k8s.io v5/v4) and returns stdout, stderr and the exit code. +func (c *kubeClient) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) { + return c.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes) +} + +// containerExec runs argv over pods/exec. The API only takes the command as +// command= query parameters, so the URL carries argv (and the env(1) arguments): +// it is never put in an error or a log line, and API error bodies are dropped. +func (c *kubeClient) containerExec(ctx context.Context, pod, container string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) { + q := url.Values{} + q.Set("container", container) + q.Set("stdout", "true") + q.Set("stderr", "true") + for _, a := range argv { + q.Add("command", a) + } + u := "wss" + strings.TrimPrefix(c.apiServer, "https") + if c.plainHTTP && strings.HasPrefix(c.apiServer, "http://") { + u = "ws" + strings.TrimPrefix(c.apiServer, "http") + } + u += c.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode() + tok, err := c.token() + if err != nil { + return "", "", false, -1, err + } + dialer := websocket.Dialer{ + Proxy: nil, + TLSClientConfig: c.tls, + HandshakeTimeout: 30 * time.Second, + Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"}, + } + hdr := http.Header{} + hdr.Set("Authorization", "Bearer "+tok) + conn, resp, err := dialer.DialContext(ctx, u, hdr) + if err != nil { + if resp != nil { + ae, _ := newKubeAPIError(resp.StatusCode, resp.Body) + resp.Body.Close() + if ae.Code == http.StatusNotFound { + return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod) + } + return "", "", false, -1, ae + } + if ctx.Err() != nil { + return "", "", false, -1, ctx.Err() + } + return "", "", false, -1, fmt.Errorf("%w: exec dial to pod %s failed", ErrDockerUnavailable, pod) + } + defer conn.Close() + proto := conn.Subprotocol() + if proto != "v5.channel.k8s.io" && proto != "v4.channel.k8s.io" { + return "", "", false, -1, fmt.Errorf("exec: API server negotiated unsupported subprotocol %q", proto) + } + conn.SetReadLimit(kubeExecReadLimit) + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() + + out := &cappedBuffer{max: maxBytes} + errb := &cappedBuffer{max: maxBytes} + closed := map[byte]bool{} + var status *kubeExecStatus + for { + _, msg, rerr := conn.ReadMessage() + if rerr != nil { + if ctx.Err() != nil { + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, ctx.Err() + } + if errors.Is(rerr, websocket.ErrReadLimit) { + return "", "", false, -1, fmt.Errorf("exec: message larger than %d bytes", kubeExecReadLimit) + } + break + } + if len(msg) == 0 || closed[msg[0]] { + continue + } + switch msg[0] { + case 1: + out.Write(msg[1:]) + case 2: + errb.Write(msg[1:]) + case 3: + var st kubeExecStatus + if json.Unmarshal(msg[1:], &st) == nil { + status = &st + } + case 255: // v5 CLOSE: [255, stream]; that stream sends nothing more. + if proto == "v5.channel.k8s.io" && len(msg) == 2 { + closed[msg[1]] = true + } + } + } + res := func(code int, err error) (string, string, bool, int, error) { + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, code, err + } + switch { + case status == nil: + return res(-1, errors.New("exec stream ended without a status")) + case status.Status == "Success": + return res(0, nil) + case status.Reason == "NonZeroExitCode": + for _, c := range status.Details.Causes { + if n, perr := strconv.Atoi(c.Message); c.Reason == "ExitCode" && perr == nil { + return res(n, nil) + } + } + return res(-1, errors.New("exec failed without an exit code")) + } + // status.Message can quote the command: report only the reason. + reason := status.Reason + if !kubeReasonRE.MatchString(reason) { + reason = "unknown" + } + return res(-1, fmt.Errorf("exec failed: %s", reason)) +} diff --git a/sandbox/kube_client_test.go b/sandbox/kube_client_test.go new file mode 100644 index 00000000..f9f36790 --- /dev/null +++ b/sandbox/kube_client_test.go @@ -0,0 +1,115 @@ +package sandbox + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +func newTestKubeClient(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *kubeClient { + t.Helper() + tok := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + c, err := newKubeClient(srv.URL, tok, "", f.ns, true) + if err != nil { + t.Fatal(err) + } + return c +} + +func TestKubeClientRefusesPlainHTTPAndMissingCA(t *testing.T) { + if _, err := newKubeClient("http://127.0.0.1:1", "tok", "", "ns", false); err == nil || !strings.Contains(err.Error(), "https://") { + t.Fatalf("http:// API server accepted outside tests: %v", err) + } + if _, err := newKubeClient("https://127.0.0.1:6443", "tok", filepath.Join(t.TempDir(), "missing.crt"), "ns", false); err == nil { + t.Fatal("https API server without a readable CA accepted") + } +} + +func TestKubeClientRefusesRedirects(t *testing.T) { + var hits atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) })) + defer target.Close() + redir := httptest.NewServer(http.RedirectHandler(target.URL+"/api/v1/namespaces/artex/pods", http.StatusFound)) + defer redir.Close() + f, _ := newFakeKubeAPI(t) + c := newTestKubeClient(t, f, redir) + if err := c.do(context.Background(), http.MethodGet, c.nsPath("pods"), nil, nil); err == nil || hits.Load() != 0 { + t.Fatalf("redirect followed: err=%v hits=%d", err, hits.Load()) + } +} + +func TestKubeClientDeleteAndErrors(t *testing.T) { + f, srv := newFakeKubeAPI(t) + c := newTestKubeClient(t, f, srv) + ctx := context.Background() + if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil { + t.Fatal(err) + } + // A UID precondition protects a different pod reusing the name. + if _, err := c.deleteObj(ctx, "pods", "p1", "uid-other"); !isKubeStatus(err, http.StatusConflict) || f.obj("pods", "p1") == nil { + t.Fatalf("delete with a stale UID = %v", err) + } + // The API body never reaches the caller: only the status and the reason. + f.failDelete["p1"] = true + if _, err := c.deleteObj(ctx, "pods", "p1", ""); err == nil || strings.Contains(err.Error(), "etcd") || !strings.Contains(err.Error(), "InternalError") { + t.Fatalf("failed delete = %v", err) + } + f.failDelete["p1"] = false + uid := dig(f.obj("pods", "p1"), "metadata", "uid").(string) + if found, err := c.deleteObj(ctx, "pods", "p1", uid); !found || err != nil || f.obj("pods", "p1") != nil { + t.Fatalf("delete = %v %v", found, err) + } + if found, err := c.deleteObj(ctx, "pods", "p1", ""); found || err != nil { + t.Fatalf("delete of a missing pod = %v %v", found, err) + } +} + +func TestKubeClientExecStream(t *testing.T) { + f, srv := newFakeKubeAPI(t) + c := newTestKubeClient(t, f, srv) + ctx := context.Background() + if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil { + t.Fatal(err) + } + set := func(frames [][]byte, fn func(string, []string) (string, string, int)) { + f.mu.Lock() + f.preFrames, f.execFn = frames, fn + f.mu.Unlock() + } + // v5 CLOSE on stdout: later stdout frames are ignored. + set([][]byte{{1, 'a'}, {255, 1}, {1, 'b'}}, func(string, []string) (string, string, int) { return "", "", 0 }) + if out, _, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "a" || code != 0 { + t.Fatalf("v5 close: %q %d %v", out, code, err) + } + // A frame over the read limit fails the exec instead of being buffered. + set([][]byte{append([]byte{1}, make([]byte, kubeExecReadLimit+1)...)}, nil) + if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "larger than") { + t.Fatalf("oversized frame = %v", err) + } + // The status message (which can quote the command) is not passed on. + set(nil, func(string, []string) (string, string, int) { return "", "", -1 }) + if _, _, _, _, err := c.podExec(ctx, "p1", []string{"secret-arg"}, 1024); err == nil || + strings.Contains(err.Error(), "container not found") || strings.Contains(err.Error(), "secret-arg") { + t.Fatalf("exec failure = %v", err) + } + // Exit codes come from the status channel. + set(nil, func(string, []string) (string, string, int) { return "o", "e", 3 }) + if out, serr, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "o" || serr != "e" || code != 3 { + t.Fatalf("exit 3: %q %q %d %v", out, serr, code, err) + } + // Only the channel.k8s.io v5/v4 subprotocols are accepted. + f.mu.Lock() + f.subprotocols = []string{"base64.channel.k8s.io"} + f.mu.Unlock() + if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "subprotocol") { + t.Fatalf("unsupported subprotocol = %v", err) + } +} diff --git a/sandbox/kube_fake_test.go b/sandbox/kube_fake_test.go new file mode 100644 index 00000000..b973782a --- /dev/null +++ b/sandbox/kube_fake_test.go @@ -0,0 +1,376 @@ +package sandbox + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/gorilla/websocket" +) + +// fakeKubeAPI is an in-memory stand-in for the parts of the Kubernetes API the +// sandbox client and backend use: pods, services, networkpolicies (CRUD + +// label-selector list) and the pods/exec WebSocket. +type fakeKubeAPI struct { + t *testing.T + ns string + token string + + mu sync.Mutex + objs map[string]map[string]map[string]any // kind -> name -> object + ops []string // "create pods/artex-w-..." in order + execs [][]string // argv of every exec + // container of every exec, parallel to execs + execContainers []string + nextIP int + podMode map[string]string // pod name -> "ready" (default) | "pull-error" | "pending" + + // execFn answers an exec; default echoes argv to stdout with exit 0. denyFn + // answers the isolation deny probes; default reports them blocked. + execFn, denyFn func(pod string, argv []string) (stdout, stderr string, exit int) + // failPing makes pod list return 403. + failPing atomic.Bool + + rv int // resourceVersion / uid counter + podLinger int // GETs a deleted pod stays visible (terminating) + terminating map[string]int // pod name -> remaining GETs + failDelete map[string]bool + subprotocols []string // exec subprotocols the server offers + preFrames [][]byte // raw exec frames sent before stdout +} + +func newFakeKubeAPI(t *testing.T) (*fakeKubeAPI, *httptest.Server) { + f := &fakeKubeAPI{ + t: t, + ns: "artex", + token: "test-sa-token", + objs: map[string]map[string]map[string]any{"pods": {}, "services": {}, "networkpolicies": {}}, + podMode: map[string]string{}, + nextIP: 10, + + terminating: map[string]int{}, + failDelete: map[string]bool{}, + subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"}, + } + srv := httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(srv.Close) + return f, srv +} + +var fakeKubePathRE = regexp.MustCompile(`^/(?:api/v1|apis/networking\.k8s\.io/v1)/namespaces/([^/]+)/(pods|services|networkpolicies)(?:/([^/]+))?(?:/(exec))?$`) + +func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+f.token { + http.Error(w, `{"reason":"Unauthorized"}`, http.StatusUnauthorized) + return + } + m := fakeKubePathRE.FindStringSubmatch(r.URL.Path) + if m == nil { + http.Error(w, "no route "+r.URL.Path, http.StatusNotFound) + return + } + ns, kind, name, sub := m[1], m[2], m[3], m[4] + if ns != f.ns { + http.Error(w, "forbidden namespace "+ns, http.StatusForbidden) + return + } + if sub == "exec" { + f.serveExec(w, r, name) + return + } + f.mu.Lock() + defer f.mu.Unlock() + store := f.objs[kind] + switch { + case r.Method == http.MethodGet && name == "": + if kind == "pods" && f.failPing.Load() { + http.Error(w, `{"reason":"Forbidden"}`, http.StatusForbidden) + return + } + sel := r.URL.Query().Get("labelSelector") + items := []any{} + for _, o := range store { + if matchSelector(o, sel) { + items = append(items, o) + } + } + writeJSON(w, map[string]any{"items": items}) + case r.Method == http.MethodGet: + o, ok := store[name] + if n, term := f.terminating[name]; ok && kind == "pods" && term { + if f.terminating[name] = n - 1; n <= 0 { + delete(store, name) + delete(f.terminating, name) + f.ops = append(f.ops, "gone pods/"+name) + ok = false + } + } + if !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + writeJSON(w, o) + case r.Method == http.MethodPost: + var o map[string]any + if err := json.NewDecoder(r.Body).Decode(&o); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + meta := o["metadata"].(map[string]any) + n := meta["name"].(string) + if !dnsLabelRE.MatchString(n) { + http.Error(w, "invalid name "+n, http.StatusUnprocessableEntity) + return + } + if _, exists := store[n]; exists { + http.Error(w, `{"reason":"AlreadyExists"}`, http.StatusConflict) + return + } + f.finalize(kind, n, o) + f.rv++ + meta["uid"], meta["resourceVersion"] = fmt.Sprintf("uid-%d", f.rv), strconv.Itoa(f.rv) + store[n] = o + f.ops = append(f.ops, "create "+kind+"/"+n) + writeJSON(w, o) + case r.Method == http.MethodPut: + var o map[string]any + if err := json.NewDecoder(r.Body).Decode(&o); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + cur, exists := store[name] + if !exists { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + // Like the API server: an update must carry the current resourceVersion. + meta := o["metadata"].(map[string]any) + switch meta["resourceVersion"] { + case nil, "": + http.Error(w, `{"reason":"Invalid","message":"metadata.resourceVersion: must be specified for an update"}`, http.StatusUnprocessableEntity) + return + case dig(cur, "metadata", "resourceVersion"): + default: + http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict) + return + } + f.rv++ + meta["uid"], meta["resourceVersion"] = dig(cur, "metadata", "uid"), strconv.Itoa(f.rv) + store[name] = o + f.ops = append(f.ops, "update "+kind+"/"+name) + writeJSON(w, o) + case r.Method == http.MethodDelete: + o, ok := store[name] + if !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + var opts map[string]any + _ = json.NewDecoder(r.Body).Decode(&opts) + if uid := dig(opts, "preconditions", "uid"); uid != nil && uid != dig(o, "metadata", "uid") { + http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict) + return + } + if kind == "pods" && dig(opts, "gracePeriodSeconds") == float64(0) { + f.t.Errorf("pod %s force-deleted (grace 0): its containers may outlive the API object", name) + } + if f.failDelete[name] { + http.Error(w, `{"reason":"InternalError","message":"etcd says no to `+name+`"}`, http.StatusInternalServerError) + return + } + f.ops = append(f.ops, "delete "+kind+"/"+name) + if _, term := f.terminating[name]; kind == "pods" && f.podLinger > 0 { + if !term { + f.terminating[name] = f.podLinger + o["metadata"].(map[string]any)["deletionTimestamp"] = "now" + } + writeJSON(w, map[string]any{"status": "Success"}) + return + } + delete(store, name) + writeJSON(w, map[string]any{"status": "Success"}) + default: + http.Error(w, "method", http.StatusMethodNotAllowed) + } +} + +// finalize fills in server-side fields (pod status, service ClusterIP). +func (f *fakeKubeAPI) finalize(kind, name string, o map[string]any) { + switch kind { + case "services": + f.nextIP++ + o["spec"].(map[string]any)["clusterIP"] = fmt.Sprintf("10.43.0.%d", f.nextIP) + case "pods": + switch f.podMode[name[:max(0, len(name)-7)]] { // keyed by name without the generation + case "pull-error": + o["status"] = map[string]any{"phase": "Pending", "containerStatuses": []any{map[string]any{ + "ready": false, "state": map[string]any{"waiting": map[string]any{"reason": "ImagePullBackOff", "message": "pull access denied"}}, + }}} + case "pending": + o["status"] = map[string]any{"phase": "Pending"} + default: + o["status"] = map[string]any{"phase": "Running", "containerStatuses": []any{map[string]any{"ready": true, "state": map[string]any{}}}} + } + } +} + +func (f *fakeKubeAPI) setPodPhase(name, phase string, ready bool) { + f.mu.Lock() + defer f.mu.Unlock() + if p := f.objs["pods"][name]; p != nil { + p["status"] = map[string]any{"phase": phase, "containerStatuses": []any{map[string]any{"ready": ready, "state": map[string]any{}}}} + } +} + +func (f *fakeKubeAPI) serveExec(w http.ResponseWriter, r *http.Request, pod string) { + f.mu.Lock() + _, ok := f.objs["pods"][pod] + f.mu.Unlock() + if !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + q := r.URL.Query() + if c := q.Get("container"); c != kubeWorkerName && c != kubeProxyName { + http.Error(w, "unexpected container "+c, http.StatusBadRequest) + return + } + if q.Get("stdout") != "true" || q.Get("stderr") != "true" || q.Has("stdin") || q.Has("tty") { + http.Error(w, "unexpected exec query "+r.URL.RawQuery, http.StatusBadRequest) + return + } + argv := q["command"] + f.mu.Lock() + f.execs = append(f.execs, argv) + f.execContainers = append(f.execContainers, q.Get("container")) + fn, pre := f.execFn, f.preFrames + if strings.Contains(strings.Join(argv, " "), kubeProbeBlocked) { + fn = f.denyFn + if fn == nil { + fn = func(string, []string) (string, string, int) { return kubeProbeBlocked + "\n", "", 0 } + } + } + up := websocket.Upgrader{Subprotocols: f.subprotocols} + f.mu.Unlock() + conn, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + for _, fr := range pre { + if conn.WriteMessage(websocket.BinaryMessage, fr) != nil { + return + } + } + stdout, stderr, exit := strings.Join(argv, " "), "", 0 + if fn != nil { + stdout, stderr, exit = fn(pod, argv) + } + send := func(ch byte, data string) { + // Split large payloads into frames like the API server does. + for len(data) > 0 { + n := min(len(data), 32*1024) + _ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{ch}, data[:n]...)) + data = data[n:] + } + } + send(1, stdout) + send(2, stderr) + var st map[string]any + switch { + case exit == 0: + st = map[string]any{"status": "Success"} + case exit < 0: + st = map[string]any{"status": "Failure", "reason": "InternalError", "message": "container not found"} + default: + st = map[string]any{"status": "Failure", "reason": "NonZeroExitCode", "message": "command terminated with non-zero exit code", + "details": map[string]any{"causes": []any{map[string]any{"reason": "ExitCode", "message": strconv.Itoa(exit)}}}} + } + raw, _ := json.Marshal(st) + _ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{3}, raw...)) + _ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) +} + +var dnsLabelRE = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`) + +func matchSelector(o map[string]any, sel string) bool { + if sel == "" { + return true + } + labels, _ := o["metadata"].(map[string]any)["labels"].(map[string]any) + for _, term := range strings.Split(sel, ",") { + k, v, _ := strings.Cut(term, "=") + if labels[k] != v { + return false + } + } + return true +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} + +func (f *fakeKubeAPI) obj(kind, name string) map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + return f.objs[kind][name] +} + +func (f *fakeKubeAPI) count(kind string) int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.objs[kind]) +} + +func (f *fakeKubeAPI) opsSnapshot() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.ops...) +} + +func (f *fakeKubeAPI) lastExec() []string { + f.mu.Lock() + defer f.mu.Unlock() + if len(f.execs) == 0 { + return nil + } + return f.execs[len(f.execs)-1] +} + +// dig walks nested map/slice JSON values: dig(o, "spec", "containers", 0, "name"). +func dig(v any, path ...any) any { + for _, p := range path { + switch k := p.(type) { + case string: + m, ok := v.(map[string]any) + if !ok { + return nil + } + v = m[k] + case int: + s, ok := v.([]any) + if !ok || k >= len(s) { + return nil + } + v = s[k] + } + } + return v +} + +func envOf(container any) map[string]string { + out := map[string]string{} + for _, e := range dig(container, "env").([]any) { + out[e.(map[string]any)["name"].(string)] = e.(map[string]any)["value"].(string) + } + return out +} diff --git a/sandbox/kube_test.go b/sandbox/kube_test.go new file mode 100644 index 00000000..38726a8a --- /dev/null +++ b/sandbox/kube_test.go @@ -0,0 +1,188 @@ +package sandbox + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, mods ...func(*KubeConfig)) *KubernetesBackend { + t.Helper() + dir := t.TempDir() + tok := filepath.Join(dir, "token") + if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + cfg := KubeConfig{ + APIServer: srv.URL, + TokenPath: tok, + Namespace: f.ns, + DataClaim: "artex-data", + WorkerImage: "artex-worker:test", + ProxyImage: "artex-egress-proxy:test", + WorkspaceRoot: filepath.Join(dir, "tasks"), + AuditRoot: filepath.Join(dir, "audit"), + PodReadyTimeout: 3 * time.Second, + allowPlainHTTP: true, + } + for _, m := range mods { + m(&cfg) + } + b, err := NewKubernetesBackend(cfg) + if err != nil { + t.Fatalf("NewKubernetesBackend: %v", err) + } + return b +} + +func execReq(argv ...string) ExecRequest { + req := ExecRequest{Argv: argv} + if err := ValidateExecRequest(&req); err != nil { + panic(err) + } + return req +} + +func TestKubeDeleteRemovesPoliciesOnlyAfterPodsAreGone(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + f.podLinger = 3 // a deleted pod stays visible (terminating) for 3 GETs + for _, id := range []string{"t1", "t2"} { + if _, err := b.Exec(ctx, id, execReq("true")); err != nil { + t.Fatal(err) + } + } + mark := len(f.opsSnapshot()) + if err := b.Delete(ctx, "t1"); err != nil { + t.Fatal(err) + } + h := kubeTaskHash("t1") + ops := f.opsSnapshot()[mark:] + firstPol, gone := -1, 0 + for i, op := range ops { + if strings.HasPrefix(op, "gone pods/") { + gone++ + } + if strings.HasPrefix(op, "delete networkpolicies/") && firstPol < 0 { + firstPol = i + if gone != 2 { + t.Fatalf("policy deleted while a pod still ran: %v", ops) + } + } + } + if firstPol < 0 || f.obj("networkpolicies", "artex-p-"+h) != nil || f.count("pods") != 2 { + t.Fatalf("delete incomplete: %v", ops) + } + + // A pod that cannot be deleted keeps its policies, and the task stays tracked. + h2 := kubeTaskHash("t2") + f.failDelete[b.getTask("t2").workerPod] = true + err := b.Delete(ctx, "t2") + if err == nil || strings.Contains(err.Error(), "etcd") { + t.Fatalf("failed pod delete = %v (want error without the API body)", err) + } + if f.obj("networkpolicies", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-p-"+h2) == nil || b.WorkerCount() != 1 { + t.Fatal("policies removed although the worker pod is still running") + } + f.failDelete = map[string]bool{} + if err := b.Delete(ctx, "t2"); err != nil { + t.Fatal(err) + } + if f.count("pods")+f.count("services")+f.count("networkpolicies") != 0 { + t.Fatalf("objects left: %v", f.opsSnapshot()) + } + if err := b.Delete(ctx, "t2"); !errors.Is(err, ErrNotFound) { + t.Fatalf("delete of nothing = %v", err) + } + b.mu.Lock() + locks := len(b.locks) + b.mu.Unlock() + if locks != 0 { + t.Fatalf("%d task locks left after Delete", locks) + } +} + +func TestKubeApplyPolicyUpdatesWithResourceVersionOnlyOwnPolicy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + // The fake enforces the API server rule: an update without resourceVersion is 422. + pol := b.workerPolicyObj("artex-w-"+h, &kubeTask{taskID: "t1", hash: h}) + if err := b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/artex-w-"+h, pol, nil); !isKubeStatus(err, http.StatusUnprocessableEntity) { + t.Fatalf("PUT without resourceVersion = %v", err) + } + rv := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion") + if err := b.applyPolicy(ctx, pol); err != nil { + t.Fatalf("409 -> PUT: %v", err) + } + if got := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion"); got == rv { + t.Fatal("policy not replaced") + } + + // A same-named policy without the runner's labels is never overwritten, and the + // failed setup leaves nothing of its own behind. + h2 := kubeTaskHash("t2") + f.mu.Lock() + f.objs["networkpolicies"]["artex-p-"+h2] = map[string]any{ + "metadata": map[string]any{"name": "artex-p-" + h2, "labels": map[string]any{"app": "x"}, "resourceVersion": "1"}, + "spec": map[string]any{"podSelector": map[string]any{"foreign": true}}} + f.mu.Unlock() + _, err := b.Exec(ctx, "t2", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "not managed by the runner") { + t.Fatalf("foreign policy = %v", err) + } + if dig(f.obj("networkpolicies", "artex-p-"+h2), "spec", "podSelector", "foreign") != true || f.obj("networkpolicies", "artex-w-"+h2) != nil { + t.Fatal("foreign policy replaced or own policy left behind") + } +} + +func TestKubeDeniedCIDRsExtendDefaults(t *testing.T) { + f, srv := newFakeKubeAPI(t) + cfg := newTestKubeBackend(t, f, srv).cfg + cfg.ProxyDeniedCIDRs = []string{"198.51.100.7/24", "10.0.0.0/8"} + nb, err := NewKubernetesBackend(cfg) + if err != nil { + t.Fatal(err) + } + want := strings.Join(append(slices.Clone(DefaultProxyDeniedCIDRs), "198.51.100.0/24"), ",") + if got := strings.Join(nb.cfg.ProxyDeniedCIDRs, ","); got != want { + t.Fatalf("denied CIDRs = %s\nwant %s", got, want) + } + cfg.ProxyDeniedCIDRs = []string{"fc00::/7"} + if _, err := NewKubernetesBackend(cfg); err == nil { + t.Fatal("IPv6 denied CIDR accepted") + } + // An empty label map must not select every pod in the DNS namespace. + cfg.ProxyDeniedCIDRs, cfg.DNSPodLabels = nil, map[string]string{} + if nb, err = NewKubernetesBackend(cfg); err != nil || nb.cfg.DNSPodLabels["k8s-app"] != "kube-dns" { + t.Fatalf("empty DNS labels: %v", err) + } +} + +func TestKubeCancelledExecKeepsTask(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + // A failed pod lookup (here a cancelled request) says nothing about the pods: + // only this exec fails, and it is not reported as the runner being unavailable. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := b.Exec(ctx, "t1", execReq("true")) + if !errors.Is(err, context.Canceled) || errors.Is(err, ErrDockerUnavailable) || f.count("pods")+f.count("networkpolicies") != 4 || b.WorkerCount() != 1 { + t.Fatalf("cancelled exec = %v; %d pods, %d tasks", err, f.count("pods"), b.WorkerCount()) + } +} diff --git a/sandbox/policy.go b/sandbox/policy.go index 6db79df2..3d7d757e 100644 --- a/sandbox/policy.go +++ b/sandbox/policy.go @@ -133,6 +133,9 @@ type EgressPolicy struct { Resolver func(ctx context.Context, host string) ([]netip.Addr, error) Dialer func(ctx context.Context, network, addr string) (net.Conn, error) Logger *EgressLogger + // Never lists prefixes denied even when a scope CIDR covers them (the + // Kubernetes backend passes cluster and metadata ranges here). + Never []netip.Prefix } // NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries. @@ -198,8 +201,21 @@ func (p *EgressPolicy) domainAllowed(host string) bool { return false } +func (p *EgressPolicy) inNever(addr netip.Addr) bool { + addr = addr.Unmap() + for _, pfx := range p.Never { + if pfx.Contains(addr) { + return true + } + } + return false +} + func (p *EgressPolicy) ipInScopeCIDR(addr netip.Addr) bool { addr = addr.Unmap() + if p.inNever(addr) { + return false + } for _, pfx := range p.CIDRs { if pfx.Contains(addr) { return true @@ -283,7 +299,7 @@ func (p *EgressPolicy) ResolveAndCheck(ctx context.Context, host string) (netip. if p.ipInScopeCIDR(addr) { return addr, nil } - if isDefaultDeniedAddr(addr) { + if isDefaultDeniedAddr(addr) || p.inNever(addr) { continue } return addr, nil @@ -381,7 +397,7 @@ func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error { } for _, addr := range addrs { addr = addr.Unmap() - if !p.ipInScopeCIDR(addr) && isDefaultDeniedAddr(addr) { + if !p.ipInScopeCIDR(addr) && (isDefaultDeniedAddr(addr) || p.inNever(addr)) { return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr) } } diff --git a/sandbox/types.go b/sandbox/types.go index 7d259b6d..9a8da36f 100644 --- a/sandbox/types.go +++ b/sandbox/types.go @@ -21,6 +21,10 @@ const ( EnvAuditRoot = "ARTEX_AUDIT_ROOT" EnvTaskNetPrefix = "ARTEX_TASK_NET_PREFIX" EnvEgressNet = "ARTEX_EGRESS_NET" + EnvRunnerBackend = "ARTEX_RUNNER_BACKEND" + + BackendDocker = "docker" + BackendKubernetes = "kubernetes" DefaultRunnerURL = "http://artex-runner:8789" DefaultRunnerAddr = ":8789"