Files
ARTEX/sandbox/policy.go
Marco Azarmaneche 1c262d3af6 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 (kube_client.go) with no
container runtime socket. Per-task NetworkPolicies are applied before the pods
and removed after them; the runner proves they are in effect before the first
command, runs commands through pods/exec under env -i and artex-exec-wrap, and
re-adopts task pods after a restart. Unit tests run against a fake API
server; this commit keeps the tests for the review items, and the other
unit tests and the live cluster test follow in a separate PR.

Changes since the first review (502e42d):

NetworkPolicies and scope:
- Delete and failed setups delete the task's pods and wait until they are
  gone before removing the service and, last, the policies. If a pod
  cannot be deleted, the policies stay and the task stays tracked. Pods
  get a 1s grace, not 0: a zero grace removes the API object before the
  kubelet has stopped the containers.
- applyPolicy replaces an existing policy only when it carries the
  runner's labels for the same task, and sends its resourceVersion.
- ARTEX_KUBE_PROXY_DENIED_CIDRS adds to DefaultProxyDeniedCIDRs instead
  of replacing it. An empty DNSPodLabels map falls back to k8s-app=kube-dns.
- No scope opens the cluster: ARTEX_KUBE_CLUSTER_CIDRS (pod, service and
  node CIDRs) plus metadata, loopback, link-local and the API server
  address form a never-reachable list. Each scope ipBlock gets them as
  except (a block inside one is dropped), the public rule excepts them,
  and the proxy refuses them through ARTEX_NEVER_CIDRS (new
  EgressPolicy.Never; Docker does not set it). Without
  ARTEX_KUBE_CLUSTER_CIDRS, scope CIDRs overlapping private, loopback or
  link-local ranges are dropped (logged), so the scope fails closed.
- Isolation does not rely on an outside default-deny policy: every task
  pod has its own Ingress+Egress policy, adopted tasks get theirs applied
  again, and before the first command the runner checks that the worker
  reaches neither the API server nor a public address directly and that
  the proxy cannot reach the API server; setup fails otherwise. A scope
  change replaces the worker too, so the checks run in a worker no
  command has used.
- The proxy pod uses ndots 1, so scope names are not first looked up as
  cluster names.

Exec:
- The worker base env comes after the request env in the env(1) argv.
  Refusing PATH, proxy and loader variables (LD_*, BASH_ENV, ...) in a
  request is a separate change to the shared ValidateEnv, which also
  covers the Docker backend.
- Any exec error after the stream started (cancel, broken stream, read
  limit) kills the worker's processes, and so does a wrapper timeout
  (exit 124 after at least timeout_ms, the Docker rule).
- Exec, Kill and Delete validate the task ID; Exec validates the request.

Concurrency and cleanup:
- Kill takes the task lock; stored tasks are copied, never changed in
  place. A Kill caused by an exec acts only on the worker pod UID that
  ran it; pod deletes carry a UID precondition.
- An exec queued behind a Delete returns ErrNotFound instead of creating
  the task again. Per-task locks are reference counted and removed.
- A failed setup removes what it created, found by label (a foreign
  object with the same name stays). Delete returns ErrNotFound only when
  no object of the task exists.
- Recover adopts only pods named artex-w-/artex-p-<hash> and services
  with a real ClusterIP; adopted tasks are re-checked on first use.
- Scope hash: full SHA-256; task object names use 128 bits.

Config: http:// API servers are refused, the tasks and audit sub paths
must not be ".", equal or nested, and NewKubernetesBackend documents what
the deployment must provide (PID limits, restricted namespace, quotas,
shared volume, shared Kill).
2026-12-03 03:03:09 +02:00

406 lines
11 KiB
Go

package sandbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
// Metadata and reserved private prefixes denied by default unless explicitly
// listed in ARTEX_SCOPE_CIDRS (CONTRACT.md §§1, 5).
var defaultDeniedPrefixes = mustParsePrefixes([]string{
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"100.100.100.200/32", // Alibaba Cloud metadata
"127.0.0.0/8",
"168.63.129.16/32", // Azure wireserver / metadata
"169.254.0.0/16", // AWS/GCP/Azure link-local & 169.254.169.254 metadata
"172.16.0.0/12",
"192.168.0.0/16",
"224.0.0.0/4",
"240.0.0.0/4",
"::/128",
"::1/128",
"fc00::/7",
"fe80::/10",
"fd00:ec2::254/128", // AWS IPv6 IMDS
"ff00::/8",
})
func mustParsePrefixes(raw []string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(raw))
for _, s := range raw {
out = append(out, netip.MustParsePrefix(s))
}
return out
}
// EgressLogEntry is one JSON line logged per connection per CONTRACT.md §5.
type EgressLogEntry struct {
TaskID string `json:"task_id"`
TS string `json:"ts"`
Host string `json:"host"`
Port int `json:"port"`
ResolvedIP string `json:"resolved_ip"`
Protocol string `json:"protocol"`
Decision string `json:"decision"`
Bytes int64 `json:"bytes"`
}
// EgressLogger writes JSONL connection records to stdout and optionally a per-task file.
type EgressLogger struct {
mu sync.Mutex
stdout io.Writer
file *os.File
taskID string
}
// NewEgressLogger creates a logger writing to stdout (or w) and optionally logPath.
func NewEgressLogger(taskID, logPath string, stdout io.Writer) *EgressLogger {
if stdout == nil {
stdout = os.Stdout
}
l := &EgressLogger{taskID: taskID, stdout: stdout}
if strings.TrimSpace(logPath) != "" {
_ = os.MkdirAll(filepath.Dir(logPath), 0o755)
if f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644); err == nil {
l.file = f
}
}
return l
}
// Close closes the underlying log file if open.
func (l *EgressLogger) Close() {
if l == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
if l.file != nil {
_ = l.file.Close()
l.file = nil
}
}
// Log emits one JSONL line to both stdout and the per-task egress.jsonl file.
func (l *EgressLogger) Log(e EgressLogEntry) {
if l == nil {
return
}
if e.TaskID == "" {
e.TaskID = l.taskID
}
if e.TS == "" {
e.TS = time.Now().UTC().Format(time.RFC3339Nano)
}
raw, err := json.Marshal(e)
if err != nil {
return
}
raw = append(raw, '\n')
l.mu.Lock()
defer l.mu.Unlock()
if l.stdout != nil {
_, _ = l.stdout.Write(raw)
}
if l.file != nil {
_, _ = l.file.Write(raw)
}
}
// EgressPolicy enforces per-task domain/CIDR allowlists with DNS pinning.
// egressScopeHint makes sandbox egress denials non-silent regarding target-gate approvals.
const egressScopeHint = " (approve target in Task Scope; target-gate approval only clears the tool gate and does not widen worker egress)"
type EgressPolicy struct {
TaskID string
Domains []string
CIDRs []netip.Prefix
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.
func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogger) (*EgressPolicy, error) {
p := &EgressPolicy{
TaskID: taskID,
Logger: logger,
}
for _, d := range domains {
d = strings.ToLower(strings.TrimSpace(d))
d = strings.TrimPrefix(d, "*.")
d = strings.TrimPrefix(d, ".")
d = strings.TrimSuffix(d, ".")
if d != "" {
p.Domains = append(p.Domains, d)
}
}
for _, raw := range cidrs {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
if strings.Contains(raw, "/") {
pfx, err := netip.ParsePrefix(raw)
if err != nil {
return nil, fmt.Errorf("invalid scope CIDR %q: %w", raw, err)
}
p.CIDRs = append(p.CIDRs, pfx.Masked())
} else {
addr, err := netip.ParseAddr(raw)
if err != nil {
return nil, fmt.Errorf("invalid scope IP %q: %w", raw, err)
}
addr = addr.Unmap()
p.CIDRs = append(p.CIDRs, netip.PrefixFrom(addr, addr.BitLen()))
}
}
return p, nil
}
// ParseCSV splits a comma-separated environment value into trimmed non-empty items.
func ParseCSV(raw string) []string {
var out []string
for _, part := range strings.Split(raw, ",") {
part = strings.TrimSpace(part)
if part != "" {
out = append(out, part)
}
}
return out
}
func (p *EgressPolicy) domainAllowed(host string) bool {
h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
if h == "" {
return false
}
for _, suffix := range p.Domains {
if h == suffix || strings.HasSuffix(h, "."+suffix) {
return true
}
}
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
}
}
return false
}
func isDefaultDeniedAddr(addr netip.Addr) bool {
addr = addr.Unmap()
// Deny all IPv6 unless explicitly in ARTEX_SCOPE_CIDRS (CONTRACT.md §5).
if addr.Is6() {
return true
}
for _, pfx := range defaultDeniedPrefixes {
if pfx.Contains(addr) {
return true
}
}
return false
}
type resolverCtxKey struct{}
// WithResolver returns ctx carrying fn: a policy without its own Resolver
// resolves names through fn for calls made with ctx (or a context derived from
// it). It is the seam tests use to answer lookups without the network, for the
// policies the panel tools build themselves; production code does not set it.
func WithResolver(ctx context.Context, fn func(ctx context.Context, host string) ([]netip.Addr, error)) context.Context {
return context.WithValue(ctx, resolverCtxKey{}, fn)
}
func (p *EgressPolicy) resolve(ctx context.Context, host string) ([]netip.Addr, error) {
if p.Resolver != nil {
return p.Resolver(ctx, host)
}
if fn, ok := ctx.Value(resolverCtxKey{}).(func(ctx context.Context, host string) ([]netip.Addr, error)); ok && fn != nil {
return fn(ctx, host)
}
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
if err != nil {
return nil, err
}
out := make([]netip.Addr, 0, len(ips))
for _, ip := range ips {
out = append(out, ip.Unmap())
}
return out, nil
}
// ResolveAndCheck validates host against the allowlist, resolves DNS once if host is
// a domain name, checks every resolved IP against default-deny/private/metadata/IPv6
// rules, and returns the pinned IP address to dial directly (zero rebinding window).
func (p *EgressPolicy) ResolveAndCheck(ctx context.Context, host string) (netip.Addr, error) {
h := strings.TrimSpace(host)
h = strings.TrimPrefix(strings.TrimSuffix(h, "]"), "[")
if h == "" {
return netip.Addr{}, errors.New("egress denied: empty host")
}
// Literal IP target: allowed ONLY if explicitly in ARTEX_SCOPE_CIDRS.
if addr, err := netip.ParseAddr(h); err == nil {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) {
return addr, fmt.Errorf("egress denied: IP %s is not in task scope CIDRs%s", addr, egressScopeHint)
}
return addr, nil
}
// Domain target: must match ARTEX_SCOPE_DOMAINS.
if !p.domainAllowed(h) {
return netip.Addr{}, fmt.Errorf("egress denied: domain %q is not in task scope%s", h, egressScopeHint)
}
addrs, err := p.resolve(ctx, h)
if err != nil || len(addrs) == 0 {
return netip.Addr{}, fmt.Errorf("egress denied: dns lookup failed for %q: %v", h, err)
}
for _, addr := range addrs {
addr = addr.Unmap()
if p.ipInScopeCIDR(addr) {
return addr, nil
}
if isDefaultDeniedAddr(addr) || p.inNever(addr) {
continue
}
return addr, nil
}
return addrs[0].Unmap(), fmt.Errorf("egress denied: %q resolved only to disallowed/private/IPv6 address %s", h, addrs[0].Unmap())
}
// DialPinned enforces the policy, pins the resolved IP, and dials directly to that IP.
func (p *EgressPolicy) DialPinned(ctx context.Context, host string, port int, protocol string) (net.Conn, netip.Addr, error) {
if port <= 0 || port > 65535 {
p.logDecision(host, port, "", protocol, "deny", 0)
return nil, netip.Addr{}, fmt.Errorf("egress denied: invalid port %d", port)
}
addr, err := p.ResolveAndCheck(ctx, host)
if err != nil {
ipStr := ""
if addr.IsValid() {
ipStr = addr.String()
}
p.logDecision(host, port, ipStr, protocol, "deny", 0)
return nil, addr, err
}
target := net.JoinHostPort(addr.String(), strconv.Itoa(port))
dialFn := p.Dialer
if dialFn == nil {
d := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}
dialFn = d.DialContext
}
conn, err := dialFn(ctx, "tcp", target)
if err != nil {
p.logDecision(host, port, addr.String(), protocol, "error", 0)
return nil, addr, err
}
return conn, addr, nil
}
func (p *EgressPolicy) logDecision(host string, port int, ip, protocol, decision string, n int64) {
if p.Logger != nil {
p.Logger.Log(EgressLogEntry{
TaskID: p.TaskID,
Host: host,
Port: port,
ResolvedIP: ip,
Protocol: protocol,
Decision: decision,
Bytes: n,
})
}
}
// CheckURL validates a navigation/fetch URL against the task scope allowlist.
// Only http/https/ws/wss schemes are permitted. Literal IPs must match
// ScopeCIDRs (blocking IMDS, loopback, RFC1918, and arbitrary non-scope IPs).
// Domains must match ScopeDomains and must resolve, and every resolved address
// must be allowed: a lookup error or an empty answer is a denial, and so is a
// name answering a public address next to a private/IMDS/IPv6 one. CheckURL
// pins nothing, and the connection may be made by someone else (a proxy, the
// browser) that picks any of the answers.
func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
return errors.New("egress denied: empty URL")
}
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("egress denied: invalid URL %q: %w", rawURL, err)
}
scheme := strings.ToLower(strings.TrimSpace(u.Scheme))
switch scheme {
case "http", "https", "ws", "wss":
default:
return fmt.Errorf("egress denied: scheme %q is not allowed in sandbox mode", scheme)
}
host := strings.TrimSpace(u.Hostname())
if host == "" {
return fmt.Errorf("egress denied: URL %q has no host", rawURL)
}
// Literal IP target: allowed ONLY if explicitly in ScopeCIDRs.
if addr, err := netip.ParseAddr(host); err == nil {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) {
return fmt.Errorf("egress denied: IP %s is not in task scope CIDRs%s", addr, egressScopeHint)
}
return nil
}
if !p.domainAllowed(host) {
return fmt.Errorf("egress denied: domain %q is not in task scope%s", host, egressScopeHint)
}
addrs, err := p.resolve(ctx, host)
if err != nil {
return fmt.Errorf("egress denied: dns lookup failed for %q: %v", host, err)
}
if len(addrs) == 0 {
return fmt.Errorf("egress denied: dns lookup for %q returned no addresses", host)
}
for _, addr := range addrs {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) && (isDefaultDeniedAddr(addr) || p.inNever(addr)) {
return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr)
}
}
return nil
}