mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
Merge pull request #780 from thecorporatetractor/feat/k8s-sandbox-backend
Some checks are pending
ci / changes (push) Waiting to run
ci / go (push) Blocked by required conditions
ci / go-stable (push) Blocked by required conditions
ci / govulncheck (push) Blocked by required conditions
ci / shell (push) Blocked by required conditions
ci / web (push) Blocked by required conditions
ci / python (push) Blocked by required conditions
Some checks are pending
ci / changes (push) Waiting to run
ci / go (push) Blocked by required conditions
ci / go-stable (push) Blocked by required conditions
ci / govulncheck (push) Blocked by required conditions
ci / shell (push) Blocked by required conditions
ci / web (push) Blocked by required conditions
ci / python (push) Blocked by required conditions
feat(sandbox): Kubernetes backend for artex-runner
This commit is contained in:
commit
0885bdd720
10 changed files with 2476 additions and 21 deletions
|
|
@ -18,6 +18,7 @@ All notable changes to this project are documented in this file. The format is b
|
|||
|
||||
### Added
|
||||
|
||||
- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. No scope opens the cluster's own ranges, the API server or cloud metadata: set `ARTEX_KUBE_CLUSTER_CIDRS` to the pod, service and node CIDRs, plus the API server endpoint addresses when they lie outside them as on managed clusters (without it, private scope CIDRs are dropped). The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart.
|
||||
- **Slack notification channel**: System → Notifications can push findings to Slack by pasting an Incoming Webhook URL; each URL posts to the channel, or the installer's own direct messages, chosen when it was created in Slack. Only `https://hooks.slack.com/services/…` (and the GovSlack host) is accepted, and the URL is stored sealed and masked like other channel credentials. Finding text is escaped (`&`, `<`, `>`) so it cannot mention `@channel` or hide a link, digests are packed under 3,900 characters and link unfurling is off. The form explains the Slack setup steps in every console language.
|
||||
|
||||
- **The task target gate has a UI.** `target_gate` was API-only (`POST /api/tasks`, `PATCH /api/tasks/{id}`), so an operator could neither see nor change it: a task-level block rule added to a task whose gate was off never reached a network target, because `CheckTargets` returns before any rule is matched. The create-task sheet now carries a `Network target gate` selector (auto / on / off; auto leaves the backend default of on for scoped tasks) and warns when block rules would be stored unenforced, and the task overview's task-level rule card carries a switch with the live state, an explicit warning while enabled block rules exist with the gate off, and a retry when the state cannot be read. The switch writes through `PATCH /api/tasks/{id}` and takes effect on the next tool call. The gate governs the targets a tool call declares, not a sandboxed worker's sockets (the sandbox egress list decides those), turning it on also attaches the panel-hosted shared browser in sandbox mode, an unpinned target waits out the 300 s bound before the call is refused, task allow rules do not affect the gate, and each flip is recorded in the task's activity history with the operator, the client address, and the previous and new setting; the chat side's `target_gate` still has no UI.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
|
|
@ -40,6 +41,15 @@ func main() {
|
|||
if err != nil {
|
||||
log.Fatalf("[egress-proxy] invalid scope policy: %v", err)
|
||||
}
|
||||
// Ranges no scope may open (set by the Kubernetes backend: cluster networks,
|
||||
// API server, metadata).
|
||||
for _, c := range sandbox.ParseCSV(os.Getenv("ARTEX_NEVER_CIDRS")) {
|
||||
pfx, err := netip.ParsePrefix(c)
|
||||
if err != nil {
|
||||
log.Fatalf("[egress-proxy] invalid ARTEX_NEVER_CIDRS entry %q: %v", c, err)
|
||||
}
|
||||
policy.Never = append(policy.Never, pfx.Masked())
|
||||
}
|
||||
proxy := sandbox.NewEgressProxy(policy)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
|
|
|||
1331
sandbox/kube.go
Normal file
1331
sandbox/kube.go
Normal file
File diff suppressed because it is too large
Load diff
385
sandbox/kube_client.go
Normal file
385
sandbox/kube_client.go
Normal file
|
|
@ -0,0 +1,385 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// Container names in the task pods of the Kubernetes backend.
|
||||
const (
|
||||
kubeWorkerName = "worker"
|
||||
kubeProxyName = "egress-proxy"
|
||||
)
|
||||
|
||||
// kubeClient is the minimal Kubernetes API client of the Kubernetes sandbox
|
||||
// backend: JSON requests on one namespace and pods/exec over WebSocket, with the
|
||||
// in-cluster service-account token (re-read on every request: bound tokens
|
||||
// rotate).
|
||||
type kubeClient struct {
|
||||
apiServer string
|
||||
tokenPath string
|
||||
namespace string
|
||||
plainHTTP bool // tests only: http:// API server
|
||||
http *http.Client
|
||||
tls *tls.Config
|
||||
}
|
||||
|
||||
// newKubeClient builds a client for apiServer. An https:// server is verified
|
||||
// against the CA in caPath. An http:// server is refused unless allowPlainHTTP
|
||||
// (set only by tests): the token would travel in clear.
|
||||
func newKubeClient(apiServer, tokenPath, caPath, namespace string, allowPlainHTTP bool) (*kubeClient, error) {
|
||||
apiServer = strings.TrimRight(apiServer, "/")
|
||||
tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
if !strings.HasPrefix(apiServer, "https://") && !allowPlainHTTP {
|
||||
return nil, fmt.Errorf("kubernetes backend: API server %q must use https:// (the service-account token would be sent in clear)", apiServer)
|
||||
}
|
||||
if strings.HasPrefix(apiServer, "https://") {
|
||||
ca, err := os.ReadFile(caPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", caPath, err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(ca) {
|
||||
return nil, fmt.Errorf("kubernetes backend: no certificates in %s", caPath)
|
||||
}
|
||||
tlsCfg.RootCAs = pool
|
||||
}
|
||||
return &kubeClient{
|
||||
apiServer: apiServer,
|
||||
tokenPath: tokenPath,
|
||||
namespace: namespace,
|
||||
plainHTTP: allowPlainHTTP && strings.HasPrefix(apiServer, "http://"),
|
||||
tls: tlsCfg,
|
||||
http: &http.Client{
|
||||
Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg},
|
||||
Timeout: 30 * time.Second,
|
||||
// Never follow a redirect: it could carry the bearer token elsewhere.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *kubeClient) token() (string, error) {
|
||||
raw, err := os.ReadFile(c.tokenPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: read service account token: %v", ErrDockerUnavailable, err)
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), nil
|
||||
}
|
||||
|
||||
// kubeAPIError carries the HTTP status and the metav1.Status reason of a failed
|
||||
// API call. The response body is never forwarded: it can echo object specs or
|
||||
// exec commands.
|
||||
type kubeAPIError struct {
|
||||
Code int
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *kubeAPIError) Error() string {
|
||||
return fmt.Sprintf("kubernetes API HTTP %d %s", e.Code, e.Reason)
|
||||
}
|
||||
|
||||
var kubeReasonRE = regexp.MustCompile(`^[A-Za-z]{1,64}$`)
|
||||
|
||||
func newKubeAPIError(code int, body io.Reader) (*kubeAPIError, string) {
|
||||
raw, _ := io.ReadAll(io.LimitReader(body, 4096))
|
||||
var st struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &st)
|
||||
if !kubeReasonRE.MatchString(st.Reason) {
|
||||
st.Reason = ""
|
||||
}
|
||||
return &kubeAPIError{Code: code, Reason: st.Reason}, string(raw)
|
||||
}
|
||||
|
||||
func isKubeStatus(err error, code int) bool {
|
||||
var ae *kubeAPIError
|
||||
return errors.As(err, &ae) && ae.Code == code
|
||||
}
|
||||
|
||||
func (c *kubeClient) do(ctx context.Context, method, apiPath string, body, out any) error {
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r = bytes.NewReader(raw)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.apiServer+apiPath, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok, err := c.token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
// The error holds the API URL and namespace: log it, return a generic one.
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("kubernetes API request cancelled: %w", ctx.Err())
|
||||
}
|
||||
log.Printf("[runner] kubernetes API %s %s: %v", method, apiPath, err)
|
||||
return fmt.Errorf("%w: kubernetes API request failed", ErrDockerUnavailable)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
ae, raw := newKubeAPIError(resp.StatusCode, resp.Body)
|
||||
if ae.Code != http.StatusNotFound && ae.Code != http.StatusConflict {
|
||||
log.Printf("[runner] kubernetes API %s %s: HTTP %d: %.512s", method, apiPath, ae.Code, raw)
|
||||
}
|
||||
return ae
|
||||
}
|
||||
if out != nil {
|
||||
return json.NewDecoder(resp.Body).Decode(out)
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *kubeClient) nsPath(kind string) string {
|
||||
switch kind {
|
||||
case "networkpolicies":
|
||||
return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(c.namespace) + "/networkpolicies"
|
||||
default:
|
||||
return "/api/v1/namespaces/" + url.PathEscape(c.namespace) + "/" + kind
|
||||
}
|
||||
}
|
||||
|
||||
func (c *kubeClient) create(ctx context.Context, kind string, obj, out any) error {
|
||||
return c.do(ctx, http.MethodPost, c.nsPath(kind), obj, out)
|
||||
}
|
||||
|
||||
// deleteObj deletes an object and reports whether it existed. Pods get a 1s
|
||||
// grace, not 0: a zero grace force-removes the API object before the kubelet has
|
||||
// stopped the containers, while with a grace the pod stays (terminating) until
|
||||
// they are dead, so waiting for 404 proves its processes are gone. A non-empty
|
||||
// uid makes the API server refuse (409) to delete a different object reusing the name.
|
||||
func (c *kubeClient) deleteObj(ctx context.Context, kind, name, uid string) (bool, error) {
|
||||
body := map[string]any{"propagationPolicy": "Background"}
|
||||
if kind == "pods" {
|
||||
body["gracePeriodSeconds"] = 1
|
||||
}
|
||||
if uid != "" {
|
||||
body["preconditions"] = map[string]any{"uid": uid}
|
||||
}
|
||||
err := c.do(ctx, http.MethodDelete, c.nsPath(kind)+"/"+url.PathEscape(name), body, nil)
|
||||
if isKubeStatus(err, http.StatusNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
type kubeObjectMeta struct {
|
||||
Name string `json:"name"`
|
||||
UID string `json:"uid,omitempty"`
|
||||
ResourceVersion string `json:"resourceVersion,omitempty"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Annotations map[string]string `json:"annotations"`
|
||||
Deletion *string `json:"deletionTimestamp,omitempty"`
|
||||
}
|
||||
|
||||
type kubePod struct {
|
||||
Metadata kubeObjectMeta `json:"metadata"`
|
||||
Status struct {
|
||||
Phase string `json:"phase"`
|
||||
ContainerStatuses []struct {
|
||||
Ready bool `json:"ready"`
|
||||
State struct {
|
||||
Waiting *struct {
|
||||
Reason string `json:"reason"`
|
||||
Message string `json:"message"`
|
||||
} `json:"waiting"`
|
||||
Terminated *struct {
|
||||
Reason string `json:"reason"`
|
||||
} `json:"terminated"`
|
||||
} `json:"state"`
|
||||
} `json:"containerStatuses"`
|
||||
} `json:"status"`
|
||||
}
|
||||
|
||||
func (c *kubeClient) getPod(ctx context.Context, name string) (*kubePod, error) {
|
||||
var p kubePod
|
||||
if err := c.do(ctx, http.MethodGet, c.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// kubeExecStatus is the metav1.Status sent on the exec error channel.
|
||||
type kubeExecStatus struct {
|
||||
Status string `json:"status"`
|
||||
Reason string `json:"reason"`
|
||||
Details struct {
|
||||
Causes []struct {
|
||||
Reason string `json:"reason"`
|
||||
Message string `json:"message"`
|
||||
} `json:"causes"`
|
||||
} `json:"details"`
|
||||
}
|
||||
|
||||
// cappedBuffer keeps the first max bytes written and records truncation.
|
||||
type cappedBuffer struct {
|
||||
buf bytes.Buffer
|
||||
max int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (c *cappedBuffer) Write(p []byte) {
|
||||
rem := c.max - c.buf.Len()
|
||||
if rem <= 0 {
|
||||
if len(p) > 0 {
|
||||
c.truncated = true
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(p) > rem {
|
||||
p = p[:rem]
|
||||
c.truncated = true
|
||||
}
|
||||
c.buf.Write(p)
|
||||
}
|
||||
|
||||
// kubeExecReadLimit caps one exec WebSocket message. The API server forwards
|
||||
// output in frames of at most a few tens of KiB; a larger frame means a broken or
|
||||
// hostile peer and fails the exec before its payload is read into memory.
|
||||
const kubeExecReadLimit = 4 << 20
|
||||
|
||||
// podExec runs argv in the pod's worker container over the Kubernetes exec
|
||||
// WebSocket (channel.k8s.io v5/v4) and returns stdout, stderr and the exit code.
|
||||
func (c *kubeClient) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
|
||||
return c.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes)
|
||||
}
|
||||
|
||||
// containerExec runs argv over pods/exec. The API only takes the command as
|
||||
// command= query parameters, so the URL carries argv (and the env(1) arguments):
|
||||
// it is never put in an error or a log line, and API error bodies are dropped.
|
||||
func (c *kubeClient) containerExec(ctx context.Context, pod, container string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
|
||||
q := url.Values{}
|
||||
q.Set("container", container)
|
||||
q.Set("stdout", "true")
|
||||
q.Set("stderr", "true")
|
||||
for _, a := range argv {
|
||||
q.Add("command", a)
|
||||
}
|
||||
u := "wss" + strings.TrimPrefix(c.apiServer, "https")
|
||||
if c.plainHTTP && strings.HasPrefix(c.apiServer, "http://") {
|
||||
u = "ws" + strings.TrimPrefix(c.apiServer, "http")
|
||||
}
|
||||
u += c.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode()
|
||||
tok, err := c.token()
|
||||
if err != nil {
|
||||
return "", "", false, -1, err
|
||||
}
|
||||
dialer := websocket.Dialer{
|
||||
Proxy: nil,
|
||||
TLSClientConfig: c.tls,
|
||||
HandshakeTimeout: 30 * time.Second,
|
||||
Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"},
|
||||
}
|
||||
hdr := http.Header{}
|
||||
hdr.Set("Authorization", "Bearer "+tok)
|
||||
conn, resp, err := dialer.DialContext(ctx, u, hdr)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
ae, _ := newKubeAPIError(resp.StatusCode, resp.Body)
|
||||
resp.Body.Close()
|
||||
if ae.Code == http.StatusNotFound {
|
||||
return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod)
|
||||
}
|
||||
return "", "", false, -1, ae
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", "", false, -1, ctx.Err()
|
||||
}
|
||||
return "", "", false, -1, fmt.Errorf("%w: exec dial to pod %s failed", ErrDockerUnavailable, pod)
|
||||
}
|
||||
defer conn.Close()
|
||||
proto := conn.Subprotocol()
|
||||
if proto != "v5.channel.k8s.io" && proto != "v4.channel.k8s.io" {
|
||||
return "", "", false, -1, fmt.Errorf("exec: API server negotiated unsupported subprotocol %q", proto)
|
||||
}
|
||||
conn.SetReadLimit(kubeExecReadLimit)
|
||||
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
|
||||
defer stop()
|
||||
|
||||
out := &cappedBuffer{max: maxBytes}
|
||||
errb := &cappedBuffer{max: maxBytes}
|
||||
closed := map[byte]bool{}
|
||||
var status *kubeExecStatus
|
||||
for {
|
||||
_, msg, rerr := conn.ReadMessage()
|
||||
if rerr != nil {
|
||||
if ctx.Err() != nil {
|
||||
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, ctx.Err()
|
||||
}
|
||||
if errors.Is(rerr, websocket.ErrReadLimit) {
|
||||
return "", "", false, -1, fmt.Errorf("exec: message larger than %d bytes", kubeExecReadLimit)
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(msg) == 0 || closed[msg[0]] {
|
||||
continue
|
||||
}
|
||||
switch msg[0] {
|
||||
case 1:
|
||||
out.Write(msg[1:])
|
||||
case 2:
|
||||
errb.Write(msg[1:])
|
||||
case 3:
|
||||
var st kubeExecStatus
|
||||
if json.Unmarshal(msg[1:], &st) == nil {
|
||||
status = &st
|
||||
}
|
||||
case 255: // v5 CLOSE: [255, stream]; that stream sends nothing more.
|
||||
if proto == "v5.channel.k8s.io" && len(msg) == 2 {
|
||||
closed[msg[1]] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
res := func(code int, err error) (string, string, bool, int, error) {
|
||||
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, code, err
|
||||
}
|
||||
switch {
|
||||
case status == nil:
|
||||
return res(-1, errors.New("exec stream ended without a status"))
|
||||
case status.Status == "Success":
|
||||
return res(0, nil)
|
||||
case status.Reason == "NonZeroExitCode":
|
||||
for _, c := range status.Details.Causes {
|
||||
if n, perr := strconv.Atoi(c.Message); c.Reason == "ExitCode" && perr == nil {
|
||||
return res(n, nil)
|
||||
}
|
||||
}
|
||||
return res(-1, errors.New("exec failed without an exit code"))
|
||||
}
|
||||
// status.Message can quote the command: report only the reason.
|
||||
reason := status.Reason
|
||||
if !kubeReasonRE.MatchString(reason) {
|
||||
reason = "unknown"
|
||||
}
|
||||
return res(-1, fmt.Errorf("exec failed: %s", reason))
|
||||
}
|
||||
115
sandbox/kube_client_test.go
Normal file
115
sandbox/kube_client_test.go
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestKubeClient(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *kubeClient {
|
||||
t.Helper()
|
||||
tok := filepath.Join(t.TempDir(), "token")
|
||||
if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := newKubeClient(srv.URL, tok, "", f.ns, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestKubeClientRefusesPlainHTTPAndMissingCA(t *testing.T) {
|
||||
if _, err := newKubeClient("http://127.0.0.1:1", "tok", "", "ns", false); err == nil || !strings.Contains(err.Error(), "https://") {
|
||||
t.Fatalf("http:// API server accepted outside tests: %v", err)
|
||||
}
|
||||
if _, err := newKubeClient("https://127.0.0.1:6443", "tok", filepath.Join(t.TempDir(), "missing.crt"), "ns", false); err == nil {
|
||||
t.Fatal("https API server without a readable CA accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeClientRefusesRedirects(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
|
||||
defer target.Close()
|
||||
redir := httptest.NewServer(http.RedirectHandler(target.URL+"/api/v1/namespaces/artex/pods", http.StatusFound))
|
||||
defer redir.Close()
|
||||
f, _ := newFakeKubeAPI(t)
|
||||
c := newTestKubeClient(t, f, redir)
|
||||
if err := c.do(context.Background(), http.MethodGet, c.nsPath("pods"), nil, nil); err == nil || hits.Load() != 0 {
|
||||
t.Fatalf("redirect followed: err=%v hits=%d", err, hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeClientDeleteAndErrors(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
c := newTestKubeClient(t, f, srv)
|
||||
ctx := context.Background()
|
||||
if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A UID precondition protects a different pod reusing the name.
|
||||
if _, err := c.deleteObj(ctx, "pods", "p1", "uid-other"); !isKubeStatus(err, http.StatusConflict) || f.obj("pods", "p1") == nil {
|
||||
t.Fatalf("delete with a stale UID = %v", err)
|
||||
}
|
||||
// The API body never reaches the caller: only the status and the reason.
|
||||
f.failDelete["p1"] = true
|
||||
if _, err := c.deleteObj(ctx, "pods", "p1", ""); err == nil || strings.Contains(err.Error(), "etcd") || !strings.Contains(err.Error(), "InternalError") {
|
||||
t.Fatalf("failed delete = %v", err)
|
||||
}
|
||||
f.failDelete["p1"] = false
|
||||
uid := dig(f.obj("pods", "p1"), "metadata", "uid").(string)
|
||||
if found, err := c.deleteObj(ctx, "pods", "p1", uid); !found || err != nil || f.obj("pods", "p1") != nil {
|
||||
t.Fatalf("delete = %v %v", found, err)
|
||||
}
|
||||
if found, err := c.deleteObj(ctx, "pods", "p1", ""); found || err != nil {
|
||||
t.Fatalf("delete of a missing pod = %v %v", found, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeClientExecStream(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
c := newTestKubeClient(t, f, srv)
|
||||
ctx := context.Background()
|
||||
if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
set := func(frames [][]byte, fn func(string, []string) (string, string, int)) {
|
||||
f.mu.Lock()
|
||||
f.preFrames, f.execFn = frames, fn
|
||||
f.mu.Unlock()
|
||||
}
|
||||
// v5 CLOSE on stdout: later stdout frames are ignored.
|
||||
set([][]byte{{1, 'a'}, {255, 1}, {1, 'b'}}, func(string, []string) (string, string, int) { return "", "", 0 })
|
||||
if out, _, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "a" || code != 0 {
|
||||
t.Fatalf("v5 close: %q %d %v", out, code, err)
|
||||
}
|
||||
// A frame over the read limit fails the exec instead of being buffered.
|
||||
set([][]byte{append([]byte{1}, make([]byte, kubeExecReadLimit+1)...)}, nil)
|
||||
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "larger than") {
|
||||
t.Fatalf("oversized frame = %v", err)
|
||||
}
|
||||
// The status message (which can quote the command) is not passed on.
|
||||
set(nil, func(string, []string) (string, string, int) { return "", "", -1 })
|
||||
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"secret-arg"}, 1024); err == nil ||
|
||||
strings.Contains(err.Error(), "container not found") || strings.Contains(err.Error(), "secret-arg") {
|
||||
t.Fatalf("exec failure = %v", err)
|
||||
}
|
||||
// Exit codes come from the status channel.
|
||||
set(nil, func(string, []string) (string, string, int) { return "o", "e", 3 })
|
||||
if out, serr, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "o" || serr != "e" || code != 3 {
|
||||
t.Fatalf("exit 3: %q %q %d %v", out, serr, code, err)
|
||||
}
|
||||
// Only the channel.k8s.io v5/v4 subprotocols are accepted.
|
||||
f.mu.Lock()
|
||||
f.subprotocols = []string{"base64.channel.k8s.io"}
|
||||
f.mu.Unlock()
|
||||
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "subprotocol") {
|
||||
t.Fatalf("unsupported subprotocol = %v", err)
|
||||
}
|
||||
}
|
||||
376
sandbox/kube_fake_test.go
Normal file
376
sandbox/kube_fake_test.go
Normal file
|
|
@ -0,0 +1,376 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// fakeKubeAPI is an in-memory stand-in for the parts of the Kubernetes API the
|
||||
// sandbox client and backend use: pods, services, networkpolicies (CRUD +
|
||||
// label-selector list) and the pods/exec WebSocket.
|
||||
type fakeKubeAPI struct {
|
||||
t *testing.T
|
||||
ns string
|
||||
token string
|
||||
|
||||
mu sync.Mutex
|
||||
objs map[string]map[string]map[string]any // kind -> name -> object
|
||||
ops []string // "create pods/artex-w-..." in order
|
||||
execs [][]string // argv of every exec
|
||||
// container of every exec, parallel to execs
|
||||
execContainers []string
|
||||
nextIP int
|
||||
podMode map[string]string // pod name -> "ready" (default) | "pull-error" | "pending"
|
||||
|
||||
// execFn answers an exec; default echoes argv to stdout with exit 0. denyFn
|
||||
// answers the isolation deny probes; default reports them blocked.
|
||||
execFn, denyFn func(pod string, argv []string) (stdout, stderr string, exit int)
|
||||
// failPing makes pod list return 403.
|
||||
failPing atomic.Bool
|
||||
|
||||
rv int // resourceVersion / uid counter
|
||||
podLinger int // GETs a deleted pod stays visible (terminating)
|
||||
terminating map[string]int // pod name -> remaining GETs
|
||||
failDelete map[string]bool
|
||||
subprotocols []string // exec subprotocols the server offers
|
||||
preFrames [][]byte // raw exec frames sent before stdout
|
||||
}
|
||||
|
||||
func newFakeKubeAPI(t *testing.T) (*fakeKubeAPI, *httptest.Server) {
|
||||
f := &fakeKubeAPI{
|
||||
t: t,
|
||||
ns: "artex",
|
||||
token: "test-sa-token",
|
||||
objs: map[string]map[string]map[string]any{"pods": {}, "services": {}, "networkpolicies": {}},
|
||||
podMode: map[string]string{},
|
||||
nextIP: 10,
|
||||
|
||||
terminating: map[string]int{},
|
||||
failDelete: map[string]bool{},
|
||||
subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"},
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(f.serve))
|
||||
t.Cleanup(srv.Close)
|
||||
return f, srv
|
||||
}
|
||||
|
||||
var fakeKubePathRE = regexp.MustCompile(`^/(?:api/v1|apis/networking\.k8s\.io/v1)/namespaces/([^/]+)/(pods|services|networkpolicies)(?:/([^/]+))?(?:/(exec))?$`)
|
||||
|
||||
func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer "+f.token {
|
||||
http.Error(w, `{"reason":"Unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
m := fakeKubePathRE.FindStringSubmatch(r.URL.Path)
|
||||
if m == nil {
|
||||
http.Error(w, "no route "+r.URL.Path, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
ns, kind, name, sub := m[1], m[2], m[3], m[4]
|
||||
if ns != f.ns {
|
||||
http.Error(w, "forbidden namespace "+ns, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if sub == "exec" {
|
||||
f.serveExec(w, r, name)
|
||||
return
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
store := f.objs[kind]
|
||||
switch {
|
||||
case r.Method == http.MethodGet && name == "":
|
||||
if kind == "pods" && f.failPing.Load() {
|
||||
http.Error(w, `{"reason":"Forbidden"}`, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
sel := r.URL.Query().Get("labelSelector")
|
||||
items := []any{}
|
||||
for _, o := range store {
|
||||
if matchSelector(o, sel) {
|
||||
items = append(items, o)
|
||||
}
|
||||
}
|
||||
writeJSON(w, map[string]any{"items": items})
|
||||
case r.Method == http.MethodGet:
|
||||
o, ok := store[name]
|
||||
if n, term := f.terminating[name]; ok && kind == "pods" && term {
|
||||
if f.terminating[name] = n - 1; n <= 0 {
|
||||
delete(store, name)
|
||||
delete(f.terminating, name)
|
||||
f.ops = append(f.ops, "gone pods/"+name)
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeJSON(w, o)
|
||||
case r.Method == http.MethodPost:
|
||||
var o map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
meta := o["metadata"].(map[string]any)
|
||||
n := meta["name"].(string)
|
||||
if !dnsLabelRE.MatchString(n) {
|
||||
http.Error(w, "invalid name "+n, http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
if _, exists := store[n]; exists {
|
||||
http.Error(w, `{"reason":"AlreadyExists"}`, http.StatusConflict)
|
||||
return
|
||||
}
|
||||
f.finalize(kind, n, o)
|
||||
f.rv++
|
||||
meta["uid"], meta["resourceVersion"] = fmt.Sprintf("uid-%d", f.rv), strconv.Itoa(f.rv)
|
||||
store[n] = o
|
||||
f.ops = append(f.ops, "create "+kind+"/"+n)
|
||||
writeJSON(w, o)
|
||||
case r.Method == http.MethodPut:
|
||||
var o map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cur, exists := store[name]
|
||||
if !exists {
|
||||
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// Like the API server: an update must carry the current resourceVersion.
|
||||
meta := o["metadata"].(map[string]any)
|
||||
switch meta["resourceVersion"] {
|
||||
case nil, "":
|
||||
http.Error(w, `{"reason":"Invalid","message":"metadata.resourceVersion: must be specified for an update"}`, http.StatusUnprocessableEntity)
|
||||
return
|
||||
case dig(cur, "metadata", "resourceVersion"):
|
||||
default:
|
||||
http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict)
|
||||
return
|
||||
}
|
||||
f.rv++
|
||||
meta["uid"], meta["resourceVersion"] = dig(cur, "metadata", "uid"), strconv.Itoa(f.rv)
|
||||
store[name] = o
|
||||
f.ops = append(f.ops, "update "+kind+"/"+name)
|
||||
writeJSON(w, o)
|
||||
case r.Method == http.MethodDelete:
|
||||
o, ok := store[name]
|
||||
if !ok {
|
||||
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var opts map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&opts)
|
||||
if uid := dig(opts, "preconditions", "uid"); uid != nil && uid != dig(o, "metadata", "uid") {
|
||||
http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if kind == "pods" && dig(opts, "gracePeriodSeconds") == float64(0) {
|
||||
f.t.Errorf("pod %s force-deleted (grace 0): its containers may outlive the API object", name)
|
||||
}
|
||||
if f.failDelete[name] {
|
||||
http.Error(w, `{"reason":"InternalError","message":"etcd says no to `+name+`"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
f.ops = append(f.ops, "delete "+kind+"/"+name)
|
||||
if _, term := f.terminating[name]; kind == "pods" && f.podLinger > 0 {
|
||||
if !term {
|
||||
f.terminating[name] = f.podLinger
|
||||
o["metadata"].(map[string]any)["deletionTimestamp"] = "now"
|
||||
}
|
||||
writeJSON(w, map[string]any{"status": "Success"})
|
||||
return
|
||||
}
|
||||
delete(store, name)
|
||||
writeJSON(w, map[string]any{"status": "Success"})
|
||||
default:
|
||||
http.Error(w, "method", http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
// finalize fills in server-side fields (pod status, service ClusterIP).
|
||||
func (f *fakeKubeAPI) finalize(kind, name string, o map[string]any) {
|
||||
switch kind {
|
||||
case "services":
|
||||
f.nextIP++
|
||||
o["spec"].(map[string]any)["clusterIP"] = fmt.Sprintf("10.43.0.%d", f.nextIP)
|
||||
case "pods":
|
||||
switch f.podMode[name[:max(0, len(name)-7)]] { // keyed by name without the generation
|
||||
case "pull-error":
|
||||
o["status"] = map[string]any{"phase": "Pending", "containerStatuses": []any{map[string]any{
|
||||
"ready": false, "state": map[string]any{"waiting": map[string]any{"reason": "ImagePullBackOff", "message": "pull access denied"}},
|
||||
}}}
|
||||
case "pending":
|
||||
o["status"] = map[string]any{"phase": "Pending"}
|
||||
default:
|
||||
o["status"] = map[string]any{"phase": "Running", "containerStatuses": []any{map[string]any{"ready": true, "state": map[string]any{}}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) setPodPhase(name, phase string, ready bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if p := f.objs["pods"][name]; p != nil {
|
||||
p["status"] = map[string]any{"phase": phase, "containerStatuses": []any{map[string]any{"ready": ready, "state": map[string]any{}}}}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) serveExec(w http.ResponseWriter, r *http.Request, pod string) {
|
||||
f.mu.Lock()
|
||||
_, ok := f.objs["pods"][pod]
|
||||
f.mu.Unlock()
|
||||
if !ok {
|
||||
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if c := q.Get("container"); c != kubeWorkerName && c != kubeProxyName {
|
||||
http.Error(w, "unexpected container "+c, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if q.Get("stdout") != "true" || q.Get("stderr") != "true" || q.Has("stdin") || q.Has("tty") {
|
||||
http.Error(w, "unexpected exec query "+r.URL.RawQuery, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
argv := q["command"]
|
||||
f.mu.Lock()
|
||||
f.execs = append(f.execs, argv)
|
||||
f.execContainers = append(f.execContainers, q.Get("container"))
|
||||
fn, pre := f.execFn, f.preFrames
|
||||
if strings.Contains(strings.Join(argv, " "), kubeProbeBlocked) {
|
||||
fn = f.denyFn
|
||||
if fn == nil {
|
||||
fn = func(string, []string) (string, string, int) { return kubeProbeBlocked + "\n", "", 0 }
|
||||
}
|
||||
}
|
||||
up := websocket.Upgrader{Subprotocols: f.subprotocols}
|
||||
f.mu.Unlock()
|
||||
conn, err := up.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
for _, fr := range pre {
|
||||
if conn.WriteMessage(websocket.BinaryMessage, fr) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
stdout, stderr, exit := strings.Join(argv, " "), "", 0
|
||||
if fn != nil {
|
||||
stdout, stderr, exit = fn(pod, argv)
|
||||
}
|
||||
send := func(ch byte, data string) {
|
||||
// Split large payloads into frames like the API server does.
|
||||
for len(data) > 0 {
|
||||
n := min(len(data), 32*1024)
|
||||
_ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{ch}, data[:n]...))
|
||||
data = data[n:]
|
||||
}
|
||||
}
|
||||
send(1, stdout)
|
||||
send(2, stderr)
|
||||
var st map[string]any
|
||||
switch {
|
||||
case exit == 0:
|
||||
st = map[string]any{"status": "Success"}
|
||||
case exit < 0:
|
||||
st = map[string]any{"status": "Failure", "reason": "InternalError", "message": "container not found"}
|
||||
default:
|
||||
st = map[string]any{"status": "Failure", "reason": "NonZeroExitCode", "message": "command terminated with non-zero exit code",
|
||||
"details": map[string]any{"causes": []any{map[string]any{"reason": "ExitCode", "message": strconv.Itoa(exit)}}}}
|
||||
}
|
||||
raw, _ := json.Marshal(st)
|
||||
_ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{3}, raw...))
|
||||
_ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||
}
|
||||
|
||||
var dnsLabelRE = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`)
|
||||
|
||||
func matchSelector(o map[string]any, sel string) bool {
|
||||
if sel == "" {
|
||||
return true
|
||||
}
|
||||
labels, _ := o["metadata"].(map[string]any)["labels"].(map[string]any)
|
||||
for _, term := range strings.Split(sel, ",") {
|
||||
k, v, _ := strings.Cut(term, "=")
|
||||
if labels[k] != v {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) obj(kind, name string) map[string]any {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.objs[kind][name]
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) count(kind string) int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.objs[kind])
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) opsSnapshot() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.ops...)
|
||||
}
|
||||
|
||||
func (f *fakeKubeAPI) lastExec() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.execs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return f.execs[len(f.execs)-1]
|
||||
}
|
||||
|
||||
// dig walks nested map/slice JSON values: dig(o, "spec", "containers", 0, "name").
|
||||
func dig(v any, path ...any) any {
|
||||
for _, p := range path {
|
||||
switch k := p.(type) {
|
||||
case string:
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
v = m[k]
|
||||
case int:
|
||||
s, ok := v.([]any)
|
||||
if !ok || k >= len(s) {
|
||||
return nil
|
||||
}
|
||||
v = s[k]
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func envOf(container any) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, e := range dig(container, "env").([]any) {
|
||||
out[e.(map[string]any)["name"].(string)] = e.(map[string]any)["value"].(string)
|
||||
}
|
||||
return out
|
||||
}
|
||||
188
sandbox/kube_test.go
Normal file
188
sandbox/kube_test.go
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, mods ...func(*KubeConfig)) *KubernetesBackend {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
tok := filepath.Join(dir, "token")
|
||||
if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := KubeConfig{
|
||||
APIServer: srv.URL,
|
||||
TokenPath: tok,
|
||||
Namespace: f.ns,
|
||||
DataClaim: "artex-data",
|
||||
WorkerImage: "artex-worker:test",
|
||||
ProxyImage: "artex-egress-proxy:test",
|
||||
WorkspaceRoot: filepath.Join(dir, "tasks"),
|
||||
AuditRoot: filepath.Join(dir, "audit"),
|
||||
PodReadyTimeout: 3 * time.Second,
|
||||
allowPlainHTTP: true,
|
||||
}
|
||||
for _, m := range mods {
|
||||
m(&cfg)
|
||||
}
|
||||
b, err := NewKubernetesBackend(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("NewKubernetesBackend: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func execReq(argv ...string) ExecRequest {
|
||||
req := ExecRequest{Argv: argv}
|
||||
if err := ValidateExecRequest(&req); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
func TestKubeDeleteRemovesPoliciesOnlyAfterPodsAreGone(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
b := newTestKubeBackend(t, f, srv)
|
||||
ctx := context.Background()
|
||||
f.podLinger = 3 // a deleted pod stays visible (terminating) for 3 GETs
|
||||
for _, id := range []string{"t1", "t2"} {
|
||||
if _, err := b.Exec(ctx, id, execReq("true")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
mark := len(f.opsSnapshot())
|
||||
if err := b.Delete(ctx, "t1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := kubeTaskHash("t1")
|
||||
ops := f.opsSnapshot()[mark:]
|
||||
firstPol, gone := -1, 0
|
||||
for i, op := range ops {
|
||||
if strings.HasPrefix(op, "gone pods/") {
|
||||
gone++
|
||||
}
|
||||
if strings.HasPrefix(op, "delete networkpolicies/") && firstPol < 0 {
|
||||
firstPol = i
|
||||
if gone != 2 {
|
||||
t.Fatalf("policy deleted while a pod still ran: %v", ops)
|
||||
}
|
||||
}
|
||||
}
|
||||
if firstPol < 0 || f.obj("networkpolicies", "artex-p-"+h) != nil || f.count("pods") != 2 {
|
||||
t.Fatalf("delete incomplete: %v", ops)
|
||||
}
|
||||
|
||||
// A pod that cannot be deleted keeps its policies, and the task stays tracked.
|
||||
h2 := kubeTaskHash("t2")
|
||||
f.failDelete[b.getTask("t2").workerPod] = true
|
||||
err := b.Delete(ctx, "t2")
|
||||
if err == nil || strings.Contains(err.Error(), "etcd") {
|
||||
t.Fatalf("failed pod delete = %v (want error without the API body)", err)
|
||||
}
|
||||
if f.obj("networkpolicies", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-p-"+h2) == nil || b.WorkerCount() != 1 {
|
||||
t.Fatal("policies removed although the worker pod is still running")
|
||||
}
|
||||
f.failDelete = map[string]bool{}
|
||||
if err := b.Delete(ctx, "t2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.count("pods")+f.count("services")+f.count("networkpolicies") != 0 {
|
||||
t.Fatalf("objects left: %v", f.opsSnapshot())
|
||||
}
|
||||
if err := b.Delete(ctx, "t2"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("delete of nothing = %v", err)
|
||||
}
|
||||
b.mu.Lock()
|
||||
locks := len(b.locks)
|
||||
b.mu.Unlock()
|
||||
if locks != 0 {
|
||||
t.Fatalf("%d task locks left after Delete", locks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeApplyPolicyUpdatesWithResourceVersionOnlyOwnPolicy(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
b := newTestKubeBackend(t, f, srv)
|
||||
ctx := context.Background()
|
||||
h := kubeTaskHash("t1")
|
||||
if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The fake enforces the API server rule: an update without resourceVersion is 422.
|
||||
pol := b.workerPolicyObj("artex-w-"+h, &kubeTask{taskID: "t1", hash: h})
|
||||
if err := b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/artex-w-"+h, pol, nil); !isKubeStatus(err, http.StatusUnprocessableEntity) {
|
||||
t.Fatalf("PUT without resourceVersion = %v", err)
|
||||
}
|
||||
rv := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion")
|
||||
if err := b.applyPolicy(ctx, pol); err != nil {
|
||||
t.Fatalf("409 -> PUT: %v", err)
|
||||
}
|
||||
if got := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion"); got == rv {
|
||||
t.Fatal("policy not replaced")
|
||||
}
|
||||
|
||||
// A same-named policy without the runner's labels is never overwritten, and the
|
||||
// failed setup leaves nothing of its own behind.
|
||||
h2 := kubeTaskHash("t2")
|
||||
f.mu.Lock()
|
||||
f.objs["networkpolicies"]["artex-p-"+h2] = map[string]any{
|
||||
"metadata": map[string]any{"name": "artex-p-" + h2, "labels": map[string]any{"app": "x"}, "resourceVersion": "1"},
|
||||
"spec": map[string]any{"podSelector": map[string]any{"foreign": true}}}
|
||||
f.mu.Unlock()
|
||||
_, err := b.Exec(ctx, "t2", execReq("true"))
|
||||
if err == nil || !strings.Contains(err.Error(), "not managed by the runner") {
|
||||
t.Fatalf("foreign policy = %v", err)
|
||||
}
|
||||
if dig(f.obj("networkpolicies", "artex-p-"+h2), "spec", "podSelector", "foreign") != true || f.obj("networkpolicies", "artex-w-"+h2) != nil {
|
||||
t.Fatal("foreign policy replaced or own policy left behind")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeDeniedCIDRsExtendDefaults(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
cfg := newTestKubeBackend(t, f, srv).cfg
|
||||
cfg.ProxyDeniedCIDRs = []string{"198.51.100.7/24", "10.0.0.0/8"}
|
||||
nb, err := NewKubernetesBackend(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Join(append(slices.Clone(DefaultProxyDeniedCIDRs), "198.51.100.0/24"), ",")
|
||||
if got := strings.Join(nb.cfg.ProxyDeniedCIDRs, ","); got != want {
|
||||
t.Fatalf("denied CIDRs = %s\nwant %s", got, want)
|
||||
}
|
||||
cfg.ProxyDeniedCIDRs = []string{"fc00::/7"}
|
||||
if _, err := NewKubernetesBackend(cfg); err == nil {
|
||||
t.Fatal("IPv6 denied CIDR accepted")
|
||||
}
|
||||
// An empty label map must not select every pod in the DNS namespace.
|
||||
cfg.ProxyDeniedCIDRs, cfg.DNSPodLabels = nil, map[string]string{}
|
||||
if nb, err = NewKubernetesBackend(cfg); err != nil || nb.cfg.DNSPodLabels["k8s-app"] != "kube-dns" {
|
||||
t.Fatalf("empty DNS labels: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKubeCancelledExecKeepsTask(t *testing.T) {
|
||||
f, srv := newFakeKubeAPI(t)
|
||||
b := newTestKubeBackend(t, f, srv)
|
||||
if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A failed pod lookup (here a cancelled request) says nothing about the pods:
|
||||
// only this exec fails, and it is not reported as the runner being unavailable.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := b.Exec(ctx, "t1", execReq("true"))
|
||||
if !errors.Is(err, context.Canceled) || errors.Is(err, ErrDockerUnavailable) || f.count("pods")+f.count("networkpolicies") != 4 || b.WorkerCount() != 1 {
|
||||
t.Fatalf("cancelled exec = %v; %d pods, %d tasks", err, f.count("pods"), b.WorkerCount())
|
||||
}
|
||||
}
|
||||
|
|
@ -133,6 +133,9 @@ type EgressPolicy struct {
|
|||
Resolver func(ctx context.Context, host string) ([]netip.Addr, error)
|
||||
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
Logger *EgressLogger
|
||||
// Never lists prefixes denied even when a scope CIDR covers them (the
|
||||
// Kubernetes backend passes cluster and metadata ranges here).
|
||||
Never []netip.Prefix
|
||||
}
|
||||
|
||||
// NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries.
|
||||
|
|
@ -198,8 +201,21 @@ func (p *EgressPolicy) domainAllowed(host string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func (p *EgressPolicy) inNever(addr netip.Addr) bool {
|
||||
addr = addr.Unmap()
|
||||
for _, pfx := range p.Never {
|
||||
if pfx.Contains(addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *EgressPolicy) ipInScopeCIDR(addr netip.Addr) bool {
|
||||
addr = addr.Unmap()
|
||||
if p.inNever(addr) {
|
||||
return false
|
||||
}
|
||||
for _, pfx := range p.CIDRs {
|
||||
if pfx.Contains(addr) {
|
||||
return true
|
||||
|
|
@ -283,7 +299,7 @@ func (p *EgressPolicy) ResolveAndCheck(ctx context.Context, host string) (netip.
|
|||
if p.ipInScopeCIDR(addr) {
|
||||
return addr, nil
|
||||
}
|
||||
if isDefaultDeniedAddr(addr) {
|
||||
if isDefaultDeniedAddr(addr) || p.inNever(addr) {
|
||||
continue
|
||||
}
|
||||
return addr, nil
|
||||
|
|
@ -381,7 +397,7 @@ func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
|
|||
}
|
||||
for _, addr := range addrs {
|
||||
addr = addr.Unmap()
|
||||
if !p.ipInScopeCIDR(addr) && isDefaultDeniedAddr(addr) {
|
||||
if !p.ipInScopeCIDR(addr) && (isDefaultDeniedAddr(addr) || p.inNever(addr)) {
|
||||
return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue