From 5fe94b67ec55c76c3d8a9b42a2247fa0075aec74 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:35:48 +0200 Subject: [PATCH 1/5] feat(sandbox): Kubernetes backend for artex-runner ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. Per-task NetworkPolicies are applied before the pods and removed after them; the runner waits until they are in effect before the first command, runs commands through pods/exec under env -i and artex-exec-wrap, and re-adopts task pods after a restart. Unit tests run against a fake API server; a live test (TestKubeSandboxE2E) drives a deployed runner. --- CHANGELOG.md | 4 + cmd/artex-runner/main.go | 67 ++- go.mod | 2 +- sandbox/kube.go | 1238 ++++++++++++++++++++++++++++++++++++++ sandbox/kube_e2e_test.go | 323 ++++++++++ sandbox/kube_test.go | 1115 ++++++++++++++++++++++++++++++++++ sandbox/types.go | 4 + 7 files changed, 2733 insertions(+), 20 deletions(-) create mode 100644 sandbox/kube.go create mode 100644 sandbox/kube_e2e_test.go create mode 100644 sandbox/kube_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 928afa0a6..47d865941 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 - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go index 830313124..9f3a77ad0 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 c5183b75c..d773029a2 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 000000000..35ca52708 --- /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_e2e_test.go b/sandbox/kube_e2e_test.go new file mode 100644 index 000000000..2121d5aad --- /dev/null +++ b/sandbox/kube_e2e_test.go @@ -0,0 +1,323 @@ +package sandbox + +import ( + "context" + "fmt" + "net" + "os" + "os/exec" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +// TestKubeSandboxE2E drives a real artex-runner deployed by the Helm chart with +// backend=kubernetes, through its HTTP API, and inspects the cluster with kubectl. +// scripts/k3d-e2e.sh sets everything up. Enable with: +// +// ARTEX_SANDBOX_KUBE_E2E=1 +// ARTEX_RUNNER_TOKEN=... (the release's ARTEX_RUNNER_TOKEN) +// ARTEX_E2E_NAMESPACE=artex +// ARTEX_E2E_KUBECONTEXT=k3d-artex (optional) +// ARTEX_E2E_INTERNET=1 (optional: test allowed egress to example.com) +func TestKubeSandboxE2E(t *testing.T) { + if os.Getenv("ARTEX_SANDBOX_KUBE_E2E") != "1" { + t.Skip("set ARTEX_SANDBOX_KUBE_E2E=1 (see scripts/k3d-e2e.sh)") + } + ns := envDefault("ARTEX_E2E_NAMESPACE", "artex") + kctx := os.Getenv("ARTEX_E2E_KUBECONTEXT") + kubectl := func(args ...string) (string, error) { + full := []string{"-n", ns} + if kctx != "" { + full = append(full, "--context", kctx) + } + out, err := exec.Command("kubectl", append(full, args...)...).CombinedOutput() + return strings.TrimSpace(string(out)), err + } + // The test owns its port-forward: a forward to a Service is pinned to one pod + // and dies when that pod does, which the runner-restart case causes. + const pfPort = "18799" + var pf *exec.Cmd + startPF := func() { + args := []string{"-n", ns, "port-forward", "svc/" + envDefault("ARTEX_E2E_RUNNER_SVC", "artex-runner"), pfPort + ":8789"} + if kctx != "" { + args = append([]string{"--context", kctx}, args...) + } + pf = exec.Command("kubectl", args...) + if err := pf.Start(); err != nil { + t.Fatalf("port-forward: %v", err) + } + for i := 0; i < 50; i++ { + if conn, err := net.DialTimeout("tcp", "127.0.0.1:"+pfPort, 200*time.Millisecond); err == nil { + conn.Close() + return + } + time.Sleep(200 * time.Millisecond) + } + t.Fatal("port-forward did not come up") + } + stopPF := func() { + if pf != nil && pf.Process != nil { + _ = pf.Process.Kill() + _ = pf.Wait() + } + } + startPF() + t.Cleanup(stopPF) + + c := NewClient("http://127.0.0.1:"+pfPort, os.Getenv(EnvRunnerToken)) + ctx := context.Background() + + health, err := c.Health(ctx) + if err != nil || !health.OK { + t.Fatalf("runner health = %+v, %v", health, err) + } + + // A unique task per run; IDs with uppercase and '_' exercise the name hashing. + taskID := fmt.Sprintf("E2E_task.%d", time.Now().UnixNano()) + h := kubeTaskHash(taskID) + t.Cleanup(func() { _, _ = c.Delete(context.Background(), taskID) }) + + run := func(t *testing.T, req ExecRequest) ExecResponse { + t.Helper() + if req.TimeoutMS == 0 { + req.TimeoutMS = 60000 + } + res, err := c.Exec(ctx, taskID, req) + if err != nil { + t.Fatalf("exec %v: %v", req.Argv, err) + } + return res + } + sh := func(t *testing.T, script string) ExecResponse { + t.Helper() + return run(t, ExecRequest{Argv: []string{"bash", "-c", script}}) + } + + t.Run("identity and hardening", func(t *testing.T) { + res := sh(t, `id -u; id -g; cat /proc/self/status | grep -E '^(NoNewPrivs|CapEff)'`) + if res.ExitCode != 0 { + t.Fatalf("%+v", res) + } + lines := strings.Fields(res.Stdout) + if lines[0] != "10001" || lines[1] != "10001" { + t.Fatalf("uid/gid = %v", lines[:2]) + } + if !regexpMatch(`NoNewPrivs:\s+1`, res.Stdout) { + t.Errorf("no_new_privs not set: %q", res.Stdout) + } + if !regexpMatch(`CapEff:\s+0000000000000000`, res.Stdout) { + t.Errorf("effective capabilities not empty: %q", res.Stdout) + } + if r := sh(t, `touch /etc/x 2>&1; echo rc=$?`); !strings.Contains(r.Stdout, "rc=1") { + t.Errorf("root filesystem writable: %q", r.Stdout) + } + if r := sh(t, `ls /var/run/secrets/kubernetes.io/serviceaccount 2>&1; echo rc=$?`); strings.Contains(r.Stdout, "token") { + t.Errorf("service account token mounted: %q", r.Stdout) + } + if r := sh(t, `env`); strings.Contains(r.Stdout, "KUBERNETES_") || strings.Contains(r.Stdout, "ARTEX_") || strings.Contains(r.Stdout, "ANTHROPIC") { + t.Errorf("worker env leaks cluster or server values: %q", r.Stdout) + } + }) + + t.Run("workspace persists and workdir and env apply", func(t *testing.T) { + if r := sh(t, `mkdir -p sub && echo persisted > sub/f.txt`); r.ExitCode != 0 { + t.Fatalf("%+v", r) + } + r := run(t, ExecRequest{Argv: []string{"bash", "-c", `pwd; cat f.txt; printf '%s' "$WEIRD"`}, Workdir: "/workspace/sub", + Env: map[string]string{"WEIRD": `a b;$(id) "q"`}}) + if r.ExitCode != 0 || r.Stdout != "/workspace/sub\npersisted\na b;$(id) \"q\"" { + t.Fatalf("%+v", r) + } + }) + + t.Run("exit codes, timeout, truncation", func(t *testing.T) { + if r := sh(t, `exit 7`); r.ExitCode != 7 || r.TimedOut { + t.Fatalf("%+v", r) + } + r := run(t, ExecRequest{Argv: []string{"sleep", "60"}, TimeoutMS: 1500}) + if r.ExitCode != 124 || !r.TimedOut || r.DurationMS > 15000 { + t.Fatalf("timeout: %+v", r) + } + r = sh(t, `head -c 3000000 /dev/zero | tr '\0' A`) + if len(r.Stdout) != MaxOutputBytes || !r.Truncated { + t.Fatalf("truncation: len=%d truncated=%v", len(r.Stdout), r.Truncated) + } + }) + + t.Run("cluster objects", func(t *testing.T) { + out, err := kubectl("get", "pods,svc,networkpolicy", "-l", LabelTaskHash+"="+h, "-o", "name") + if err != nil { + t.Fatal(out) + } + for _, want := range []string{"pod/artex-w-" + h, "pod/artex-p-" + h, "service/artex-p-" + h, + "networkpolicy.networking.k8s.io/artex-w-" + h, "networkpolicy.networking.k8s.io/artex-p-" + h} { + if !strings.Contains(out, want) { + t.Errorf("missing %s in:\n%s", want, out) + } + } + out, _ = kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.annotations.artex\\.task}") + if out != taskID { + t.Errorf("task annotation = %q", out) + } + }) + + t.Run("network isolation", func(t *testing.T) { + lookup := func(args ...string) string { + out, err := kubectl(args...) + if err != nil { + return "" + } + return out + } + apiIP := lookup("get", "svc", "kubernetes", "-n", "default", "-o", "jsonpath={.spec.clusterIP}") + panelIP := lookup("get", "svc", "-l", "app.kubernetes.io/component=panel", "-o", "jsonpath={.items[0].spec.clusterIP}") + pgPod := lookup("get", "pod", "-l", "app.kubernetes.io/component=postgres", "-o", "jsonpath={.items[0].status.podIP}") + dnsIP := lookup("get", "svc", "kube-dns", "-n", "kube-system", "-o", "jsonpath={.spec.clusterIP}") + targets := map[string]string{ + "internet": "1.1.1.1:443", + "kube-api": apiIP + ":443", + "panel": panelIP + ":8787", + "postgres": pgPod + ":5432", + "kube-dns": dnsIP + ":53", + "metadata": "169.254.169.254:80", + } + for name, addr := range targets { + if strings.HasPrefix(addr, ":") { + t.Logf("skip %s: address unknown", name) + continue + } + host, port, _ := strings.Cut(addr, ":") + // Direct TCP connect, bypassing the proxy: must fail. + r := sh(t, fmt.Sprintf(`timeout 6 bash -c 'exec 3<>/dev/tcp/%s/%s' 2>/dev/null && echo OPEN || echo BLOCKED`, host, port)) + if !strings.Contains(r.Stdout, "BLOCKED") { + t.Errorf("worker reached %s (%s) directly: %q", name, addr, r.Stdout) + } + } + // Through the proxy: cluster addresses are refused BY THE PROXY (403), which + // also proves the worker reaches its proxy (a connect failure would hide it). + if panelIP != "" { + r := sh(t, fmt.Sprintf(`curl -s -o /dev/null -w '%%{http_code}' --max-time 10 http://%s:8787/api/health`, panelIP)) + if r.Stdout != "403" { + t.Errorf("panel via proxy: got %q, want the proxy's 403", r.Stdout) + } + } + // Out-of-scope domain: the proxy answers the CONNECT with 403. + r := sh(t, `curl -s -o /dev/null -w '%{http_connect}' --max-time 15 https://example.org`) + if r.Stdout != "403" { + t.Errorf("out-of-scope CONNECT: got %q, want the proxy's 403", r.Stdout) + } + // SOCKS5 path refuses too. + r = sh(t, `curl -s -o /dev/null -w '%{http_code}' --max-time 15 --socks5-hostname "${ALL_PROXY#socks5h://}" https://example.org; echo " rc=$?"`) + if strings.HasPrefix(r.Stdout, "200") { + t.Errorf("out-of-scope host reachable over SOCKS5: %q", r.Stdout) + } + }) + + t.Run("in-scope egress through proxy", func(t *testing.T) { + if os.Getenv("ARTEX_E2E_INTERNET") != "1" { + t.Skip("set ARTEX_E2E_INTERNET=1 to test egress to example.com") + } + r := run(t, ExecRequest{Argv: []string{"bash", "-c", `curl -s -o /dev/null -w '%{http_code}' --max-time 20 https://example.com`}, + ScopeDomains: []string{"example.com"}}) + if r.Stdout != "200" { + t.Fatalf("in-scope request: %+v", r) + } + // The proxy logs the decision to the per-task audit file on the volume. + audit, err := kubectl("logs", "artex-p-"+h) + if err != nil || !strings.Contains(audit, "example.com") { + t.Errorf("proxy decision not logged: %v %q", err, audit) + } + // Scope change replaced the proxy; the worker kept its workspace. + if r := sh(t, `cat sub/f.txt`); r.Stdout != "persisted\n" { + t.Errorf("workspace lost across scope change: %+v", r) + } + }) + + t.Run("kill stops running commands", func(t *testing.T) { + var wg sync.WaitGroup + var res ExecResponse + wg.Add(1) + go func() { + defer wg.Done() + res, _ = c.Exec(ctx, taskID, ExecRequest{Argv: []string{"sleep", "300"}, TimeoutMS: 600000}) + }() + time.Sleep(3 * time.Second) + start := time.Now() + if _, err := c.Kill(ctx, taskID); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("exec still running 30s after Kill") + } + if res.ExitCode == 0 { + t.Errorf("killed exec exit code 0: %+v", res) + } + t.Logf("kill returned the exec in %s (exit %d)", time.Since(start), res.ExitCode) + if r := sh(t, `pgrep -u 10001 sleep || echo none`); !strings.Contains(r.Stdout, "none") { + t.Errorf("sleep survived Kill: %q", r.Stdout) + } + }) + + t.Run("runner restart recovers tasks", func(t *testing.T) { + before, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}") + if out, err := kubectl("rollout", "restart", "deploy", "-l", "app.kubernetes.io/component=runner"); err != nil { + t.Fatal(out) + } + if out, err := kubectl("rollout", "status", "deploy", "-l", "app.kubernetes.io/component=runner", "--timeout=120s"); err != nil { + t.Fatal(out) + } + stopPF() + startPF() + var r ExecResponse + var err error + for i := 0; i < 30; i++ { + r, err = c.Exec(ctx, taskID, ExecRequest{Argv: []string{"cat", "sub/f.txt"}, TimeoutMS: 30000}) + if err == nil { + break + } + time.Sleep(2 * time.Second) + } + if err != nil || r.Stdout != "persisted\n" { + t.Fatalf("exec after runner restart: %+v %v", r, err) + } + after, _ := kubectl("get", "pod", "artex-w-"+h, "-o", "jsonpath={.metadata.uid}") + if before == "" || before != after { + t.Errorf("worker pod replaced across runner restart (%s -> %s): recovery did not adopt it", before, after) + } + }) + + t.Run("delete removes task objects", func(t *testing.T) { + if _, err := c.Delete(ctx, taskID); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(60 * time.Second) + for { + out, _ := kubectl("get", "pods,svc,networkpolicy", "-l", LabelTaskHash+"="+h, "-o", "name") + if out == "" || strings.Contains(out, "No resources") { + break + } + if time.Now().After(deadline) { + t.Fatalf("objects left after delete:\n%s", out) + } + time.Sleep(2 * time.Second) + } + }) +} + +func envDefault(k, def string) string { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return v + } + return def +} + +func regexpMatch(pattern, s string) bool { + return regexp.MustCompile(pattern).MatchString(s) +} diff --git a/sandbox/kube_test.go b/sandbox/kube_test.go new file mode 100644 index 000000000..20af60f15 --- /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 9995e26d1..4cee149a9 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" From f8d6a2b2ec7fb03ea031a8af256c9f0ac15af83a Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:21 +0200 Subject: [PATCH 2/5] feat(deploy): Helm chart with the Kubernetes sandbox deploy/helm/artex deploys the panel, PostgreSQL and artex-runner with a namespace-scoped Role, default-deny NetworkPolicies and a values schema. A volume-permissions init container restores root ownership of /app/data and /app/keys, fixing the isolation self-test failure on world-writable volumes (#620). scripts/k3d-e2e.sh and the kubernetes CI job test it live on k3d. --- .github/workflows/ci.yml | 50 +- CHANGELOG.md | 1 + INSTALL.md | 4 + deploy/helm/artex/Chart.yaml | 14 + deploy/helm/artex/README.md | 143 +++++ deploy/helm/artex/templates/NOTES.txt | 26 + deploy/helm/artex/templates/_helpers.tpl | 74 +++ deploy/helm/artex/templates/ingress.yaml | 31 + .../helm/artex/templates/networkpolicy.yaml | 87 +++ deploy/helm/artex/templates/panel.yaml | 217 +++++++ deploy/helm/artex/templates/postgres.yaml | 108 ++++ deploy/helm/artex/templates/pvc.yaml | 37 ++ deploy/helm/artex/templates/runner.yaml | 205 +++++++ deploy/helm/artex/templates/secret.yaml | 28 + .../artex/templates/tests/test-panel.yaml | 38 ++ deploy/helm/artex/values.schema.json | 73 +++ deploy/helm/artex/values.yaml | 154 +++++ sandbox/helmchart_test.go | 568 ++++++++++++++++++ scripts/k3d-e2e.sh | 103 ++++ 19 files changed, 1960 insertions(+), 1 deletion(-) create mode 100644 deploy/helm/artex/Chart.yaml create mode 100644 deploy/helm/artex/README.md create mode 100644 deploy/helm/artex/templates/NOTES.txt create mode 100644 deploy/helm/artex/templates/_helpers.tpl create mode 100644 deploy/helm/artex/templates/ingress.yaml create mode 100644 deploy/helm/artex/templates/networkpolicy.yaml create mode 100644 deploy/helm/artex/templates/panel.yaml create mode 100644 deploy/helm/artex/templates/postgres.yaml create mode 100644 deploy/helm/artex/templates/pvc.yaml create mode 100644 deploy/helm/artex/templates/runner.yaml create mode 100644 deploy/helm/artex/templates/secret.yaml create mode 100644 deploy/helm/artex/templates/tests/test-panel.yaml create mode 100644 deploy/helm/artex/values.schema.json create mode 100644 deploy/helm/artex/values.yaml create mode 100644 sandbox/helmchart_test.go create mode 100755 scripts/k3d-e2e.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5aaf7a9dc..0012a95e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: web: ${{ steps.filter.outputs.web }} python: ${{ steps.filter.outputs.python }} shell: ${{ steps.filter.outputs.shell }} + kubernetes: ${{ steps.filter.outputs.kubernetes }} steps: - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 id: filter @@ -40,6 +41,19 @@ jobs: - '**/*.py' - 'scripts/benchmark/**' - '.github/**' + kubernetes: + - 'sandbox/**' + - 'deploy/**' + - 'cmd/artex-runner/**' + - 'cmd/artex-exec-wrap/**' + - 'cmd/artex-egress-proxy/**' + - 'Dockerfile.runner' + - 'Dockerfile.worker' + - 'Dockerfile.egress-proxy' + - 'scripts/k3d-e2e.sh' + - 'go.mod' + - 'go.sum' + - '.github/workflows/ci.yml' # Added files too: a new top-level directory must appear in the bot summary. shell: - '**/*.sh' @@ -188,7 +202,7 @@ jobs: # shellcheck is preinstalled on the ubuntu runners. -S warning: the scripts # currently have only info-level notes (intentional A && B || C chains in # update.sh, an unquoted glob in backup.sh's prune), so fail on warnings. - - run: shellcheck -S warning install.sh update.sh start.sh scripts/backup.sh scripts/verify.sh reset-password.sh scripts/extract-changelog-section.sh scripts/test-extract-changelog-section.sh .github/scripts/bot.sh scripts/test-bot-context.sh scripts/test-start-sh.sh + - run: shellcheck -S warning install.sh update.sh start.sh scripts/backup.sh scripts/verify.sh reset-password.sh scripts/extract-changelog-section.sh scripts/test-extract-changelog-section.sh .github/scripts/bot.sh scripts/test-bot-context.sh scripts/test-start-sh.sh scripts/k3d-e2e.sh - run: bash scripts/test-extract-changelog-section.sh # start.sh is the Docker ENTRYPOINT and runs under dash there, as /bin/sh does here. - run: bash scripts/test-start-sh.sh @@ -197,6 +211,40 @@ jobs: # scripts/benchmark/ exist. - run: bash scripts/test-bot-context.sh + # Live test of the Kubernetes sandbox backend and the Helm chart on k3d: the runner, + # worker and egress-proxy images are built from this checkout, the chart is installed + # runner-only (the panel image is not needed), and TestKubeSandboxE2E checks pod + # hardening, NetworkPolicy isolation, the egress proxy, kill, recovery and cleanup. + kubernetes: + needs: changes + if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.kubernetes == 'true') }} + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + K3D_VERSION: v5.9.0 + # Pinned here, not taken from the release's own checksums file (see the + # Dockerfile tools stage for why). + K3D_SHA256: 06d8f25bc3a971c4eb29e0ff08429b180402db0f4dec838c9eac427e296800a0 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + with: + go-version-file: go.mod + - name: install k3d + run: | + curl -fsSL -o /tmp/k3d "https://github.com/k3d-io/k3d/releases/download/${K3D_VERSION}/k3d-linux-amd64" + echo "${K3D_SHA256} /tmp/k3d" | sha256sum -c - + sudo install -m 0755 /tmp/k3d /usr/local/bin/k3d + k3d version + helm version --short + - name: helm lint + run: helm lint --strict deploy/helm/artex + - name: k3d sandbox e2e + env: + RUNNER_ONLY: "1" + ARTEX_E2E_INTERNET: "1" + run: bash scripts/k3d-e2e.sh + web: needs: changes if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.web == 'true') }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 47d865941..14b467fbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,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. 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. +- **Helm chart for Kubernetes.** `deploy/helm/artex` deploys the panel, PostgreSQL and `artex-runner` with the Kubernetes sandbox backend, a namespace-scoped Role, NetworkPolicies and a values schema. A chart-level default-deny covers every runner-managed pod, so a missing per-task policy fails closed. The `volume-permissions` init container fixes the `Bash can create files in /app/data` self-test failure on world-writable volumes (#620). `scripts/k3d-e2e.sh` and the new `kubernetes` CI job test the chart live on k3d. ### Security diff --git a/INSTALL.md b/INSTALL.md index ff99d47e6..521f941c4 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -109,6 +109,10 @@ not the console afterwards. - Prebuilt GHCR images: the image is published from the next tagged release. Until then, `docker-compose.ghcr.yml` and `docker pull ghcr.io/baarai/artex` return `denied`; use the checkout build above. +- Kubernetes: the Helm chart in [`deploy/helm/artex`](deploy/helm/artex/README.md) runs the panel, + PostgreSQL and the sandbox runner with its Kubernetes backend: every agent command runs in a + per-task pod, with no Docker socket. It needs a CNI that enforces NetworkPolicy. + `scripts/k3d-e2e.sh` installs and tests it on a local k3d cluster. ## Troubleshooting diff --git a/deploy/helm/artex/Chart.yaml b/deploy/helm/artex/Chart.yaml new file mode 100644 index 000000000..5ba9ab412 --- /dev/null +++ b/deploy/helm/artex/Chart.yaml @@ -0,0 +1,14 @@ +apiVersion: v2 +name: artex +description: ARTEX autonomous pentest platform with the per-task Kubernetes sandbox (no Docker socket). +type: application +version: 0.1.0 +appVersion: "0.7.1" +kubeVersion: ">=1.25.0-0" +home: https://github.com/BaaRai/ARTEX +sources: + - https://github.com/BaaRai/ARTEX +keywords: + - pentest + - security + - sandbox diff --git a/deploy/helm/artex/README.md b/deploy/helm/artex/README.md new file mode 100644 index 000000000..56b18e9fe --- /dev/null +++ b/deploy/helm/artex/README.md @@ -0,0 +1,143 @@ +# ARTEX Helm chart + +Deploys ARTEX on Kubernetes: the panel (web UI, API, agent engine), PostgreSQL, and +`artex-runner` with the **Kubernetes sandbox backend**. Every agent command runs in +a per-task worker pod behind a per-task egress-proxy pod. The runner creates them +through the Kubernetes API. No Docker socket is mounted anywhere. + +## Requirements + +- Kubernetes 1.25 or later. +- **A CNI that enforces NetworkPolicy**, such as k3s/k3d (embedded kube-router), + Calico, Cilium or Antrea. Task isolation depends on it: + without enforcement a worker can reach the panel, the database and the internet + directly. The runner refuses to run a command until it has observed the per-task + policies in effect (see [Network readiness](#network-readiness)). +- A StorageClass for the data volume. See [Storage](#storage). +- A runner image that includes the Kubernetes backend: ARTEX after 0.7.1, or the + images built from this repository. + +## Quick start + +```sh +helm install artex deploy/helm/artex -n artex --create-namespace \ + --set-file secrets.anthropicApiKey=./anthropic.key + +kubectl -n artex port-forward svc/artex-panel 8787:8787 +kubectl -n artex logs deploy/artex-panel -c artex | grep "Setup token" # first start only +``` + +Open http://127.0.0.1:8787/setup and set the admin password with the setup token. + +To try it on a local k3d cluster with images built from this checkout, run +`scripts/k3d-e2e.sh`. It creates the cluster, builds and imports the four images, +installs the chart, runs `helm test` and the live sandbox test suite, and deletes +the cluster afterwards (`KEEP=1` keeps it). + +## What gets deployed + +| Object | Purpose | +|---|---| +| `Deployment/-panel` | ARTEX panel. Starts as root and drops every agent process to uid/gid 10001 itself. Its startup self-test refuses to run if that isolation fails. Capabilities: `CHOWN DAC_OVERRIDE FOWNER SETUID SETGID KILL` only, `allowPrivilegeEscalation: false`, no service-account token. | +| `Deployment/-runner` | `artex-runner` with `ARTEX_RUNNER_BACKEND=kubernetes`. Root only for `CAP_CHOWN` (per-task directories are handed to uid 10001), read-only root filesystem. | +| `Role/-runner` | Namespace-scoped: pods (get/list/create/delete), pods/exec, services, and networkpolicies. No secrets, no cluster-wide access. | +| `ServiceAccount/-task` | Identity of task pods. Its token is never mounted. | +| `StatefulSet/-postgres` | Bundled PostgreSQL 16 with SCRAM auth (`postgres.enabled=false` for an external database). | +| `NetworkPolicy` × 4 | Default-deny for every runner-managed pod. Only the panel may reach the runner and PostgreSQL. Panel ingress on 8787. | +| `Secret/-secrets` | Runner token and database password (generated once and kept across upgrades), plus LLM keys. | +| PVCs | `data` (shared: panel, runner, task pods) and `keys` (panel only). Both have `helm.sh/resource-policy: keep`. | + +### Per task (created by the runner) + +| Object | Spec | +|---|---| +| `NetworkPolicy/artex-w-` | Worker: no ingress. Egress only to its own proxy on 3128/1080. | +| `NetworkPolicy/artex-p-` | Proxy: ingress only from its own worker. Egress to cluster DNS, `0.0.0.0/0` minus RFC1918, CGNAT, loopback, link-local, metadata and multicast (`sandbox.proxyDeniedCIDRs`), plus the task's scope CIDRs. | +| `Service/artex-p-` | Stable ClusterIP for the proxy. The worker uses the IP, never DNS. | +| `Pod/artex-p-` | `artex-egress-proxy`: the task's domain/CIDR allowlist, with an audit log at `egress-audit//egress.jsonl` on the data volume. | +| `Pod/artex-w-` | `artex-worker`: uid/gid 10001, `runAsNonRoot`, read-only root filesystem, all capabilities dropped, no privilege escalation, `seccomp: RuntimeDefault`, no service-account token, no service links, `dnsPolicy: None`. Mounts only `tasks/` at `/workspace` plus in-memory `/tmp` and `$HOME`. Limits: 2 CPU, 2Gi memory, 1Gi ephemeral storage (configurable). | + +Policies are created **before** pods and deleted **after** them. `` is the +first 16 hex characters of the SHA-256 of the task ID: task IDs may contain +characters Kubernetes names reject. The real ID is in the `artex.task` annotation. + +Commands run through `pods/exec` as +`env -i -C artex-exec-wrap -- `. +That gives each command a clean environment, its own process group, and a +SIGTERM → 5 s → SIGKILL timeout. Kill scans `/proc` for uid 10001. If that scan +fails, the worker pod is deleted and the workspace survives. + +## Storage + +The data volume is shared. The panel mounts all of it, the runner mounts `tasks/` +and `egress-audit/`, and task pods mount their own sub-directories. + +- `persistence.data.accessMode: ReadWriteOnce` (default) works with any block or + local-path storage. The panel is scheduled on the runner's node, and the runner + pins every task pod to that node (`nodeAffinity` on `metadata.name`). Use it for + single-node clusters and k3d. +- `ReadWriteMany` (NFS, CephFS, Longhorn RWX, EFS, Azure Files, ...) lets task pods + schedule anywhere. + +`ReadWriteOncePod` is rejected: several pods must mount the volume. + +## Configuration + +| Value | Default | | +|---|---|---| +| `images.*.repository` / `tag` | `ghcr.io/baarai/artex*` / appVersion | Four images: `artex`, `runner`, `worker`, `egressProxy`. | +| `images.pullPolicy` | `IfNotPresent` | `Never` for side-loaded images. The PostgreSQL image has its own `postgres.pullPolicy`. | +| `secrets.existingSecret` | `""` | Use your own Secret with keys `ARTEX_RUNNER_TOKEN`, `POSTGRES_PASSWORD`, and optionally `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `ARTEX_SECRET_KEY`. | +| `secrets.anthropicApiKey` / `openaiApiKey` | `""` | Prefer `--set-file` or `existingSecret` over putting keys on the command line. | +| `panel.env` | `{}` | Plain settings (`ARTEX_LLM_MODEL`, ...). The schema rejects names ending in `_KEY`, `_TOKEN`, `_PASSWORD` or `_SECRET`. | +| `sandbox.mode` | `required` | `off` runs agents inside the panel container. Not recommended. | +| `sandbox.runtimeClassName` | `""` | Run task pods under gVisor or Kata for kernel isolation. | +| `sandbox.worker.cpuLimit` / `memoryLimit` | `2` / `2Gi` | | +| `sandbox.podReadyTimeout` | `2m` | Image pull, scheduling and policy programming must finish within it. | +| `sandbox.proxyDeniedCIDRs` | built-in | IPv4 only (it sits inside the `0.0.0.0/0` ipBlock). | +| `sandbox.dns.namespace` / `podLabels` | `kube-system` / `k8s-app: kube-dns` | Cluster DNS the proxy may query. | +| `persistence.data.accessMode` | `ReadWriteOnce` | See [Storage](#storage). | +| `postgres.enabled` | `true` | `false` plus `postgres.external.*` for a managed database. | +| `networkPolicy.enabled` | `true` | Turning it off removes the sandbox's network isolation. | +| `networkPolicy.panelIngressFrom` | `[]` (any) | NetworkPolicy peers allowed to reach the UI, for example your ingress controller. | +| `ingress.*` | disabled | | + +`values.schema.json` validates the values. Invalid modes, pull policies, access +modes, replica counts above 1, and IPv6 deny ranges fail at install time. + +## Network readiness + +A pod becomes Ready before the CNI has programmed NetworkPolicy for its new IP. +On k3s this takes a few seconds. After it creates or replaces a task's pods, the +runner probes two paths before it runs a command: + +- worker → proxy (TCP to the proxy ClusterIP); +- proxy → cluster DNS (`getent hosts kubernetes.default.svc`). + +If either path stays closed for `sandbox.podReadyTimeout`, the exec fails with +`network path ... not open (network policy not applied? ...)`. That usually means +the CNI does not enforce NetworkPolicy the way the chart expects, or the DNS pods +do not match `sandbox.dns.*`. + +## Troubleshooting + +- **`agent isolation self-test failed: Bash can create files in /app/data`** + (issue #620). The volume root was created world-writable, as local-path and many + other provisioners do. The chart's `volume-permissions` init container resets + `/app/data` to `root:root 0755` and `/app/keys` to `0700` before the panel starts. + The panel itself must run as root with the capabilities above. With + `runAsNonRoot`, or with `fsGroup` set on the panel, the self-test fails by design. +- **Runner health returns 409.** The runner cannot list pods. Check the Role + binding and `kubectl -n logs deploy/-runner`. +- **Task pods stay Pending.** With `ReadWriteOnce`, the node the runner runs on + needs capacity for the task pods. + +## Limitations + +- One panel and one runner (single-writer data, in-memory task state in the + runner, which re-adopts existing task pods by label after a restart). +- There is no per-pod PID limit in the pod API. Set `--pod-max-pids` on the kubelet + to bound fork bombs, as the Docker backend's `PidsLimit` does. +- The opt-in DNS egress guard (`docker-compose.egress.yml`) has no Kubernetes + equivalent. Agent egress is governed by the per-task proxies and their + NetworkPolicies. diff --git a/deploy/helm/artex/templates/NOTES.txt b/deploy/helm/artex/templates/NOTES.txt new file mode 100644 index 000000000..25ae59b9c --- /dev/null +++ b/deploy/helm/artex/templates/NOTES.txt @@ -0,0 +1,26 @@ +ARTEX {{ .Chart.AppVersion }} is deployed in namespace {{ .Release.Namespace }}. + +1. Open the console: + + kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "artex.fullname" . }}-panel 8787:{{ .Values.panel.service.port }} + then browse to http://127.0.0.1:8787 + +2. First start only: the one-time setup token for the /setup page is printed on the + panel's stderr: + + kubectl -n {{ .Release.Namespace }} logs deploy/{{ include "artex.fullname" . }}-panel | grep "Setup token" + +{{- if eq .Values.sandbox.mode "required" }} + +3. Agent commands run in per-task pods created by the runner: + + kubectl -n {{ .Release.Namespace }} get pods -l artex.managed_by=artex-runner +{{- if not .Values.networkPolicy.enabled }} + +WARNING: networkPolicy.enabled=false. Task pods are NOT network-isolated: a worker can +reach the panel, the database and the internet directly, bypassing the egress proxy. +{{- end }} +{{- else }} + +WARNING: sandbox.mode=off. Agent commands run inside the panel container. +{{- end }} diff --git a/deploy/helm/artex/templates/_helpers.tpl b/deploy/helm/artex/templates/_helpers.tpl new file mode 100644 index 000000000..a15a412dd --- /dev/null +++ b/deploy/helm/artex/templates/_helpers.tpl @@ -0,0 +1,74 @@ +{{/* Chart name, truncated to fit Kubernetes name limits. */}} +{{- define "artex.name" -}} +{{- .Chart.Name | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* Release-scoped base name for every object. */}} +{{- define "artex.fullname" -}} +{{- if contains .Chart.Name .Release.Name -}} +{{- .Release.Name | trunc 40 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 40 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} + +{{- define "artex.labels" -}} +helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }} +app.kubernetes.io/name: {{ include "artex.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} + +{{/* Selector labels for one component: include "artex.selector" (list . "panel") */}} +{{- define "artex.selector" -}} +{{- $root := index . 0 -}} +app.kubernetes.io/name: {{ include "artex.name" $root }} +app.kubernetes.io/instance: {{ $root.Release.Name }} +app.kubernetes.io/component: {{ index . 1 }} +{{- end -}} + +{{- define "artex.secretName" -}} +{{- default (printf "%s-secrets" (include "artex.fullname" .)) .Values.secrets.existingSecret -}} +{{- end -}} + +{{- define "artex.dataClaim" -}} +{{- default (printf "%s-data" (include "artex.fullname" .)) .Values.persistence.data.existingClaim -}} +{{- end -}} + +{{- define "artex.keysClaim" -}} +{{- default (printf "%s-keys" (include "artex.fullname" .)) .Values.persistence.keys.existingClaim -}} +{{- end -}} + +{{- define "artex.runnerURL" -}} +{{- printf "http://%s-runner:%d" (include "artex.fullname" .) (int .Values.runner.port) -}} +{{- end -}} + +{{/* Image reference: include "artex.image" (list . .Values.images.runner) */}} +{{- define "artex.image" -}} +{{- $root := index . 0 -}} +{{- $img := index . 1 -}} +{{- printf "%s:%s" $img.repository (default $root.Chart.AppVersion $img.tag) -}} +{{- end -}} + +{{- define "artex.pgHost" -}} +{{- if .Values.postgres.enabled -}} +{{- printf "%s-postgres" (include "artex.fullname" .) -}} +{{- else -}} +{{- required "postgres.external.host is required when postgres.enabled=false" .Values.postgres.external.host -}} +{{- end -}} +{{- end -}} + +{{/* True when the data volume is ReadWriteOnce and all mounting pods must share a node. */}} +{{- define "artex.pinToNode" -}} +{{- if eq .Values.persistence.data.accessMode "ReadWriteOnce" -}}true{{- end -}} +{{- end -}} + +{{- define "artex.pullSecrets" -}} +{{- with .Values.images.pullSecrets }} +imagePullSecrets: +{{- range . }} + - name: {{ . }} +{{- end }} +{{- end }} +{{- end -}} diff --git a/deploy/helm/artex/templates/ingress.yaml b/deploy/helm/artex/templates/ingress.yaml new file mode 100644 index 000000000..2f2e42691 --- /dev/null +++ b/deploy/helm/artex/templates/ingress.yaml @@ -0,0 +1,31 @@ +{{- if .Values.ingress.enabled }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "artex.fullname" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- with .Values.ingress.className }} + ingressClassName: {{ . }} + {{- end }} + {{- with .Values.ingress.tls }} + tls: + {{- toYaml . | nindent 4 }} + {{- end }} + rules: + - host: {{ .Values.ingress.host | quote }} + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: {{ include "artex.fullname" . }}-panel + port: + name: http +{{- end }} diff --git a/deploy/helm/artex/templates/networkpolicy.yaml b/deploy/helm/artex/templates/networkpolicy.yaml new file mode 100644 index 000000000..9c9768165 --- /dev/null +++ b/deploy/helm/artex/templates/networkpolicy.yaml @@ -0,0 +1,87 @@ +{{- if .Values.networkPolicy.enabled }} +# Baseline for every pod the runner creates: no traffic at all. The runner adds a +# per-task policy pair (worker -> own proxy; proxy -> DNS + internet + scope) before +# it creates a task's pods, so a missing per-task policy fails closed. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-sandbox-default-deny + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + artex.managed_by: artex-runner + policyTypes: ["Ingress", "Egress"] +{{- if eq .Values.sandbox.mode "required" }} +--- +# Only the panel may call the runner API. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 6 }} + policyTypes: ["Ingress"] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 14 }} + ports: + - protocol: TCP + port: {{ .Values.runner.port }} +{{- end }} +{{- if .Values.postgres.enabled }} +--- +# Only the panel may reach the database. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "postgres") | nindent 6 }} + policyTypes: ["Ingress", "Egress"] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 14 }} + ports: + - protocol: TCP + port: 5432 + egress: [] +{{- end }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 6 }} + policyTypes: ["Ingress"] + ingress: + - ports: + - protocol: TCP + port: 8787 + {{- if .Values.panel.recordingProxy.enabled }} + - protocol: TCP + port: {{ .Values.panel.recordingProxy.port }} + {{- end }} + {{- with .Values.networkPolicy.panelIngressFrom }} + from: + {{- toYaml . | nindent 8 }} + {{- end }} +{{- end }} diff --git a/deploy/helm/artex/templates/panel.yaml b/deploy/helm/artex/templates/panel.yaml new file mode 100644 index 000000000..94a0c8604 --- /dev/null +++ b/deploy/helm/artex/templates/panel.yaml @@ -0,0 +1,217 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel +spec: + replicas: {{ .Values.panel.replicas }} + # The data and keys volumes are single-writer: never run two panels at once. + strategy: + type: Recreate + selector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: panel + annotations: + checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + # The panel never talks to the Kubernetes API: the runner does. + automountServiceAccountToken: false + enableServiceLinks: false + terminationGracePeriodSeconds: 30 + securityContext: + seccompProfile: + type: RuntimeDefault + {{- with .Values.panel.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.panel.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- if and (include "artex.pinToNode" .) (eq .Values.sandbox.mode "required") }} + # ReadWriteOnce data volume: every pod mounting it shares the runner's node + # (the runner pins task pods there). + affinity: + podAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 18 }} + {{- else if .Values.panel.affinity }} + affinity: + {{- toYaml .Values.panel.affinity | nindent 8 }} + {{- end }} + initContainers: + # Volume provisioners often create the volume root world-writable (local-path + # uses 0777). The panel's isolation self-test then fails ("Bash can create + # files in /app/data", issue #620), correctly: agent processes (uid 10001) + # must not create entries at the top of the data directory or read the keys. + # Restore the ownership ARTEX expects before it starts. + - name: volume-permissions + image: {{ include "artex.image" (list . .Values.images.artex) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + command: + - sh + - -c + - | + set -eu + chown 0:0 /app/data /app/keys + chmod 0755 /app/data + chmod 0700 /app/keys + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + add: ["CHOWN", "FOWNER"] + resources: + limits: + cpu: 100m + memory: 64Mi + volumeMounts: + - name: data + mountPath: /app/data + - name: keys + mountPath: /app/keys + containers: + - name: artex + image: {{ include "artex.image" (list . .Values.images.artex) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + args: + - -addr + - ":8787" + - -proxy + - {{ if .Values.panel.recordingProxy.enabled }}{{ printf ":%d" (int .Values.panel.recordingProxy.port) | quote }}{{ else }}""{{ end }} + env: + - name: ARTEX_PG_HOST + value: {{ include "artex.pgHost" . | quote }} + - name: ARTEX_PG_PORT + value: {{ ternary "5432" (toString .Values.postgres.external.port) .Values.postgres.enabled | quote }} + - name: ARTEX_PG_USER + value: {{ ternary .Values.postgres.user .Values.postgres.external.user .Values.postgres.enabled | quote }} + - name: ARTEX_PG_DBNAME + value: {{ ternary .Values.postgres.database .Values.postgres.external.database .Values.postgres.enabled | quote }} + - name: ARTEX_PG_SSLMODE + value: {{ ternary "disable" .Values.postgres.external.sslMode .Values.postgres.enabled | quote }} + - name: ARTEX_PG_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: POSTGRES_PASSWORD + - name: ANTHROPIC_API_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ANTHROPIC_API_KEY + optional: true + - name: OPENAI_API_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: OPENAI_API_KEY + optional: true + - name: ARTEX_SECRET_KEY + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_SECRET_KEY + optional: true + - name: ARTEX_JWT_KEY_DIR + value: /app/keys + - name: ARTEX_SANDBOX + value: {{ .Values.sandbox.mode | quote }} + {{- if eq .Values.sandbox.mode "required" }} + - name: ARTEX_RUNNER_URL + value: {{ include "artex.runnerURL" . | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN + {{- end }} + {{- range $k, $v := .Values.panel.env }} + - name: {{ $k }} + value: {{ $v | quote }} + {{- end }} + ports: + - name: http + containerPort: 8787 + {{- if .Values.panel.recordingProxy.enabled }} + - name: recording + containerPort: {{ .Values.panel.recordingProxy.port }} + {{- end }} + startupProbe: + httpGet: + path: /api/health + port: http + periodSeconds: 5 + failureThreshold: 60 + readinessProbe: + httpGet: + path: /api/ready + port: http + periodSeconds: 10 + livenessProbe: + httpGet: + path: /api/health + port: http + periodSeconds: 20 + failureThreshold: 3 + # The panel starts as root and drops every agent process to uid/gid 10001 + # itself (-exec-uid). Its startup self-test refuses to run when that drop + # cannot isolate agents, so it cannot run with runAsNonRoot. It keeps only + # the capabilities the drop and the shared run directories need. + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + add: ["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"] + resources: + {{- toYaml .Values.panel.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: /app/data + - name: keys + mountPath: /app/keys + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ include "artex.dataClaim" . }} + - name: keys + persistentVolumeClaim: + claimName: {{ include "artex.keysClaim" . }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel +spec: + type: {{ .Values.panel.service.type }} + selector: + {{- include "artex.selector" (list . "panel") | nindent 4 }} + ports: + - name: http + port: {{ .Values.panel.service.port }} + targetPort: http + {{- if .Values.panel.recordingProxy.enabled }} + - name: recording + port: {{ .Values.panel.recordingProxy.port }} + targetPort: recording + {{- end }} diff --git a/deploy/helm/artex/templates/postgres.yaml b/deploy/helm/artex/templates/postgres.yaml new file mode 100644 index 000000000..5e87f2d29 --- /dev/null +++ b/deploy/helm/artex/templates/postgres.yaml @@ -0,0 +1,108 @@ +{{- if .Values.postgres.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: postgres +spec: + clusterIP: None + selector: + {{- include "artex.selector" (list . "postgres") | nindent 4 }} + ports: + - name: postgres + port: 5432 + targetPort: postgres +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "artex.fullname" . }}-postgres + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: postgres +spec: + serviceName: {{ include "artex.fullname" . }}-postgres + replicas: 1 + selector: + matchLabels: + {{- include "artex.selector" (list . "postgres") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: postgres + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + automountServiceAccountToken: false + enableServiceLinks: false + securityContext: + runAsUser: 70 # postgres user in the alpine image + runAsGroup: 70 + fsGroup: 70 + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: postgres + image: {{ .Values.postgres.image }} + imagePullPolicy: {{ .Values.postgres.pullPolicy }} + env: + - name: POSTGRES_USER + value: {{ .Values.postgres.user | quote }} + - name: POSTGRES_DB + value: {{ .Values.postgres.database | quote }} + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: POSTGRES_PASSWORD + # Password (SCRAM) for every TCP connection, as in docker-compose.yml. + - name: POSTGRES_HOST_AUTH_METHOD + value: scram-sha-256 + - name: PGDATA + value: /var/lib/postgresql/data/pgdata + ports: + - name: postgres + containerPort: 5432 + readinessProbe: + exec: + command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -h 127.0.0.1"] + periodSeconds: 5 + livenessProbe: + exec: + command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -h 127.0.0.1"] + initialDelaySeconds: 30 + periodSeconds: 10 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + {{- toYaml .Values.postgres.resources | nindent 12 }} + volumeMounts: + - name: pgdata + mountPath: /var/lib/postgresql/data + - name: run + mountPath: /var/run/postgresql + - name: tmp + mountPath: /tmp + volumes: + - name: run + emptyDir: {} + - name: tmp + emptyDir: {} + volumeClaimTemplates: + - metadata: + name: pgdata + spec: + accessModes: ["ReadWriteOnce"] + {{- with .Values.postgres.storage.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.postgres.storage.size }} +{{- end }} diff --git a/deploy/helm/artex/templates/pvc.yaml b/deploy/helm/artex/templates/pvc.yaml new file mode 100644 index 000000000..7bccc5bfe --- /dev/null +++ b/deploy/helm/artex/templates/pvc.yaml @@ -0,0 +1,37 @@ +{{- if not .Values.persistence.data.existingClaim }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "artex.dataClaim" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +spec: + accessModes: [{{ .Values.persistence.data.accessMode | quote }}] + {{- with .Values.persistence.data.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.data.size }} +{{- end }} +{{- if not .Values.persistence.keys.existingClaim }} +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "artex.keysClaim" . }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +spec: + accessModes: ["ReadWriteOnce"] + {{- with .Values.persistence.keys.storageClass }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.keys.size }} +{{- end }} diff --git a/deploy/helm/artex/templates/runner.yaml b/deploy/helm/artex/templates/runner.yaml new file mode 100644 index 000000000..facb24f47 --- /dev/null +++ b/deploy/helm/artex/templates/runner.yaml @@ -0,0 +1,205 @@ +{{- if eq .Values.sandbox.mode "required" }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +--- +# Task pods run under this account; its token is never mounted. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "artex.fullname" . }}-task + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: task +automountServiceAccountToken: false +--- +# Namespace-scoped and limited to what the KubernetesBackend calls. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "create", "delete"] + # Exec over WebSocket is a GET on pods/exec; create covers SPDY clients. + - apiGroups: [""] + resources: ["pods/exec"] + verbs: ["get", "create"] + - apiGroups: [""] + resources: ["services"] + verbs: ["get", "list", "create", "delete"] + - apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + verbs: ["get", "list", "create", "update", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "artex.fullname" . }}-runner +subjects: + - kind: ServiceAccount + name: {{ include "artex.fullname" . }}-runner + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +spec: + replicas: {{ .Values.runner.replicas }} + strategy: + type: Recreate + selector: + matchLabels: + {{- include "artex.selector" (list . "runner") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: runner + annotations: + checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + serviceAccountName: {{ include "artex.fullname" . }}-runner + enableServiceLinks: false + securityContext: + seccompProfile: + type: RuntimeDefault + {{- with .Values.runner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.runner.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: runner + image: {{ include "artex.image" (list . .Values.images.runner) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + env: + - name: ARTEX_RUNNER_BACKEND + value: kubernetes + - name: ARTEX_RUNNER_ADDR + value: {{ printf ":%d" (int .Values.runner.port) | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN + - name: ARTEX_KUBE_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: ARTEX_KUBE_DATA_CLAIM + value: {{ include "artex.dataClaim" . | quote }} + - name: ARTEX_KUBE_SERVICE_ACCOUNT + value: {{ include "artex.fullname" . }}-task + - name: ARTEX_KUBE_IMAGE_PULL_POLICY + value: {{ .Values.images.pullPolicy | quote }} + - name: ARTEX_WORKER_IMAGE + value: {{ include "artex.image" (list . .Values.images.worker) | quote }} + - name: ARTEX_EGRESS_PROXY_IMAGE + value: {{ include "artex.image" (list . .Values.images.egressProxy) | quote }} + - name: ARTEX_WORKSPACE_ROOT + value: /app/data/tasks + - name: ARTEX_AUDIT_ROOT + value: /app/data/egress-audit + - name: ARTEX_KUBE_POD_READY_TIMEOUT + value: {{ .Values.sandbox.podReadyTimeout | quote }} + - name: ARTEX_KUBE_WORKER_CPU_LIMIT + value: {{ .Values.sandbox.worker.cpuLimit | quote }} + - name: ARTEX_KUBE_WORKER_MEMORY_LIMIT + value: {{ .Values.sandbox.worker.memoryLimit | quote }} + - name: ARTEX_KUBE_DNS_NAMESPACE + value: {{ .Values.sandbox.dns.namespace | quote }} + - name: ARTEX_KUBE_DNS_LABELS + value: {{ $l := list }}{{ range $k, $v := .Values.sandbox.dns.podLabels }}{{ $l = append $l (printf "%s=%s" $k $v) }}{{ end }}{{ join "," $l | quote }} + {{- with .Values.sandbox.proxyDeniedCIDRs }} + - name: ARTEX_KUBE_PROXY_DENIED_CIDRS + value: {{ join "," . | quote }} + {{- end }} + {{- with .Values.sandbox.runtimeClassName }} + - name: ARTEX_KUBE_RUNTIME_CLASS + value: {{ . | quote }} + {{- end }} + {{- if include "artex.pinToNode" . }} + - name: ARTEX_KUBE_PIN_NODE + valueFrom: + fieldRef: + fieldPath: spec.nodeName + {{- end }} + ports: + - name: runner + containerPort: {{ .Values.runner.port }} + readinessProbe: + exec: + command: ["sh", "-c", "curl -fsS -H \"Authorization: Bearer $ARTEX_RUNNER_TOKEN\" http://127.0.0.1:{{ .Values.runner.port }}/v1/health"] + periodSeconds: 10 + timeoutSeconds: 5 + livenessProbe: + tcpSocket: + port: runner + periodSeconds: 20 + # Root only to create and chown per-task directories to 10001 (CAP_CHOWN); + # no other capability, read-only root filesystem. + securityContext: + runAsUser: 0 + runAsGroup: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + add: ["CHOWN"] + resources: + {{- toYaml .Values.runner.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: /app/data/tasks + subPath: tasks + - name: data + mountPath: /app/data/egress-audit + subPath: egress-audit + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ include "artex.dataClaim" . }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "artex.fullname" . }}-runner + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: runner +spec: + selector: + {{- include "artex.selector" (list . "runner") | nindent 4 }} + ports: + - name: runner + port: {{ .Values.runner.port }} + targetPort: runner +{{- end }} diff --git a/deploy/helm/artex/templates/secret.yaml b/deploy/helm/artex/templates/secret.yaml new file mode 100644 index 000000000..4ef281826 --- /dev/null +++ b/deploy/helm/artex/templates/secret.yaml @@ -0,0 +1,28 @@ +{{- if not .Values.secrets.existingSecret }} +{{- /* Generated values are kept across upgrades: a new runner token or database + password on every upgrade would break the running release. */}} +{{- $name := include "artex.secretName" . }} +{{- $existing := (lookup "v1" "Secret" .Release.Namespace $name) | default dict }} +{{- $data := get $existing "data" | default dict }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ $name }} + labels: + {{- include "artex.labels" . | nindent 4 }} + annotations: + helm.sh/resource-policy: keep +type: Opaque +data: + ARTEX_RUNNER_TOKEN: {{ .Values.secrets.runnerToken | default (get $data "ARTEX_RUNNER_TOKEN" | default "" | b64dec) | default (randAlphaNum 48) | b64enc | quote }} + POSTGRES_PASSWORD: {{ .Values.secrets.postgresPassword | default (get $data "POSTGRES_PASSWORD" | default "" | b64dec) | default (randAlphaNum 32) | b64enc | quote }} + {{- with (.Values.secrets.anthropicApiKey | default (get $data "ANTHROPIC_API_KEY" | default "" | b64dec)) }} + ANTHROPIC_API_KEY: {{ . | b64enc | quote }} + {{- end }} + {{- with (.Values.secrets.openaiApiKey | default (get $data "OPENAI_API_KEY" | default "" | b64dec)) }} + OPENAI_API_KEY: {{ . | b64enc | quote }} + {{- end }} + {{- with (.Values.secrets.secretKey | default (get $data "ARTEX_SECRET_KEY" | default "" | b64dec)) }} + ARTEX_SECRET_KEY: {{ . | b64enc | quote }} + {{- end }} +{{- end }} diff --git a/deploy/helm/artex/templates/tests/test-panel.yaml b/deploy/helm/artex/templates/tests/test-panel.yaml new file mode 100644 index 000000000..ceff9d322 --- /dev/null +++ b/deploy/helm/artex/templates/tests/test-panel.yaml @@ -0,0 +1,38 @@ +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "artex.fullname" . }}-test-panel + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: test + annotations: + helm.sh/hook: test + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + restartPolicy: Never + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + containers: + # The runner image ships curl; reusing it avoids pulling another image. + - name: health + image: {{ include "artex.image" (list . .Values.images.runner) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + command: + - sh + - -c + - | + set -eu + base=http://{{ include "artex.fullname" . }}-panel:{{ .Values.panel.service.port }} + curl -fsS "$base/api/health" + echo + curl -fsS "$base/api/ready" + echo + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] diff --git a/deploy/helm/artex/values.schema.json b/deploy/helm/artex/values.schema.json new file mode 100644 index 000000000..b4779c359 --- /dev/null +++ b/deploy/helm/artex/values.schema.json @@ -0,0 +1,73 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["images", "sandbox", "persistence", "postgres", "networkPolicy"], + "properties": { + "images": { + "type": "object", + "properties": { + "pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] }, + "pullSecrets": { "type": "array", "items": { "type": "string" } } + } + }, + "panel": { + "type": "object", + "properties": { + "replicas": { "type": "integer", "minimum": 0, "maximum": 1 }, + "env": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", "not": { "pattern": "(?i)(_KEY|_TOKEN|_PASSWORD|_SECRET)$" } }, + "additionalProperties": { "type": ["string", "number", "boolean"] } + } + } + }, + "runner": { + "type": "object", + "properties": { + "replicas": { "type": "integer", "minimum": 0, "maximum": 1 }, + "port": { "type": "integer", "minimum": 1, "maximum": 65535 } + } + }, + "sandbox": { + "type": "object", + "required": ["mode"], + "properties": { + "mode": { "enum": ["required", "off"] }, + "runtimeClassName": { "type": "string" }, + "podReadyTimeout": { "type": "string", "pattern": "^[0-9]+(ms|s|m|h)$" }, + "proxyDeniedCIDRs": { + "type": "array", + "items": { "type": "string", "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$" } + } + } + }, + "persistence": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { "accessMode": { "enum": ["ReadWriteOnce", "ReadWriteMany"] } } + } + } + }, + "postgres": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "external": { + "type": "object", + "properties": { + "sslMode": { "enum": ["disable", "allow", "prefer", "require", "verify-ca", "verify-full"] } + } + } + } + }, + "networkPolicy": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "panelIngressFrom": { "type": "array" } + } + } + } +} diff --git a/deploy/helm/artex/values.yaml b/deploy/helm/artex/values.yaml new file mode 100644 index 000000000..148f59f4c --- /dev/null +++ b/deploy/helm/artex/values.yaml @@ -0,0 +1,154 @@ +# Default values for the ARTEX chart. See README.md in this directory. + +# Release images published to GHCR. An empty tag means the chart's appVersion. +# Locally built images: set repository to artex, artex-runner, ... and tag to +# local, and pullPolicy to Never after importing them (see scripts/k3d-e2e.sh). +images: + # Panel (web UI + API + agent engine). + artex: + repository: ghcr.io/baarai/artex + tag: "" + # Sandbox runner: creates per-task pods through the Kubernetes API. + runner: + repository: ghcr.io/baarai/artex-runner + tag: "" + # Per-task worker (runs agent commands) and egress proxy. + worker: + repository: ghcr.io/baarai/artex-worker + tag: "" + egressProxy: + repository: ghcr.io/baarai/artex-egress-proxy + tag: "" + pullPolicy: IfNotPresent + pullSecrets: [] + +# Secrets. Either name an existing Secret (existingSecret) holding the keys below, +# or let the chart create one. Values left empty are generated once and kept across +# upgrades (runnerToken, postgresPassword), or simply omitted (LLM keys). +secrets: + existingSecret: "" + # Keys in the Secret: + # ARTEX_RUNNER_TOKEN, POSTGRES_PASSWORD, ANTHROPIC_API_KEY, OPENAI_API_KEY, ARTEX_SECRET_KEY + runnerToken: "" + postgresPassword: "" + anthropicApiKey: "" + openaiApiKey: "" + # Optional key for secrets at rest; empty = generated by ARTEX in the keys volume. + secretKey: "" + +panel: + replicas: 1 # ARTEX is a single-writer service; keep 1. + # Extra plain environment for the panel (ARTEX_LLM_PROVIDER, ARTEX_LLM_MODEL, ...). + # Never put secrets here: use the secrets block. + env: {} + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + memory: 4Gi + service: + type: ClusterIP + port: 8787 + # The recording proxy (8788) is exposed only inside the cluster when enabled. + recordingProxy: + enabled: false + port: 8788 + nodeSelector: {} + tolerations: [] + # Ignored when the data volume is ReadWriteOnce and the sandbox is on: the panel + # must then share the runner's node. + affinity: {} + +runner: + replicas: 1 # Task state is kept per runner; keep 1. + port: 8789 + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + memory: 256Mi + nodeSelector: {} + tolerations: [] + +sandbox: + # "required": every agent command runs in a per-task pod (recommended). + # "off": agents run inside the panel container (not recommended on shared clusters). + mode: required + # Optional RuntimeClass for task pods (gvisor, kata, ...) for kernel isolation. + runtimeClassName: "" + podReadyTimeout: 2m + worker: + cpuLimit: "2" + memoryLimit: 2Gi + # IPv4 ranges the egress proxy pods may never reach (NetworkPolicy, in addition to + # the proxy's own allowlist). Task scope CIDRs are allowed back explicitly. + # Empty = built-in default (RFC1918, CGNAT, loopback, link-local, metadata, multicast). + proxyDeniedCIDRs: [] + # Cluster DNS the egress proxy may query. + dns: + namespace: kube-system + podLabels: + k8s-app: kube-dns + +persistence: + # Shared data volume: the panel mounts all of it, the runner mounts tasks/ and + # egress-audit/, task pods mount their own sub-directories. + data: + existingClaim: "" + size: 20Gi + storageClass: "" + # ReadWriteOnce: every pod is pinned to the panel's node (single-node, k3d, + # local-path). ReadWriteMany (NFS, CephFS, Longhorn RWX, EFS, ...) lets task pods + # schedule anywhere. + accessMode: ReadWriteOnce + keys: + existingClaim: "" + size: 64Mi + storageClass: "" + +postgres: + # Bundled single-instance PostgreSQL. Disable to use an external database. + enabled: true + image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d + # Separate from images.pullPolicy: the ARTEX images may be side-loaded (Never), + # the database image is public. + pullPolicy: IfNotPresent + user: artex + database: artex + storage: + size: 10Gi + storageClass: "" + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + memory: 1Gi + # Used when enabled=false. + external: + host: "" + port: 5432 + user: artex + database: artex + sslMode: require + +networkPolicy: + # Requires a CNI that enforces NetworkPolicy (k3s/kube-router, Calico, Cilium, ...). + # The sandbox relies on it: without enforcement task pods are NOT network-isolated. + enabled: true + # Namespaces/pods allowed to reach the panel UI (an ingress controller, for + # example). Empty = any source. Entries are NetworkPolicy "from" peers. + panelIngressFrom: [] + +ingress: + enabled: false + className: "" + annotations: {} + host: artex.example.com + tls: [] + +serviceAccount: + # Extra annotations for the runner's service account. + annotations: {} diff --git a/sandbox/helmchart_test.go b/sandbox/helmchart_test.go new file mode 100644 index 000000000..b9689458a --- /dev/null +++ b/sandbox/helmchart_test.go @@ -0,0 +1,568 @@ +package sandbox + +import ( + "bytes" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +// These tests render deploy/helm/artex with `helm template` and check the security +// and wiring invariants the KubernetesBackend depends on. They skip when helm is not +// installed. + +const chartDir = "../deploy/helm/artex" + +type k8sObj = map[string]any + +func renderChart(t *testing.T, set ...string) []k8sObj { + t.Helper() + helm := helmOrSkip(t) + args := []string{"template", "rel", chartDir, "--namespace", "artex-ns"} + for _, s := range set { + args = append(args, "--set", s) + } + cmd := exec.Command(helm, args...) + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil { + t.Fatalf("helm template %v: %v\n%s", set, err, stderr.String()) + } + var objs []k8sObj + dec := yaml.NewDecoder(bytes.NewReader(out)) + for { + var o k8sObj + err := dec.Decode(&o) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatalf("decode rendered chart: %v", err) + } + if o != nil { + objs = append(objs, o) + } + } + return objs +} + +func findObj(objs []k8sObj, kind, name string) k8sObj { + for _, o := range objs { + if o["kind"] == kind && dig(o, "metadata", "name") == name { + return o + } + } + return nil +} + +func objsOfKind(objs []k8sObj, kind string) []k8sObj { + var out []k8sObj + for _, o := range objs { + if o["kind"] == kind { + out = append(out, o) + } + } + return out +} + +// podSpecOf returns the pod spec of a workload or a bare Pod. +func podSpecOf(o k8sObj) any { + if o["kind"] == "Pod" { + return o["spec"] + } + return dig(o, "spec", "template", "spec") +} + +func containerEnv(c any) (plain map[string]string, refs map[string]any) { + plain, refs = map[string]string{}, map[string]any{} + env, _ := dig(c, "env").([]any) + for _, e := range env { + name := dig(e, "name").(string) + if v, ok := dig(e, "value").(string); ok { + plain[name] = v + } else { + refs[name] = dig(e, "valueFrom") + } + } + return plain, refs +} + +func strList(v any) []string { + var out []string + s, _ := v.([]any) + for _, x := range s { + out = append(out, x.(string)) + } + return out +} + +func TestHelmChartPodSecurityBaseline(t *testing.T) { + objs := renderChart(t) + workloads := append(append(objsOfKind(objs, "Deployment"), objsOfKind(objs, "StatefulSet")...), objsOfKind(objs, "Pod")...) + if len(workloads) != 4 { // panel, runner, postgres, helm test pod + t.Fatalf("workloads = %d", len(workloads)) + } + for _, w := range workloads { + name := dig(w, "metadata", "name").(string) + spec := podSpecOf(w) + if dig(spec, "securityContext", "seccompProfile", "type") != "RuntimeDefault" { + t.Errorf("%s: pod seccompProfile = %v", name, dig(spec, "securityContext", "seccompProfile")) + } + for _, k := range []string{"hostNetwork", "hostPID", "hostIPC"} { + if dig(spec, k) == true { + t.Errorf("%s: %s=true", name, k) + } + } + vols, _ := dig(spec, "volumes").([]any) + for _, v := range vols { + if dig(v, "hostPath") != nil { + t.Errorf("%s: hostPath volume %v", name, v) + } + } + isRunner := strings.HasSuffix(name, "-runner") + if dig(spec, "automountServiceAccountToken") != false && !isRunner { + t.Errorf("%s: service account token mounted", name) + } + if !isRunner && dig(w, "kind") != "Pod" && dig(spec, "enableServiceLinks") != false { + t.Errorf("%s: enableServiceLinks not false", name) + } + all := dig(spec, "containers").([]any) + if ics, ok := dig(spec, "initContainers").([]any); ok { + all = append(all, ics...) + } + for _, c := range all { + sc := dig(c, "securityContext") + if dig(sc, "allowPrivilegeEscalation") != false { + t.Errorf("%s: allowPrivilegeEscalation = %v", name, dig(sc, "allowPrivilegeEscalation")) + } + if dig(sc, "privileged") == true { + t.Errorf("%s: privileged", name) + } + if d := strList(dig(sc, "capabilities", "drop")); !slices.Equal(d, []string{"ALL"}) { + t.Errorf("%s: capabilities.drop = %v", name, d) + } + for _, cap := range strList(dig(sc, "capabilities", "add")) { + if slices.Contains([]string{"SYS_ADMIN", "NET_ADMIN", "NET_RAW", "SYS_PTRACE", "SYS_MODULE", "ALL"}, cap) { + t.Errorf("%s: dangerous capability %s", name, cap) + } + } + } + } + + panel := findObj(objs, "Deployment", "rel-artex-panel") + pc := dig(podSpecOf(panel), "containers", 0) + if got := strList(dig(pc, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"}) { + t.Errorf("panel capabilities = %v", got) + } + // Init container restores root ownership of the volume roots (issue #620). + ic := dig(podSpecOf(panel), "initContainers", 0) + script := strings.Join(strList(dig(ic, "command")), " ") + for _, want := range []string{"chown 0:0 /app/data /app/keys", "chmod 0755 /app/data", "chmod 0700 /app/keys"} { + if !strings.Contains(script, want) { + t.Errorf("panel init container missing %q: %s", want, script) + } + } + if got := strList(dig(ic, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN", "FOWNER"}) { + t.Errorf("init container capabilities = %v", got) + } + runner := findObj(objs, "Deployment", "rel-artex-runner") + rc := dig(podSpecOf(runner), "containers", 0) + if got := strList(dig(rc, "securityContext", "capabilities", "add")); !slices.Equal(got, []string{"CHOWN"}) { + t.Errorf("runner capabilities = %v", got) + } + if dig(rc, "securityContext", "readOnlyRootFilesystem") != true { + t.Error("runner root filesystem writable") + } + // The runner never mounts a container runtime socket. + for _, m := range dig(rc, "volumeMounts").([]any) { + if strings.Contains(dig(m, "mountPath").(string), ".sock") { + t.Errorf("runner mounts a socket: %v", m) + } + } + for _, o := range objs { + if o["kind"] == "Deployment" && dig(o, "spec", "strategy", "type") != "Recreate" { + t.Errorf("%s: strategy %v (single-writer volumes need Recreate)", dig(o, "metadata", "name"), dig(o, "spec", "strategy", "type")) + } + } +} + +func TestHelmChartRunnerEnvMatchesBackend(t *testing.T) { + objs := renderChart(t) + runner := findObj(objs, "Deployment", "rel-artex-runner") + rc := dig(podSpecOf(runner), "containers", 0) + plain, refs := containerEnv(rc) + + if plain[EnvRunnerBackend] != BackendKubernetes { + t.Fatalf("runner backend env = %q", plain[EnvRunnerBackend]) + } + // Every ARTEX_KUBE_* name the chart sets must be one the backend reads. + src, err := os.ReadFile("kube.go") + if err != nil { + t.Fatal(err) + } + for name := range plain { + if strings.HasPrefix(name, "ARTEX_KUBE_") && !bytes.Contains(src, []byte(`"`+name+`"`)) { + t.Errorf("chart sets %s but kube.go never reads it", name) + } + } + for name := range refs { + if strings.HasPrefix(name, "ARTEX_KUBE_") && !bytes.Contains(src, []byte(`"`+name+`"`)) { + t.Errorf("chart sets %s but kube.go never reads it", name) + } + } + // The rendered plain values parse with the backend's own config reader. + for k, v := range plain { + t.Setenv(k, v) + } + t.Setenv("ARTEX_KUBE_NAMESPACE", "artex-ns") + cfg, err := KubeConfigFromEnv() + if err != nil { + t.Fatalf("KubeConfigFromEnv on rendered env: %v", err) + } + if cfg.DataClaim != "rel-artex-data" || findObj(objs, "PersistentVolumeClaim", cfg.DataClaim) == nil { + t.Errorf("data claim %q not rendered", cfg.DataClaim) + } + if cfg.DNSPodLabels["k8s-app"] != "kube-dns" || cfg.DNSNamespace != "kube-system" { + t.Errorf("dns = %s %v", cfg.DNSNamespace, cfg.DNSPodLabels) + } + if cfg.ServiceAccount != "rel-artex-task" { + t.Errorf("task service account = %q", cfg.ServiceAccount) + } + taskSA := findObj(objs, "ServiceAccount", cfg.ServiceAccount) + if taskSA == nil || taskSA["automountServiceAccountToken"] != false { + t.Errorf("task service account %v", taskSA) + } + if plain[EnvWorkerImage] != "ghcr.io/baarai/artex-worker:"+chartAppVersion(t) || plain[EnvProxyImage] != "ghcr.io/baarai/artex-egress-proxy:"+chartAppVersion(t) { + t.Errorf("images = %s %s", plain[EnvWorkerImage], plain[EnvProxyImage]) + } + // Runner mounts exactly the sub paths the backend hands to task pods. + mounts := map[string]string{} + for _, m := range dig(rc, "volumeMounts").([]any) { + mounts[dig(m, "mountPath").(string)] = dig(m, "subPath").(string) + } + if mounts[plain[EnvWorkspaceRoot]] != "tasks" || mounts[plain[EnvAuditRoot]] != "egress-audit" { + t.Errorf("runner mounts %v vs roots %s %s", mounts, plain[EnvWorkspaceRoot], plain[EnvAuditRoot]) + } + if dig(refs["ARTEX_KUBE_NAMESPACE"], "fieldRef", "fieldPath") != "metadata.namespace" { + t.Errorf("namespace env = %v", refs["ARTEX_KUBE_NAMESPACE"]) + } + + // Panel talks to the runner service with the same secret key. + panel := findObj(objs, "Deployment", "rel-artex-panel") + pplain, prefs := containerEnv(dig(podSpecOf(panel), "containers", 0)) + if pplain[EnvSandboxMode] != ModeRequired { + t.Errorf("panel sandbox mode = %q", pplain[EnvSandboxMode]) + } + svc := findObj(objs, "Service", "rel-artex-runner") + if svc == nil || pplain[EnvRunnerURL] != "http://rel-artex-runner:8789" { + t.Errorf("runner URL %q / service %v", pplain[EnvRunnerURL], svc != nil) + } + if dig(prefs[EnvRunnerToken], "secretKeyRef", "key") != dig(refs[EnvRunnerToken], "secretKeyRef", "key") { + t.Error("panel and runner read different token keys") + } + // The panel never carries Kubernetes credentials or the runner backend's settings. + for k := range pplain { + if strings.HasPrefix(k, "ARTEX_KUBE_") { + t.Errorf("panel env has %s", k) + } + } +} + +func chartAppVersion(t *testing.T) string { + t.Helper() + raw, err := os.ReadFile(filepath.Join(chartDir, "Chart.yaml")) + if err != nil { + t.Fatal(err) + } + m := regexp.MustCompile(`(?m)^appVersion:\s*"?([^"\n]+)"?`).FindSubmatch(raw) + if m == nil { + t.Fatal("no appVersion in Chart.yaml") + } + return string(m[1]) +} + +func TestHelmChartImageOverrides(t *testing.T) { + objs := renderChart(t, "images.runner.repository=artex-runner", "images.runner.tag=local", "images.worker.tag=9.9.9") + runner := dig(podSpecOf(findObj(objs, "Deployment", "rel-artex-runner")), "containers", 0) + if dig(runner, "image") != "artex-runner:local" { + t.Errorf("runner image = %v", dig(runner, "image")) + } + plain, _ := containerEnv(runner) + if plain[EnvWorkerImage] != "ghcr.io/baarai/artex-worker:9.9.9" { + t.Errorf("worker image = %v", plain[EnvWorkerImage]) + } + panel := podSpecOf(findObj(objs, "Deployment", "rel-artex-panel")) + if dig(panel, "containers", 0, "image") != dig(panel, "initContainers", 0, "image") { + t.Error("panel init container uses a different image than the panel") + } +} + +func TestHelmChartSecretsWiring(t *testing.T) { + objs := renderChart(t, "secrets.anthropicApiKey=sk-test") + sec := findObj(objs, "Secret", "rel-artex-secrets") + if sec == nil { + t.Fatal("secret not rendered") + } + keys := sec["data"].(map[string]any) + for _, k := range []string{"ARTEX_RUNNER_TOKEN", "POSTGRES_PASSWORD", "ANTHROPIC_API_KEY"} { + if keys[k] == nil || keys[k] == "" { + t.Errorf("secret missing %s", k) + } + } + if keys["OPENAI_API_KEY"] != nil { + t.Error("empty OpenAI key rendered") + } + // Every non-optional secretKeyRef resolves to a key the chart renders. + for _, w := range append(objsOfKind(objs, "Deployment"), objsOfKind(objs, "StatefulSet")...) { + for _, c := range dig(podSpecOf(w), "containers").([]any) { + _, refs := containerEnv(c) + for name, ref := range refs { + sk := dig(ref, "secretKeyRef") + if sk == nil { + continue + } + if dig(sk, "name") != "rel-artex-secrets" { + t.Errorf("%s reads secret %v", name, dig(sk, "name")) + } + if dig(sk, "optional") != true && keys[dig(sk, "key").(string)] == nil { + t.Errorf("%s needs missing key %v", name, dig(sk, "key")) + } + } + } + } + // No secret value ever appears as a plain env value. + for _, w := range objsOfKind(objs, "Deployment") { + for _, c := range dig(podSpecOf(w), "containers").([]any) { + plain, _ := containerEnv(c) + for k, v := range plain { + if IsForbiddenEnvName(k) && strings.HasSuffix(k, "_TOKEN") || v == "sk-test" { + t.Errorf("secret-looking env %s in plain text", k) + } + } + } + } + + existing := renderChart(t, "secrets.existingSecret=mine") + if len(objsOfKind(existing, "Secret")) != 0 { + t.Error("secret rendered despite existingSecret") + } + _, refs := containerEnv(dig(podSpecOf(findObj(existing, "Deployment", "rel-artex-runner")), "containers", 0)) + if dig(refs[EnvRunnerToken], "secretKeyRef", "name") != "mine" { + t.Errorf("existingSecret not used: %v", refs[EnvRunnerToken]) + } +} + +func TestHelmChartRunnerRBACIsMinimal(t *testing.T) { + objs := renderChart(t) + if len(objsOfKind(objs, "ClusterRole"))+len(objsOfKind(objs, "ClusterRoleBinding")) != 0 { + t.Fatal("chart grants cluster-wide RBAC") + } + role := findObj(objs, "Role", "rel-artex-runner") + want := map[string][]string{ + "/pods": {"get", "list", "create", "delete"}, + "/pods/exec": {"get", "create"}, + "/services": {"get", "list", "create", "delete"}, + "networking.k8s.io/networkpolicies": {"get", "list", "create", "update", "delete"}, + } + got := map[string][]string{} + for _, r := range role["rules"].([]any) { + groups, res, verbs := strList(dig(r, "apiGroups")), strList(dig(r, "resources")), strList(dig(r, "verbs")) + for _, g := range groups { + for _, rs := range res { + if g == "*" || rs == "*" || slices.Contains(verbs, "*") { + t.Fatalf("wildcard rule %v", r) + } + if rs == "secrets" || rs == "pods/attach" || rs == "serviceaccounts/token" { + t.Errorf("runner may access %s", rs) + } + got[g+"/"+rs] = verbs + } + } + } + for k, v := range want { + if !slices.Equal(got[k], v) { + t.Errorf("rule %s = %v, want %v", k, got[k], v) + } + } + if len(got) != len(want) { + t.Errorf("extra rules: %v", got) + } + rb := findObj(objs, "RoleBinding", "rel-artex-runner") + if dig(rb, "subjects", 0, "name") != "rel-artex-runner" || dig(rb, "subjects", 0, "namespace") != "artex-ns" { + t.Errorf("binding subjects = %v", dig(rb, "subjects")) + } + if dig(podSpecOf(findObj(objs, "Deployment", "rel-artex-runner")), "serviceAccountName") != "rel-artex-runner" { + t.Error("runner not using its service account") + } +} + +func TestHelmChartNetworkPolicies(t *testing.T) { + objs := renderChart(t) + deny := findObj(objs, "NetworkPolicy", "rel-artex-sandbox-default-deny") + if deny == nil { + t.Fatal("sandbox default-deny missing") + } + sel := dig(deny, "spec", "podSelector", "matchLabels").(map[string]any) + if len(sel) != 1 || sel[LabelManagedBy] != ManagedByRunner { + t.Errorf("default-deny selector %v does not match runner-managed pods", sel) + } + if pt := strList(dig(deny, "spec", "policyTypes")); !slices.Equal(pt, []string{"Ingress", "Egress"}) { + t.Errorf("default-deny policyTypes %v", pt) + } + if dig(deny, "spec", "ingress") != nil || dig(deny, "spec", "egress") != nil { + t.Error("default-deny has allow rules") + } + runnerNP := findObj(objs, "NetworkPolicy", "rel-artex-runner") + if dig(runnerNP, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", "app.kubernetes.io/component") != "panel" { + t.Errorf("runner ingress %v", dig(runnerNP, "spec", "ingress")) + } + pgNP := findObj(objs, "NetworkPolicy", "rel-artex-postgres") + if dig(pgNP, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels", "app.kubernetes.io/component") != "panel" { + t.Errorf("postgres ingress %v", dig(pgNP, "spec", "ingress")) + } + + off := renderChart(t, "networkPolicy.enabled=false") + if n := len(objsOfKind(off, "NetworkPolicy")); n != 0 { + t.Errorf("networkPolicy.enabled=false rendered %d policies", n) + } +} + +func TestHelmChartAccessModePinning(t *testing.T) { + // ReadWriteOnce: the panel follows the runner's node and task pods are pinned to + // it, so a runner-only install (panel.replicas=0) still schedules. + rwo := renderChart(t) + runner := podSpecOf(findObj(rwo, "Deployment", "rel-artex-runner")) + if dig(runner, "affinity") != nil { + t.Errorf("runner has affinity %v: it would not schedule without a panel", dig(runner, "affinity")) + } + panel := podSpecOf(findObj(rwo, "Deployment", "rel-artex-panel")) + if dig(panel, "affinity", "podAffinity", "requiredDuringSchedulingIgnoredDuringExecution", 0, "labelSelector", "matchLabels", "app.kubernetes.io/component") != "runner" { + t.Errorf("RWO panel not co-located with runner: %v", dig(panel, "affinity")) + } + _, refs := containerEnv(dig(runner, "containers", 0)) + if dig(refs["ARTEX_KUBE_PIN_NODE"], "fieldRef", "fieldPath") != "spec.nodeName" { + t.Errorf("RWO pin node env = %v", refs["ARTEX_KUBE_PIN_NODE"]) + } + if am := strList(dig(findObj(rwo, "PersistentVolumeClaim", "rel-artex-data"), "spec", "accessModes")); !slices.Equal(am, []string{"ReadWriteOnce"}) { + t.Errorf("data access modes %v", am) + } + + rwx := renderChart(t, "persistence.data.accessMode=ReadWriteMany") + runner = podSpecOf(findObj(rwx, "Deployment", "rel-artex-runner")) + if a := dig(podSpecOf(findObj(rwx, "Deployment", "rel-artex-panel")), "affinity"); a != nil { + t.Errorf("RWX panel pinned: %v", a) + } + // sandbox off has no runner to follow. + if a := dig(podSpecOf(findObj(renderChart(t, "sandbox.mode=off"), "Deployment", "rel-artex-panel")), "affinity"); a != nil { + t.Errorf("sandbox off panel has affinity %v", a) + } + _, refs = containerEnv(dig(runner, "containers", 0)) + if refs["ARTEX_KUBE_PIN_NODE"] != nil { + t.Error("RWX still pins task pods") + } +} + +func TestHelmChartModesAndOptions(t *testing.T) { + off := renderChart(t, "sandbox.mode=off") + for _, kind := range []string{"Role", "RoleBinding", "ServiceAccount"} { + if n := len(objsOfKind(off, kind)); n != 0 { + t.Errorf("sandbox off renders %d %s", n, kind) + } + } + if findObj(off, "Deployment", "rel-artex-runner") != nil { + t.Error("sandbox off renders the runner") + } + pplain, prefs := containerEnv(dig(podSpecOf(findObj(off, "Deployment", "rel-artex-panel")), "containers", 0)) + if pplain[EnvSandboxMode] != ModeOff || pplain[EnvRunnerURL] != "" || prefs[EnvRunnerToken] != nil { + t.Errorf("sandbox off panel env %v %v", pplain, prefs) + } + + never := renderChart(t, "images.pullPolicy=Never") + pg := dig(podSpecOf(findObj(never, "StatefulSet", "rel-artex-postgres")), "containers", 0) + if dig(pg, "imagePullPolicy") != "IfNotPresent" { + t.Errorf("postgres follows the side-loaded ARTEX pull policy: %v", dig(pg, "imagePullPolicy")) + } + + ext := renderChart(t, "postgres.enabled=false", "postgres.external.host=db.example", "postgres.external.sslMode=verify-full") + if len(objsOfKind(ext, "StatefulSet")) != 0 || findObj(ext, "NetworkPolicy", "rel-artex-postgres") != nil { + t.Error("external postgres still renders the bundled database") + } + pplain, _ = containerEnv(dig(podSpecOf(findObj(ext, "Deployment", "rel-artex-panel")), "containers", 0)) + if pplain["ARTEX_PG_HOST"] != "db.example" || pplain["ARTEX_PG_SSLMODE"] != "verify-full" { + t.Errorf("external pg env %v", pplain) + } + + opts := renderChart(t, "sandbox.runtimeClassName=gvisor", "sandbox.proxyDeniedCIDRs={10.0.0.0/8,192.168.0.0/16}", + "ingress.enabled=true", "ingress.host=artex.test", "panel.recordingProxy.enabled=true", "panel.env.ARTEX_LLM_MODEL=claude-opus-5-5") + rplain, _ := containerEnv(dig(podSpecOf(findObj(opts, "Deployment", "rel-artex-runner")), "containers", 0)) + if rplain["ARTEX_KUBE_RUNTIME_CLASS"] != "gvisor" || rplain["ARTEX_KUBE_PROXY_DENIED_CIDRS"] != "10.0.0.0/8,192.168.0.0/16" { + t.Errorf("runner options env %v", rplain) + } + if ing := findObj(opts, "Ingress", "rel-artex"); dig(ing, "spec", "rules", 0, "host") != "artex.test" { + t.Errorf("ingress %v", ing) + } + panel := dig(podSpecOf(findObj(opts, "Deployment", "rel-artex-panel")), "containers", 0) + pplain, _ = containerEnv(panel) + if pplain["ARTEX_LLM_MODEL"] != "claude-opus-5-5" { + t.Errorf("panel.env not applied: %v", pplain) + } + if args := strList(dig(panel, "args")); !slices.Equal(args, []string{"-addr", ":8787", "-proxy", ":8788"}) { + t.Errorf("panel args %v", args) + } + defArgs := strList(dig(podSpecOf(findObj(renderChart(t), "Deployment", "rel-artex-panel")), "containers", 0, "args")) + if !slices.Equal(defArgs, []string{"-addr", ":8787", "-proxy", ""}) { + t.Errorf("default panel args %v (recording proxy must be off)", defArgs) + } +} + +// helmOrSkip returns the helm binary. Locally a missing helm skips the chart tests; +// in CI it fails them, so they can never pass by not running. +func helmOrSkip(t *testing.T) string { + t.Helper() + helm, err := exec.LookPath("helm") + if err != nil { + if os.Getenv("CI") == "true" { + t.Fatal("helm not installed in CI: the chart tests would silently skip") + } + t.Skip("helm not installed") + } + return helm +} + +func TestHelmChartSchemaRejectsUnsafeValues(t *testing.T) { + helm := helmOrSkip(t) + for _, set := range []string{ + "sandbox.mode=permissive", + "panel.env.MY_API_KEY=x", + "panel.replicas=2", + "runner.replicas=3", + "persistence.data.accessMode=ReadWriteOncePod", + "sandbox.proxyDeniedCIDRs={fc00::/7}", + "images.pullPolicy=Sometimes", + "postgres.enabled=false", + } { + out, err := exec.Command(helm, "template", "rel", chartDir, "--set", set).CombinedOutput() + if err == nil { + t.Errorf("--set %s accepted", set) + } else if !regexp.MustCompile(`schema|required`).Match(out) { + t.Errorf("--set %s failed for an unexpected reason: %s", set, out) + } + } +} + +func TestHelmChartLint(t *testing.T) { + helm := helmOrSkip(t) + abs, _ := filepath.Abs(chartDir) + if out, err := exec.Command(helm, "lint", "--strict", abs).CombinedOutput(); err != nil { + t.Fatalf("helm lint: %v\n%s", err, out) + } +} diff --git a/scripts/k3d-e2e.sh b/scripts/k3d-e2e.sh new file mode 100755 index 000000000..195c57051 --- /dev/null +++ b/scripts/k3d-e2e.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# End-to-end test of the Helm chart and the Kubernetes sandbox backend on a local +# k3d cluster. +# +# scripts/k3d-e2e.sh create cluster, build + import images, install, test +# SKIP_BUILD=1 scripts/k3d-e2e.sh reuse images already built locally +# KEEP=1 scripts/k3d-e2e.sh leave the cluster running afterwards +# RUNNER_ONLY=1 scripts/k3d-e2e.sh sandbox only (panel.replicas=0): builds the three +# small sandbox images, skips the panel checks (CI) +# +# Optional: ANTHROPIC_API_KEY is passed to the chart Secret (never echoed). +# ARTEX_E2E_INTERNET=1 also tests allowed egress to example.com. +# Requires: docker, k3d, kubectl, helm, go. +set -euo pipefail + +CLUSTER=${CLUSTER:-artex-e2e} +NS=${NS:-artex} +RELEASE=${RELEASE:-artex} +CTX="k3d-${CLUSTER}" +ROOT=$(cd "$(dirname "$0")/.." && pwd) +IMAGES=(artex-runner:local artex-worker:local artex-egress-proxy:local) +[ "${RUNNER_ONLY:-0}" = "1" ] || IMAGES+=(artex:local) + +log() { printf '\n==> %s\n' "$*"; } + +cleanup() { + if [ "${KEEP:-0}" != "1" ]; then + log "deleting cluster ${CLUSTER} (KEEP=1 keeps it)" + k3d cluster delete "$CLUSTER" >/dev/null 2>&1 || true + fi +} +trap cleanup EXIT + +if ! k3d cluster get "$CLUSTER" >/dev/null 2>&1; then + log "creating k3d cluster ${CLUSTER}" + # k3s enforces NetworkPolicy with its embedded controller; traefik is not needed. + k3d cluster create "$CLUSTER" --servers 1 --agents 0 --wait --timeout 180s \ + --k3s-arg "--disable=traefik@server:0" +fi + +if [ "${SKIP_BUILD:-0}" != "1" ]; then + log "building images" + docker build -t artex-runner:local -f "$ROOT/Dockerfile.runner" "$ROOT" + docker build -t artex-worker:local -f "$ROOT/Dockerfile.worker" "$ROOT" + docker build -t artex-egress-proxy:local -f "$ROOT/Dockerfile.egress-proxy" "$ROOT" + if [ "${RUNNER_ONLY:-0}" != "1" ]; then + docker build -t artex:local -f "$ROOT/Dockerfile" "$ROOT" + fi +fi + +log "importing images into ${CLUSTER}" +k3d image import -c "$CLUSTER" "${IMAGES[@]}" + +log "installing chart" +kubectl --context "$CTX" create namespace "$NS" --dry-run=client -o yaml | kubectl --context "$CTX" apply -f - +set_args=(--set images.pullPolicy=Never + --set images.artex.repository=artex --set images.artex.tag=local + --set images.runner.repository=artex-runner --set images.runner.tag=local + --set images.worker.repository=artex-worker --set images.worker.tag=local + --set images.egressProxy.repository=artex-egress-proxy --set images.egressProxy.tag=local) +if [ "${RUNNER_ONLY:-0}" = "1" ]; then + # No panel: the keys volume never binds (WaitForFirstConsumer), so wait on the + # workloads instead of helm --wait. + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" --set panel.replicas=0 + kubectl --context "$CTX" -n "$NS" rollout status deploy/"$RELEASE"-runner --timeout=300s + kubectl --context "$CTX" -n "$NS" rollout status sts/"$RELEASE"-postgres --timeout=300s +elif [ -n "${ANTHROPIC_API_KEY:-}" ]; then + # Through a values file on a pipe, so the key never appears in the process list. + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" -f <(printf 'secrets:\n anthropicApiKey: %s\n' "$ANTHROPIC_API_KEY") --wait --timeout 10m +else + helm upgrade --install "$RELEASE" "$ROOT/deploy/helm/artex" --kube-context "$CTX" -n "$NS" \ + "${set_args[@]}" --wait --timeout 10m +fi + +if [ "${RUNNER_ONLY:-0}" != "1" ]; then +log "helm test" +helm test "$RELEASE" --kube-context "$CTX" -n "$NS" --logs + +log "checking panel isolation self-test" +# Read the log first: with pipefail, grep -q exiting early can fail the pipe. +panel_log=$(kubectl --context "$CTX" -n "$NS" logs deploy/"$RELEASE"-panel) +if ! grep -q "\[isolation\] self-test passed" <<<"$panel_log"; then + tail -40 <<<"$panel_log" + echo "panel did not start with agent isolation" >&2 + exit 1 +fi +fi + +TOKEN=$(kubectl --context "$CTX" -n "$NS" get secret "$RELEASE"-secrets -o jsonpath='{.data.ARTEX_RUNNER_TOKEN}' | base64 -d) + +log "running sandbox e2e tests" +( + cd "$ROOT" + ARTEX_SANDBOX_KUBE_E2E=1 \ + ARTEX_RUNNER_TOKEN="$TOKEN" \ + ARTEX_E2E_RUNNER_SVC="${RELEASE}-runner" \ + ARTEX_E2E_NAMESPACE="$NS" \ + ARTEX_E2E_KUBECONTEXT="$CTX" \ + go test ./sandbox -run TestKubeSandboxE2E -count=1 -v -timeout 20m +) +log "e2e passed" From f12f7dfb39c77658e9dc983e564c0249e5f19f94 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:57 +0200 Subject: [PATCH 3/5] feat(sandbox): panel egress controller backend for artex-runner ARTEX_RUNNER_BACKEND=panel-egress turns artex-runner into a policy-only controller for ARTEX_SANDBOX=off on Kubernetes. It accepts the panel's scope union over the token-authenticated PUT /v1/panel-egress (GET reports the state) and keeps one NetworkPolicy selecting the panel pod: approved CIDRs as they are, and the addresses the scope hosts resolve to as /32 ipBlocks. Resolved addresses in DefaultProxyDeniedCIDRs (or the configured list) and IPv6 answers are dropped unless an approved CIDR covers them, mirroring the per-task proxy policy. Hosts are re-resolved every refresh; an address stays allowed for the retention window after a host last resolved to it, a failed lookup keeps the last known addresses until they expire, and a host that leaves the scope loses its addresses on that push. Before the first push and while it is down, the last policy stays in place (fail closed). Exec, kill and delete are refused. The API connection setup of the Kubernetes backend is shared through newKubeConn. --- cmd/artex-runner/main.go | 24 +- sandbox/client.go | 16 + sandbox/kube.go | 49 ++- sandbox/paneleggress.go | 719 +++++++++++++++++++++++++++++++++++ sandbox/paneleggress_test.go | 643 +++++++++++++++++++++++++++++++ sandbox/runner.go | 43 +++ 6 files changed, 1470 insertions(+), 24 deletions(-) create mode 100644 sandbox/paneleggress.go create mode 100644 sandbox/paneleggress_test.go diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go index 9f3a77ad0..8091a83d7 100644 --- a/cmd/artex-runner/main.go +++ b/cmd/artex-runner/main.go @@ -23,8 +23,8 @@ func envOr(k, def string) string { return def } -// buildBackend selects the container backend from ARTEX_RUNNER_BACKEND -// ("docker", the default, or "kubernetes"). +// buildBackend selects the backend from ARTEX_RUNNER_BACKEND ("docker", the +// default, "kubernetes", or "panel-egress"). func buildBackend() (sandbox.Backend, error) { wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) @@ -62,8 +62,22 @@ func buildBackend() (sandbox.Backend, error) { } log.Printf("[runner] backend=kubernetes namespace=%s claim=%s", b.Namespace(), cfg.DataClaim) return b, nil + case sandbox.BackendPanelEgress: + // ARTEX_SANDBOX=off on Kubernetes: no task pods, only the panel's scope + // NetworkPolicy (sandbox/paneleggress.go). + cfg, err := sandbox.PanelEgressConfigFromEnv() + if err != nil { + return nil, err + } + c, err := sandbox.NewPanelEgressController(cfg) + if err != nil { + return nil, err + } + log.Printf("[runner] backend=panel-egress policy=%s refresh=%s retention=%s extra_hosts=%d extra_cidrs=%d", + cfg.PolicyName, cfg.Refresh, cfg.Retention, len(cfg.ExtraHosts), len(cfg.ExtraCIDRs)) + return c, nil default: - return nil, fmt.Errorf("invalid %s=%q (want %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes) + return nil, fmt.Errorf("invalid %s=%q (want %q, %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes, sandbox.BackendPanelEgress) } } @@ -87,6 +101,10 @@ func main() { log.Printf("[runner] recovered %d managed task container(s) by label", n) } + if r, ok := backend.(interface{ Run(context.Context) }); ok { + go r.Run(ctx) + } + rs, err := sandbox.NewRunnerServer(token, version, backend) if err != nil { log.Fatalf("[runner] init failed: %v", err) diff --git a/sandbox/client.go b/sandbox/client.go index 42593b82b..b376f14ad 100644 --- a/sandbox/client.go +++ b/sandbox/client.go @@ -127,3 +127,19 @@ func (c *Client) Delete(ctx context.Context, taskID string) (DeleteResponse, err err := c.doJSON(ctx, http.MethodDelete, "/v1/tasks/"+url.PathEscape(taskID), nil, &out) return out, err } + +// ApplyPanelEgress calls PUT /v1/panel-egress on the panel egress controller. When +// the controller accepted the scope but could not write the policy, the returned +// status carries State=error and err is non-nil. +func (c *Client) ApplyPanelEgress(ctx context.Context, scope PanelEgressScope) (PanelEgressStatus, error) { + var out PanelEgressStatus + err := c.doJSON(ctx, http.MethodPut, "/v1/panel-egress", scope, &out) + return out, err +} + +// PanelEgressStatus calls GET /v1/panel-egress. +func (c *Client) PanelEgressStatus(ctx context.Context) (PanelEgressStatus, error) { + var out PanelEgressStatus + err := c.doJSON(ctx, http.MethodGet, "/v1/panel-egress", nil, &out) + return out, err +} diff --git a/sandbox/kube.go b/sandbox/kube.go index 35ca52708..17aa7ecbe 100644 --- a/sandbox/kube.go +++ b/sandbox/kube.go @@ -125,27 +125,6 @@ var DefaultProxyDeniedCIDRs = []string{ // 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 } @@ -194,6 +173,34 @@ func NewKubernetesBackend(cfg KubeConfig) (*KubernetesBackend, error) { cfg.PodReadyTimeout = kubeDefaultTimeout } + return newKubeConn(cfg) +} + +// newKubeConn fills the API connection settings of cfg (API server, token, CA, +// namespace) from the in-cluster environment and returns a backend that can call +// the API. NewKubernetesBackend adds the task-pod settings on top. +func newKubeConn(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)) + } tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} if strings.HasPrefix(cfg.APIServer, "https://") { ca, err := os.ReadFile(cfg.CAPath) diff --git a/sandbox/paneleggress.go b/sandbox/paneleggress.go new file mode 100644 index 000000000..612ad4a28 --- /dev/null +++ b/sandbox/paneleggress.go @@ -0,0 +1,719 @@ +package sandbox + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "net" + "net/http" + "net/netip" + "net/url" + "os" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// Panel egress controller for ARTEX_SANDBOX=off on Kubernetes. +// +// With the sandbox off, agent commands run inside the panel pod. The Helm chart +// then gives the panel a static egress NetworkPolicy that allows only cluster DNS, +// the database and this controller. This controller (artex-runner with +// ARTEX_RUNNER_BACKEND=panel-egress) owns a second NetworkPolicy that adds the +// union of the approved scope of the panel's live tasks, as IP blocks. The panel +// pushes that union (PUT /v1/panel-egress) and never holds Kubernetes credentials; +// the controller only manages NetworkPolicies in its own namespace. +// +// NetworkPolicies are additive, so the scope policy can only widen what the static +// policy allows. If the controller stops, the last policy it wrote stays in place +// and nothing new is allowed (fail closed). + +const ( + BackendPanelEgress = "panel-egress" + + // EnvPanelEgressURL, set on the panel, is the controller's base URL. It is only + // used with ARTEX_SANDBOX=off; the request token is ARTEX_RUNNER_TOKEN. + EnvPanelEgressURL = "ARTEX_PANEL_EGRESS_URL" + + ManagedByPanelEgress = "artex-panel-egress" + AnnotationEgressTask = "artex.panel-egress/tasks" + + PanelEgressWaiting = "waiting" // no scope pushed since the controller started + PanelEgressEnforced = "enforced" // the policy matches the last pushed scope + PanelEgressError = "error" // the last policy write failed; the previous policy stays + + defaultPanelEgressRefresh = time.Minute + defaultPanelEgressRetention = time.Hour + defaultPanelEgressMaxBlocks = 4000 + panelEgressMaxHosts = 5000 + panelEgressMaxCIDRs = 2000 + panelEgressResolveTimeout = 5 * time.Second + panelEgressResolveWorkers = 16 +) + +// PanelEgressScope is what the panel pushes: the union of the approved scope of +// its live tasks plus the services the panel itself must reach. +type PanelEgressScope struct { + // Domains are approved scope domains (the domain itself is resolved). + Domains []string `json:"domains,omitempty"` + // Hostnames are known hosts under an approved domain (discovered assets). + Hostnames []string `json:"hostnames,omitempty"` + // CIDRs are approved scope CIDRs and IPs, allowed as they are. + CIDRs []string `json:"cidrs,omitempty"` + // ServiceHosts are hosts the panel needs whatever the tasks (LLM endpoints). + ServiceHosts []string `json:"service_hosts,omitempty"` + // Tasks is the number of tasks the union was built from (informational). + Tasks int `json:"tasks"` +} + +// PanelEgressStatus reports the controller's enforcement state. +type PanelEgressStatus struct { + State string `json:"state"` + Policy string `json:"policy"` + Tasks int `json:"tasks"` + Hosts int `json:"hosts"` + IPBlocks int `json:"ip_blocks"` + DeniedIPs int `json:"denied_ips,omitempty"` + Rejected int `json:"rejected,omitempty"` + Truncated bool `json:"truncated,omitempty"` + ResolveErrors []string `json:"resolve_errors,omitempty"` + ScopeAt time.Time `json:"scope_at,omitzero"` + AppliedAt time.Time `json:"applied_at,omitzero"` + LastError string `json:"last_error,omitempty"` +} + +// PanelEgressBackend is implemented by the panel-egress controller; RunnerServer +// serves /v1/panel-egress only for a backend that implements it. +type PanelEgressBackend interface { + ApplyPanelEgress(ctx context.Context, scope PanelEgressScope) (PanelEgressStatus, error) + PanelEgressStatus() PanelEgressStatus +} + +// PanelEgressConfig configures the controller. +type PanelEgressConfig struct { + // Kube carries the API connection settings only (APIServer, TokenPath, CAPath, + // Namespace). + Kube KubeConfig + // PolicyName is the NetworkPolicy the controller owns. + PolicyName string + // PanelSelector selects the panel pod. + PanelSelector map[string]string + // PolicyLabels are added to the policy's labels (e.g. the Helm instance). + PolicyLabels map[string]string + // ExtraHosts and ExtraCIDRs are always allowed (webhooks, MCP servers, ...). + ExtraHosts []string + ExtraCIDRs []string + // DeniedCIDRs: resolved addresses inside these ranges are never allowed unless + // an allowed CIDR covers them (same semantics as the per-task egress proxy). + // Default DefaultProxyDeniedCIDRs. + DeniedCIDRs []string + // Refresh is how often hosts are re-resolved; Retention is how long an address + // stays allowed after a host last resolved to it (DNS rotation). + Refresh time.Duration + Retention time.Duration + // MaxIPBlocks caps the policy size. + MaxIPBlocks int + + // Resolver and Now are replaced in tests. + Resolver func(ctx context.Context, host string) ([]netip.Addr, error) + Now func() time.Time +} + +// PanelEgressController maintains the panel's scope NetworkPolicy. +type PanelEgressController struct { + cfg PanelEgressConfig + kube *KubernetesBackend + denied []netip.Prefix + extraCIDRs []netip.Prefix + extraHosts []string + + // applyMu serialises policy writes. + applyMu sync.Mutex + + mu sync.Mutex + scope *PanelEgressScope + // seen: host -> address -> last time the host resolved to it. + seen map[string]map[netip.Addr]time.Time + resolveErrors map[string]string + rejected int + lastHash string + lastApply time.Time + status PanelEgressStatus +} + +var policyNameRE = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$`) + +var hostnameRE = regexp.MustCompile(`^([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?\.)*[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$`) + +// normalizeEgressHost lowercases host, strips a wildcard prefix and a trailing +// dot, and returns "" for anything that is not a DNS name (IP literals included: +// like the per-task proxy, an IP is allowed only through a scope CIDR). +func normalizeEgressHost(h string) string { + h = strings.ToLower(strings.TrimSpace(h)) + h = strings.TrimPrefix(h, "*.") + h = strings.TrimPrefix(h, ".") + h = strings.TrimSuffix(h, ".") + if h == "" || len(h) > 253 { + return "" + } + if _, err := netip.ParseAddr(h); err == nil { + return "" + } + if !hostnameRE.MatchString(h) { + return "" + } + return h +} + +// parseEgressCIDR accepts a CIDR or a bare IP and returns the masked prefix. +func parseEgressCIDR(s string) (netip.Prefix, bool) { + s = strings.TrimSpace(s) + if p, err := netip.ParsePrefix(s); err == nil { + return p.Masked(), true + } + if a, err := netip.ParseAddr(s); err == nil { + a = a.Unmap() + return netip.PrefixFrom(a, a.BitLen()), true + } + return netip.Prefix{}, false +} + +// NewPanelEgressController validates cfg and connects to the Kubernetes API. +func NewPanelEgressController(cfg PanelEgressConfig) (*PanelEgressController, error) { + if cfg.PolicyName == "" || !policyNameRE.MatchString(cfg.PolicyName) { + return nil, fmt.Errorf("panel egress: invalid policy name %q", cfg.PolicyName) + } + if len(cfg.PanelSelector) == 0 { + return nil, errors.New("panel egress: a panel pod selector is required") + } + if cfg.DeniedCIDRs == nil { + cfg.DeniedCIDRs = DefaultProxyDeniedCIDRs + } + if cfg.Refresh <= 0 { + cfg.Refresh = defaultPanelEgressRefresh + } + if cfg.Retention <= 0 { + cfg.Retention = defaultPanelEgressRetention + } + if cfg.Retention < cfg.Refresh { + return nil, fmt.Errorf("panel egress: retention %s is shorter than the refresh interval %s", cfg.Retention, cfg.Refresh) + } + if cfg.MaxIPBlocks <= 0 { + cfg.MaxIPBlocks = defaultPanelEgressMaxBlocks + } + if cfg.Now == nil { + cfg.Now = time.Now + } + if cfg.Resolver == nil { + cfg.Resolver = func(ctx context.Context, host string) ([]netip.Addr, error) { + return net.DefaultResolver.LookupNetIP(ctx, "ip", host) + } + } + c := &PanelEgressController{ + cfg: cfg, + seen: map[string]map[netip.Addr]time.Time{}, + resolveErrors: map[string]string{}, + status: PanelEgressStatus{State: PanelEgressWaiting, Policy: cfg.PolicyName}, + } + for _, d := range cfg.DeniedCIDRs { + p, ok := parseEgressCIDR(d) + if !ok { + return nil, fmt.Errorf("panel egress: invalid denied CIDR %q", d) + } + c.denied = append(c.denied, p) + } + for _, e := range cfg.ExtraCIDRs { + p, ok := parseEgressCIDR(e) + if !ok { + return nil, fmt.Errorf("panel egress: invalid extra CIDR %q", e) + } + c.extraCIDRs = append(c.extraCIDRs, p) + } + for _, h := range cfg.ExtraHosts { + n := normalizeEgressHost(h) + if n == "" { + return nil, fmt.Errorf("panel egress: invalid extra host %q (IP addresses go in the extra CIDRs)", h) + } + c.extraHosts = append(c.extraHosts, n) + } + kube, err := newKubeConn(cfg.Kube) + if err != nil { + return nil, err + } + c.kube = kube + return c, nil +} + +// PanelEgressConfigFromEnv reads the controller settings: +// +// ARTEX_KUBE_NAMESPACE namespace of the panel (default: own) +// ARTEX_PANEL_EGRESS_POLICY NetworkPolicy name (required) +// ARTEX_PANEL_EGRESS_SELECTOR comma list of k=v selecting the panel pod (required) +// ARTEX_PANEL_EGRESS_LABELS comma list of k=v added to the policy +// ARTEX_PANEL_EGRESS_EXTRA_HOSTS comma list of always-allowed hosts +// ARTEX_PANEL_EGRESS_EXTRA_CIDRS comma list of always-allowed CIDRs +// ARTEX_PANEL_EGRESS_DENIED_CIDRS comma list; default DefaultProxyDeniedCIDRs +// ARTEX_PANEL_EGRESS_REFRESH Go duration; default 1m +// ARTEX_PANEL_EGRESS_RETENTION Go duration; default 1h +// ARTEX_PANEL_EGRESS_MAX_IP_BLOCKS default 4000 +func PanelEgressConfigFromEnv() (PanelEgressConfig, error) { + get := func(k string) string { return strings.TrimSpace(os.Getenv(k)) } + cfg := PanelEgressConfig{ + Kube: KubeConfig{Namespace: get("ARTEX_KUBE_NAMESPACE")}, + PolicyName: get("ARTEX_PANEL_EGRESS_POLICY"), + ExtraHosts: ParseCSV(get("ARTEX_PANEL_EGRESS_EXTRA_HOSTS")), + ExtraCIDRs: ParseCSV(get("ARTEX_PANEL_EGRESS_EXTRA_CIDRS")), + } + labels := func(env string) (map[string]string, error) { + out := map[string]string{} + for _, kv := range ParseCSV(get(env)) { + k, v, ok := strings.Cut(kv, "=") + if !ok || k == "" { + return nil, fmt.Errorf("%s: %q is not key=value", env, kv) + } + out[k] = v + } + return out, nil + } + var err error + if cfg.PanelSelector, err = labels("ARTEX_PANEL_EGRESS_SELECTOR"); err != nil { + return cfg, err + } + if cfg.PolicyLabels, err = labels("ARTEX_PANEL_EGRESS_LABELS"); err != nil { + return cfg, err + } + if v := get("ARTEX_PANEL_EGRESS_DENIED_CIDRS"); v != "" { + cfg.DeniedCIDRs = ParseCSV(v) + } + for env, dst := range map[string]*time.Duration{"ARTEX_PANEL_EGRESS_REFRESH": &cfg.Refresh, "ARTEX_PANEL_EGRESS_RETENTION": &cfg.Retention} { + if v := get(env); v != "" { + d, err := time.ParseDuration(v) + if err != nil || d <= 0 { + return cfg, fmt.Errorf("%s: %q is not a positive duration", env, v) + } + *dst = d + } + } + if v := get("ARTEX_PANEL_EGRESS_MAX_IP_BLOCKS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n <= 0 { + return cfg, fmt.Errorf("ARTEX_PANEL_EGRESS_MAX_IP_BLOCKS: %q is not a positive integer", v) + } + cfg.MaxIPBlocks = n + } + return cfg, nil +} + +// getPolicy reads the scope policy; found is false when it does not exist. The +// chart's Role allows get/update on this one name only. +func (c *PanelEgressController) getPolicy(ctx context.Context) (found bool, err error) { + err = c.kube.do(ctx, http.MethodGet, c.kube.nsPath("networkpolicies")+"/"+url.PathEscape(c.cfg.PolicyName), nil, nil) + if isKubeStatus(err, http.StatusNotFound) { + return false, nil + } + return err == nil, err +} + +// Ping checks that the API is reachable and the controller may read its policy. +func (c *PanelEgressController) Ping(ctx context.Context) error { + _, err := c.getPolicy(ctx) + if err != nil && !errors.Is(err, ErrDockerUnavailable) { + return fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + return err +} + +// Recover leaves an existing policy untouched: until the panel pushes its scope, +// the policy written before a restart keeps applying. It reports 1 when one exists. +func (c *PanelEgressController) Recover(ctx context.Context) (int, error) { + found, err := c.getPolicy(ctx) + if found { + return 1, nil + } + return 0, err +} + +// WorkerCount is always 0: the controller runs no task pods. +func (c *PanelEgressController) WorkerCount() int { return 0 } + +var errPanelEgressNoExec = fmt.Errorf("%w: this runner only manages the panel egress policy (ARTEX_RUNNER_BACKEND=%s)", ErrBadRequest, BackendPanelEgress) + +func (c *PanelEgressController) Exec(context.Context, string, ExecRequest) (ExecResponse, error) { + return ExecResponse{}, errPanelEgressNoExec +} +func (c *PanelEgressController) Kill(context.Context, string) error { return errPanelEgressNoExec } +func (c *PanelEgressController) Delete(context.Context, string) error { return errPanelEgressNoExec } + +// PanelEgressStatus returns a copy of the current status. +func (c *PanelEgressController) PanelEgressStatus() PanelEgressStatus { + c.mu.Lock() + defer c.mu.Unlock() + st := c.status + st.ResolveErrors = slices.Clone(st.ResolveErrors) + return st +} + +// wantedHosts returns every host the current scope needs resolved. +func (c *PanelEgressController) wantedHosts() map[string]bool { + want := map[string]bool{} + for _, h := range c.extraHosts { + want[h] = true + } + if c.scope != nil { + for _, list := range [][]string{c.scope.Domains, c.scope.Hostnames, c.scope.ServiceHosts} { + for _, h := range list { + want[h] = true + } + } + } + return want +} + +// ApplyPanelEgress replaces the scope, drops addresses of hosts that left it, +// resolves hosts that are new, and writes the policy. +func (c *PanelEgressController) ApplyPanelEgress(ctx context.Context, in PanelEgressScope) (PanelEgressStatus, error) { + if len(in.Domains)+len(in.Hostnames)+len(in.ServiceHosts) > panelEgressMaxHosts { + return c.PanelEgressStatus(), fmt.Errorf("%w: more than %d hosts", ErrBadRequest, panelEgressMaxHosts) + } + if len(in.CIDRs) > panelEgressMaxCIDRs { + return c.PanelEgressStatus(), fmt.Errorf("%w: more than %d CIDRs", ErrBadRequest, panelEgressMaxCIDRs) + } + rejected := 0 + norm := func(list []string) []string { + seen := map[string]bool{} + var out []string + for _, h := range list { + n := normalizeEgressHost(h) + if n == "" { + rejected++ + continue + } + if !seen[n] { + seen[n] = true + out = append(out, n) + } + } + sort.Strings(out) + return out + } + scope := PanelEgressScope{ + Domains: norm(in.Domains), + Hostnames: norm(in.Hostnames), + ServiceHosts: norm(in.ServiceHosts), + Tasks: in.Tasks, + } + cidrSeen := map[string]bool{} + for _, raw := range in.CIDRs { + p, ok := parseEgressCIDR(raw) + if !ok { + rejected++ + continue + } + if s := p.String(); !cidrSeen[s] { + cidrSeen[s] = true + scope.CIDRs = append(scope.CIDRs, s) + } + } + sort.Strings(scope.CIDRs) + + c.mu.Lock() + c.scope = &scope + c.rejected = rejected + c.status.ScopeAt = c.cfg.Now() + want := c.wantedHosts() + for h := range c.seen { + if !want[h] { + delete(c.seen, h) // revoked: its addresses go now, not after the retention window + } + } + for h := range c.resolveErrors { + if !want[h] { + delete(c.resolveErrors, h) + } + } + var fresh []string + for h := range want { + if _, ok := c.seen[h]; !ok { + fresh = append(fresh, h) + } + } + c.mu.Unlock() + + c.resolve(ctx, fresh) + err := c.reconcile(ctx, false) + return c.PanelEgressStatus(), err +} + +// Refresh re-resolves every wanted host, expires stale addresses and writes the +// policy if it changed. Run calls it every cfg.Refresh. +func (c *PanelEgressController) Refresh(ctx context.Context) error { + c.mu.Lock() + if c.scope == nil { + c.mu.Unlock() + return nil // nothing pushed yet: keep whatever policy exists + } + var hosts []string + for h := range c.wantedHosts() { + hosts = append(hosts, h) + } + c.mu.Unlock() + c.resolve(ctx, hosts) + return c.reconcile(ctx, false) +} + +// Run refreshes periodically until ctx ends. +func (c *PanelEgressController) Run(ctx context.Context) { + t := time.NewTicker(c.cfg.Refresh) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + if err := c.Refresh(ctx); err != nil { + log.Printf("[panel-egress] refresh: %v", err) + } + } + } +} + +// resolve looks hosts up concurrently and records the answers. A failed lookup +// keeps the host's previous addresses until they expire. +func (c *PanelEgressController) resolve(ctx context.Context, hosts []string) { + if len(hosts) == 0 { + return + } + type result struct { + host string + addrs []netip.Addr + err error + } + jobs := make(chan string) + results := make(chan result) + workers := min(panelEgressResolveWorkers, len(hosts)) + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for h := range jobs { + rctx, cancel := context.WithTimeout(ctx, panelEgressResolveTimeout) + addrs, err := c.cfg.Resolver(rctx, h) + cancel() + results <- result{h, addrs, err} + } + }() + } + go func() { + for _, h := range hosts { + jobs <- h + } + close(jobs) + wg.Wait() + close(results) + }() + var got []result + for r := range results { + got = append(got, r) + } + now := c.cfg.Now() + c.mu.Lock() + defer c.mu.Unlock() + want := c.wantedHosts() + for _, r := range got { + if !want[r.host] { + continue // revoked while resolving + } + if _, ok := c.seen[r.host]; !ok { + c.seen[r.host] = map[netip.Addr]time.Time{} + } + if r.err != nil || len(r.addrs) == 0 { + msg := "no addresses" + if r.err != nil { + msg = r.err.Error() + } + c.resolveErrors[r.host] = msg + continue + } + delete(c.resolveErrors, r.host) + for _, a := range r.addrs { + c.seen[r.host][a.Unmap()] = now + } + } +} + +func (c *PanelEgressController) isDenied(a netip.Addr) bool { + if a.Is6() { + return true // like the per-task proxy: IPv6 only through a scope CIDR + } + for _, p := range c.denied { + if p.Contains(a) { + return true + } + } + return false +} + +// buildPolicy computes the NetworkPolicy for the current state. Callers hold c.mu. +func (c *PanelEgressController) buildPolicy() (obj map[string]any, st PanelEgressStatus) { + now := c.cfg.Now() + allowed := slices.Clone(c.extraCIDRs) + if c.scope != nil { + for _, s := range c.scope.CIDRs { + if p, ok := parseEgressCIDR(s); ok { + allowed = append(allowed, p) + } + } + } + covered := func(a netip.Addr) bool { + for _, p := range allowed { + if p.Contains(a) { + return true + } + } + return false + } + seenPrefix := map[netip.Prefix]bool{} + var cidrs []netip.Prefix + for _, p := range allowed { + if !seenPrefix[p] { + seenPrefix[p] = true + cidrs = append(cidrs, p) + } + } + var addrs []netip.Prefix + for _, m := range c.seen { + for a, at := range m { + if now.Sub(at) > c.cfg.Retention { + delete(m, a) // expired: the host has not resolved to it for a whole window + continue + } + switch { + case covered(a): + case c.isDenied(a): + st.DeniedIPs++ + default: + p := netip.PrefixFrom(a, a.BitLen()) + if !seenPrefix[p] { + seenPrefix[p] = true + addrs = append(addrs, p) + } + } + } + } + cmp := func(a, b netip.Prefix) int { + if c := a.Addr().Compare(b.Addr()); c != 0 { + return c + } + return a.Bits() - b.Bits() + } + slices.SortFunc(cidrs, cmp) + slices.SortFunc(addrs, cmp) + // Explicit CIDRs first: when the cap is hit, resolved addresses are dropped. + all := append(cidrs, addrs...) + if len(all) > c.cfg.MaxIPBlocks { + all = all[:c.cfg.MaxIPBlocks] + st.Truncated = true + } + blocks := make([]any, 0, len(all)) + for _, p := range all { + blocks = append(blocks, map[string]any{"ipBlock": map[string]any{"cidr": p.String()}}) + } + // An egress rule with no "to" allows everything: emit a rule only with peers. + egress := []any{} + if len(blocks) > 0 { + egress = append(egress, map[string]any{"to": blocks}) + } + labels := map[string]string{} + for k, v := range c.cfg.PolicyLabels { + labels[k] = v + } + labels[LabelManagedBy] = ManagedByPanelEgress + tasks := 0 + if c.scope != nil { + tasks = c.scope.Tasks + } + obj = map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": map[string]any{ + "name": c.cfg.PolicyName, + "labels": labels, + "annotations": map[string]string{AnnotationEgressTask: strconv.Itoa(tasks)}, + }, + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": c.cfg.PanelSelector}, + "policyTypes": []string{"Egress"}, + "egress": egress, + }, + } + st.Tasks = tasks + st.Hosts = len(c.seen) + st.IPBlocks = len(all) + return obj, st +} + +// reconcile writes the policy when it differs from the last one written, or when +// the last write is older than five refresh intervals (re-creates a deleted policy). +func (c *PanelEgressController) reconcile(ctx context.Context, force bool) error { + c.applyMu.Lock() + defer c.applyMu.Unlock() + + c.mu.Lock() + obj, st := c.buildPolicy() + raw, _ := json.Marshal(obj) + sum := sha256.Sum256(raw) + hash := hex.EncodeToString(sum[:]) + now := c.cfg.Now() + stale := now.Sub(c.lastApply) > 5*c.cfg.Refresh + same := hash == c.lastHash && c.status.State == PanelEgressEnforced + c.mu.Unlock() + + var err error + if force || !same || stale { + err = c.kube.applyPolicy(ctx, obj) + } + + c.mu.Lock() + defer c.mu.Unlock() + prev := c.status + st.Policy = c.cfg.PolicyName + st.Rejected = c.rejected + st.ScopeAt = prev.ScopeAt + for h, e := range c.resolveErrors { + if len(st.ResolveErrors) >= 10 { + break + } + st.ResolveErrors = append(st.ResolveErrors, h+": "+e) + } + sort.Strings(st.ResolveErrors) + if err != nil { + st.State = PanelEgressError + st.LastError = err.Error() + st.AppliedAt = prev.AppliedAt + c.status = st + log.Printf("[panel-egress] write %s failed, previous policy stays: %v", c.cfg.PolicyName, err) + return err + } + st.State = PanelEgressEnforced + st.AppliedAt = prev.AppliedAt + if force || !same || stale { + st.AppliedAt = now + c.lastApply = now + if hash != c.lastHash { + log.Printf("[panel-egress] policy %s enforced: %d task(s), %d host(s), %d IP block(s), %d denied address(es)%s", + c.cfg.PolicyName, st.Tasks, st.Hosts, st.IPBlocks, st.DeniedIPs, map[bool]string{true: ", TRUNCATED", false: ""}[st.Truncated]) + } + c.lastHash = hash + } + c.status = st + return nil +} diff --git a/sandbox/paneleggress_test.go b/sandbox/paneleggress_test.go new file mode 100644 index 000000000..c1ab897bb --- /dev/null +++ b/sandbox/paneleggress_test.go @@ -0,0 +1,643 @@ +package sandbox + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/netip" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "testing" + "time" +) + +// fakeDNS is a mutable resolver for the panel egress controller. +type fakeDNS struct { + mu sync.Mutex + answers map[string][]string + fail map[string]bool + calls map[string]int +} + +func newFakeDNS(answers map[string][]string) *fakeDNS { + return &fakeDNS{answers: answers, fail: map[string]bool{}, calls: map[string]int{}} +} + +func (d *fakeDNS) set(host string, ips ...string) { + d.mu.Lock() + defer d.mu.Unlock() + d.answers[host] = ips +} + +func (d *fakeDNS) setFail(host string, fail bool) { + d.mu.Lock() + defer d.mu.Unlock() + d.fail[host] = fail +} + +func (d *fakeDNS) resolve(_ context.Context, host string) ([]netip.Addr, error) { + d.mu.Lock() + defer d.mu.Unlock() + d.calls[host]++ + if d.fail[host] { + return nil, errors.New("SERVFAIL") + } + var out []netip.Addr + for _, s := range d.answers[host] { + out = append(out, netip.MustParseAddr(s)) + } + if len(out) == 0 { + return nil, fmt.Errorf("no such host %s", host) + } + return out, nil +} + +type egressClock struct { + mu sync.Mutex + t time.Time +} + +func (c *egressClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *egressClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +func newTestPanelEgress(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, dns *fakeDNS, clk *egressClock, mut func(*PanelEgressConfig)) *PanelEgressController { + t.Helper() + tok := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(tok, []byte(f.token), 0o600); err != nil { + t.Fatal(err) + } + cfg := PanelEgressConfig{ + Kube: KubeConfig{APIServer: srv.URL, TokenPath: tok, Namespace: f.ns}, + PolicyName: "rel-artex-panel-egress-scope", + PanelSelector: map[string]string{"app.kubernetes.io/component": "panel", "app.kubernetes.io/instance": "rel"}, + PolicyLabels: map[string]string{"app.kubernetes.io/instance": "rel"}, + Refresh: time.Minute, + Retention: time.Hour, + Resolver: dns.resolve, + Now: clk.now, + } + if mut != nil { + mut(&cfg) + } + c, err := NewPanelEgressController(cfg) + if err != nil { + t.Fatalf("NewPanelEgressController: %v", err) + } + return c +} + +// policyCIDRs returns the ipBlock CIDRs of the scope policy, failing on any rule +// shape the controller must never write. +func policyCIDRs(t *testing.T, f *fakeKubeAPI) []string { + t.Helper() + o := f.obj("networkpolicies", "rel-artex-panel-egress-scope") + if o == nil { + t.Fatal("scope policy not written") + } + if pt := strList(dig(o, "spec", "policyTypes")); !slices.Equal(pt, []string{"Egress"}) { + t.Fatalf("policyTypes = %v (must not touch ingress)", pt) + } + if dig(o, "spec", "ingress") != nil { + t.Fatal("scope policy has ingress rules") + } + rules, ok := dig(o, "spec", "egress").([]any) + if !ok { + t.Fatalf("egress = %#v", dig(o, "spec", "egress")) + } + var out []string + for _, r := range rules { + to, _ := dig(r, "to").([]any) + if len(to) == 0 { + t.Fatalf("egress rule without peers allows everything: %v", r) + } + if dig(r, "ports") != nil { + t.Fatalf("scope rule restricts ports: %v", r) + } + for _, p := range to { + if dig(p, "podSelector") != nil || dig(p, "namespaceSelector") != nil { + t.Fatalf("scope rule selects pods: %v", p) + } + if dig(p, "ipBlock", "except") != nil { + t.Fatalf("unexpected except: %v", p) + } + out = append(out, dig(p, "ipBlock", "cidr").(string)) + } + } + return out +} + +func TestPanelEgressPolicyShape(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{ + "example.com": {"93.184.215.14", "2606:2800:21f:cb07::1"}, + "www.example.com": {"93.184.215.14"}, // duplicate address + "api.anthropic.com": {"160.79.104.10"}, + "hooks.slack.com": {"34.1.2.3"}, + }) + clk := &egressClock{t: time.Unix(1_700_000_000, 0)} + c := newTestPanelEgress(t, f, srv, dns, clk, func(cfg *PanelEgressConfig) { + cfg.ExtraHosts = []string{"hooks.slack.com"} + cfg.ExtraCIDRs = []string{"10.20.0.0/16"} + }) + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{ + Domains: []string{"Example.COM.", "*.example.com"}, + Hostnames: []string{"www.example.com"}, + CIDRs: []string{"198.51.100.0/24", "203.0.113.7", "198.51.100.9/24"}, + ServiceHosts: []string{"api.anthropic.com"}, + Tasks: 2, + }) + if err != nil { + t.Fatal(err) + } + got := policyCIDRs(t, f) + want := []string{"10.20.0.0/16", "198.51.100.0/24", "203.0.113.7/32", "34.1.2.3/32", "93.184.215.14/32", "160.79.104.10/32"} + if !slices.Equal(got, want) { + t.Fatalf("ipBlocks = %v\nwant %v", got, want) + } + if st.State != PanelEgressEnforced || st.IPBlocks != len(want) || st.Tasks != 2 || st.Hosts != 4 { + t.Fatalf("status = %+v", st) + } + if st.DeniedIPs != 1 { // the IPv6 answer + t.Errorf("denied = %d", st.DeniedIPs) + } + o := f.obj("networkpolicies", "rel-artex-panel-egress-scope") + if sel := dig(o, "spec", "podSelector", "matchLabels"); dig(sel, "app.kubernetes.io/component") != "panel" || dig(sel, "app.kubernetes.io/instance") != "rel" { + t.Errorf("podSelector = %v", sel) + } + if dig(o, "metadata", "labels", LabelManagedBy) != ManagedByPanelEgress || dig(o, "metadata", "labels", "app.kubernetes.io/instance") != "rel" { + t.Errorf("labels = %v", dig(o, "metadata", "labels")) + } + if dig(o, "metadata", "annotations", AnnotationEgressTask) != "2" { + t.Errorf("annotations = %v", dig(o, "metadata", "annotations")) + } + // The API server rejects label/annotation keys that are not qualified names + // (prefix: lowercase RFC 1123 subdomain); the fake does not, so check here. + qualified := regexp.MustCompile(`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$`) + for _, field := range []string{"labels", "annotations"} { + for k := range dig(o, "metadata", field).(map[string]any) { + if !qualified.MatchString(k) { + t.Errorf("%s key %q is not a valid qualified name", field, k) + } + } + } + + // Pushing the same scope again does not rewrite the policy. + before := len(f.opsSnapshot()) + if _, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{ + Domains: []string{"example.com"}, Hostnames: []string{"www.example.com"}, + CIDRs: []string{"198.51.100.0/24", "203.0.113.7"}, ServiceHosts: []string{"api.anthropic.com"}, Tasks: 2, + }); err != nil { + t.Fatal(err) + } + if ops := f.opsSnapshot(); len(ops) != before { + t.Errorf("unchanged scope rewrote the policy: %v", ops[before:]) + } +} + +func TestPanelEgressEmptyScopeAllowsNothing(t *testing.T) { + f, srv := newFakeKubeAPI(t) + c := newTestPanelEgress(t, f, srv, newFakeDNS(map[string][]string{}), &egressClock{t: time.Now()}, nil) + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{}) + if err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 0 { + t.Fatalf("empty scope allows %v", got) + } + if st.State != PanelEgressEnforced || st.IPBlocks != 0 { + t.Fatalf("status %+v", st) + } + // A host that does not resolve adds nothing either. + st, err = c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"nx.example"}}) + if err != nil || len(policyCIDRs(t, f)) != 0 || len(st.ResolveErrors) != 1 { + t.Fatalf("unresolvable host: %+v %v %v", st, err, policyCIDRs(t, f)) + } +} + +func TestPanelEgressDeniedRangesMirrorProxyPolicy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{ + "internal.corp.example": {"10.1.2.3"}, + "meta.corp.example": {"169.254.169.254"}, + "loop.corp.example": {"127.0.0.1"}, + "cgnat.corp.example": {"100.64.1.1"}, + "lab.corp.example": {"192.168.5.5"}, + "pub.corp.example": {"8.8.4.4"}, + "v6.corp.example": {"2001:db8::1"}, + }) + c := newTestPanelEgress(t, f, srv, dns, &egressClock{t: time.Now()}, nil) + hosts := []string{"internal.corp.example", "meta.corp.example", "loop.corp.example", "cgnat.corp.example", "lab.corp.example", "pub.corp.example", "v6.corp.example"} + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"corp.example"}, Hostnames: hosts}) + if err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"8.8.4.4/32"}) { + t.Fatalf("resolved private/metadata/IPv6 allowed: %v", got) + } + if st.DeniedIPs != 6 { + t.Errorf("denied = %d", st.DeniedIPs) + } + // An approved scope CIDR covers private addresses (and makes the /32 redundant), + // exactly as the per-task proxy allows a scope CIDR back. + if _, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"corp.example"}, Hostnames: hosts, CIDRs: []string{"10.1.0.0/16", "2001:db8::/32"}}); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"10.1.0.0/16", "2001:db8::/32", "8.8.4.4/32"}) { + t.Fatalf("with scope CIDR: %v", got) + } + + // The denied list follows sandbox.proxyDeniedCIDRs when it is set. + f2, srv2 := newFakeKubeAPI(t) + c2 := newTestPanelEgress(t, f2, srv2, dns, &egressClock{t: time.Now()}, func(cfg *PanelEgressConfig) { + cfg.DeniedCIDRs = []string{"8.8.0.0/16"} + }) + if _, err := c2.ApplyPanelEgress(context.Background(), PanelEgressScope{Hostnames: []string{"pub.corp.example", "lab.corp.example"}}); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f2); !slices.Equal(got, []string{"192.168.5.5/32"}) { + t.Fatalf("custom denied list: %v", got) + } +} + +func TestPanelEgressUnionDedupAndRejects(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"a.example": {"203.0.113.1"}, "b.example": {"203.0.113.1", "203.0.113.2"}}) + c := newTestPanelEgress(t, f, srv, dns, &egressClock{t: time.Now()}, nil) + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{ + Domains: []string{"a.example", "A.EXAMPLE", "b.example", "bad host", "http://x.example/", "10.0.0.1", strings.Repeat("a", 254)}, + Hostnames: []string{"b.example"}, + CIDRs: []string{"203.0.113.0/30", "203.0.113.1/30", "not-a-cidr", "300.1.1.1/8"}, + }) + if err != nil { + t.Fatal(err) + } + // Both resolved addresses sit inside the scope CIDR: one block. + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"203.0.113.0/30"}) { + t.Fatalf("ipBlocks = %v", got) + } + if st.Rejected != 6 { + t.Errorf("rejected = %d, want 6 (IP literal in domains, junk hosts, bad CIDRs)", st.Rejected) + } + if st.Hosts != 2 { + t.Errorf("hosts = %d", st.Hosts) + } + if dns.calls["a.example"] != 1 { + t.Errorf("duplicate host resolved %d times", dns.calls["a.example"]) + } + // Oversized pushes are refused outright. + big := make([]string, panelEgressMaxHosts+1) + for i := range big { + big[i] = fmt.Sprintf("h%d.example", i) + } + if _, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Hostnames: big}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("oversized push = %v", err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"203.0.113.0/30"}) { + t.Fatalf("refused push changed the policy: %v", got) + } +} + +func TestPanelEgressRevokeDropsImmediately(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"example.com": {"93.184.215.14"}, "example.org": {"93.184.215.15"}}) + c := newTestPanelEgress(t, f, srv, dns, &egressClock{t: time.Now()}, nil) + ctx := context.Background() + if _, err := c.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"example.com", "example.org"}, CIDRs: []string{"198.51.100.0/24"}}); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 3 { + t.Fatalf("before revoke %v", got) + } + // Revoked: example.org and the CIDR leave the policy on this push, well inside + // the retention window. + if _, err := c.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"example.com"}}); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"93.184.215.14/32"}) { + t.Fatalf("after revoke %v", got) + } + // All tasks finished. + if _, err := c.ApplyPanelEgress(ctx, PanelEgressScope{}); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 0 { + t.Fatalf("no tasks still allows %v", got) + } +} + +func TestPanelEgressRetentionWindow(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"cdn.example": {"203.0.113.1"}}) + clk := &egressClock{t: time.Unix(1_700_000_000, 0)} + c := newTestPanelEgress(t, f, srv, dns, clk, func(cfg *PanelEgressConfig) { + cfg.Refresh, cfg.Retention = time.Minute, 10*time.Minute + }) + ctx := context.Background() + if _, err := c.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"cdn.example"}}); err != nil { + t.Fatal(err) + } + // DNS rotates: both addresses stay allowed while the old one is in the window. + dns.set("cdn.example", "203.0.113.2") + clk.advance(time.Minute) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"203.0.113.1/32", "203.0.113.2/32"}) { + t.Fatalf("after rotation %v", got) + } + // 203.0.113.1 was last seen at t0; at t0+10m it is still inside the window. + clk.advance(9 * time.Minute) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 2 { + t.Fatalf("expired too early: %v", got) + } + clk.advance(time.Minute + time.Second) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"203.0.113.2/32"}) { + t.Fatalf("after expiry %v", got) + } +} + +func TestPanelEgressResolverFailureKeepsLastKnown(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"example.com": {"93.184.215.14"}}) + clk := &egressClock{t: time.Unix(1_700_000_000, 0)} + c := newTestPanelEgress(t, f, srv, dns, clk, func(cfg *PanelEgressConfig) { + cfg.Refresh, cfg.Retention = time.Minute, 30*time.Minute + }) + ctx := context.Background() + if _, err := c.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"example.com"}}); err != nil { + t.Fatal(err) + } + dns.setFail("example.com", true) + clk.advance(5 * time.Minute) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"93.184.215.14/32"}) { + t.Fatalf("resolver failure dropped last-known address: %v", got) + } + st := c.PanelEgressStatus() + if st.State != PanelEgressEnforced || len(st.ResolveErrors) != 1 || !strings.Contains(st.ResolveErrors[0], "SERVFAIL") { + t.Fatalf("status %+v", st) + } + // Still failing after the retention window: fail closed. + clk.advance(30 * time.Minute) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 0 { + t.Fatalf("stale address kept forever: %v", got) + } + // Recovery. + dns.setFail("example.com", false) + if err := c.Refresh(ctx); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 1 || len(c.PanelEgressStatus().ResolveErrors) != 0 { + t.Fatalf("after recovery %v %+v", got, c.PanelEgressStatus()) + } +} + +func TestPanelEgressNoPushKeepsExistingPolicy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + // A policy left by a previous controller instance. + f.objs["networkpolicies"]["rel-artex-panel-egress-scope"] = map[string]any{ + "metadata": map[string]any{"name": "rel-artex-panel-egress-scope"}, + "spec": map[string]any{"egress": []any{map[string]any{"to": []any{map[string]any{"ipBlock": map[string]any{"cidr": "203.0.113.9/32"}}}}}}, + } + c := newTestPanelEgress(t, f, srv, newFakeDNS(map[string][]string{}), &egressClock{t: time.Now()}, nil) + if n, err := c.Recover(context.Background()); n != 1 || err != nil { + t.Fatalf("recover = %d, %v", n, err) + } + if err := c.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if ops := f.opsSnapshot(); len(ops) != 0 { + t.Fatalf("controller touched the policy before any push: %v", ops) + } + if st := c.PanelEgressStatus(); st.State != PanelEgressWaiting { + t.Fatalf("state %q", st.State) + } +} + +func TestPanelEgressWriteFailureReportsError(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"example.com": {"93.184.215.14"}}) + c := newTestPanelEgress(t, f, srv, dns, &egressClock{t: time.Now()}, nil) + f.token = "rotated" // API now rejects the controller + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"example.com"}}) + if err == nil || st.State != PanelEgressError || st.LastError == "" { + t.Fatalf("status %+v err %v", st, err) + } + if f.obj("networkpolicies", "rel-artex-panel-egress-scope") != nil { + t.Fatal("policy written despite the error") + } + f.token = "test-sa-token" + if err := os.WriteFile(c.kube.cfg.TokenPath, []byte("test-sa-token"), 0o600); err != nil { + t.Fatal(err) + } + // Same scope, previous write failed: the retry writes it. + st, err = c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"example.com"}}) + if err != nil || st.State != PanelEgressEnforced || st.LastError != "" { + t.Fatalf("after recovery %+v %v", st, err) + } + if got := policyCIDRs(t, f); len(got) != 1 { + t.Fatalf("policy %v", got) + } +} + +func TestPanelEgressRecreatesDeletedPolicy(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"example.com": {"93.184.215.14"}}) + clk := &egressClock{t: time.Unix(1_700_000_000, 0)} + c := newTestPanelEgress(t, f, srv, dns, clk, nil) + if _, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Domains: []string{"example.com"}}); err != nil { + t.Fatal(err) + } + f.mu.Lock() + delete(f.objs["networkpolicies"], "rel-artex-panel-egress-scope") + f.mu.Unlock() + clk.advance(5*time.Minute + time.Second) + if err := c.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); len(got) != 1 { + t.Fatalf("policy not re-created: %v", got) + } +} + +func TestPanelEgressTruncatesResolvedAddressesFirst(t *testing.T) { + f, srv := newFakeKubeAPI(t) + answers := map[string][]string{} + var hosts []string + for i := 1; i <= 5; i++ { + h := fmt.Sprintf("h%d.example", i) + hosts = append(hosts, h) + answers[h] = []string{fmt.Sprintf("203.0.113.%d", i)} + } + c := newTestPanelEgress(t, f, srv, newFakeDNS(answers), &egressClock{t: time.Now()}, func(cfg *PanelEgressConfig) { cfg.MaxIPBlocks = 3 }) + st, err := c.ApplyPanelEgress(context.Background(), PanelEgressScope{Hostnames: hosts, CIDRs: []string{"198.51.100.0/24"}}) + if err != nil { + t.Fatal(err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"198.51.100.0/24", "203.0.113.1/32", "203.0.113.2/32"}) || !st.Truncated { + t.Fatalf("truncated policy %v %+v", got, st) + } +} + +func TestPanelEgressConfigValidation(t *testing.T) { + f, srv := newFakeKubeAPI(t) + base := func() PanelEgressConfig { + return PanelEgressConfig{ + Kube: KubeConfig{APIServer: srv.URL, TokenPath: "/dev/null", Namespace: f.ns}, + PolicyName: "p", + PanelSelector: map[string]string{"a": "b"}, + } + } + for name, mut := range map[string]func(*PanelEgressConfig){ + "no policy": func(c *PanelEgressConfig) { c.PolicyName = "" }, + "bad policy": func(c *PanelEgressConfig) { c.PolicyName = "Bad_Name" }, + "no selector": func(c *PanelEgressConfig) { c.PanelSelector = nil }, + "bad extra cidr": func(c *PanelEgressConfig) { c.ExtraCIDRs = []string{"x"} }, + "ip as extra host": func(c *PanelEgressConfig) { c.ExtraHosts = []string{"1.2.3.4"} }, + "bad extra host": func(c *PanelEgressConfig) { c.ExtraHosts = []string{"a b"} }, + "bad denied": func(c *PanelEgressConfig) { c.DeniedCIDRs = []string{"10/8"} }, + "short retention": func(c *PanelEgressConfig) { c.Refresh, c.Retention = time.Hour, time.Minute }, + } { + cfg := base() + mut(&cfg) + if _, err := NewPanelEgressController(cfg); err == nil { + t.Errorf("%s: accepted", name) + } + } + c, err := NewPanelEgressController(base()) + if err != nil { + t.Fatal(err) + } + if c.cfg.Refresh != time.Minute || c.cfg.Retention != time.Hour || c.cfg.MaxIPBlocks != 4000 || len(c.denied) != len(DefaultProxyDeniedCIDRs) { + t.Errorf("defaults %+v", c.cfg) + } + + t.Setenv("ARTEX_KUBE_NAMESPACE", "ns1") + t.Setenv("ARTEX_PANEL_EGRESS_POLICY", "rel-artex-panel-egress-scope") + t.Setenv("ARTEX_PANEL_EGRESS_SELECTOR", "app.kubernetes.io/component=panel,app.kubernetes.io/instance=rel") + t.Setenv("ARTEX_PANEL_EGRESS_LABELS", "x=y") + t.Setenv("ARTEX_PANEL_EGRESS_EXTRA_HOSTS", "hooks.slack.com, mcp.example") + t.Setenv("ARTEX_PANEL_EGRESS_EXTRA_CIDRS", "10.9.0.0/16") + t.Setenv("ARTEX_PANEL_EGRESS_DENIED_CIDRS", "10.0.0.0/8") + t.Setenv("ARTEX_PANEL_EGRESS_REFRESH", "30s") + t.Setenv("ARTEX_PANEL_EGRESS_RETENTION", "2h") + t.Setenv("ARTEX_PANEL_EGRESS_MAX_IP_BLOCKS", "100") + cfg, err := PanelEgressConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.Kube.Namespace != "ns1" || cfg.PanelSelector["app.kubernetes.io/instance"] != "rel" || len(cfg.PanelSelector) != 2 || + !slices.Equal(cfg.ExtraHosts, []string{"hooks.slack.com", "mcp.example"}) || cfg.Refresh != 30*time.Second || + cfg.Retention != 2*time.Hour || cfg.MaxIPBlocks != 100 || !slices.Equal(cfg.DeniedCIDRs, []string{"10.0.0.0/8"}) || cfg.PolicyLabels["x"] != "y" { + t.Fatalf("from env %+v", cfg) + } + for k, v := range map[string]string{ + "ARTEX_PANEL_EGRESS_SELECTOR": "novalue", + "ARTEX_PANEL_EGRESS_REFRESH": "-1s", + "ARTEX_PANEL_EGRESS_RETENTION": "soon", + "ARTEX_PANEL_EGRESS_MAX_IP_BLOCKS": "0", + } { + t.Run(k, func(t *testing.T) { + t.Setenv(k, v) + if _, err := PanelEgressConfigFromEnv(); err == nil { + t.Errorf("%s=%s accepted", k, v) + } + }) + } +} + +func TestPanelEgressRunnerEndpoint(t *testing.T) { + f, srv := newFakeKubeAPI(t) + dns := newFakeDNS(map[string][]string{"example.com": {"93.184.215.14"}}) + c := newTestPanelEgress(t, f, srv, dns, &egressClock{t: time.Now()}, nil) + rs, err := NewRunnerServer("tok", "v", c) + if err != nil { + t.Fatal(err) + } + h := httptest.NewServer(rs.Handler()) + defer h.Close() + ctx := context.Background() + + // Auth: a missing or wrong token never reaches the controller. + for _, tok := range []string{"", "wrong"} { + if _, err := NewClient(h.URL, tok).ApplyPanelEgress(ctx, PanelEgressScope{CIDRs: []string{"0.0.0.0/0"}}); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("token %q: %v", tok, err) + } + if _, err := NewClient(h.URL, tok).PanelEgressStatus(ctx); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("status with token %q: %v", tok, err) + } + } + if f.obj("networkpolicies", "rel-artex-panel-egress-scope") != nil { + t.Fatal("unauthenticated push wrote a policy") + } + + cl := NewClient(h.URL, "tok") + if st, err := cl.PanelEgressStatus(ctx); err != nil || st.State != PanelEgressWaiting { + t.Fatalf("initial status %+v %v", st, err) + } + st, err := cl.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"example.com"}, Tasks: 1}) + if err != nil || st.State != PanelEgressEnforced || st.IPBlocks != 1 { + t.Fatalf("apply %+v %v", st, err) + } + if got := policyCIDRs(t, f); !slices.Equal(got, []string{"93.184.215.14/32"}) { + t.Fatalf("policy %v", got) + } + // Unknown fields are refused (a typo must not silently drop scope). + req, _ := http.NewRequest(http.MethodPut, h.URL+"/v1/panel-egress", strings.NewReader(`{"domain":["x.example"]}`)) + req.Header.Set("Authorization", "Bearer tok") + resp, err := http.DefaultClient.Do(req) + if err != nil || resp.StatusCode != http.StatusBadRequest { + t.Fatalf("unknown field: %v %v", resp, err) + } + resp.Body.Close() + // Exec and friends are refused by a policy-only runner. + if _, err := cl.Exec(ctx, "1", ExecRequest{Argv: []string{"id"}}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("exec on panel-egress runner = %v", err) + } + if _, err := cl.Kill(ctx, "1"); !errors.Is(err, ErrBadRequest) { + t.Fatalf("kill = %v", err) + } + if hl, err := cl.Health(ctx); err != nil || !hl.OK || hl.Workers != 0 { + t.Fatalf("health %+v %v", hl, err) + } + // A write failure is reported, not hidden. + f.token = "rotated" + if _, err := cl.ApplyPanelEgress(ctx, PanelEgressScope{Domains: []string{"example.org"}}); err == nil || !IsUnavailable(err) { + t.Fatalf("write failure = %v", err) + } + + // The task runner (Kubernetes backend) does not serve the endpoint. + f2, srv2 := newFakeKubeAPI(t) + rs2, _ := NewRunnerServer("tok", "v", newTestKubeBackend(t, f2, srv2)) + h2 := httptest.NewServer(rs2.Handler()) + defer h2.Close() + if _, err := NewClient(h2.URL, "tok").ApplyPanelEgress(ctx, PanelEgressScope{}); !errors.Is(err, ErrNotFound) { + t.Fatalf("task runner panel-egress = %v", err) + } +} diff --git a/sandbox/runner.go b/sandbox/runner.go index 6f8803af9..cf359e480 100644 --- a/sandbox/runner.go +++ b/sandbox/runner.go @@ -50,6 +50,8 @@ func NewRunnerServer(token, version string, backend Backend) (*RunnerServer, err rs.mux.HandleFunc("POST /v1/tasks/{id}/exec", rs.withAuth(rs.handleExec)) rs.mux.HandleFunc("POST /v1/tasks/{id}/kill", rs.withAuth(rs.handleKill)) rs.mux.HandleFunc("DELETE /v1/tasks/{id}", rs.withAuth(rs.handleDelete)) + rs.mux.HandleFunc("PUT /v1/panel-egress", rs.withAuth(rs.handlePanelEgressApply)) + rs.mux.HandleFunc("GET /v1/panel-egress", rs.withAuth(rs.handlePanelEgressStatus)) return rs, nil } @@ -141,6 +143,47 @@ func (rs *RunnerServer) handleDelete(w http.ResponseWriter, r *http.Request) { writeRunnerJSON(w, http.StatusOK, DeleteResponse{Deleted: true}) } +// panelEgress returns the backend as a PanelEgressBackend, or writes 404. +func (rs *RunnerServer) panelEgress(w http.ResponseWriter) (PanelEgressBackend, bool) { + pe, ok := rs.backend.(PanelEgressBackend) + if !ok { + writeRunnerErr(w, http.StatusNotFound, "panel egress is not managed by this runner (ARTEX_RUNNER_BACKEND="+BackendPanelEgress+" is)") + } + return pe, ok +} + +func (rs *RunnerServer) handlePanelEgressApply(w http.ResponseWriter, r *http.Request) { + pe, ok := rs.panelEgress(w) + if !ok { + return + } + var scope PanelEgressScope + dec := json.NewDecoder(io.LimitReader(r.Body, 4<<20)) + dec.DisallowUnknownFields() + if err := dec.Decode(&scope); err != nil { + writeRunnerErr(w, http.StatusBadRequest, "invalid json: "+err.Error()) + return + } + st, err := pe.ApplyPanelEgress(r.Context(), scope) + if err != nil { + if errors.Is(err, ErrBadRequest) { + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + return + } + // The scope was accepted but the policy write failed: the previous policy + // stays in place. Report the state so the panel can show it. + writeRunnerJSON(w, http.StatusBadGateway, st) + return + } + writeRunnerJSON(w, http.StatusOK, st) +} + +func (rs *RunnerServer) handlePanelEgressStatus(w http.ResponseWriter, r *http.Request) { + if pe, ok := rs.panelEgress(w); ok { + writeRunnerJSON(w, http.StatusOK, pe.PanelEgressStatus()) + } +} + func (rs *RunnerServer) writeBackendErr(w http.ResponseWriter, err error) { switch { case errors.Is(err, ErrBadRequest): From 5e72fb34d00850fb22fea906102079fdfca9f675 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:57 +0200 Subject: [PATCH 4/5] feat(server): push task scope to the panel egress controller in off mode With ARTEX_SANDBOX=off and ARTEX_PANEL_EGRESS_URL set (the Helm chart sets it), the panel builds the union of the operator-approved scope of every live task with taskSandboxRunInfo, adds the known asset hostnames under the approved domains and the LLM endpoints from the environment and the saved profiles, and pushes it to the controller before each planner/worker turn when it changed and every 30 s. A failed push is retried by the periodic sync and, after 15 s, by the next turn. The state is logged on change and reported to signed-in sessions in GET /api/health as sandbox_egress. Nothing changes without the variable: Docker deployments and required mode behave as before. ARTEX_RUNNER_TOKEN, which now also authorizes scope pushes, is scrubbed and sealed like the other startup secrets. --- cmd/artex/main.go | 18 +- server/engine.go | 4 + server/env_scrub.go | 1 + server/envseal_linux_test.go | 2 + server/paneleggress.go | 366 +++++++++++++++++++++++++++++++++++ server/paneleggress_test.go | 349 +++++++++++++++++++++++++++++++++ server/server.go | 6 + 7 files changed, 745 insertions(+), 1 deletion(-) create mode 100644 server/paneleggress.go create mode 100644 server/paneleggress_test.go diff --git a/cmd/artex/main.go b/cmd/artex/main.go index 14e62d485..befde63f8 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -262,6 +262,8 @@ func run() int { return 1 } var sandboxClient server.SandboxClient + panelEgressURL := strings.TrimSpace(os.Getenv(sandbox.EnvPanelEgressURL)) + var panelEgressOpt server.Option = func(*server.Server) {} if sandboxCfg.Mode == sandbox.ModeRequired { sandboxClient = sandbox.NewClient(sandboxCfg.RunnerURL, sandboxCfg.RunnerToken) hctx, hcancel := context.WithTimeout(ctx, 5*time.Second) @@ -272,11 +274,25 @@ func run() int { } else { slog.Info("[sandbox] ARTEX_SANDBOX=required: connected to artex-runner", "runner_url", sandboxCfg.RunnerURL, "workers", h.Workers, "version", h.Version) } + if panelEgressURL != "" { + slog.Warn("[sandbox] " + sandbox.EnvPanelEgressURL + " is ignored: panel egress control applies only to ARTEX_SANDBOX=off") + } } else { server.LogSandboxOffBanner() + // Kubernetes (Helm chart, sandbox.offModeEgress): the panel's egress is + // limited to the approved scope of its tasks by a NetworkPolicy the panel + // egress controller maintains from the scope pushed here. + if panelEgressURL != "" { + if sandboxCfg.RunnerToken == "" { + slog.Error("[sandbox] " + sandbox.EnvPanelEgressURL + " is set but " + sandbox.EnvRunnerToken + " is empty") + return 1 + } + panelEgressOpt = server.WithPanelEgress(sandbox.NewClient(panelEgressURL, sandboxCfg.RunnerToken), server.PanelEgressEnvHosts()) + slog.Info("[sandbox] ARTEX_SANDBOX=off: panel egress is limited to task scope by the panel egress controller", "controller", panelEgressURL) + } } - srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout), server.WithSandbox(sandboxClient, sandboxCfg.Mode)) + srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout), server.WithSandbox(sandboxClient, sandboxCfg.Mode), panelEgressOpt) // ReadTimeout bounds how long the request headers and body may take to arrive. // It does not limit how long a handler runs, so an event stream stays open. // WriteTimeout is left unset: a write deadline would cut that stream. diff --git a/server/engine.go b/server/engine.go index 093c4cd44..bf1636716 100644 --- a/server/engine.go +++ b/server/engine.go @@ -98,6 +98,7 @@ type Engine struct { statefulGuardOnce sync.Once statefulGuard *intercept.StatefulTargetGuard sandboxClient SandboxClient + panelEgress *panelEgress // ARTEX_SANDBOX=off on Kubernetes: pushes task scope to the panel egress policy sandboxMode string sandboxDataDir string m *Manager @@ -210,6 +211,9 @@ func (e *Engine) killSandboxTask(taskID string) { func (e *Engine) withTaskSandbox(ctx context.Context, taskID string) context.Context { if e.sandboxMode != sandbox.ModeRequired { + // Off mode on Kubernetes: the turn's commands run in the panel pod, whose + // egress follows the union of task scopes. Bring it up to date first. + e.panelEgress.ensure(ctx) return ctx } var pg *db.DB diff --git a/server/env_scrub.go b/server/env_scrub.go index 5a1759168..d9c090f52 100644 --- a/server/env_scrub.go +++ b/server/env_scrub.go @@ -19,6 +19,7 @@ import "os" // the environment: the scrub does not hide them from child processes. var secretEnv = []string{ "ARTEX_PG_DSN", "ARTEX_PG_PASSWORD", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", + "ARTEX_RUNNER_TOKEN", // also authenticates scope pushes to the panel egress controller "ARTEX_LLM_API_KEY", "ARTEX_LLM_CUSTOM_HEADERS", "ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN", diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go index e9fae29f7..c111fc9fb 100644 --- a/server/envseal_linux_test.go +++ b/server/envseal_linux_test.go @@ -55,6 +55,8 @@ func TestSealedEnvironmentHandoff(t *testing.T) { "ARTEX_SECRET_KEY": "", "ANTHROPIC_API_KEY": "sk-ant-test", "OPENAI_API_KEY": "=leading-equals", + // Authorizes runner calls and, in sandbox off mode, scope pushes. + "ARTEX_RUNNER_TOKEN": "runner-token-test", // The Bedrock gateway reads a bearer token and supports multiline headers. "ARTEX_LLM_API_KEY": "synthetic-gateway-token", "ARTEX_LLM_CUSTOM_HEADERS": "X-Example-Secret: synthetic-header-value\nX-Example-Route: demo", diff --git a/server/paneleggress.go b/server/paneleggress.go new file mode 100644 index 000000000..9d2482af2 --- /dev/null +++ b/server/paneleggress.go @@ -0,0 +1,366 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "log" + "net/netip" + "net/url" + "os" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/sandbox" +) + +// Scope-restricted panel egress for ARTEX_SANDBOX=off on Kubernetes. +// +// With the sandbox off, agent commands run inside the panel pod. The Helm chart +// then restricts the panel's egress to DNS, the database and the panel egress +// controller (an artex-runner with ARTEX_RUNNER_BACKEND=panel-egress), which +// adds the approved scope of the live tasks as a NetworkPolicy. The panel computes +// that scope from PostgreSQL with the same taskSandboxRunInfo the per-task egress +// proxy uses, and pushes it: on each planner/worker turn (so a task's scope is in +// place before its commands run) and every panelEgressInterval (so a revoked scope +// or a finished task drops out, and a restarted controller gets the scope back). +// The panel holds no Kubernetes credentials. Nothing here runs without +// ARTEX_PANEL_EGRESS_URL, which only the chart sets, and only in off mode. + +// PanelEgressClient is the subset of *sandbox.Client the panel uses. +type PanelEgressClient interface { + ApplyPanelEgress(ctx context.Context, scope sandbox.PanelEgressScope) (sandbox.PanelEgressStatus, error) +} + +const ( + panelEgressInterval = 30 * time.Second + panelEgressPushTimeout = 10 * time.Second + // panelEgressRetryAfter: after a failed push, turns do not retry for this long + // (the periodic sync still does), so a dead controller does not slow every turn. + panelEgressRetryAfter = 15 * time.Second + // panelEgressMaxKnownHosts caps the discovered hostnames pushed per sync. + panelEgressMaxKnownHosts = 2000 +) + +// PanelEgressState is what GET /api/health reports as "sandbox_egress". +type PanelEgressState struct { + // State: "pending" (no successful push yet), "enforced", or "error" (the last + // push failed; the previous policy, if any, stays in place). + State string `json:"state"` + Policy string `json:"policy,omitempty"` + Tasks int `json:"tasks"` + Hosts int `json:"hosts"` + IPBlocks int `json:"ip_blocks"` + Truncated bool `json:"truncated,omitempty"` + LastSync time.Time `json:"last_sync,omitzero"` + LastError string `json:"last_error,omitempty"` +} + +type panelEgress struct { + client PanelEgressClient + pg *db.DB + dataDir string + serviceHosts []string + interval time.Duration + now func() time.Time + + syncMu sync.Mutex // one push at a time + lastHash string + lastPush time.Time + lastFail time.Time + + mu sync.Mutex + state PanelEgressState +} + +// WithPanelEgress enables scope-restricted panel egress (ARTEX_SANDBOX=off on +// Kubernetes). serviceHosts are hosts the panel always needs (LLM endpoints from +// the environment, see PanelEgressEnvHosts). +func WithPanelEgress(client PanelEgressClient, serviceHosts []string) Option { + return func(s *Server) { + if client == nil { + return + } + s.panelEgress = &panelEgress{ + client: client, + serviceHosts: serviceHosts, + interval: panelEgressInterval, + now: time.Now, + state: PanelEgressState{State: "pending"}, + } + } +} + +// startPanelEgress wires the panel egress sync into the engine and starts it. +// Only ARTEX_SANDBOX=off uses it: required mode has its per-task proxies. +func (s *Server) startPanelEgress(ctx context.Context, dataDir string) { + if s.panelEgress == nil { + return + } + if s.sandboxMode != sandbox.ModeOff { + log.Printf("[sandbox] %s is set but ARTEX_SANDBOX=%s: panel egress control applies only to ARTEX_SANDBOX=off, ignored", sandbox.EnvPanelEgressURL, s.sandboxMode) + s.panelEgress = nil + return + } + if s.m != nil { + s.panelEgress.pg = s.m.pg + } + s.panelEgress.dataDir = dataDir + s.engine.panelEgress = s.panelEgress + go s.panelEgress.run(ctx) +} + +// PanelEgressEnvHosts returns the LLM endpoint hosts implied by the startup +// environment. Call it before New: New scrubs these variables. +func PanelEgressEnvHosts() []string { + var out []string + if os.Getenv("ANTHROPIC_API_KEY") != "" { + out = append(out, "api.anthropic.com") + } + if os.Getenv("OPENAI_API_KEY") != "" { + out = append(out, "api.openai.com") + } + for _, k := range []string{"ARTEX_LLM_BASE_URL", "ARTEX_LLM_PROXY"} { + if h := urlHost(os.Getenv(k)); h != "" { + out = append(out, h) + } + } + return out +} + +// urlHost returns the DNS host of a URL, or "" for an empty, unparsable or IP +// literal URL (an IP endpoint belongs in sandbox.offModeEgress.extraCIDRs). +func urlHost(raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + if !strings.Contains(raw, "://") { + raw = "http://" + raw + } + u, err := url.Parse(raw) + if err != nil { + return "" + } + h := strings.ToLower(u.Hostname()) + if _, err := netip.ParseAddr(h); err == nil || h == "" { + return "" + } + return h +} + +// llmProfileHosts returns the endpoint and proxy hosts of every saved LLM profile. +func llmProfileHosts(pg *db.DB) []string { + if pg == nil { + return nil + } + rows, err := pg.Query(`SELECT format, COALESCE(base_url,''), COALESCE(proxy,'') FROM llm_profiles`) + if err != nil { + return nil + } + defer rows.Close() + var out []string + for rows.Next() { + var format, base, proxy string + if rows.Scan(&format, &base, &proxy) != nil { + continue + } + if base == "" { + switch format { + case "anthropic": + base = "https://api.anthropic.com" + case "openai", "openai-responses": + base = "https://api.openai.com" + } + } + for _, u := range []string{base, proxy} { + if h := urlHost(u); h != "" { + out = append(out, h) + } + } + } + return out +} + +// liveTaskIDs returns the tasks whose agents may still run commands. +func liveTaskIDs(pg *db.DB) ([]int64, error) { + if pg == nil { + return nil, nil + } + rows, err := pg.Query(`SELECT id FROM tasks WHERE deleted_at IS NULL AND archived_at IS NULL AND status IN ('created','running','paused') ORDER BY id`) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +// knownHostsUnder returns discovered asset hostnames equal to or under one of +// domains (at most limit). An approved domain covers its subdomains, as in the +// per-task proxy; a NetworkPolicy needs addresses, so the hosts are listed. +func knownHostsUnder(pg *db.DB, domains []string, limit int) []string { + if pg == nil || len(domains) == 0 { + return nil + } + rows, err := pg.Query(`SELECT DISTINCT lower(a.domain) FROM assets a + JOIN unnest($1::text[]) AS s(d) ON lower(a.domain) = s.d OR lower(a.domain) LIKE '%.' || s.d + WHERE a.domain IS NOT NULL AND a.domain <> '' ORDER BY 1 LIMIT $2`, domains, limit*2) + if err != nil { + return nil + } + defer rows.Close() + var out []string + for rows.Next() { + var h string + if rows.Scan(&h) != nil { + continue + } + // LIKE treats '_' as a wildcard: check the suffix exactly. + for _, d := range domains { + if h == d || strings.HasSuffix(h, "."+d) { + out = append(out, h) + break + } + } + if len(out) >= limit { + break + } + } + return out +} + +// buildPanelEgressScope computes the union of the approved scope of every live +// task, the known hosts under it, and the LLM endpoints. +func buildPanelEgressScope(pg *db.DB, dataDir string, serviceHosts []string) (sandbox.PanelEgressScope, error) { + var scope sandbox.PanelEgressScope + ids, err := liveTaskIDs(pg) + if err != nil { + return scope, err + } + doms, cidrs := map[string]bool{}, map[string]bool{} + for _, id := range ids { + info := taskSandboxRunInfo(pg, dataDir, strconv.FormatInt(id, 10)) + for _, d := range info.ScopeDomains { + doms[d] = true + } + for _, c := range info.ScopeCIDRs { + cidrs[c] = true + } + } + scope.Tasks = len(ids) + for d := range doms { + scope.Domains = append(scope.Domains, d) + } + for c := range cidrs { + scope.CIDRs = append(scope.CIDRs, c) + } + sort.Strings(scope.Domains) + sort.Strings(scope.CIDRs) + scope.Hostnames = knownHostsUnder(pg, scope.Domains, panelEgressMaxKnownHosts) + svc := map[string]bool{} + for _, h := range append(append([]string{}, serviceHosts...), llmProfileHosts(pg)...) { + svc[h] = true + } + for h := range svc { + scope.ServiceHosts = append(scope.ServiceHosts, h) + } + sort.Strings(scope.ServiceHosts) + return scope, nil +} + +func scopeHash(s sandbox.PanelEgressScope) string { + raw, _ := json.Marshal(s) + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + +// sync pushes the current scope when it changed since the last successful push, +// or when force is set. +func (p *panelEgress) sync(ctx context.Context, force bool) error { + p.syncMu.Lock() + defer p.syncMu.Unlock() + scope, err := buildPanelEgressScope(p.pg, p.dataDir, p.serviceHosts) + if err != nil { + p.setError("read scope: " + err.Error()) + return err + } + h := scopeHash(scope) + if !force && (h == p.lastHash || p.now().Sub(p.lastFail) < panelEgressRetryAfter) { + return nil + } + pctx, cancel := context.WithTimeout(ctx, panelEgressPushTimeout) + st, err := p.client.ApplyPanelEgress(pctx, scope) + cancel() + if err != nil { + p.lastHash, p.lastFail = "", p.now() // a later turn retries + p.setError(err.Error()) + return err + } + p.lastHash, p.lastPush = h, p.now() + p.mu.Lock() + prev := p.state.State + p.state = PanelEgressState{ + State: st.State, Policy: st.Policy, Tasks: st.Tasks, Hosts: st.Hosts, IPBlocks: st.IPBlocks, + Truncated: st.Truncated, LastSync: p.lastPush, LastError: st.LastError, + } + p.mu.Unlock() + if prev != st.State { + log.Printf("[sandbox] off-mode panel egress %s: policy %s, %d task(s), %d host(s), %d IP block(s)", st.State, st.Policy, st.Tasks, st.Hosts, st.IPBlocks) + } + return nil +} + +func (p *panelEgress) setError(msg string) { + p.mu.Lock() + prev := p.state.State + p.state.State = "error" + p.state.LastError = msg + p.mu.Unlock() + if prev != "error" { + log.Printf("[sandbox] off-mode panel egress: push failed, the previous policy stays and new scope is not reachable: %s", msg) + } +} + +// snapshot returns the state for /api/health. +func (p *panelEgress) snapshot() PanelEgressState { + p.mu.Lock() + defer p.mu.Unlock() + return p.state +} + +// ensure is called before every planner/worker turn of a task: a scope approved +// since the last push is in the policy before the turn's commands run. +func (p *panelEgress) ensure(ctx context.Context) { + if p == nil { + return + } + _ = p.sync(context.WithoutCancel(ctx), false) +} + +// run pushes the scope at startup and every interval until ctx ends. +func (p *panelEgress) run(ctx context.Context) { + _ = p.sync(ctx, true) + t := time.NewTicker(p.interval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + _ = p.sync(ctx, true) + } + } +} diff --git a/server/paneleggress_test.go b/server/paneleggress_test.go new file mode 100644 index 000000000..29f984d88 --- /dev/null +++ b/server/paneleggress_test.go @@ -0,0 +1,349 @@ +package server + +import ( + "context" + "fmt" + "os" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/sandbox" +) + +type fakePanelEgressClient struct { + mu sync.Mutex + pushes []sandbox.PanelEgressScope + err error +} + +func (f *fakePanelEgressClient) ApplyPanelEgress(_ context.Context, s sandbox.PanelEgressScope) (sandbox.PanelEgressStatus, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.pushes = append(f.pushes, s) + if f.err != nil { + return sandbox.PanelEgressStatus{State: sandbox.PanelEgressError}, f.err + } + return sandbox.PanelEgressStatus{State: sandbox.PanelEgressEnforced, Policy: "p", Tasks: s.Tasks, Hosts: len(s.Domains) + len(s.Hostnames) + len(s.ServiceHosts), IPBlocks: len(s.CIDRs)}, nil +} + +func (f *fakePanelEgressClient) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.pushes) +} + +func (f *fakePanelEgressClient) last() sandbox.PanelEgressScope { + f.mu.Lock() + defer f.mu.Unlock() + return f.pushes[len(f.pushes)-1] +} + +func TestURLHost(t *testing.T) { + for in, want := range map[string]string{ + "https://api.anthropic.com": "api.anthropic.com", + "https://Gateway.Example:8443/v1/x": "gateway.example", + "gateway.example:8080": "gateway.example", + "socks5://proxy.corp.example:1080": "proxy.corp.example", + "http://10.0.0.5:11434": "", + "http://[2001:db8::1]/v1": "", + "": "", + " ": "", + "http://user:pw@llm.example/anthropic": "llm.example", + } { + if got := urlHost(in); got != want { + t.Errorf("urlHost(%q) = %q, want %q", in, got, want) + } + } +} + +func TestPanelEgressEnvHosts(t *testing.T) { + for _, k := range []string{"ANTHROPIC_API_KEY", "OPENAI_API_KEY", "ARTEX_LLM_BASE_URL", "ARTEX_LLM_PROXY"} { + t.Setenv(k, "") + } + if h := PanelEgressEnvHosts(); len(h) != 0 { + t.Fatalf("no keys: %v", h) + } + t.Setenv("ANTHROPIC_API_KEY", "x") + t.Setenv("OPENAI_API_KEY", "y") + t.Setenv("ARTEX_LLM_BASE_URL", "https://llm-gw.example/v1") + t.Setenv("ARTEX_LLM_PROXY", "http://10.1.1.1:3128") // IP literal: needs extraCIDRs + got := PanelEgressEnvHosts() + if !slices.Equal(got, []string{"api.anthropic.com", "api.openai.com", "llm-gw.example"}) { + t.Fatalf("hosts %v", got) + } +} + +func newTestPanelEgressSync(c PanelEgressClient, hosts ...string) *panelEgress { + var s Server + WithPanelEgress(c, hosts)(&s) + return s.panelEgress +} + +func TestPanelEgressSyncPushesOnlyChanges(t *testing.T) { + fc := &fakePanelEgressClient{} + p := newTestPanelEgressSync(fc, "api.anthropic.com") + if st := p.snapshot(); st.State != "pending" { + t.Fatalf("initial %+v", st) + } + ctx := context.Background() + p.ensure(ctx) + if fc.count() != 1 || p.snapshot().State != sandbox.PanelEgressEnforced { + t.Fatalf("first ensure: %d pushes, %+v", fc.count(), p.snapshot()) + } + if got := fc.last().ServiceHosts; !slices.Equal(got, []string{"api.anthropic.com"}) { + t.Fatalf("service hosts %v", got) + } + // No database: no task scope at all. + if l := fc.last(); len(l.Domains)+len(l.CIDRs)+len(l.Hostnames) != 0 || l.Tasks != 0 { + t.Fatalf("scope without DB %+v", l) + } + // Unchanged scope: ensure does not push again; the periodic sync does. + p.ensure(ctx) + p.ensure(ctx) + if fc.count() != 1 { + t.Fatalf("unchanged scope pushed %d times", fc.count()) + } + if err := p.sync(ctx, true); err != nil || fc.count() != 2 { + t.Fatalf("forced sync: %v, %d", err, fc.count()) + } + + // Controller down: state error, and the next turn retries. + fc.mu.Lock() + fc.err = fmt.Errorf("%w: connection refused", sandbox.ErrRunnerUnavailable) + fc.mu.Unlock() + if err := p.sync(ctx, true); err == nil { + t.Fatal("push error swallowed") + } + st := p.snapshot() + if st.State != "error" || !strings.Contains(st.LastError, "connection refused") { + t.Fatalf("after failure %+v", st) + } + fc.mu.Lock() + fc.err = nil + fc.mu.Unlock() + n := fc.count() + p.ensure(ctx) // within the retry delay: no push + if fc.count() != n { + t.Fatal("turn retried a failed push immediately") + } + p.now = func() time.Time { return time.Now().Add(panelEgressRetryAfter + time.Second) } + p.ensure(ctx) + if fc.count() != n+1 || p.snapshot().State != sandbox.PanelEgressEnforced || p.snapshot().LastError != "" { + t.Fatalf("retry after failure: %d pushes, %+v", fc.count()-n, p.snapshot()) + } + + var nilP *panelEgress + nilP.ensure(ctx) // Docker deployments and required mode: no-op +} + +func TestPanelEgressRunLoop(t *testing.T) { + fc := &fakePanelEgressClient{} + p := newTestPanelEgressSync(fc) + p.interval = 20 * time.Millisecond + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { p.run(ctx); close(done) }() + deadline := time.Now().Add(5 * time.Second) + for fc.count() < 3 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + cancel() + <-done + if fc.count() < 3 { + t.Fatalf("periodic pushes %d", fc.count()) + } +} + +func TestStartPanelEgressOnlyInOffMode(t *testing.T) { + fc := &fakePanelEgressClient{} + s := &Server{engine: &Engine{}, sandboxMode: sandbox.ModeRequired} + WithPanelEgress(fc, nil)(s) + s.startPanelEgress(context.Background(), t.TempDir()) + if s.panelEgress != nil || s.engine.panelEgress != nil { + t.Fatal("panel egress active in required mode") + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s = &Server{engine: &Engine{}, sandboxMode: sandbox.ModeOff} + WithPanelEgress(fc, nil)(s) + s.startPanelEgress(ctx, t.TempDir()) + if s.panelEgress == nil || s.engine.panelEgress != s.panelEgress { + t.Fatal("panel egress not wired in off mode") + } + // The engine's per-turn hook pushes in off mode. + n := fc.count() + s.engine.sandboxMode = sandbox.ModeOff + s.engine.panelEgress.lastHash = "" + _ = s.engine.withTaskSandbox(context.Background(), "1") + if fc.count() <= n { + t.Fatal("withTaskSandbox did not sync in off mode") + } + + // Without the option nothing is wired (Docker deployments). + s = &Server{engine: &Engine{}, sandboxMode: sandbox.ModeOff} + WithPanelEgress(nil, nil)(s) + s.startPanelEgress(ctx, t.TempDir()) + if s.panelEgress != nil || s.engine.panelEgress != nil { + t.Fatal("nil client enabled panel egress") + } +} + +func TestRunnerTokenIsScrubbed(t *testing.T) { + if !slices.Contains(secretEnv, sandbox.EnvRunnerToken) { + t.Fatal("ARTEX_RUNNER_TOKEN must be scrubbed: in off mode it authorises scope pushes") + } +} + +// TestPanelEgressScopeFromDB checks the union against PostgreSQL: only +// operator-approved scope of live tasks, the known hosts under it, and LLM hosts. +func TestPanelEgressScopeFromDB(t *testing.T) { + dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) + if dsn == "" { + t.Skip("ARTEX_PG_DSN not set") + } + pg, err := db.Open(dsn) + if err != nil { + db.SkipPGUnavailable(t, err) + } + t.Cleanup(func() { _ = pg.Close() }) + sfx := fmt.Sprintf("%d", time.Now().UnixNano()) + as := pg.Assets() + + mk := func(name string) *db.Task { + tk, err := pg.CreateTaskWithOptions(name+"-"+sfx, "goal", db.TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pg.DeleteTask(tk.ID) }) + return tk + } + live, live2, done := mk("pe-live"), mk("pe-live2"), mk("pe-done") + + approved := "pe-" + sfx + ".example" + approved2 := "pe2-" + sfx + ".example" + agentDom := "pe-agent-" + sfx + ".example" + doneDom := "pe-done-" + sfx + ".example" + mustScope := func(tid int64, kind, val string) db.TaskScope { + ts, err := as.AddOperatorScope(tid, kind, val, "test") + if err != nil { + t.Fatalf("AddOperatorScope %s %s: %v", kind, val, err) + } + return ts + } + mustScope(live.ID, "root_domain", approved) + // Unique per run: the shared test database may hold other live tasks scoped + // to the TEST-NET ranges. + n0 := time.Now().UnixNano() + uniqCIDR := fmt.Sprintf("198.18.%d.%d/32", n0%250, (n0/250)%250) + mustScope(live.ID, "cidr", uniqCIDR) + mustScope(live2.ID, "root_domain", approved2) + mustScope(live2.ID, "root_domain", approved) // overlap: deduplicated + mustScope(done.ID, "root_domain", doneDom) + mustScope(done.ID, "ip", "203.0.113.77") + if _, err := as.AddAgentScope(live.ID, "root_domain", agentDom, "agent", "agent"); err != nil { + t.Fatal(err) + } + if err := as.AddAutoScope(live.ID, "ip", "", "", "192.0.2.55"); err != nil { + t.Fatal(err) + } + if err := pg.SetStatus(done.ID, "done"); err != nil { + t.Fatal(err) + } + // Discovered hosts: one under the approved domain, one under an unapproved one. + for _, h := range []string{"www." + approved, "deep.api." + approved, "x." + agentDom} { + if _, err := as.UpsertSubdomain(db.UpsertSubdomainReq{Domain: h, TaskID: live.ID}); err != nil { + t.Fatalf("UpsertSubdomain %s: %v", h, err) + } + } + profile := "pe-profile-" + sfx + if _, err := pg.Exec(`INSERT INTO llm_profiles (name, format, base_url, proxy, model) VALUES ($1,'openai','https://gw-`+sfx+`.example/v1','socks5://px-`+sfx+`.example:1080','m')`, profile); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM llm_profiles WHERE name=$1`, profile) }) + + scope, err := buildPanelEgressScope(pg, t.TempDir(), []string{"api.anthropic.com"}) + if err != nil { + t.Fatal(err) + } + has := func(list []string, v string) bool { return slices.Contains(list, v) } + for _, d := range []string{approved, approved2} { + if !has(scope.Domains, d) { + t.Errorf("approved domain %s missing: %v", d, scope.Domains) + } + } + n := 0 + for _, d := range scope.Domains { + if d == approved { + n++ + } + } + if n != 1 { + t.Errorf("overlapping scope not deduplicated: %v", scope.Domains) + } + for _, bad := range []string{agentDom, doneDom} { + if has(scope.Domains, bad) { + t.Errorf("%s in the union (agent-added or finished task)", bad) + } + } + if !has(scope.CIDRs, uniqCIDR) { + t.Errorf("approved CIDR missing: %v", scope.CIDRs) + } + for _, c := range scope.CIDRs { + if strings.HasPrefix(c, "203.0.113.77") || strings.HasPrefix(c, "192.0.2.55") { + t.Errorf("CIDR %s from a finished task or auto scope", c) + } + } + for _, h := range []string{"www." + approved, "deep.api." + approved} { + if !has(scope.Hostnames, h) { + t.Errorf("known host %s missing: %v", h, scope.Hostnames) + } + } + if has(scope.Hostnames, "x."+agentDom) { + t.Error("host under an unapproved domain listed") + } + for _, h := range []string{"api.anthropic.com", "gw-" + sfx + ".example", "px-" + sfx + ".example"} { + if !has(scope.ServiceHosts, h) { + t.Errorf("service host %s missing: %v", h, scope.ServiceHosts) + } + } + if scope.Tasks < 2 { + t.Errorf("tasks = %d", scope.Tasks) + } + + // Revoke: the scope row goes, and the next push no longer carries it. + rows, err := as.ListTaskScope(live.ID) + if err != nil { + t.Fatal(err) + } + var cidrRow int64 + for _, r := range rows { + if r.Kind == "cidr" && strings.HasPrefix(r.Net, uniqCIDR) { + cidrRow = r.ID + } + } + if ok, err := as.DeleteTaskScope(live.ID, cidrRow); err != nil || !ok { + t.Fatalf("DeleteTaskScope: %v %v", ok, err) + } + fc := &fakePanelEgressClient{} + p := newTestPanelEgressSync(fc) + p.pg, p.dataDir = pg, t.TempDir() + if err := p.sync(context.Background(), true); err != nil { + t.Fatal(err) + } + if has(fc.last().CIDRs, uniqCIDR) { + t.Error("revoked CIDR still pushed") + } + // The task finishing removes its domain too (approved2 belongs to live2 only). + if err := pg.SetStatus(live2.ID, "failed"); err != nil { + t.Fatal(err) + } + p.ensure(context.Background()) + if has(fc.last().Domains, approved2) || !has(fc.last().Domains, approved) { + t.Errorf("after live2 failed: %v", fc.last().Domains) + } +} diff --git a/server/server.go b/server/server.go index 20601a7c4..ad6fe53f5 100644 --- a/server/server.go +++ b/server/server.go @@ -60,6 +60,7 @@ type Server struct { isolation IsolationStatus sandboxMode string sandboxClient SandboxClient // result of the startup isolation self-test (isolation.go); zero when not run + panelEgress *panelEgress // scope-restricted panel egress (ARTEX_SANDBOX=off on Kubernetes); nil when not configured chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL @@ -223,6 +224,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi } s.engine.SetKillSwitchConfig(dataDir, s.execPriv) s.engine.SetSandbox(s.sandboxClient, s.sandboxMode, dataDir) + s.startPanelEgress(ctx, dataDir) if s.sandboxMode != "" { agent.SetSandboxExecutor(&agent.SandboxExecutor{ Mode: s.sandboxMode, @@ -1163,6 +1165,10 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) { if s.isolation.Mode != "" { out["isolation"] = s.isolation } + // ARTEX_SANDBOX=off on Kubernetes: whether the panel's egress is limited to scope. + if s.panelEgress != nil { + out["sandbox_egress"] = s.panelEgress.snapshot() + } // Opt-in only (ARTEX_UPDATE_CHECK); off, this returns "" without any request. if latest := updates.newerVersion(r.Context(), time.Now(), BuildVersion); latest != "" { out["latest_version"] = latest From ceea0fb3a7717dedee6d3c6f87fcf122c0b45980 Mon Sep 17 00:00:00 2001 From: Marco Azarmaneche <306425250+thecorporatetractor@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:36:57 +0200 Subject: [PATCH 5/5] feat(deploy): scope-restricted panel egress for sandbox off mode With sandbox.mode=off the chart now restricts the panel's egress by default (sandbox.offModeEgress.enabled=true): a static NetworkPolicy allows only cluster DNS, the database (bundled, or postgresCIDRs) and the panel egress controller, which runs from the runner image as non-root with no capabilities and a Role limited to creating NetworkPolicies and reading/updating the one scope policy. extraHosts/extraCIDRs, refresh and retention are configurable. Rendering fails instead of running open when NetworkPolicy is disabled or an external database has no CIDRs; values from an older release count as enabled. enabled=false keeps the previous unrestricted behaviour, documented as unsafe. Chart render tests cover the policies, RBAC, wiring and schema rejections, and lint both modes. TestPanelEgressOffModeE2E checks live, as the agent uid inside the panel, that in-scope hosts (including nmap -sT) are reachable and other namespaces, the API server, nodes, metadata and out-of-scope hosts are not, that revocation and task deletion remove access, and that a stopped controller fails closed; scripts/k3d-e2e.sh runs it with OFF_MODE=1. scripts/k3d-e2e.sh reads the panel log before grepping it for the isolation self-test: with pipefail, grep -q exiting early failed the check on the longer off-mode log. --- CHANGELOG.md | 1 + deploy/helm/artex/README.md | 73 ++++- deploy/helm/artex/templates/NOTES.txt | 11 + deploy/helm/artex/templates/_helpers.tpl | 31 ++ deploy/helm/artex/templates/panel-egress.yaml | 234 ++++++++++++++ deploy/helm/artex/templates/panel.yaml | 9 + deploy/helm/artex/values.schema.json | 22 ++ deploy/helm/artex/values.yaml | 23 +- docs/SANDBOX.md | 33 ++ sandbox/helmchart_offmode_test.go | 289 +++++++++++++++++ sandbox/helmchart_test.go | 3 +- sandbox/paneleggress_e2e_test.go | 301 ++++++++++++++++++ scripts/k3d-e2e.sh | 52 ++- 13 files changed, 1074 insertions(+), 8 deletions(-) create mode 100644 deploy/helm/artex/templates/panel-egress.yaml create mode 100644 sandbox/helmchart_offmode_test.go create mode 100644 sandbox/paneleggress_e2e_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b467fbf..76c442ca9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented in this file. The format is b - **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. - **Helm chart for Kubernetes.** `deploy/helm/artex` deploys the panel, PostgreSQL and `artex-runner` with the Kubernetes sandbox backend, a namespace-scoped Role, NetworkPolicies and a values schema. A chart-level default-deny covers every runner-managed pod, so a missing per-task policy fails closed. The `volume-permissions` init container fixes the `Bash can create files in /app/data` self-test failure on world-writable volumes (#620). `scripts/k3d-e2e.sh` and the new `kubernetes` CI job test the chart live on k3d. +- **Scope-restricted panel egress for `sandbox.mode=off` on Kubernetes.** With the sandbox off, agent commands run in the panel pod, whose egress was open to the internet, other namespaces, the nodes and the Kubernetes API. The chart now restricts it by default (`sandbox.offModeEgress.enabled=true`): a static NetworkPolicy allows only cluster DNS, the database and a small controller, and the controller (`artex-runner` with `ARTEX_RUNNER_BACKEND=panel-egress`, a Role limited to NetworkPolicies, non-root, no capabilities) keeps a second NetworkPolicy with the IP addresses of the operator-approved scope of every live task, the known hostnames under it, the LLM endpoints and `extraHosts`/`extraCIDRs`. The panel computes the scope with the same code as the per-task proxy and pushes it over the new authenticated `PUT /v1/panel-egress` before each agent turn and every 30 s; it holds no Kubernetes credentials. Resolved private, metadata and IPv6 addresses are dropped unless an approved CIDR covers them, revoked scope leaves on the next push, DNS rotation is tolerated for `retention`, and a stopped controller leaves the last policy in place (fail closed). `GET /api/health` reports the state as `sandbox_egress`. In-scope direct scans such as `nmap -sT` work; the limits (union of tasks, IP-based, DNS still resolvable, IPv6, no `NET_RAW`) are in the chart README. `sandbox.offModeEgress.enabled=false` restores the old open egress. The panel also scrubs `ARTEX_RUNNER_TOKEN` from its environment after startup. Docker deployments and required mode are unchanged. `scripts/k3d-e2e.sh` gains `OFF_MODE=1`. ### Security diff --git a/deploy/helm/artex/README.md b/deploy/helm/artex/README.md index 56b18e9fe..9b1385fd8 100644 --- a/deploy/helm/artex/README.md +++ b/deploy/helm/artex/README.md @@ -90,7 +90,11 @@ and `egress-audit/`, and task pods mount their own sub-directories. | `secrets.existingSecret` | `""` | Use your own Secret with keys `ARTEX_RUNNER_TOKEN`, `POSTGRES_PASSWORD`, and optionally `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `ARTEX_SECRET_KEY`. | | `secrets.anthropicApiKey` / `openaiApiKey` | `""` | Prefer `--set-file` or `existingSecret` over putting keys on the command line. | | `panel.env` | `{}` | Plain settings (`ARTEX_LLM_MODEL`, ...). The schema rejects names ending in `_KEY`, `_TOKEN`, `_PASSWORD` or `_SECRET`. | -| `sandbox.mode` | `required` | `off` runs agents inside the panel container. Not recommended. | +| `sandbox.mode` | `required` | `off` runs agents inside the panel container. Not recommended. See [Sandbox off mode](#sandbox-off-mode). | +| `sandbox.offModeEgress.enabled` | `true` | `mode=off` only: limit the panel's egress to the approved scope of live tasks. `false` is **unsafe**: agent commands can reach any address the pod can. | +| `sandbox.offModeEgress.extraHosts` / `extraCIDRs` | `[]` | Always-allowed destinations in off mode: webhooks, HTTP MCP servers, a custom LLM gateway, an IP-literal LLM endpoint. | +| `sandbox.offModeEgress.postgresCIDRs` | `[]` | Required in off mode with `postgres.enabled=false`. | +| `sandbox.offModeEgress.refresh` / `retention` | `1m` / `1h` | Re-resolve interval, and how long an address stays allowed after a host last resolved to it. | | `sandbox.runtimeClassName` | `""` | Run task pods under gVisor or Kata for kernel isolation. | | `sandbox.worker.cpuLimit` / `memoryLimit` | `2` / `2Gi` | | | `sandbox.podReadyTimeout` | `2m` | Image pull, scheduling and policy programming must finish within it. | @@ -105,6 +109,71 @@ and `egress-audit/`, and task pods mount their own sub-directories. `values.schema.json` validates the values. Invalid modes, pull policies, access modes, replica counts above 1, and IPv6 deny ranges fail at install time. +## Sandbox off mode + +With `sandbox.mode=off` there is no runner and no task pod: agent commands run +inside the panel pod, dropped to uid 10001, with the tools of the panel image +(`nmap`, `dig`, `nc`, ...). Without a restriction the panel's egress is open: +other namespaces, the nodes, the Kubernetes API and anything on the internet. + +`sandbox.offModeEgress.enabled=true` (the default) limits it: + +| Object | Purpose | +|---|---| +| `NetworkPolicy/-panel-egress-base` | Selects the panel with `policyTypes: [Egress]`: only cluster DNS, the bundled PostgreSQL (or `postgresCIDRs`) and the controller. Everything else is denied. | +| `Deployment/-panel-egress` | The runner image with `ARTEX_RUNNER_BACKEND=panel-egress`. Non-root, no capabilities, read-only root filesystem, no volumes. | +| `Role/-panel-egress` | `create` on networkpolicies, `get`/`update` on the one scope policy. Nothing else. | +| `NetworkPolicy/-panel-egress` | Only the panel may call the controller. | +| `NetworkPolicy/-panel-egress-scope` | Written by the controller, not by Helm: the panel's allowed destinations as `ipBlock`s, all ports and protocols. | + +The panel computes the union of the operator-approved scope of every task that is +not finished (`created`, `running`, `paused`) with the same code the per-task +egress proxy uses (approved scope domains and CIDRs, frozen company grants, +operator allow rules; agent-added and auto-discovered rows never count). It adds +the discovered hostnames under the approved domains and the LLM endpoints (from +`ANTHROPIC_API_KEY`/`OPENAI_API_KEY`, `ARTEX_LLM_BASE_URL`, `ARTEX_LLM_PROXY` and +the saved LLM profiles), and pushes the list to the controller with the runner +token (`PUT /v1/panel-egress`): before every planner and worker turn when it +changed, and every 30 s. The panel itself holds no Kubernetes credentials. + +The controller resolves the hosts every `refresh`, keeps every address a host +resolved to within `retention` (DNS rotation), and writes the scope policy: +approved CIDRs as they are, resolved addresses as `/32`. Resolved addresses in +the denied ranges (`sandbox.proxyDeniedCIDRs`: RFC1918, CGNAT, loopback, +link-local, metadata, multicast) and IPv6 answers are dropped unless an approved +CIDR covers them, as in the per-task proxy policy. A revoked scope or a finished +task leaves the policy on the next push. A failed lookup keeps the last known +addresses until they expire. + +It fails closed. Before the first push, and whenever the controller is down, the +last policy it wrote stays in place and nothing new is allowed. Deleting the scope +policy leaves only the base policy. The panel reports the state in its log +(`off-mode panel egress enforced`) and, to a signed-in session, in +`GET /api/health` as `sandbox_egress` (`state`: `pending`, `enforced` or `error`). + +Limits, compared with `sandbox.mode=required`: + +- **Union, not per task.** Every task's agent can reach the scope of every other + live task. +- **IP based.** An allowed CDN or shared-hosting address also serves out-of-scope + sites. A hostname discovered during a task becomes reachable on the next push + only once it is stored as an asset (up to 30 s, or the next turn); until then, + only the approved domain itself and the hosts already known are reachable. + Hostnames under an approved domain that were never recorded are not reachable + at all (the proxy in required mode allows any of them). +- **DNS is open.** The panel can resolve any name through cluster DNS, so data + can still leave through DNS queries. +- **IPv6** destinations are reachable only through an approved IPv6 CIDR. +- **No raw sockets.** Agents run as uid 10001 without `NET_RAW`: `nmap -sT` works, + `nmap -sS`/`-sU`/OS detection do not. +- **Removal lag.** A revoked scope stops being allowed on the next push (at most + 30 s) plus the CNI's update time. Established connections may survive, depending + on the CNI. +- **Stale if the controller is down.** Revocations are not applied until it is + back. +- The scope policy outlives `helm uninstall`; delete it with + `kubectl delete networkpolicy -l artex.managed_by=artex-panel-egress`. + ## Network readiness A pod becomes Ready before the CNI has programmed NetworkPolicy for its new IP. @@ -140,4 +209,4 @@ do not match `sandbox.dns.*`. to bound fork bombs, as the Docker backend's `PidsLimit` does. - The opt-in DNS egress guard (`docker-compose.egress.yml`) has no Kubernetes equivalent. Agent egress is governed by the per-task proxies and their - NetworkPolicies. + NetworkPolicies, or in `sandbox.mode=off` by the panel egress policies. diff --git a/deploy/helm/artex/templates/NOTES.txt b/deploy/helm/artex/templates/NOTES.txt index 25ae59b9c..e261c051d 100644 --- a/deploy/helm/artex/templates/NOTES.txt +++ b/deploy/helm/artex/templates/NOTES.txt @@ -23,4 +23,15 @@ reach the panel, the database and the internet directly, bypassing the egress pr {{- else }} WARNING: sandbox.mode=off. Agent commands run inside the panel container. +{{- if include "artex.offModeEgress" . }} +The panel's egress is limited to cluster DNS, the database and the approved scope of +live tasks (NetworkPolicy {{ include "artex.panelEgressPolicy" . }}, kept up to date by +deploy/{{ include "artex.fullname" . }}-panel-egress). Check it is enforced: + + kubectl -n {{ .Release.Namespace }} logs deploy/{{ include "artex.fullname" . }}-panel | grep "panel egress" +{{- else }} +sandbox.offModeEgress.enabled=false: the panel's egress is NOT restricted. Agent +commands can reach any address the pod can, including other namespaces, the nodes +and the Kubernetes API. +{{- end }} {{- end }} diff --git a/deploy/helm/artex/templates/_helpers.tpl b/deploy/helm/artex/templates/_helpers.tpl index a15a412dd..8104e431c 100644 --- a/deploy/helm/artex/templates/_helpers.tpl +++ b/deploy/helm/artex/templates/_helpers.tpl @@ -64,6 +64,37 @@ app.kubernetes.io/component: {{ index . 1 }} {{- if eq .Values.persistence.data.accessMode "ReadWriteOnce" -}}true{{- end -}} {{- end -}} +{{/* True when the panel's egress is limited to task scope (sandbox off). */}} +{{- define "artex.offModeEgress" -}} +{{- /* Absent (an upgrade with --reuse-values from a release that predates the + setting) counts as enabled: an upgrade must not leave the panel open. */ -}} +{{- $oe := .Values.sandbox.offModeEgress | default dict -}} +{{- $enabled := ternary $oe.enabled true (hasKey $oe "enabled") -}} +{{- if and (eq .Values.sandbox.mode "off") $enabled -}} +{{- if not .Values.networkPolicy.enabled -}} +{{- fail "sandbox.offModeEgress.enabled needs networkPolicy.enabled=true: the panel's egress is enforced by NetworkPolicy (sandbox.offModeEgress.enabled=false runs with unrestricted panel egress, which is unsafe)" -}} +{{- end -}} +{{- if and (not .Values.postgres.enabled) (not $oe.postgresCIDRs) -}} +{{- fail "sandbox.offModeEgress.postgresCIDRs is required with postgres.enabled=false: the panel's egress is restricted in sandbox off mode" -}} +{{- end -}} +true +{{- end -}} +{{- end -}} + +{{/* NetworkPolicy the panel egress controller owns. */}} +{{- define "artex.panelEgressPolicy" -}} +{{- printf "%s-panel-egress-scope" (include "artex.fullname" .) -}} +{{- end -}} + +{{/* A map as a sorted k=v,k=v list. */}} +{{- define "artex.kvList" -}} +{{- $l := list -}} +{{- range $k, $v := . -}} +{{- $l = append $l (printf "%s=%s" $k $v) -}} +{{- end -}} +{{- join "," $l -}} +{{- end -}} + {{- define "artex.pullSecrets" -}} {{- with .Values.images.pullSecrets }} imagePullSecrets: diff --git a/deploy/helm/artex/templates/panel-egress.yaml b/deploy/helm/artex/templates/panel-egress.yaml new file mode 100644 index 000000000..4e842a814 --- /dev/null +++ b/deploy/helm/artex/templates/panel-egress.yaml @@ -0,0 +1,234 @@ +{{- if include "artex.offModeEgress" . }} +{{- $oe := .Values.sandbox.offModeEgress | default dict }} +{{- $peName := printf "%s-panel-egress" (include "artex.fullname" .) }} +# sandbox.mode=off: agent commands run inside the panel pod. The panel egress +# controller (artex-runner, backend panel-egress) keeps the NetworkPolicy +# -panel-egress-scope in line with the approved scope of the live tasks, +# which the panel pushes to it. It can manage NetworkPolicies in this namespace and +# nothing else; the panel itself holds no Kubernetes credentials. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel-egress +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel-egress +rules: + # create cannot be limited by name; read and update only the scope policy. + - apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + verbs: ["create"] + - apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + resourceNames: [{{ include "artex.panelEgressPolicy" . | quote }}] + verbs: ["get", "update"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel-egress +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $peName }} +subjects: + - kind: ServiceAccount + name: {{ $peName }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel-egress +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + {{- include "artex.selector" (list . "panel-egress") | nindent 6 }} + template: + metadata: + labels: + {{- include "artex.labels" . | nindent 8 }} + app.kubernetes.io/component: panel-egress + annotations: + checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }} + spec: + {{- include "artex.pullSecrets" . | nindent 6 }} + serviceAccountName: {{ $peName }} + enableServiceLinks: false + securityContext: + runAsNonRoot: true + runAsUser: 65534 + runAsGroup: 65534 + seccompProfile: + type: RuntimeDefault + {{- with .Values.runner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.runner.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: panel-egress + image: {{ include "artex.image" (list . .Values.images.runner) }} + imagePullPolicy: {{ .Values.images.pullPolicy }} + env: + - name: ARTEX_RUNNER_BACKEND + value: panel-egress + - name: ARTEX_RUNNER_ADDR + value: {{ printf ":%d" (int .Values.runner.port) | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN + - name: ARTEX_KUBE_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: ARTEX_PANEL_EGRESS_POLICY + value: {{ include "artex.panelEgressPolicy" . | quote }} + - name: ARTEX_PANEL_EGRESS_SELECTOR + value: {{ include "artex.selector" (list . "panel") | fromYaml | include "artex.kvList" | quote }} + - name: ARTEX_PANEL_EGRESS_LABELS + value: {{ printf "app.kubernetes.io/name=%s,app.kubernetes.io/instance=%s,app.kubernetes.io/component=panel-egress" (include "artex.name" .) .Release.Name | quote }} + - name: ARTEX_PANEL_EGRESS_EXTRA_HOSTS + value: {{ join "," ($oe.extraHosts | default list) | quote }} + - name: ARTEX_PANEL_EGRESS_EXTRA_CIDRS + value: {{ join "," ($oe.extraCIDRs | default list) | quote }} + {{- with .Values.sandbox.proxyDeniedCIDRs }} + - name: ARTEX_PANEL_EGRESS_DENIED_CIDRS + value: {{ join "," . | quote }} + {{- end }} + - name: ARTEX_PANEL_EGRESS_REFRESH + value: {{ $oe.refresh | default "1m" | quote }} + - name: ARTEX_PANEL_EGRESS_RETENTION + value: {{ $oe.retention | default "1h" | quote }} + ports: + - name: runner + containerPort: {{ .Values.runner.port }} + readinessProbe: + exec: + command: ["sh", "-c", "curl -fsS -H \"Authorization: Bearer $ARTEX_RUNNER_TOKEN\" http://127.0.0.1:{{ .Values.runner.port }}/v1/health"] + periodSeconds: 10 + timeoutSeconds: 5 + livenessProbe: + tcpSocket: + port: runner + periodSeconds: 20 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + {{- toYaml .Values.runner.resources | nindent 12 }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} + app.kubernetes.io/component: panel-egress +spec: + selector: + {{- include "artex.selector" (list . "panel-egress") | nindent 4 }} + ports: + - name: runner + port: {{ .Values.runner.port }} + targetPort: runner +--- +# Only the panel may push scope to the controller. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ $peName }} + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel-egress") | nindent 6 }} + policyTypes: ["Ingress"] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 14 }} + ports: + - protocol: TCP + port: {{ .Values.runner.port }} +--- +# Static part of the panel's egress: cluster DNS, the database and the controller. +# Selecting the panel with policyTypes Egress denies everything else; the +# controller's -panel-egress-scope policy adds the task scope on top. +# Without the controller (or before its first write) the panel reaches only these. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ $peName }}-base + labels: + {{- include "artex.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel") | nindent 6 }} + policyTypes: ["Egress"] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .Values.sandbox.dns.namespace }} + podSelector: + matchLabels: + {{- toYaml .Values.sandbox.dns.podLabels | nindent 14 }} + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + {{- if .Values.postgres.enabled }} + - to: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "postgres") | nindent 14 }} + ports: + - protocol: TCP + port: 5432 + {{- else }} + - to: + {{- range $oe.postgresCIDRs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + ports: + - protocol: TCP + port: {{ .Values.postgres.external.port }} + {{- end }} + - to: + - podSelector: + matchLabels: + {{- include "artex.selector" (list . "panel-egress") | nindent 14 }} + ports: + - protocol: TCP + port: {{ .Values.runner.port }} +{{- end }} diff --git a/deploy/helm/artex/templates/panel.yaml b/deploy/helm/artex/templates/panel.yaml index 94a0c8604..2c82ad6af 100644 --- a/deploy/helm/artex/templates/panel.yaml +++ b/deploy/helm/artex/templates/panel.yaml @@ -140,6 +140,15 @@ spec: secretKeyRef: name: {{ include "artex.secretName" . }} key: ARTEX_RUNNER_TOKEN + {{- else if include "artex.offModeEgress" . }} + # The panel pushes its task scope to the panel egress controller. + - name: ARTEX_PANEL_EGRESS_URL + value: {{ printf "http://%s-panel-egress:%d" (include "artex.fullname" .) (int .Values.runner.port) | quote }} + - name: ARTEX_RUNNER_TOKEN + valueFrom: + secretKeyRef: + name: {{ include "artex.secretName" . }} + key: ARTEX_RUNNER_TOKEN {{- end }} {{- range $k, $v := .Values.panel.env }} - name: {{ $k }} diff --git a/deploy/helm/artex/values.schema.json b/deploy/helm/artex/values.schema.json index b4779c359..db2e1e5d9 100644 --- a/deploy/helm/artex/values.schema.json +++ b/deploy/helm/artex/values.schema.json @@ -38,6 +38,28 @@ "proxyDeniedCIDRs": { "type": "array", "items": { "type": "string", "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$" } + }, + "offModeEgress": { + "type": "object", + "additionalProperties": false, + "required": ["enabled"], + "properties": { + "enabled": { "type": "boolean" }, + "extraHosts": { + "type": "array", + "items": { "type": "string", "pattern": "^(\\*\\.)?([A-Za-z0-9_]([A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?\\.)+[A-Za-z][A-Za-z0-9-]{0,61}[A-Za-z0-9]$" } + }, + "extraCIDRs": { + "type": "array", + "items": { "type": "string", "pattern": "^(([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}|[0-9A-Fa-f:]+/[0-9]{1,3})$" } + }, + "postgresCIDRs": { + "type": "array", + "items": { "type": "string", "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$" } + }, + "refresh": { "type": "string", "pattern": "^[0-9]+(s|m|h)$" }, + "retention": { "type": "string", "pattern": "^[0-9]+(s|m|h)$" } + } } } }, diff --git a/deploy/helm/artex/values.yaml b/deploy/helm/artex/values.yaml index 148f59f4c..cc946e32a 100644 --- a/deploy/helm/artex/values.yaml +++ b/deploy/helm/artex/values.yaml @@ -86,7 +86,28 @@ sandbox: # the proxy's own allowlist). Task scope CIDRs are allowed back explicitly. # Empty = built-in default (RFC1918, CGNAT, loopback, link-local, metadata, multicast). proxyDeniedCIDRs: [] - # Cluster DNS the egress proxy may query. + # mode=off only. With the sandbox off, agent commands run inside the panel pod. + # offModeEgress limits the panel's outbound traffic to cluster DNS, the database, + # and the IP addresses of the operator-approved scope of live tasks plus the LLM + # endpoints and the extras below. A NetworkPolicy enforces it; a small controller + # (the runner image with ARTEX_RUNNER_BACKEND=panel-egress, RBAC limited to + # NetworkPolicies in this namespace) keeps it in line with the scope the panel + # pushes. Needs networkPolicy.enabled. See README.md for the limits. + # enabled=false restores unrestricted panel egress: UNSAFE, agent commands can + # then reach any address the pod can (other namespaces, nodes, the API server). + offModeEgress: + enabled: true + # Always-allowed DNS names (webhooks, MCP servers, a custom LLM gateway, ...). + extraHosts: [] + # Always-allowed CIDRs (IP-literal endpoints; private ranges are allowed here). + extraCIDRs: [] + # Required with postgres.enabled=false: the external database's CIDRs. + postgresCIDRs: [] + # How often hosts are re-resolved, and how long an address stays allowed + # after a host last resolved to it (DNS rotation). + refresh: 1m + retention: 1h + # Cluster DNS the egress proxy (and, with mode=off, the panel) may query. dns: namespace: kube-system podLabels: diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md index 6afe9f63c..3cb9efe96 100644 --- a/docs/SANDBOX.md +++ b/docs/SANDBOX.md @@ -68,6 +68,39 @@ warning banner and records `sandbox=off` in every task event log): ARTEX_SANDBOX=off ``` +With Docker, off mode leaves the panel's egress as open as the container's; the +optional `docker-compose.egress.yml` overlay (`egress-guard/`) restricts it. + +### Kubernetes: off mode with scope-restricted panel egress + +The Helm chart (`deploy/helm/artex`, `sandbox.mode=off`) restricts the panel's +egress by default (`sandbox.offModeEgress.enabled=true`), so agent commands that +run in the panel pod, direct scanners included (`nmap -sT`), reach only: + +- cluster DNS, the database, and the panel egress controller (static NetworkPolicy); +- the IP addresses of the operator-approved scope of every live task, the known + hostnames under the approved domains, the LLM endpoints, and + `sandbox.offModeEgress.extraHosts`/`extraCIDRs` (a NetworkPolicy the controller + maintains). + +The scope comes from the same `taskSandboxRunInfo` that feeds the per-task proxy in +required mode (`approved_by_operator=true`, not expanded; frozen company grants; +operator allow rules). The panel pushes the union to the controller, an +`artex-runner` with `ARTEX_RUNNER_BACKEND=panel-egress` and a Role limited to +NetworkPolicies, over `PUT /v1/panel-egress` with the runner token; the panel +holds no Kubernetes credentials. Resolved addresses in the proxy's denied ranges +are dropped unless an approved CIDR covers them. The enforcement state is in the +panel log and in `GET /api/health` (`sandbox_egress`). If the controller stops, +the last policy stays and nothing new is allowed. + +This is weaker than required mode: the boundary is the union of all live tasks, +not one task; it is IP based (CDN-shared addresses, DNS rotation within the +retention window, newly discovered hosts reachable only once stored as assets); DNS +queries still leave the cluster; IPv6 needs an approved IPv6 CIDR; and uid 10001 +has no `NET_RAW`, so `nmap -sS`/`-sU` do not work. See the chart README for the +details. `sandbox.offModeEgress.enabled=false` restores unrestricted egress and is +unsafe. Docker deployments and required mode are unchanged. + ## Security Hardening Notes - **Tamper-proof egress audit log**: `artex-egress-` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit//egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/:/workspace:rw` and cannot read, truncate, or forge the egress audit log. diff --git a/sandbox/helmchart_offmode_test.go b/sandbox/helmchart_offmode_test.go new file mode 100644 index 000000000..23bccb3cd --- /dev/null +++ b/sandbox/helmchart_offmode_test.go @@ -0,0 +1,289 @@ +package sandbox + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// TestHelmChartOffModeEgress checks the scope-restricted panel egress of +// sandbox.mode=off: a static egress policy (DNS, database, controller) and a +// controller limited to the one scope NetworkPolicy. +func TestHelmChartOffModeEgress(t *testing.T) { + objs := renderChart(t, "sandbox.mode=off") + panelSel := map[string]any{"app.kubernetes.io/name": "artex", "app.kubernetes.io/instance": "rel", "app.kubernetes.io/component": "panel"} + ctrlSel := map[string]any{"app.kubernetes.io/name": "artex", "app.kubernetes.io/instance": "rel", "app.kubernetes.io/component": "panel-egress"} + + // Static egress policy: exactly DNS, bundled PostgreSQL and the controller. + base := findObj(objs, "NetworkPolicy", "rel-artex-panel-egress-base") + if base == nil { + t.Fatal("static panel egress policy missing") + } + if !flatMapEqual(dig(base, "spec", "podSelector", "matchLabels"), panelSel) { + t.Errorf("base selects %v", dig(base, "spec", "podSelector")) + } + if pt := strList(dig(base, "spec", "policyTypes")); !slices.Equal(pt, []string{"Egress"}) { + t.Errorf("base policyTypes %v", pt) + } + rules := dig(base, "spec", "egress").([]any) + if len(rules) != 3 { + t.Fatalf("base has %d egress rules: %v", len(rules), rules) + } + for _, r := range rules { + if to, _ := dig(r, "to").([]any); len(to) == 0 { + t.Fatalf("rule without peers allows everything: %v", r) + } + if ports, _ := dig(r, "ports").([]any); len(ports) == 0 { + t.Fatalf("rule without ports: %v", r) + } + for _, p := range dig(r, "to").([]any) { + if dig(p, "ipBlock") != nil { + t.Errorf("base allows an ipBlock: %v", p) + } + } + } + if dig(rules[0], "to", 0, "namespaceSelector", "matchLabels", "kubernetes.io/metadata.name") != "kube-system" || + dig(rules[0], "to", 0, "podSelector", "matchLabels", "k8s-app") != "kube-dns" || dig(rules[0], "ports", 0, "port") != 53 { + t.Errorf("dns rule %v", rules[0]) + } + if dig(rules[1], "to", 0, "podSelector", "matchLabels", "app.kubernetes.io/component") != "postgres" || dig(rules[1], "ports", 0, "port") != 5432 { + t.Errorf("postgres rule %v", rules[1]) + } + if !flatMapEqual(dig(rules[2], "to", 0, "podSelector", "matchLabels"), ctrlSel) || dig(rules[2], "ports", 0, "port") != 8789 { + t.Errorf("controller rule %v", rules[2]) + } + // Only the panel may push scope to the controller. + ctrlNP := findObj(objs, "NetworkPolicy", "rel-artex-panel-egress") + if !flatMapEqual(dig(ctrlNP, "spec", "podSelector", "matchLabels"), ctrlSel) || + !flatMapEqual(dig(ctrlNP, "spec", "ingress", 0, "from", 0, "podSelector", "matchLabels"), panelSel) || + len(dig(ctrlNP, "spec", "ingress").([]any)) != 1 { + t.Errorf("controller ingress policy %v", ctrlNP) + } + + // RBAC: namespaced, NetworkPolicies only, get/update only on the scope policy. + if len(objsOfKind(objs, "ClusterRole"))+len(objsOfKind(objs, "ClusterRoleBinding")) != 0 { + t.Fatal("cluster-wide RBAC in off mode") + } + if n := len(objsOfKind(objs, "Role")); n != 1 { + t.Fatalf("%d Roles in off mode", n) + } + role := findObj(objs, "Role", "rel-artex-panel-egress") + type rule struct{ groups, res, names, verbs []string } + var got []rule + for _, r := range role["rules"].([]any) { + got = append(got, rule{strList(dig(r, "apiGroups")), strList(dig(r, "resources")), strList(dig(r, "resourceNames")), strList(dig(r, "verbs"))}) + } + want := []rule{ + {[]string{"networking.k8s.io"}, []string{"networkpolicies"}, nil, []string{"create"}}, + {[]string{"networking.k8s.io"}, []string{"networkpolicies"}, []string{"rel-artex-panel-egress-scope"}, []string{"get", "update"}}, + } + if len(got) != len(want) { + t.Fatalf("role rules %v", got) + } + for i := range want { + if !slices.Equal(got[i].groups, want[i].groups) || !slices.Equal(got[i].res, want[i].res) || !slices.Equal(got[i].names, want[i].names) || !slices.Equal(got[i].verbs, want[i].verbs) { + t.Errorf("rule %d = %+v, want %+v", i, got[i], want[i]) + } + } + rb := findObj(objs, "RoleBinding", "rel-artex-panel-egress") + if dig(rb, "subjects", 0, "name") != "rel-artex-panel-egress" || dig(rb, "subjects", 0, "namespace") != "artex-ns" || dig(rb, "roleRef", "name") != "rel-artex-panel-egress" { + t.Errorf("binding %v", rb) + } + + // Controller workload: runner image, policy-only backend, non-root, no caps. + ctrl := findObj(objs, "Deployment", "rel-artex-panel-egress") + spec := podSpecOf(ctrl) + if dig(spec, "serviceAccountName") != "rel-artex-panel-egress" || dig(spec, "securityContext", "runAsNonRoot") != true || dig(spec, "securityContext", "seccompProfile", "type") != "RuntimeDefault" { + t.Errorf("controller pod spec %v", spec) + } + if dig(ctrl, "spec", "replicas") != 1 || dig(ctrl, "spec", "strategy", "type") != "Recreate" { + t.Errorf("controller replicas/strategy %v %v", dig(ctrl, "spec", "replicas"), dig(ctrl, "spec", "strategy")) + } + cc := dig(spec, "containers", 0) + if !strings.HasPrefix(dig(cc, "image").(string), "ghcr.io/baarai/artex-runner:") { + t.Errorf("controller image %v", dig(cc, "image")) + } + sc := dig(cc, "securityContext") + if dig(sc, "allowPrivilegeEscalation") != false || dig(sc, "readOnlyRootFilesystem") != true || + !slices.Equal(strList(dig(sc, "capabilities", "drop")), []string{"ALL"}) || dig(sc, "capabilities", "add") != nil { + t.Errorf("controller securityContext %v", sc) + } + if dig(spec, "volumes") != nil { + t.Errorf("controller mounts volumes: %v", dig(spec, "volumes")) + } + plain, refs := containerEnv(cc) + if plain[EnvRunnerBackend] != BackendPanelEgress || dig(refs[EnvRunnerToken], "secretKeyRef", "key") != "ARTEX_RUNNER_TOKEN" { + t.Errorf("controller env %v %v", plain, refs) + } + src, err := os.ReadFile("paneleggress.go") + if err != nil { + t.Fatal(err) + } + for name := range plain { + if strings.HasPrefix(name, "ARTEX_PANEL_EGRESS_") && !bytes.Contains(src, []byte(`"`+name+`"`)) { + t.Errorf("chart sets %s but paneleggress.go never reads it", name) + } + } + for k, v := range plain { + t.Setenv(k, v) + } + t.Setenv("ARTEX_KUBE_NAMESPACE", "artex-ns") + cfg, err := PanelEgressConfigFromEnv() + if err != nil { + t.Fatalf("PanelEgressConfigFromEnv on rendered env: %v", err) + } + if cfg.PolicyName != "rel-artex-panel-egress-scope" || cfg.Refresh != time.Minute || cfg.Retention != time.Hour { + t.Errorf("controller config %+v", cfg) + } + panel := findObj(objs, "Deployment", "rel-artex-panel") + podLabels := dig(panel, "spec", "template", "metadata", "labels").(map[string]any) + for k, v := range cfg.PanelSelector { + if podLabels[k] != v { + t.Errorf("policy selector %s=%s does not match the panel pod (%v)", k, v, podLabels[k]) + } + } + if len(cfg.PanelSelector) != 3 { + t.Errorf("selector %v", cfg.PanelSelector) + } + if findObj(objs, "NetworkPolicy", cfg.PolicyName) != nil { + t.Error("the chart must not render the controller-owned scope policy (an upgrade would reset it)") + } + + // Panel: pushes to the controller service with the shared token; still no + // Kubernetes credentials. + pspec := podSpecOf(panel) + pplain, prefs := containerEnv(dig(pspec, "containers", 0)) + svc := findObj(objs, "Service", "rel-artex-panel-egress") + if svc == nil || pplain[EnvPanelEgressURL] != "http://rel-artex-panel-egress:8789" || dig(svc, "spec", "ports", 0, "port") != 8789 { + t.Errorf("panel egress URL %q, service %v", pplain[EnvPanelEgressURL], svc) + } + if dig(prefs[EnvRunnerToken], "secretKeyRef", "key") != "ARTEX_RUNNER_TOKEN" || pplain[EnvRunnerURL] != "" { + t.Errorf("panel token/runner env %v %v", pplain, prefs) + } + if dig(pspec, "automountServiceAccountToken") != false { + t.Error("panel mounts a service account token") + } + for k := range pplain { + if strings.HasPrefix(k, "ARTEX_KUBE_") { + t.Errorf("panel env has %s", k) + } + } + + // Options flow to the controller. + opts := renderChart(t, "sandbox.mode=off", "sandbox.offModeEgress.extraHosts={hooks.slack.com,mcp.example}", + "sandbox.offModeEgress.extraCIDRs={10.9.0.0/16}", "sandbox.proxyDeniedCIDRs={10.0.0.0/8}", + "sandbox.offModeEgress.refresh=30s", "sandbox.offModeEgress.retention=6h") + oplain, _ := containerEnv(dig(podSpecOf(findObj(opts, "Deployment", "rel-artex-panel-egress")), "containers", 0)) + if oplain["ARTEX_PANEL_EGRESS_EXTRA_HOSTS"] != "hooks.slack.com,mcp.example" || oplain["ARTEX_PANEL_EGRESS_EXTRA_CIDRS"] != "10.9.0.0/16" || + oplain["ARTEX_PANEL_EGRESS_DENIED_CIDRS"] != "10.0.0.0/8" || oplain["ARTEX_PANEL_EGRESS_REFRESH"] != "30s" || oplain["ARTEX_PANEL_EGRESS_RETENTION"] != "6h" { + t.Errorf("controller options env %v", oplain) + } + + // External database: its CIDRs replace the bundled PostgreSQL rule. + ext := renderChart(t, "sandbox.mode=off", "postgres.enabled=false", "postgres.external.host=db.example", + "postgres.external.port=6432", "sandbox.offModeEgress.postgresCIDRs={10.5.0.0/24,10.6.0.7/32}") + er := dig(findObj(ext, "NetworkPolicy", "rel-artex-panel-egress-base"), "spec", "egress").([]any) + if dig(er[1], "to", 0, "ipBlock", "cidr") != "10.5.0.0/24" || dig(er[1], "to", 1, "ipBlock", "cidr") != "10.6.0.7/32" || dig(er[1], "ports", 0, "port") != 6432 { + t.Errorf("external postgres rule %v", er[1]) + } + + // Values from a release that predates the setting (helm upgrade --reuse-values): + // restricted, with the defaults, never silently open. + legacy := renderChart(t, "sandbox.mode=off", "sandbox.offModeEgress=null") + if findObj(legacy, "NetworkPolicy", "rel-artex-panel-egress-base") == nil { + t.Fatal("upgrade without offModeEgress values renders an unrestricted panel") + } + lplain, _ := containerEnv(dig(podSpecOf(findObj(legacy, "Deployment", "rel-artex-panel-egress")), "containers", 0)) + if lplain["ARTEX_PANEL_EGRESS_REFRESH"] != "1m" || lplain["ARTEX_PANEL_EGRESS_RETENTION"] != "1h" || lplain["ARTEX_PANEL_EGRESS_EXTRA_HOSTS"] != "" { + t.Errorf("legacy defaults %v", lplain) + } + + // Disabled, or required mode: nothing of the above. + for _, set := range [][]string{{"sandbox.mode=off", "sandbox.offModeEgress.enabled=false"}, {}, {"sandbox.mode=required", "sandbox.offModeEgress.enabled=true"}} { + o := renderChart(t, set...) + for _, kind := range []string{"Deployment", "Service", "NetworkPolicy", "Role", "RoleBinding", "ServiceAccount"} { + for _, x := range objsOfKind(o, kind) { + if strings.Contains(dig(x, "metadata", "name").(string), "panel-egress") { + t.Errorf("%v renders %s %s", set, kind, dig(x, "metadata", "name")) + } + } + } + pe, _ := containerEnv(dig(podSpecOf(findObj(o, "Deployment", "rel-artex-panel")), "containers", 0)) + if pe[EnvPanelEgressURL] != "" { + t.Errorf("%v sets %s", set, EnvPanelEgressURL) + } + } +} + +func flatMapEqual(a, b any) bool { + am, ok1 := a.(map[string]any) + bm, ok2 := b.(map[string]any) + if !ok1 || !ok2 || len(am) != len(bm) { + return false + } + for k, v := range am { + if bm[k] != v { + return false + } + } + return true +} + +func TestHelmChartOffModeEgressFailsClosed(t *testing.T) { + helm := helmOrSkip(t) + for _, c := range []struct { + set []string + want string + }{ + // Enforcement needs NetworkPolicy: refuse rather than silently run open. + {[]string{"sandbox.mode=off", "networkPolicy.enabled=false"}, "networkPolicy.enabled"}, + // The panel could not reach an external database it has no rule for. + {[]string{"sandbox.mode=off", "postgres.enabled=false", "postgres.external.host=db.example"}, "postgresCIDRs"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.enabled=yes"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.extraHosts={1.2.3.4}"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.extraHosts={https://x.example}"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.extraCIDRs={x}"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.postgresCIDRs={db.example}"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.refresh=soon"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.retention=1d"}, "schema"}, + {[]string{"sandbox.mode=off", "sandbox.offModeEgress.enable=true"}, "schema"}, + } { + args := []string{"template", "rel", chartDir} + for _, s := range c.set { + args = append(args, "--set", s) + } + out, err := exec.Command(helm, args...).CombinedOutput() + if err == nil { + t.Errorf("%v accepted", c.set) + } else if !strings.Contains(string(out), c.want) { + t.Errorf("%v failed for an unexpected reason: %s", c.set, out) + } + } + // Explicitly unrestricted off mode still renders without NetworkPolicy. + if out, err := exec.Command(helm, "template", "rel", chartDir, "--set", "sandbox.mode=off", "--set", "networkPolicy.enabled=false", "--set", "sandbox.offModeEgress.enabled=false").CombinedOutput(); err != nil { + t.Errorf("unrestricted off mode: %v\n%s", err, out) + } +} + +func TestHelmChartLintOffMode(t *testing.T) { + helm := helmOrSkip(t) + abs, _ := filepath.Abs(chartDir) + for _, set := range [][]string{ + {"sandbox.mode=off"}, + {"sandbox.mode=off", "sandbox.offModeEgress.enabled=false"}, + {"sandbox.mode=off", "postgres.enabled=false", "postgres.external.host=db.example", "sandbox.offModeEgress.postgresCIDRs={10.5.0.0/24}"}, + } { + args := []string{"lint", "--strict", abs} + for _, s := range set { + args = append(args, "--set", s) + } + if out, err := exec.Command(helm, args...).CombinedOutput(); err != nil { + t.Errorf("helm lint %v: %v\n%s", set, err, out) + } + } +} diff --git a/sandbox/helmchart_test.go b/sandbox/helmchart_test.go index b9689458a..595562fb6 100644 --- a/sandbox/helmchart_test.go +++ b/sandbox/helmchart_test.go @@ -472,7 +472,8 @@ func TestHelmChartAccessModePinning(t *testing.T) { } func TestHelmChartModesAndOptions(t *testing.T) { - off := renderChart(t, "sandbox.mode=off") + // Off mode with unrestricted panel egress (the pre-offModeEgress behaviour). + off := renderChart(t, "sandbox.mode=off", "sandbox.offModeEgress.enabled=false") for _, kind := range []string{"Role", "RoleBinding", "ServiceAccount"} { if n := len(objsOfKind(off, kind)); n != 0 { t.Errorf("sandbox off renders %d %s", n, kind) diff --git a/sandbox/paneleggress_e2e_test.go b/sandbox/paneleggress_e2e_test.go new file mode 100644 index 000000000..2d59e8248 --- /dev/null +++ b/sandbox/paneleggress_e2e_test.go @@ -0,0 +1,301 @@ +package sandbox + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "regexp" + "strings" + "testing" + "time" +) + +// TestPanelEgressOffModeE2E drives a release installed with sandbox.mode=off (and +// the default sandbox.offModeEgress.enabled=true) through the panel API and checks, +// as the agent uid 10001 inside the panel pod, which destinations are reachable. +// It needs a dedicated cluster (no other task may approve example.com/.org/.net) +// and internet access. scripts/k3d-e2e.sh (OFF_MODE=1) sets it up. Enable with: +// +// ARTEX_PANEL_EGRESS_E2E=1 +// ARTEX_E2E_NAMESPACE=artex +// ARTEX_E2E_RELEASE=artex +// ARTEX_E2E_KUBECONTEXT=k3d-artex-off (optional) +// ARTEX_E2E_ADMIN_PASSWORD=... (login; on a fresh install the test sets it +// with the setup token from the panel log) +// ARTEX_E2E_LLM_HOST=api.anthropic.com (optional: an LLM host that must stay reachable) +func TestPanelEgressOffModeE2E(t *testing.T) { + if os.Getenv("ARTEX_PANEL_EGRESS_E2E") != "1" { + t.Skip("set ARTEX_PANEL_EGRESS_E2E=1 (see scripts/k3d-e2e.sh OFF_MODE=1)") + } + ns := envDefault("ARTEX_E2E_NAMESPACE", "artex") + rel := envDefault("ARTEX_E2E_RELEASE", "artex") + kctx := os.Getenv("ARTEX_E2E_KUBECONTEXT") + password := os.Getenv("ARTEX_E2E_ADMIN_PASSWORD") + if password == "" { + t.Fatal("ARTEX_E2E_ADMIN_PASSWORD is required") + } + kubectl := func(args ...string) (string, error) { + full := []string{"-n", ns} + if kctx != "" { + full = append(full, "--context", kctx) + } + out, err := exec.Command("kubectl", append(full, args...)...).CombinedOutput() + return strings.TrimSpace(string(out)), err + } + mustKubectl := func(args ...string) string { + t.Helper() + out, err := kubectl(args...) + if err != nil { + t.Fatalf("kubectl %v: %v\n%s", args, err, out) + } + return out + } + panelDeploy := "deploy/" + rel + "-panel" + ctrlDeploy := "deploy/" + rel + "-panel-egress" + scopePolicy := rel + "-panel-egress-scope" + + // reach runs a probe in the panel container as the agent user. + reach := func(script string) bool { + _, err := kubectl("exec", panelDeploy, "-c", "artex", "--", "setpriv", "--reuid", "10001", "--regid", "10001", "--clear-groups", "sh", "-c", script) + return err == nil + } + tcp := func(host string, port int) bool { return reach(fmt.Sprintf("nc -z -w 5 %s %d", host, port)) } + nmapOpen := func(host string) bool { + out, _ := kubectl("exec", panelDeploy, "-c", "artex", "--", "setpriv", "--reuid", "10001", "--regid", "10001", "--clear-groups", + "nmap", "-sT", "-Pn", "-n", "--host-timeout", "20s", "-p443", host) + return regexp.MustCompile(`(?m)^443/tcp\s+open`).MatchString(out) + } + waitFor := func(what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(150 * time.Second) + for time.Now().Before(deadline) { + if cond() { + return + } + time.Sleep(5 * time.Second) + } + t.Fatalf("timed out waiting for %s", what) + } + // stays checks cond holds for a whole window (fail closed: no new access). + stays := func(what string, window time.Duration, cond func() bool) { + t.Helper() + deadline := time.Now().Add(window) + for time.Now().Before(deadline) { + if !cond() { + t.Fatalf("%s did not hold", what) + } + time.Sleep(10 * time.Second) + } + } + + // The identity probes run as. + if out := mustKubectl("exec", panelDeploy, "-c", "artex", "--", "setpriv", "--reuid", "10001", "--regid", "10001", "--clear-groups", "id", "-u"); out != "10001" { + t.Fatalf("probe uid %q", out) + } + + // Panel API through a port-forward. + const pfPort = "18797" + pfArgs := []string{"-n", ns, "port-forward", "svc/" + rel + "-panel", pfPort + ":8787"} + if kctx != "" { + pfArgs = append([]string{"--context", kctx}, pfArgs...) + } + pf := exec.Command("kubectl", pfArgs...) + if err := pf.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pf.Process.Kill(); _ = pf.Wait() }) + for i := 0; i < 50; i++ { + if c, err := net.DialTimeout("tcp", "127.0.0.1:"+pfPort, 200*time.Millisecond); err == nil { + c.Close() + break + } + time.Sleep(200 * time.Millisecond) + } + base := "http://127.0.0.1:" + pfPort + var token string + api := func(method, path string, body any, out any) int { + t.Helper() + var r io.Reader + if body != nil { + raw, _ := json.Marshal(body) + r = bytes.NewReader(raw) + } + req, _ := http.NewRequest(method, base+path, r) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("%s %s: %v", method, path, err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + if out != nil { + _ = json.Unmarshal(raw, out) + } + return resp.StatusCode + } + var login struct { + Token string `json:"token"` + } + if code := api("POST", "/api/auth/login", map[string]string{"username": "ARTEX", "password": password}, &login); code == http.StatusForbidden { + // Fresh install: set the password with the one-time setup token. + logs := mustKubectl("logs", panelDeploy, "-c", "artex") + m := regexp.MustCompile(`Setup token for the /setup page: (\S+)`).FindAllStringSubmatch(logs, -1) + if len(m) == 0 { + t.Fatal("no setup token in the panel log") + } + if code := api("POST", "/api/auth/init", map[string]string{"password": password, "setup_token": m[len(m)-1][1]}, nil); code != http.StatusOK { + t.Fatalf("auth init = %d", code) + } + if code := api("POST", "/api/auth/login", map[string]string{"username": "ARTEX", "password": password}, &login); code != http.StatusOK { + t.Fatalf("login after init = %d", code) + } + } else if code != http.StatusOK { + t.Fatalf("login = %d", code) + } + token = login.Token + + health := func() map[string]any { + var h map[string]any + api("GET", "/api/health", nil, &h) + se, _ := h["sandbox_egress"].(map[string]any) + return se + } + waitFor("sandbox_egress enforced", func() bool { se := health(); return se != nil && se["state"] == PanelEgressEnforced }) + + node := mustKubectl("get", "nodes", "-o", `jsonpath={.items[0].status.addresses[?(@.type=="InternalIP")].address}`) + apiEP := mustKubectl("-n", "default", "get", "endpointslices", "-l", "kubernetes.io/service-name=kubernetes", "-o", "jsonpath={.items[0].endpoints[0].addresses[0]}") + apiPort := mustKubectl("-n", "default", "get", "endpointslices", "-l", "kubernetes.io/service-name=kubernetes", "-o", "jsonpath={.items[0].ports[0].port}") + dnsPod := mustKubectl("-n", "kube-system", "get", "pods", "-l", "k8s-app=kube-dns", "-o", "jsonpath={.items[0].status.podIP}") + + blockedAlways := func(t *testing.T) { + t.Helper() + for name, ok := range map[string]bool{ + "kubernetes.default.svc:443": tcp("kubernetes.default.svc", 443), + "API endpoint " + apiEP + ":" + apiPort: reach(fmt.Sprintf("nc -z -w 5 %s %s", apiEP, apiPort)), + "node " + node + ":10250": tcp(node, 10250), + "kube-dns pod metrics :9153": tcp(dnsPod, 9153), + "metadata 169.254.169.254:80": tcp("169.254.169.254", 80), + "example.org:443 (out of scope)": tcp("example.org", 443), + } { + if ok { + t.Errorf("%s reachable from the panel as uid 10001", name) + } + } + } + t.Run("baseline", func(t *testing.T) { + blockedAlways(t) + if tcp("example.com", 443) { + t.Fatal("example.com reachable before any task approves it (is another task scoped to it?)") + } + if !tcp(rel+"-postgres", 5432) { + t.Error("database unreachable") + } + if !reach("dig +short +time=3 +tries=1 example.org A | grep -q .") { + t.Error("cluster DNS unreachable") + } + if h := os.Getenv("ARTEX_E2E_LLM_HOST"); h != "" && !tcp(h, 443) { + t.Errorf("LLM host %s unreachable", h) + } + }) + + // A task scoped to example.com. Paused right away: the test needs its scope, + // not its agent (status paused still counts as live). + var task struct { + ID any `json:"id"` + } + if code := api("POST", "/api/tasks", map[string]any{"name": "panel-egress-e2e", "description": "panel egress e2e: no work", + "goal": "[targetless] Automated network egress test fixture: this task only holds operator scope. Run no command, call no tool, and stop at once.", + "timeout_seconds": 600}, &task); code != http.StatusCreated { + t.Fatalf("create task = %d", code) + } + taskID := fmt.Sprint(task.ID) + api("POST", "/api/tasks/control/batch", map[string]any{"task_ids": []string{taskID}, "action": "pause"}, nil) + t.Cleanup(func() { api("DELETE", "/api/tasks/"+taskID, nil, nil) }) + addScope := func(value string) string { + t.Helper() + if code := api("POST", "/api/tasks/"+taskID+"/scope", map[string]string{"kind": "root_domain", "value": value, "reason": "e2e"}, nil); code/100 != 2 { + t.Fatalf("add scope %s = %d", value, code) + } + // The add response does not carry the row id: look it up. + var list struct { + Scope []struct { + ID any `json:"id"` + Domain string `json:"domain"` + } `json:"scope"` + } + api("GET", "/api/tasks/"+taskID+"/scope", nil, &list) + for _, sc := range list.Scope { + if sc.Domain == value { + return fmt.Sprint(sc.ID) + } + } + t.Fatalf("scope %s not listed", value) + return "" + } + + var scopeID string + t.Run("in-scope reachable, direct scan works", func(t *testing.T) { + scopeID = addScope("example.com") + waitFor("example.com reachable", func() bool { return tcp("example.com", 443) }) + if !nmapOpen("example.com") { + t.Error("nmap -sT -Pn -p443 example.com: port not open") + } + if !reach("curl -fsS -m 10 -o /dev/null https://example.com/") { + t.Error("curl https://example.com failed") + } + blockedAlways(t) + if nmapOpen("example.org") { + t.Error("nmap reports example.org:443 open (out of scope)") + } + se := health() + if se["state"] != PanelEgressEnforced || se["ip_blocks"].(float64) < 1 { + t.Errorf("health sandbox_egress = %v", se) + } + pol := mustKubectl("get", "networkpolicy", scopePolicy, "-o", "jsonpath={.spec.egress[*].to[*].ipBlock.cidr}") + if pol == "" { + t.Errorf("scope policy has no ipBlocks") + } + }) + + t.Run("revoke removes access", func(t *testing.T) { + if code := api("DELETE", "/api/tasks/"+taskID+"/scope/"+scopeID, nil, nil); code/100 != 2 { + t.Fatalf("delete scope = %d", code) + } + waitFor("example.com blocked after revoke", func() bool { return !tcp("example.com", 443) }) + }) + + t.Run("controller down fails closed", func(t *testing.T) { + addScope("example.com") + waitFor("example.com reachable again", func() bool { return tcp("example.com", 443) }) + mustKubectl("scale", ctrlDeploy, "--replicas=0") + t.Cleanup(func() { _, _ = kubectl("scale", ctrlDeploy, "--replicas=1") }) + mustKubectl("wait", "--for=delete", "pod", "-l", "app.kubernetes.io/component=panel-egress", "--timeout=120s") + addScope("example.net") + waitFor("panel reports the push failure", func() bool { return health()["state"] == "error" }) + // The last policy stays: existing scope still works, the new scope does not. + stays("existing scope kept, new scope blocked", 60*time.Second, func() bool { + return tcp("example.com", 443) && !tcp("example.net", 443) + }) + blockedAlways(t) + mustKubectl("scale", ctrlDeploy, "--replicas=1") + mustKubectl("rollout", "status", ctrlDeploy, "--timeout=180s") + waitFor("example.net reachable once the controller is back", func() bool { return tcp("example.net", 443) }) + waitFor("sandbox_egress enforced again", func() bool { return health()["state"] == PanelEgressEnforced }) + }) + + t.Run("task deleted removes its scope", func(t *testing.T) { + if code := api("DELETE", "/api/tasks/"+taskID, nil, nil); code/100 != 2 { + t.Fatalf("delete task = %d", code) + } + waitFor("example.com and example.net blocked", func() bool { return !tcp("example.com", 443) && !tcp("example.net", 443) }) + blockedAlways(t) + }) +} diff --git a/scripts/k3d-e2e.sh b/scripts/k3d-e2e.sh index 195c57051..99b2a3032 100755 --- a/scripts/k3d-e2e.sh +++ b/scripts/k3d-e2e.sh @@ -7,6 +7,13 @@ # KEEP=1 scripts/k3d-e2e.sh leave the cluster running afterwards # RUNNER_ONLY=1 scripts/k3d-e2e.sh sandbox only (panel.replicas=0): builds the three # small sandbox images, skips the panel checks (CI) +# OFF_MODE=1 scripts/k3d-e2e.sh sandbox.mode=off with the scope-restricted panel +# egress (sandbox.offModeEgress): builds the panel and +# runner images, checks from inside the panel what the +# agent user can reach (needs internet access) +# +# OFF_MODE=1 sets the panel's admin password to ARTEX_E2E_ADMIN_PASSWORD (generated +# when unset) on a fresh install. # # Optional: ANTHROPIC_API_KEY is passed to the chart Secret (never echoed). # ARTEX_E2E_INTERNET=1 also tests allowed egress to example.com. @@ -18,8 +25,18 @@ NS=${NS:-artex} RELEASE=${RELEASE:-artex} CTX="k3d-${CLUSTER}" ROOT=$(cd "$(dirname "$0")/.." && pwd) -IMAGES=(artex-runner:local artex-worker:local artex-egress-proxy:local) -[ "${RUNNER_ONLY:-0}" = "1" ] || IMAGES+=(artex:local) +OFF_MODE=${OFF_MODE:-0} +if [ "$OFF_MODE" = "1" ] && [ "${RUNNER_ONLY:-0}" = "1" ]; then + echo "OFF_MODE=1 and RUNNER_ONLY=1 are exclusive" >&2 + exit 2 +fi +if [ "$OFF_MODE" = "1" ]; then + # No task pods: the runner image runs the panel egress controller. + IMAGES=(artex-runner:local artex:local) +else + IMAGES=(artex-runner:local artex-worker:local artex-egress-proxy:local) + [ "${RUNNER_ONLY:-0}" = "1" ] || IMAGES+=(artex:local) +fi log() { printf '\n==> %s\n' "$*"; } @@ -41,8 +58,10 @@ fi if [ "${SKIP_BUILD:-0}" != "1" ]; then log "building images" docker build -t artex-runner:local -f "$ROOT/Dockerfile.runner" "$ROOT" - docker build -t artex-worker:local -f "$ROOT/Dockerfile.worker" "$ROOT" - docker build -t artex-egress-proxy:local -f "$ROOT/Dockerfile.egress-proxy" "$ROOT" + if [ "$OFF_MODE" != "1" ]; then + docker build -t artex-worker:local -f "$ROOT/Dockerfile.worker" "$ROOT" + docker build -t artex-egress-proxy:local -f "$ROOT/Dockerfile.egress-proxy" "$ROOT" + fi if [ "${RUNNER_ONLY:-0}" != "1" ]; then docker build -t artex:local -f "$ROOT/Dockerfile" "$ROOT" fi @@ -58,6 +77,7 @@ set_args=(--set images.pullPolicy=Never --set images.runner.repository=artex-runner --set images.runner.tag=local --set images.worker.repository=artex-worker --set images.worker.tag=local --set images.egressProxy.repository=artex-egress-proxy --set images.egressProxy.tag=local) +[ "$OFF_MODE" = "1" ] && set_args+=(--set sandbox.mode=off) if [ "${RUNNER_ONLY:-0}" = "1" ]; then # No panel: the keys volume never binds (WaitForFirstConsumer), so wait on the # workloads instead of helm --wait. @@ -88,6 +108,30 @@ if ! grep -q "\[isolation\] self-test passed" <<<"$panel_log"; then fi fi +if [ "$OFF_MODE" = "1" ]; then + log "waiting for the panel egress controller" + kubectl --context "$CTX" -n "$NS" rollout status deploy/"$RELEASE"-panel-egress --timeout=300s + log "running off-mode panel egress e2e tests" + if [ -z "${ARTEX_E2E_ADMIN_PASSWORD:-}" ]; then + ARTEX_E2E_ADMIN_PASSWORD=$(head -c 24 /dev/urandom | base64 | tr -dc 'A-Za-z0-9') + echo "admin password for this run is in ARTEX_E2E_ADMIN_PASSWORD (not printed)" + fi + llm_host="" + [ -n "${ANTHROPIC_API_KEY:-}" ] && llm_host=api.anthropic.com + ( + cd "$ROOT" + ARTEX_PANEL_EGRESS_E2E=1 \ + ARTEX_E2E_ADMIN_PASSWORD="$ARTEX_E2E_ADMIN_PASSWORD" \ + ARTEX_E2E_LLM_HOST="$llm_host" \ + ARTEX_E2E_RELEASE="$RELEASE" \ + ARTEX_E2E_NAMESPACE="$NS" \ + ARTEX_E2E_KUBECONTEXT="$CTX" \ + go test ./sandbox -run TestPanelEgressOffModeE2E -count=1 -v -timeout 30m + ) + log "off-mode e2e passed" + exit 0 +fi + TOKEN=$(kubectl --context "$CTX" -n "$NS" get secret "$RELEASE"-secrets -o jsonpath='{.data.ARTEX_RUNNER_TOKEN}' | base64 -d) log "running sandbox e2e tests"