diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d6ed713..6cd4eb4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project are documented in this file. The format is b ## [Unreleased] +### 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. 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. + ### Security - **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side. 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/go.mod b/go.mod index c5183b75..d773029a 100644 --- a/go.mod +++ b/go.mod @@ -74,7 +74,7 @@ require ( golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 golang.org/x/tools v0.52.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + gopkg.in/yaml.v3 v3.0.1 modernc.org/libc v1.72.3 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/sandbox/kube.go b/sandbox/kube.go new file mode 100644 index 00000000..35ca5270 --- /dev/null +++ b/sandbox/kube.go @@ -0,0 +1,1238 @@ +package sandbox + +import ( + "bytes" + "context" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/netip" + "net/url" + "os" + "path" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +// 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" + kubeWorkerName = "worker" + kubeProxyName = "egress-proxy" + 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 is 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. + DNSNamespace string + DNSPodLabels map[string]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 +} + +type kubeTask struct { + taskID string + hash string + scopeHash string + workerPod string + proxyPod string + proxyIP string // ClusterIP of the per-task proxy Service +} + +// 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 { + cfg KubeConfig + http *http.Client + tls *tls.Config + mu sync.Mutex + tasks map[string]*kubeTask + // locks serialises ensureTask per task so concurrent execs never race to + // delete and recreate each other's pods. + locks map[string]*sync.Mutex + // tokenOverride is used by tests instead of reading TokenPath. + tokenOverride string +} + +// 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", +} + +// NewKubernetesBackend builds a backend from cfg, filling defaults from the +// in-cluster environment. +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" + } + for _, p := range []string{cfg.TasksSubPath, cfg.AuditSubPath} { + if path.IsAbs(p) || strings.Contains(p, "..") { + return nil, fmt.Errorf("kubernetes backend: sub path %q must be relative without ..", p) + } + } + if cfg.WorkspaceRoot == "" { + cfg.WorkspaceRoot = DefaultWorkspaceRoot + } + if cfg.AuditRoot == "" { + cfg.AuditRoot = DefaultAuditRoot + } + if cfg.ProxyDeniedCIDRs == nil { + cfg.ProxyDeniedCIDRs = DefaultProxyDeniedCIDRs + } + if cfg.DNSNamespace == "" { + cfg.DNSNamespace = "kube-system" + } + if cfg.DNSPodLabels == nil { + 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 + } + + tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} + if strings.HasPrefix(cfg.APIServer, "https://") { + ca, err := os.ReadFile(cfg.CAPath) + if err != nil { + return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", cfg.CAPath, err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(ca) { + return nil, fmt.Errorf("kubernetes backend: no certificates in %s", cfg.CAPath) + } + tlsCfg.RootCAs = pool + } + return &KubernetesBackend{ + cfg: cfg, + tls: tlsCfg, + http: &http.Client{Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg}, Timeout: 30 * time.Second}, + tasks: map[string]*kubeTask{}, + locks: map[string]*sync.Mutex{}, + }, 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; default DefaultProxyDeniedCIDRs +// 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"), + + 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 kubeTaskHash(taskID string) string { + sum := sha256.Sum256([]byte(taskID)) + return hex.EncodeToString(sum[:])[:16] +} + +func (b *KubernetesBackend) token() (string, error) { + if b.tokenOverride != "" { + return b.tokenOverride, nil + } + raw, err := os.ReadFile(b.cfg.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 of a failed API call. +type kubeAPIError struct { + Code int + Body string +} + +func (e *kubeAPIError) Error() string { + return fmt.Sprintf("kubernetes API HTTP %d: %s", e.Code, e.Body) +} + +func isKubeStatus(err error, code int) bool { + var ae *kubeAPIError + return errors.As(err, &ae) && ae.Code == code +} + +func (b *KubernetesBackend) 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, b.cfg.APIServer+apiPath, r) + if err != nil { + return err + } + tok, err := b.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 := b.http.Do(req) + if err != nil { + return fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return &kubeAPIError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))} + } + if out != nil { + return json.NewDecoder(resp.Body).Decode(out) + } + _, _ = io.Copy(io.Discard, resp.Body) + return nil +} + +func (b *KubernetesBackend) nsPath(kind string) string { + switch kind { + case "networkpolicies": + return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(b.cfg.Namespace) + "/networkpolicies" + default: + return "/api/v1/namespaces/" + url.PathEscape(b.cfg.Namespace) + "/" + kind + } +} + +func (b *KubernetesBackend) create(ctx context.Context, kind string, obj any) error { + return b.do(ctx, http.MethodPost, b.nsPath(kind), obj, nil) +} + +// deleteObj deletes an object; a missing object is not an error. +func (b *KubernetesBackend) deleteObj(ctx context.Context, kind, name string, grace *int) error { + var body any + if grace != nil { + body = map[string]any{"gracePeriodSeconds": *grace, "propagationPolicy": "Background"} + } + err := b.do(ctx, http.MethodDelete, b.nsPath(kind)+"/"+url.PathEscape(name), body, nil) + if isKubeStatus(err, http.StatusNotFound) { + return nil + } + return err +} + +// 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) +} + +type kubeObjectMeta struct { + Name string `json:"name"` + 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"` +} + +// Recover rebuilds task state from pods carrying artex.managed_by=artex-runner. +// Only pods that also carry a valid task annotation whose hash matches their label +// are adopted. +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 { + svcIP[s.Metadata.Labels[LabelTaskHash]] = 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] + if ValidateTaskID(tid) != nil || kubeTaskHash(tid) != p.Metadata.Labels[LabelTaskHash] { + continue + } + kt := b.tasks[tid] + if kt == nil { + kt = &kubeTask{taskID: tid, hash: kubeTaskHash(tid), proxyIP: svcIP[kubeTaskHash(tid)]} + b.tasks[tid] = kt + } + switch p.Metadata.Labels[LabelComponent] { + case ComponentWorker: + kt.workerPod = p.Metadata.Name + case ComponentProxy: + kt.proxyPod = p.Metadata.Name + 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) proxyPodObj(name string, kt *kubeTask, scopeDomains, scopeCIDRs []string) map[string]any { + _, ctrSec := b.podSecurity() + spec := b.basePodSpec() + 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"}, + }, + "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 := fmt.Sprintf("http://%s:%d", proxyIP, DefaultProxyPort) + socksURL := fmt.Sprintf("socks5h://%s:%d", proxyIP, 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}, + } +} + +// workerPolicyObj lets the task's worker reach only its own proxy. Together with the +// chart's default-deny policy for every runner-managed pod, a worker whose per-task +// policy is missing has no network at all (fail closed). +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}}}}, + } + var scopeBlocks []any + for _, c := range scopeCIDRs { + if p, err := netip.ParsePrefix(strings.TrimSpace(c)); err == nil { + scopeBlocks = append(scopeBlocks, map[string]any{"ipBlock": map[string]any{"cidr": p.Masked().String()}}) + } else if a, err := netip.ParseAddr(strings.TrimSpace(c)); err == nil { + scopeBlocks = append(scopeBlocks, map[string]any{"ipBlock": map[string]any{"cidr": netip.PrefixFrom(a, a.BitLen()).String()}}) + } + } + 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, + }, + } +} + +// applyPolicy creates a NetworkPolicy or replaces an existing one. +func (b *KubernetesBackend) applyPolicy(ctx context.Context, obj map[string]any) error { + name := obj["metadata"].(map[string]any)["name"].(string) + err := b.create(ctx, "networkpolicies", obj) + if isKubeStatus(err, http.StatusConflict) { + return b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/"+url.PathEscape(name), obj, nil) + } + return err +} + +func (b *KubernetesBackend) getPod(ctx context.Context, name string) (*kubePod, error) { + var p kubePod + if err := b.do(ctx, http.MethodGet, b.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// waitPodReady polls until every container of the pod is ready. It fails fast on +// image pull errors and terminated 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": + return fmt.Errorf("pod %s: %s: %s", name, w.Reason, w.Message) + } + } + 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): + } + } +} + +func (b *KubernetesBackend) podAlive(ctx context.Context, name string) bool { + if name == "" { + return false + } + p, err := b.getPod(ctx, name) + if err != nil || p.Metadata.Deletion != nil { + return false + } + if p.Status.Phase != "Running" { + return false + } + for _, cs := range p.Status.ContainerStatuses { + if !cs.Ready { + return false + } + } + return true +} + +// deletePod removes a pod immediately and waits until it is gone, so a pod with the +// same name can be created again. +func (b *KubernetesBackend) deletePodAndWait(ctx context.Context, name string) error { + zero := 0 + if err := b.deleteObj(ctx, "pods", name, &zero); err != nil { + return err + } + wctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + for { + _, err := b.getPod(wctx, name) + if isKubeStatus(err, http.StatusNotFound) { + return nil + } + select { + case <-wctx.Done(): + return fmt.Errorf("pod %s still present after delete: %w", name, wctx.Err()) + case <-time.After(300 * time.Millisecond): + } + } +} + +func (b *KubernetesBackend) taskLock(taskID string) *sync.Mutex { + b.mu.Lock() + defer b.mu.Unlock() + l := b.locks[taskID] + if l == nil { + l = &sync.Mutex{} + b.locks[taskID] = l + } + return l +} + +func (b *KubernetesBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*kubeTask, error) { + l := b.taskLock(taskID) + l.Lock() + defer l.Unlock() + + b.mu.Lock() + kt := b.tasks[taskID] + b.mu.Unlock() + if kt != nil { + cp := *kt + kt = &cp + } + + sh := kubeTaskHash(scopeFingerprint(scopeDomains, scopeCIDRs))[:8] + if kt == nil { + kt = &kubeTask{taskID: taskID, hash: kubeTaskHash(taskID)} + } + if kt.scopeHash == sh && kt.proxyIP != "" && b.podAlive(ctx, kt.proxyPod) && b.podAlive(ctx, kt.workerPod) { + return kt, nil + } + + b.prepareDirs(taskID) + + workerPolicy := "artex-w-" + kt.hash + proxyPolicy := "artex-p-" + kt.hash + svcName := "artex-p-" + kt.hash + proxyPod := "artex-p-" + kt.hash + workerPod := "artex-w-" + kt.hash + + // Policies first: a pod must never run before its isolation exists. + if err := b.applyPolicy(ctx, b.workerPolicyObj(workerPolicy, kt)); err != nil { + return nil, fmt.Errorf("worker network policy: %w", err) + } + if err := b.applyPolicy(ctx, b.proxyPolicyObj(proxyPolicy, kt, scopeCIDRs)); err != nil { + return nil, fmt.Errorf("proxy network policy: %w", err) + } + + if kt.proxyIP == "" { + err := b.create(ctx, "services", b.proxyServiceObj(svcName, kt)) + if err != nil && !isKubeStatus(err, http.StatusConflict) { + return nil, 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 nil, fmt.Errorf("proxy service: %w", err) + } + if svc.Metadata.Labels[LabelManagedBy] != ManagedByRunner || svc.Metadata.Labels[LabelTaskHash] != kt.hash { + return nil, fmt.Errorf("existing service %s has untrusted labels %v (refusing to route worker through it)", svcName, svc.Metadata.Labels) + } + if ip := net.ParseIP(svc.Spec.ClusterIP); ip == nil { + return nil, fmt.Errorf("proxy service %s has no ClusterIP (%q)", svcName, svc.Spec.ClusterIP) + } + kt.proxyIP = svc.Spec.ClusterIP + } + + // (Re)create the proxy when missing, dead, or the scope changed. + if kt.scopeHash != sh || !b.podAlive(ctx, kt.proxyPod) { + if err := b.deletePodAndWait(ctx, proxyPod); err != nil { + return nil, err + } + kt.scopeHash = sh + if err := b.create(ctx, "pods", b.proxyPodObj(proxyPod, kt, scopeDomains, scopeCIDRs)); err != nil { + return nil, fmt.Errorf("create proxy pod: %w", err) + } + kt.proxyPod = proxyPod + } + if !b.podAlive(ctx, kt.workerPod) { + if err := b.deletePodAndWait(ctx, workerPod); err != nil { + return nil, err + } + if err := b.create(ctx, "pods", b.workerPodObj(workerPod, kt)); err != nil { + return nil, fmt.Errorf("create worker pod: %w", err) + } + kt.workerPod = workerPod + } + if err := b.waitPodReady(ctx, kt.proxyPod); err != nil { + return nil, err + } + if err := b.waitPodReady(ctx, kt.workerPod); err != nil { + return nil, err + } + if err := b.waitNetworkReady(ctx, kt); err != nil { + return nil, err + } + + b.mu.Lock() + b.tasks[taskID] = kt + b.mu.Unlock() + return kt, nil +} + +// 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. Running the first command in that window +// would fail spuriously, so probe both paths first. +func (b *KubernetesBackend) waitNetworkReady(ctx context.Context, kt *kubeTask) error { + ctx, cancel := context.WithTimeout(ctx, b.cfg.PodReadyTimeout) + defer cancel() + workerProbe := []string{"/usr/local/bin/artex-exec-wrap", "3000", "--", "bash", "-c", + fmt.Sprintf("exec 3<>/dev/tcp/%s/%d", kt.proxyIP, DefaultProxyPort)} + proxyProbe := []string{"getent", "hosts", "kubernetes.default.svc"} + 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"}, + } { + var last string + for { + pctx, pcancel := context.WithTimeout(ctx, 10*time.Second) + _, serr, _, code, err := b.containerExec(pctx, p.pod, p.container, p.argv, 4096) + pcancel() + if err == nil && code == 0 { + break + } + last = fmt.Sprintf("exit %d err %v %s", code, err, strings.TrimSpace(serr)) + select { + case <-ctx.Done(): + return fmt.Errorf("network path %s not open after %s (network policy not applied? last: %s)", p.what, b.cfg.PodReadyTimeout, last) + case <-time.After(500 * time.Millisecond): + } + } + } + return nil +} + +// kubeExecStatus is the metav1.Status sent on the exec error channel. +type kubeExecStatus struct { + Status string `json:"status"` + Message string `json:"message"` + 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) +} + +// 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 (b *KubernetesBackend) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) { + return b.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes) +} + +func (b *KubernetesBackend) 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, err := url.Parse(b.cfg.APIServer + b.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode()) + if err != nil { + return "", "", false, -1, err + } + switch u.Scheme { + case "https": + u.Scheme = "wss" + case "http": + u.Scheme = "ws" + } + tok, err := b.token() + if err != nil { + return "", "", false, -1, err + } + dialer := websocket.Dialer{ + Proxy: nil, + TLSClientConfig: b.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.String(), hdr) + if err != nil { + if resp != nil { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod) + } + return "", "", false, -1, &kubeAPIError{Code: resp.StatusCode, Body: strings.TrimSpace(string(raw))} + } + return "", "", false, -1, fmt.Errorf("%w: exec dial: %v", ErrDockerUnavailable, err) + } + defer conn.Close() + stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) + defer stop() + + out := &cappedBuffer{max: maxBytes} + errb := &cappedBuffer{max: maxBytes} + exitCode = -1 + 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() + } + break + } + if len(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 + } + } + } + if status == nil { + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, errors.New("exec stream ended without a status") + } + switch { + case status.Status == "Success": + exitCode = 0 + case status.Reason == "NonZeroExitCode": + for _, c := range status.Details.Causes { + if c.Reason == "ExitCode" { + if n, perr := strconv.Atoi(c.Message); perr == nil { + exitCode = n + } + } + } + default: + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, fmt.Errorf("exec failed: %s", status.Message) + } + return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, exitCode, 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 worker base env +// plus the request's variables. 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" + } + base := workerBaseEnv(proxyIP) + out := make([]string, 0, len(base)+len(envList)+len(req.Argv)+8) + out = append(out, "/usr/bin/env", "-i", "-C", workdir) + for _, kv := range base { + out = append(out, kv[0]+"="+kv[1]) + } + out = append(out, envList...) + 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) { + start := time.Now() + kt, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs) + if err != nil { + return ExecResponse{}, err + } + execCtx, cancel := context.WithTimeout(ctx, time.Duration(req.TimeoutMS)*time.Millisecond+12*time.Second) + defer cancel() + stdout, stderr, truncated, code, err := b.podExec(execCtx, kt.workerPod, kubeExecArgv(req, kt.proxyIP), MaxOutputBytes) + if err != nil { + if ctx.Err() != nil || execCtx.Err() != nil { + _ = b.Kill(context.Background(), taskID) + } + return ExecResponse{}, err + } + return ExecResponse{ + ExitCode: code, + Stdout: stdout, + Stderr: stderr, + Truncated: truncated, + TimedOut: code == 124, + 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 { + b.mu.Lock() + kt := b.tasks[taskID] + b.mu.Unlock() + if kt == nil || kt.workerPod == "" { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + 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) + zero := 0 + if derr := b.deleteObj(context.Background(), "pods", kt.workerPod, &zero); derr != nil { + return derr + } + b.mu.Lock() + if cur := b.tasks[taskID]; cur != nil { + cur.workerPod = "" + } + b.mu.Unlock() + return nil +} + +// Delete removes the task's pods, proxy service and network policies, keeping the +// workspace directory on the volume. Policies go last so no pod outlives them. +func (b *KubernetesBackend) Delete(ctx context.Context, taskID string) error { + l := b.taskLock(taskID) + l.Lock() + defer l.Unlock() + b.mu.Lock() + kt := b.tasks[taskID] + delete(b.tasks, taskID) + b.mu.Unlock() + if kt == nil { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + zero := 0 + var errs []error + for _, obj := range [][2]string{ + {"pods", "artex-w-" + kt.hash}, + {"pods", "artex-p-" + kt.hash}, + {"services", "artex-p-" + kt.hash}, + } { + g := &zero + if obj[0] != "pods" { + g = nil + } + if err := b.deleteObj(ctx, obj[0], obj[1], g); err != nil { + errs = append(errs, err) + } + } + for _, name := range []string{"artex-w-" + kt.hash, "artex-p-" + kt.hash} { + if err := b.deleteObj(ctx, "networkpolicies", name, nil); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} diff --git a/sandbox/kube_test.go b/sandbox/kube_test.go new file mode 100644 index 00000000..20af60f1 --- /dev/null +++ b/sandbox/kube_test.go @@ -0,0 +1,1115 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +// fakeKubeAPI is an in-memory stand-in for the parts of the Kubernetes API the +// backend uses: 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. + execFn func(pod string, argv []string) (stdout, stderr string, exit int) + // failPing makes pod list return 403. + failPing atomic.Bool +} + +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, + } + 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 !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) + 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 + } + if _, exists := store[name]; !exists { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + store[name] = o + f.ops = append(f.ops, "update "+kind+"/"+name) + writeJSON(w, o) + case r.Method == http.MethodDelete: + if _, ok := store[name]; !ok { + http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound) + return + } + delete(store, name) + f.ops = append(f.ops, "delete "+kind+"/"+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] { + 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 := f.execFn + f.mu.Unlock() + up := websocket.Upgrader{Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"}} + conn, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + if conn.Subprotocol() == "" { + f.t.Errorf("exec negotiated no channel subprotocol") + 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] +} + +func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *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) + } + b, err := NewKubernetesBackend(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, + }) + if err != nil { + t.Fatalf("NewKubernetesBackend: %v", err) + } + return b +} + +// 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 +} + +func execReq(argv ...string) ExecRequest { + req := ExecRequest{Argv: argv} + if err := ValidateExecRequest(&req); err != nil { + panic(err) + } + return req +} + +func TestKubeConfigFromEnv(t *testing.T) { + t.Setenv("ARTEX_KUBE_DATA_CLAIM", "data") + t.Setenv("ARTEX_KUBE_NAMESPACE", "ns1") + t.Setenv("ARTEX_KUBE_DNS_LABELS", "k8s-app=kube-dns,tier=dns") + t.Setenv("ARTEX_KUBE_PROXY_DENIED_CIDRS", "10.0.0.0/8, 192.168.1.7/16") + t.Setenv("ARTEX_KUBE_POD_READY_TIMEOUT", "45s") + t.Setenv("ARTEX_KUBE_IMAGE_PULL_POLICY", "Never") + t.Setenv("ARTEX_KUBE_RUNTIME_CLASS", "gvisor") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.DataClaim != "data" || cfg.Namespace != "ns1" || cfg.ImagePullPolicy != "Never" || cfg.RuntimeClassName != "gvisor" { + t.Fatalf("cfg = %+v", cfg) + } + if cfg.DNSPodLabels["tier"] != "dns" || cfg.DNSPodLabels["k8s-app"] != "kube-dns" { + t.Fatalf("dns labels = %v", cfg.DNSPodLabels) + } + if strings.Join(cfg.ProxyDeniedCIDRs, " ") != "10.0.0.0/8 192.168.0.0/16" { + t.Fatalf("denied CIDRs not masked: %v", cfg.ProxyDeniedCIDRs) + } + if cfg.PodReadyTimeout != 45*time.Second { + t.Fatalf("timeout = %v", cfg.PodReadyTimeout) + } + + for k, v := range map[string]string{ + "ARTEX_KUBE_PROXY_DENIED_CIDRS": "not-a-cidr", + "ARTEX_KUBE_DNS_LABELS": "novalue", + "ARTEX_KUBE_POD_READY_TIMEOUT": "-1s", + "ARTEX_KUBE_IMAGE_PULL_POLICY": "Sometimes", + } { + t.Run(k, func(t *testing.T) { + t.Setenv(k, v) + if _, err := KubeConfigFromEnv(); err == nil { + t.Fatalf("%s=%q accepted", k, v) + } + }) + } + t.Run("ipv6 denied cidr", func(t *testing.T) { + t.Setenv("ARTEX_KUBE_PROXY_DENIED_CIDRS", "fc00::/7") + if _, err := KubeConfigFromEnv(); err == nil { + t.Fatal("IPv6 prefix accepted inside the 0.0.0.0/0 ipBlock") + } + }) +} + +func TestNewKubernetesBackendValidation(t *testing.T) { + base := KubeConfig{APIServer: "http://127.0.0.1:1", Namespace: "ns", DataClaim: "c"} + if _, err := NewKubernetesBackend(base); err != nil { + t.Fatalf("valid config rejected: %v", err) + } + noClaim := base + noClaim.DataClaim = "" + if _, err := NewKubernetesBackend(noClaim); err == nil { + t.Fatal("missing data claim accepted") + } + for _, sp := range []string{"/abs", "../up", "a/../../b"} { + c := base + c.TasksSubPath = sp + if _, err := NewKubernetesBackend(c); err == nil { + t.Fatalf("sub path %q accepted", sp) + } + } + noAPI := base + noAPI.APIServer = "" + t.Setenv("KUBERNETES_SERVICE_HOST", "") + if _, err := NewKubernetesBackend(noAPI); err == nil { + t.Fatal("no API server and no in-cluster env accepted") + } + httpsNoCA := base + httpsNoCA.APIServer = "https://127.0.0.1:6443" + httpsNoCA.CAPath = filepath.Join(t.TempDir(), "missing.crt") + if _, err := NewKubernetesBackend(httpsNoCA); err == nil { + t.Fatal("https API server without a readable CA accepted") + } +} + +func TestKubeTaskNamesAreValidForAnyTaskID(t *testing.T) { + for _, id := range []string{"a", "Task_ABC.1-x", strings.Repeat("Z", 64), "0.-_"} { + if err := ValidateTaskID(id); err != nil { + continue + } + h := kubeTaskHash(id) + for _, n := range []string{"artex-w-" + h, "artex-p-" + h} { + if !dnsLabelRE.MatchString(n) { + t.Errorf("task %q -> name %q is not a DNS-1035 label", id, n) + } + } + } + if kubeTaskHash("a") == kubeTaskHash("A") { + t.Fatal("task hash is case-insensitive: distinct tasks would share pods") + } +} + +func TestKubeExecCreatesIsolatedTaskAndRunsCommand(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + taskID := "Task_1" + h := kubeTaskHash(taskID) + + req := execReq("sh", "-c", "echo hi; echo err >&2") + req.Env = map[string]string{"FOO": "a b; $(rm -rf /)", "BAR": "x=y"} + req.Workdir = "/workspace/sub" + req.ScopeDomains = []string{"example.com"} + req.ScopeCIDRs = []string{"203.0.113.0/24", "10.1.2.3"} + f.execFn = func(_ string, argv []string) (string, string, int) { return "hi\n", "err\n", 0 } + + res, err := b.Exec(ctx, taskID, req) + if err != nil { + t.Fatalf("Exec: %v", err) + } + if res.ExitCode != 0 || res.Stdout != "hi\n" || res.Stderr != "err\n" || res.TimedOut || res.Truncated { + t.Fatalf("result = %+v", res) + } + + // Ordering: both NetworkPolicies exist before any pod is created. + ops := f.opsSnapshot() + firstPod := -1 + policies := 0 + for i, op := range ops { + if strings.HasPrefix(op, "create pods/") && firstPod < 0 { + firstPod = i + } + if strings.HasPrefix(op, "create networkpolicies/") { + if firstPod >= 0 { + t.Fatalf("network policy created after a pod: %v", ops) + } + policies++ + } + } + if policies != 2 || firstPod < 0 { + t.Fatalf("ops = %v", ops) + } + + svc := f.obj("services", "artex-p-"+h) + clusterIP := dig(svc, "spec", "clusterIP").(string) + + // Exec argv: env(1) clears the environment, sets workdir, the worker base env and + // the request env, then artex-exec-wrap; every value is one argv element. + wantArgv := []string{"/usr/bin/env", "-i", "-C", "/workspace/sub"} + for _, kv := range workerBaseEnv(clusterIP) { + wantArgv = append(wantArgv, kv[0]+"="+kv[1]) + } + wantArgv = append(wantArgv, "BAR=x=y", "FOO=a b; $(rm -rf /)", + "/usr/local/bin/artex-exec-wrap", strconv.Itoa(DefaultTimeoutMS), "--", "sh", "-c", "echo hi; echo err >&2") + if got := f.lastExec(); strings.Join(got, "\x00") != strings.Join(wantArgv, "\x00") { + t.Fatalf("exec argv\n got %q\nwant %q", got, wantArgv) + } + // Before the first command, the network paths were probed in both pods. + f.mu.Lock() + probes := strings.Join(f.execContainers, ",") + firstProbe := strings.Join(f.execs[0], " ") + f.mu.Unlock() + if probes != "worker,egress-proxy,worker" || !strings.Contains(firstProbe, "/dev/tcp/"+clusterIP+"/3128") { + t.Fatalf("network probes = %s (%s)", probes, firstProbe) + } + if sel := dig(svc, "spec", "selector").(map[string]any); sel[LabelComponent] != ComponentProxy || sel[LabelTaskHash] != h { + t.Fatalf("service selector = %v", sel) + } + + // Worker pod hardening. + w := f.obj("pods", "artex-w-"+h) + if w == nil { + t.Fatal("worker pod missing") + } + spec := dig(w, "spec") + for k, want := range map[string]any{ + "automountServiceAccountToken": false, "enableServiceLinks": false, "hostNetwork": false, + "hostPID": false, "hostIPC": false, "dnsPolicy": "None", + } { + if got := dig(spec, k); got != want { + t.Errorf("worker spec.%s = %v, want %v", k, got, want) + } + } + if dig(spec, "securityContext", "runAsNonRoot") != true || dig(spec, "securityContext", "runAsUser") != float64(WorkerUID) || + dig(spec, "securityContext", "seccompProfile", "type") != "RuntimeDefault" { + t.Errorf("worker pod securityContext = %v", dig(spec, "securityContext")) + } + c := dig(spec, "containers", 0) + if dig(c, "securityContext", "readOnlyRootFilesystem") != true || dig(c, "securityContext", "allowPrivilegeEscalation") != false || + dig(c, "securityContext", "privileged") != false || dig(c, "securityContext", "capabilities", "drop", 0) != "ALL" { + t.Errorf("worker container securityContext = %v", dig(c, "securityContext")) + } + if dig(c, "image") != "artex-worker:test" || dig(c, "command", 0) != "/usr/local/bin/artex-exec-wrap" { + t.Errorf("worker image/command = %v %v", dig(c, "image"), dig(c, "command")) + } + if dig(c, "volumeMounts", 0, "subPath") != "tasks/"+taskID || dig(c, "volumeMounts", 0, "mountPath") != "/workspace" { + t.Errorf("worker workspace mount = %v", dig(c, "volumeMounts", 0)) + } + if dig(spec, "volumes", 0, "persistentVolumeClaim", "claimName") != "artex-data" { + t.Errorf("worker data volume = %v", dig(spec, "volumes", 0)) + } + if len(dig(c, "volumeMounts").([]any)) != 3 { + t.Errorf("worker has unexpected mounts: %v", dig(c, "volumeMounts")) + } + env := envOf(c) + if env["HTTP_PROXY"] != "http://"+clusterIP+":3128" || env["ALL_PROXY"] != "socks5h://"+clusterIP+":1080" { + t.Errorf("worker proxy env = %v (clusterIP %s)", env, clusterIP) + } + for k := range env { + if IsForbiddenEnvName(k) { + t.Errorf("worker env carries forbidden %s", k) + } + } + if dig(w, "metadata", "annotations", AnnotationTaskID) != taskID { + t.Errorf("worker annotations = %v", dig(w, "metadata", "annotations")) + } + + // Proxy pod: scope in env, audit sub path, same hardening. + p := f.obj("pods", "artex-p-"+h) + pc := dig(p, "spec", "containers", 0) + penv := envOf(pc) + if penv["ARTEX_SCOPE_DOMAINS"] != "example.com" || penv["ARTEX_SCOPE_CIDRS"] != "203.0.113.0/24,10.1.2.3" || penv["ARTEX_TASK_ID"] != taskID { + t.Errorf("proxy env = %v", penv) + } + if dig(pc, "volumeMounts", 0, "subPath") != "egress-audit/"+taskID || dig(pc, "volumeMounts", 0, "mountPath") != "/audit" { + t.Errorf("proxy audit mount = %v", dig(pc, "volumeMounts", 0)) + } + if dig(p, "spec", "automountServiceAccountToken") != false || dig(pc, "securityContext", "readOnlyRootFilesystem") != true { + t.Errorf("proxy pod not hardened") + } + + // Worker policy: egress only to own proxy on proxy ports, no ingress. + wp := f.obj("networkpolicies", "artex-w-"+h) + if dig(wp, "spec", "podSelector", "matchLabels", LabelComponent) != ComponentWorker || + dig(wp, "spec", "podSelector", "matchLabels", LabelTaskHash) != h { + t.Errorf("worker policy selector = %v", dig(wp, "spec", "podSelector")) + } + if n := len(dig(wp, "spec", "ingress").([]any)); n != 0 { + t.Errorf("worker policy allows ingress: %v", dig(wp, "spec", "ingress")) + } + eg := dig(wp, "spec", "egress").([]any) + if len(eg) != 1 || dig(eg[0], "to", 0, "podSelector", "matchLabels", LabelTaskHash) != h || + dig(eg[0], "to", 0, "podSelector", "matchLabels", LabelComponent) != ComponentProxy || len(dig(eg[0], "ports").([]any)) != 2 { + t.Errorf("worker policy egress = %v", eg) + } + + // Proxy policy: ingress only from own worker; egress DNS + public minus private + scope CIDRs. + pp := f.obj("networkpolicies", "artex-p-"+h) + if dig(pp, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", LabelTaskHash) != h || + dig(pp, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", LabelComponent) != ComponentWorker { + t.Errorf("proxy policy ingress = %v", dig(pp, "spec", "ingress")) + } + peg := dig(pp, "spec", "egress").([]any) + if dig(peg[0], "to", 0, "podSelector", "matchLabels", "k8s-app") != "kube-dns" { + t.Errorf("proxy DNS rule = %v", peg[0]) + } + except := dig(peg[1], "to", 0, "ipBlock", "except").([]any) + if dig(peg[1], "to", 0, "ipBlock", "cidr") != "0.0.0.0/0" || len(except) != len(DefaultProxyDeniedCIDRs) { + t.Errorf("proxy public rule = %v", peg[1]) + } + var scope []string + for _, blk := range dig(peg[2], "to").([]any) { + scope = append(scope, dig(blk, "ipBlock", "cidr").(string)) + } + if strings.Join(scope, ",") != "203.0.113.0/24,10.1.2.3/32" { + t.Errorf("proxy scope rule = %v", scope) + } + + // Per-task directories prepared for the mounts. + for _, d := range []string{filepath.Join(b.cfg.WorkspaceRoot, taskID), filepath.Join(b.cfg.AuditRoot, taskID)} { + if st, err := os.Stat(d); err != nil || !st.IsDir() { + t.Errorf("dir %s not prepared: %v", d, err) + } + } + if b.WorkerCount() != 1 { + t.Fatalf("WorkerCount = %d", b.WorkerCount()) + } +} + +func TestKubePinNodeAndWorkerLimits(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PinNode = "k3d-artex-server-0" + b.cfg.WorkerCPULimit, b.cfg.WorkerMemoryLimit = "500m", "1Gi" + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + h := kubeTaskHash("t1") + for _, name := range []string{"artex-w-" + h, "artex-p-" + h} { + term := dig(f.obj("pods", name), "spec", "affinity", "nodeAffinity", "requiredDuringSchedulingIgnoredDuringExecution", "nodeSelectorTerms", 0, "matchFields", 0) + if dig(term, "key") != "metadata.name" || dig(term, "operator") != "In" || dig(term, "values", 0) != "k3d-artex-server-0" { + t.Errorf("%s node affinity = %v", name, term) + } + } + lim := dig(f.obj("pods", "artex-w-"+h), "spec", "containers", 0, "resources", "limits") + if dig(lim, "cpu") != "500m" || dig(lim, "memory") != "1Gi" { + t.Errorf("worker limits = %v", lim) + } + // Without PinNode there is no affinity at all. + f2, srv2 := newFakeKubeAPI(t) + b2 := newTestKubeBackend(t, f2, srv2) + if _, err := b2.Exec(context.Background(), "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if a := dig(f2.obj("pods", "artex-w-"+h), "spec", "affinity"); a != nil { + t.Errorf("unpinned worker has affinity %v", a) + } +} + +func TestKubeExecReusesTaskAndReportsExitCodes(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + creates := len(f.opsSnapshot()) + + f.execFn = func(string, []string) (string, string, int) { return "", "boom", 3 } + res, err := b.Exec(ctx, "t1", execReq("false")) + if err != nil || res.ExitCode != 3 || res.Stderr != "boom" || res.TimedOut { + t.Fatalf("nonzero exit: res=%+v err=%v", res, err) + } + f.execFn = func(string, []string) (string, string, int) { return "", "timeout", 124 } + res, err = b.Exec(ctx, "t1", execReq("sleep", "999")) + if err != nil || res.ExitCode != 124 || !res.TimedOut { + t.Fatalf("timeout: res=%+v err=%v", res, err) + } + f.execFn = func(string, []string) (string, string, int) { return "", "", -1 } + if _, err := b.Exec(ctx, "t1", execReq("x")); err == nil { + t.Fatal("exec failure status (no exit code) not reported as error") + } + if got := len(f.opsSnapshot()); got != creates { + t.Fatalf("second exec mutated cluster: %v", f.opsSnapshot()[creates:]) + } +} + +func TestKubeExecTruncatesOutput(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + big := strings.Repeat("A", MaxOutputBytes+100*1024) + f.execFn = func(string, []string) (string, string, int) { return big, "small", 0 } + res, err := b.Exec(context.Background(), "t1", execReq("cat", "big")) + if err != nil { + t.Fatal(err) + } + if len(res.Stdout) != MaxOutputBytes || !res.Truncated || res.Stderr != "small" { + t.Fatalf("stdout=%d truncated=%v stderr=%q", len(res.Stdout), res.Truncated, res.Stderr) + } +} + +func TestKubeScopeChangeRecreatesOnlyProxy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + req := execReq("true") + req.ScopeDomains = []string{"a.example"} + if _, err := b.Exec(ctx, "t1", req); err != nil { + t.Fatal(err) + } + ip := dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP") + mark := len(f.opsSnapshot()) + + req.ScopeDomains = []string{"b.example"} + req.ScopeCIDRs = []string{"198.51.100.0/24"} + if _, err := b.Exec(ctx, "t1", req); err != nil { + t.Fatal(err) + } + ops := strings.Join(f.opsSnapshot()[mark:], ",") + if !strings.Contains(ops, "delete pods/artex-p-"+h) || !strings.Contains(ops, "create pods/artex-p-"+h) { + t.Fatalf("proxy not recreated: %s", ops) + } + if strings.Contains(ops, "pods/artex-w-") || strings.Contains(ops, "services/") { + t.Fatalf("worker or service touched on scope change: %s", ops) + } + if !strings.Contains(ops, "update networkpolicies/artex-p-"+h) { + t.Fatalf("proxy policy not updated: %s", ops) + } + if penv := envOf(dig(f.obj("pods", "artex-p-"+h), "spec", "containers", 0)); penv["ARTEX_SCOPE_DOMAINS"] != "b.example" { + t.Fatalf("proxy scope env = %v", penv) + } + if dig(f.obj("services", "artex-p-"+h), "spec", "clusterIP") != ip { + t.Fatal("service ClusterIP changed: worker proxy env would be stale") + } + peg := dig(f.obj("networkpolicies", "artex-p-"+h), "spec", "egress").([]any) + if len(peg) != 3 || dig(peg[2], "to", 0, "ipBlock", "cidr") != "198.51.100.0/24" { + t.Fatalf("proxy policy scope = %v", peg) + } +} + +func TestKubeWaitsForNetworkPolicyToApply(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + var probes atomic.Int32 + f.execFn = func(_ string, argv []string) (string, string, int) { + if strings.Contains(strings.Join(argv, " "), "/dev/tcp/") { + // The CNI has not programmed the policy yet for the first few probes. + if probes.Add(1) <= 3 { + return "", "connection refused", 1 + } + } + return "ok", "", 0 + } + res, err := b.Exec(context.Background(), "t1", execReq("true")) + if err != nil || res.Stdout != "ok" { + t.Fatalf("exec = %+v, %v", res, err) + } + if probes.Load() != 4 { + t.Fatalf("worker probe attempts = %d, want 4", probes.Load()) + } +} + +func TestKubeNetworkNeverReadyFails(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 1500 * time.Millisecond + f.execFn = func(_ string, argv []string) (string, string, int) { + if argv[0] == "getent" { + return "", "", 2 // DNS blocked: the proxy policy never applied + } + return "", "", 0 + } + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "proxy to cluster DNS") { + t.Fatalf("err = %v", err) + } + if b.WorkerCount() != 0 { + t.Fatal("task registered although its network never came up") + } +} + +func TestKubeRecreatesDeadWorker(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) + } + f.setPodPhase("artex-w-"+h, "Failed", false) + mark := len(f.opsSnapshot()) + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + // Policies are re-asserted (repairing any tampering) before the pod returns; + // the proxy and the service are left alone. + ops := strings.Join(f.opsSnapshot()[mark:], ",") + want := "update networkpolicies/artex-w-" + h + ",update networkpolicies/artex-p-" + h + + ",delete pods/artex-w-" + h + ",create pods/artex-w-" + h + if ops != want { + t.Fatalf("ops\n got %s\nwant %s", ops, want) + } +} + +func TestKubeImagePullErrorFailsFast(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 30 * time.Second + f.podMode["artex-w-"+kubeTaskHash("t1")] = "pull-error" + start := time.Now() + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "ImagePullBackOff") { + t.Fatalf("err = %v", err) + } + if time.Since(start) > 5*time.Second { + t.Fatal("pull error waited for the full readiness timeout") + } + if b.WorkerCount() != 0 { + t.Fatal("failed task tracked as a worker") + } +} + +func TestKubePodReadyTimeout(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + b.cfg.PodReadyTimeout = 700 * time.Millisecond + f.podMode["artex-p-"+kubeTaskHash("t1")] = "pending" + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err == nil || !strings.Contains(err.Error(), "not ready") { + t.Fatalf("err = %v", err) + } +} + +func TestKubeRefusesForeignService(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + h := kubeTaskHash("t1") + f.objs["services"]["artex-p-"+h] = map[string]any{ + "metadata": map[string]any{"name": "artex-p-" + h, "labels": map[string]any{"app": "evil"}}, + "spec": map[string]any{"clusterIP": "10.43.9.9"}, + } + _, err := b.Exec(context.Background(), "t1", execReq("true")) + if err == nil || !strings.Contains(err.Error(), "untrusted labels") { + t.Fatalf("err = %v", err) + } + if f.count("pods") != 0 { + t.Fatal("pods created behind a foreign service") + } +} + +func TestKubeKill(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + h := kubeTaskHash("t1") + if err := b.Kill(ctx, "t1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("kill unknown = %v", err) + } + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + f.execFn = nil + if err := b.Kill(ctx, "t1"); err != nil { + t.Fatal(err) + } + if got := strings.Join(f.lastExec(), " "); got != "/usr/local/bin/artex-exec-wrap --kill-uid 10001" { + t.Fatalf("kill argv = %q", got) + } + if f.obj("pods", "artex-w-"+h) == nil { + t.Fatal("successful kill-uid removed the worker") + } + + // kill-uid fails: fall back to deleting the worker pod; next exec recreates it. + f.execFn = func(string, []string) (string, string, int) { return "", "survivors", 1 } + if err := b.Kill(ctx, "t1"); err != nil { + t.Fatal(err) + } + if f.obj("pods", "artex-w-"+h) != nil { + t.Fatal("worker pod survived a failed kill-uid") + } + if f.obj("pods", "artex-p-"+h) == nil { + t.Fatal("proxy pod removed by Kill") + } + f.execFn = nil + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if f.obj("pods", "artex-w-"+h) == nil { + t.Fatal("worker not recreated after kill fallback") + } +} + +func TestKubeExecCancelKillsTask(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) + } + release := make(chan struct{}) + var killed atomic.Bool + f.execFn = func(_ string, argv []string) (string, string, int) { + if len(argv) > 1 && argv[1] == "--kill-uid" { + killed.Store(true) + return "", "", 0 + } + <-release + return "", "", 0 + } + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + _, err := b.Exec(ctx, "t1", execReq("sleep", "100")) + close(release) + if err == nil { + t.Fatal("cancelled exec returned no error") + } + if !killed.Load() { + t.Fatal("cancelled exec did not kill the task's processes") + } +} + +func TestKubeDelete(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if err := b.Delete(ctx, "t1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("delete unknown = %v", err) + } + if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil { + t.Fatal(err) + } + if _, err := b.Exec(ctx, "t2", execReq("true")); err != nil { + t.Fatal(err) + } + if err := b.Delete(ctx, "t1"); err != nil { + t.Fatal(err) + } + h1, h2 := kubeTaskHash("t1"), kubeTaskHash("t2") + for _, kind := range []string{"pods", "services", "networkpolicies"} { + for _, pfx := range []string{"artex-w-", "artex-p-"} { + if f.obj(kind, pfx+h1) != nil { + t.Errorf("%s/%s%s survived Delete", kind, pfx, h1) + } + } + } + if f.obj("pods", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-w-"+h2) == nil { + t.Fatal("Delete removed another task's objects") + } + // Policies go after pods: no window where a pod exists without its policy. + ops := f.opsSnapshot() + lastPod, firstPol := -1, len(ops) + for i, op := range ops { + if strings.HasPrefix(op, "delete pods/") && strings.HasSuffix(op, h1) { + lastPod = i + } + if strings.HasPrefix(op, "delete networkpolicies/") && i < firstPol { + firstPol = i + } + } + if lastPod > firstPol { + t.Fatalf("policy deleted before pod: %v", ops) + } + if _, err := os.Stat(filepath.Join(b.cfg.WorkspaceRoot, "t1")); err != nil { + t.Fatalf("workspace removed by Delete: %v", err) + } + if b.WorkerCount() != 1 { + t.Fatalf("WorkerCount = %d", b.WorkerCount()) + } +} + +func TestKubeRecoverAdoptsOnlyManagedPods(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + ctx := context.Background() + if _, err := b.Exec(ctx, "good", execReq("true")); err != nil { + t.Fatal(err) + } + // A pod with runner labels whose annotation does not hash to its label, a pod with + // an invalid task id, and an unlabelled pod: none may be adopted. + f.objs["pods"]["artex-w-forged"] = map[string]any{"metadata": map[string]any{"name": "artex-w-forged", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: "0000000000000000"}, + "annotations": map[string]any{AnnotationTaskID: "victim"}}} + f.objs["pods"]["artex-w-bad"] = map[string]any{"metadata": map[string]any{"name": "artex-w-bad", + "labels": map[string]any{LabelManagedBy: ManagedByRunner, LabelComponent: ComponentWorker, LabelTaskHash: kubeTaskHash("../x")}, + "annotations": map[string]any{AnnotationTaskID: "../x"}}} + f.objs["pods"]["other"] = map[string]any{"metadata": map[string]any{"name": "other", "labels": map[string]any{"app": "x"}}} + + fresh := newTestKubeBackend(t, f, srv) + n, err := fresh.Recover(ctx) + if err != nil || n != 1 { + t.Fatalf("Recover = %d, %v", n, err) + } + kt := fresh.tasks["good"] + h := kubeTaskHash("good") + if kt == nil || kt.workerPod != "artex-w-"+h || kt.proxyPod != "artex-p-"+h || kt.proxyIP == "" || kt.scopeHash == "" { + t.Fatalf("recovered task = %+v", kt) + } + // After recovery the same scope needs no cluster changes, and Kill/Delete work. + mark := len(f.opsSnapshot()) + if _, err := fresh.Exec(ctx, "good", execReq("true")); err != nil { + t.Fatal(err) + } + if ops := f.opsSnapshot()[mark:]; len(ops) != 0 { + t.Fatalf("exec after recover mutated cluster: %v", ops) + } + if err := fresh.Delete(ctx, "good"); err != nil { + t.Fatal(err) + } +} + +func TestKubeConcurrentExecSameTaskCreatesOnce(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + var wg sync.WaitGroup + errs := make(chan error, 8) + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil { + errs <- err + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } + creates := 0 + for _, op := range f.opsSnapshot() { + if strings.HasPrefix(op, "create pods/") || strings.HasPrefix(op, "delete pods/") { + creates++ + } + } + if creates != 2 { + t.Fatalf("pod create/delete ops = %d: %v", creates, f.opsSnapshot()) + } +} + +func TestKubePingAndRunnerHealth(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if err := b.Ping(context.Background()); err != nil { + t.Fatalf("ping: %v", err) + } + f.failPing.Store(true) + if err := b.Ping(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("ping with RBAC denied = %v, want ErrDockerUnavailable", err) + } + + rs, err := NewRunnerServer("tok", "v", b) + if err != nil { + t.Fatal(err) + } + h := httptest.NewServer(rs.Handler()) + defer h.Close() + get := func() int { + req, _ := http.NewRequest(http.MethodGet, h.URL+"/v1/health", nil) + req.Header.Set("Authorization", "Bearer tok") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + return resp.StatusCode + } + if code := get(); code != http.StatusConflict { + t.Fatalf("health with API denied = %d", code) + } + f.failPing.Store(false) + if code := get(); code != http.StatusOK { + t.Fatalf("health = %d", code) + } +} + +func TestKubeRunnerHTTPEndToEnd(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + rs, _ := NewRunnerServer("tok", "v", b) + h := httptest.NewServer(rs.Handler()) + defer h.Close() + c := NewClient(h.URL, "tok") + ctx := context.Background() + f.execFn = func(_ string, argv []string) (string, string, int) { return "out:" + argv[len(argv)-1], "", 0 } + res, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"echo", "x"}}) + if err != nil || res.Stdout != "out:x" { + t.Fatalf("exec via client = %+v, %v", res, err) + } + if _, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"x"}, Workdir: "/etc"}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("workdir escape = %v", err) + } + if _, err := c.Exec(ctx, "Task.HTTP", ExecRequest{Argv: []string{"x"}, Env: map[string]string{"AWS_SECRET": "x"}}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("forbidden env = %v", err) + } + if _, err := c.Kill(ctx, "Task.HTTP"); err != nil { + t.Fatal(err) + } + if _, err := c.Delete(ctx, "Task.HTTP"); err != nil { + t.Fatal(err) + } + if _, err := c.Delete(ctx, "Task.HTTP"); !errors.Is(err, ErrNotFound) { + t.Fatalf("second delete = %v", err) + } +} + +func TestKubeAPIUnauthorizedIsUnavailable(t *testing.T) { + f, srv := newFakeKubeAPI(t) + b := newTestKubeBackend(t, f, srv) + if err := os.WriteFile(b.cfg.TokenPath, []byte("wrong"), 0o600); err != nil { + t.Fatal(err) + } + if err := b.Ping(context.Background()); !IsUnavailable(err) { + t.Fatalf("ping with bad token = %v", err) + } + // Token is re-read per request: rotating it back restores access. + if err := os.WriteFile(b.cfg.TokenPath, []byte(f.token), 0o600); err != nil { + t.Fatal(err) + } + if err := b.Ping(context.Background()); err != nil { + t.Fatalf("ping after token rotation: %v", err) + } +} diff --git a/sandbox/types.go b/sandbox/types.go index 392b349d..6abd4eb1 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"