Merge pull request #895 from thecorporatetractor/fix/sandbox-reserved-env

fix(sandbox): refuse exec env names that override the proxy, PATH or the loader
This commit is contained in:
BaaRai 2026-12-03 14:00:01 +01:00 • committed by GitHub
commit 4fda8db604
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 163 additions and 5 deletions

View file

@ -37,6 +37,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **The goal decomposer caches its system prompt**: `DecomposeGoalsWithProvider` built its session without a `DynamicBoundary`, and Norma reads 0 as "no cache breakpoint", so each turn of goal decomposition resent its tools and system prompt uncached on Anthropic profiles. It now sets 1, the same breakpoint #836 gave the other agents without global MCP tools.
- **Exec requests can no longer set the worker's proxy, `PATH` or interpreter start-up variables, or smuggle scope entries.** The runner accepted any non-secret env name in an exec request. It now refuses with 400 the proxy variables (any case), `PATH`, `LD_*`, and variables that make a shell or interpreter run extra code (`BASH_ENV`, `ENV`, `SHELLOPTS`, `PS4`, `NODE_OPTIONS`, `PERL5OPT`, `PYTHONSTARTUP` and similar); the panel drops them from the env it forwards. Scope entries are checked one by one and passed on in canonical form: an entry that is not a valid domain, prefix or address, or an IPv6 address with a zone, is dropped and logged with the task, never split at a comma, so `1.2.3.4/32,10.0.0.0/8` or `fe80::1%x,0.0.0.0/0` can no longer add scope nobody approved. Scope lists are capped at 8,192 entries and 120 KiB each.
- **Docker updates reuse the runtime image layers again**: the runtime stage declared `ARTEX_VERSION` and `ARTEX_REVISION` before its first `RUN`, and a declared build argument is part of the cache key of every later `RUN`. `update.sh` writes the new commit into `.env`, so each update reinstalled apt packages, bbot, Playwright and the rest of the stage (6 to 11 minutes per update) and left another copy of about 8 GB of layers in the build cache. The arguments and the `LABEL` that uses them now come at the end of the stage. The Go, Next.js and npm caches are also kept between builds as BuildKit cache mounts, so a code change recompiles only what changed: an update rebuild drops to well under a minute.
- **A command that exits 124 no longer removes the Docker worker.** The runner treated every exit code 124 as its own timeout and removed the task's worker container, which also stopped the task's background jobs. Commands such as `timeout 5 curl ...` exit 124 by themselves. An exit 124 now counts as a runner timeout only when the command ran for at least `timeout_ms`.
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.

View file

@ -107,6 +107,12 @@ func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if d := req.droppedScope; len(d) > 0 {
if len(d) > 20 {
d = append(d[:20:20], fmt.Sprintf("... %d more", len(req.droppedScope)-20))
}
log.Printf("[runner] task %s: dropped %d invalid scope entries: %q", taskID, len(req.droppedScope), d)
}
res, err := rs.backend.Exec(r.Context(), taskID, req)
if err != nil {
rs.writeBackendErr(w, err)

View file

@ -73,6 +73,10 @@ type ExecRequest struct {
Env map[string]string `json:"env,omitempty"`
ScopeDomains []string `json:"scope_domains,omitempty"`
ScopeCIDRs []string `json:"scope_cidrs,omitempty"`
// droppedScope holds the scope entries ValidateExecRequest dropped as
// invalid, for the runner's log.
droppedScope []string
}
// ExecResponse is the response body for POST /v1/tasks/{id}/exec.

View file

@ -2,6 +2,7 @@ package sandbox
import (
"fmt"
"net/netip"
"path"
"regexp"
"strings"
@ -10,6 +11,16 @@ import (
var (
taskIDRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`)
envNameRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`)
// A scope domain: labels of letters, digits, '-' or '_', optionally "*." first.
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
)
// MaxScopeEntries caps scope_domains and scope_cidrs (each) in one request, and
// MaxScopeBytes their comma-joined length: the egress proxy gets each list as one
// environment string, which Linux limits to 128 KiB.
const (
MaxScopeEntries = 8192
MaxScopeBytes = 120 << 10
)
// ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths.
@ -41,14 +52,31 @@ func IsForbiddenEnvName(name string) bool {
return false
}
// ValidateEnv rejects forbidden variable names, invalid names, NUL bytes, or values > 8192 bytes.
// isReservedEnvName reports whether name is set by the worker itself (proxy
// routing, PATH) or makes a shell, the loader or Python run code the command did
// not ask for (LD_*, BASH_ENV, ENV, GCONV_PATH, PYTHONPATH). A request may not
// set these in either backend.
func isReservedEnvName(name string) bool {
u := strings.ToUpper(name)
switch u {
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "PROMPT_COMMAND",
"GCONV_PATH", "GLIBC_TUNABLES", "PYTHONPATH", "PYTHONSTARTUP", "PYTHONHOME",
"NODE_OPTIONS", "PERL5OPT", "PERL5LIB", "RUBYOPT", "JAVA_TOOL_OPTIONS",
"GIT_SSH_COMMAND", "GIT_CONFIG_PARAMETERS":
return true
}
return strings.HasPrefix(u, "LD_")
}
// ValidateEnv rejects forbidden or reserved variable names, invalid names, NUL bytes, or values > 8192 bytes.
// Per CONTRACT.md §3 this is always a 400 validation error, never a silent drop.
func ValidateEnv(env map[string]string) error {
for k, v := range env {
if !envNameRE.MatchString(k) {
return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k)
}
if IsForbiddenEnvName(k) {
if IsForbiddenEnvName(k) || isReservedEnvName(k) {
return fmt.Errorf("%w: forbidden env variable %q", ErrBadRequest, k)
}
if len(v) > MaxEnvValueBytes {
@ -67,12 +95,12 @@ func FilterPanelEnv(kvs []string) map[string]string {
out := make(map[string]string)
for _, kv := range kvs {
k, v, ok := strings.Cut(kv, "=")
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
continue
}
// Never override worker proxy or home variables from panel process env.
// Never override worker home variables from panel process env.
switch strings.ToUpper(k) {
case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY":
case "HOME", "XDG_CACHE_HOME":
continue
}
out[k] = v
@ -108,5 +136,63 @@ func ValidateExecRequest(req *ExecRequest) error {
}
req.Workdir = clean
}
if len(req.ScopeDomains) > MaxScopeEntries || len(req.ScopeCIDRs) > MaxScopeEntries {
return fmt.Errorf("%w: more than %d scope entries", ErrBadRequest, MaxScopeEntries)
}
var d1, d2 []string
req.ScopeDomains, d1 = filterScope(req.ScopeDomains, canonScopeDomain)
req.ScopeCIDRs, d2 = filterScope(req.ScopeCIDRs, canonScopeCIDR)
req.droppedScope = append(d1, d2...)
if joinedLen(req.ScopeDomains) > MaxScopeBytes || joinedLen(req.ScopeCIDRs) > MaxScopeBytes {
return fmt.Errorf("%w: scope lists longer than %d bytes", ErrBadRequest, MaxScopeBytes)
}
return ValidateEnv(req.Env)
}
// filterScope keeps the canonical form of each entry canon accepts and returns
// the dropped ones. Backends join scope entries with commas into the egress
// proxy's environment, so only the canonical form (which never holds a comma,
// space or IPv6 zone) is passed on, and an invalid entry is dropped whole,
// never split. The panel builds scope from free-text fields, so one odd entry
// must not fail every command: a narrower scope fails closed at the
// deny-by-default proxy.
func filterScope(entries []string, canon func(string) (string, bool)) (kept, dropped []string) {
kept = entries[:0:0]
for _, e := range entries {
if c, ok := canon(e); ok {
kept = append(kept, c)
} else {
dropped = append(dropped, e)
}
}
return kept, dropped
}
func joinedLen(entries []string) int {
n := 0
for _, e := range entries {
n += len(e) + 1
}
return n
}
func canonScopeDomain(d string) (string, bool) {
return d, len(d) <= 253 && scopeDomainRE.MatchString(d)
}
// canonScopeCIDR returns a prefix or address in canonical form. An address with
// a zone is refused (the zone may hold any text, commas included), and an
// IPv4-mapped IPv6 entry becomes the IPv4 range it maps.
func canonScopeCIDR(c string) (string, bool) {
if p, err := netip.ParsePrefix(c); err == nil {
if p.Addr().Is4In6() && p.Bits() >= 96 {
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
}
return p.Masked().String(), true
}
a, err := netip.ParseAddr(c)
if err != nil || a.Zone() != "" {
return "", false
}
return a.Unmap().String(), true
}

61
sandbox/validate_test.go Normal file
View file

@ -0,0 +1,61 @@
package sandbox
import (
"errors"
"strings"
"testing"
)
func TestValidateEnvRefusesReservedNames(t *testing.T) {
for _, k := range []string{"PATH", "path", "HTTP_PROXY", "https_proxy", "All_Proxy", "no_proxy",
"LD_PRELOAD", "LD_LIBRARY_PATH", "ld_audit", "BASH_ENV", "env", "GCONV_PATH", "PythonPath",
"SHELLOPTS", "PS4", "NODE_OPTIONS", "PERL5OPT", "GIT_SSH_COMMAND", "GLIBC_TUNABLES"} {
if err := ValidateEnv(map[string]string{k: "x"}); !errors.Is(err, ErrBadRequest) {
t.Errorf("ValidateEnv(%s) = %v", k, err)
}
// The panel drops them instead of sending a request the runner refuses.
if got := FilterPanelEnv([]string{k + "=x", "KEEP=1"}); len(got) != 1 || got["KEEP"] != "1" {
t.Errorf("FilterPanelEnv kept %s: %v", k, got)
}
}
if err := ValidateEnv(map[string]string{"PYTHONUNBUFFERED": "1", "LANGUAGE": "en", "ENVIRONMENT": "x"}); err != nil {
t.Fatalf("ordinary names refused: %v", err)
}
}
func TestValidateExecRequestFiltersScopeEntries(t *testing.T) {
req := ExecRequest{Argv: []string{"true"},
ScopeDomains: []string{"example.com", "a.example,evil.example", "*.example.org", "a.example evil", "",
"example.com:8443", "https://x", "api-*.example.com", "xn--bcher-kva.example", "bücher.example", "host_1.lab.", strings.Repeat("a", 254)},
ScopeCIDRs: []string{"203.0.113.0/24", "1.2.3.4/32,10.0.0.0/8", "10.0.0.0/33", " 10.0.0.1", "198.51.100.7", "2001:db8::/32",
"fe80::1%eth0,10.0.0.0/8", "::1%a,0.0.0.0/0", "fe80::1%eth0", "203.0.113.9/24", "::ffff:10.1.0.0/112", "::ffff:198.51.100.8"}}
if err := ValidateExecRequest(&req); err != nil {
t.Fatalf("invalid entries failed the request: %v", err)
}
// Invalid entries are dropped whole (never split at the comma); valid ones stay.
if got := strings.Join(req.ScopeDomains, " "); got != "example.com *.example.org xn--bcher-kva.example bücher.example host_1.lab." {
t.Errorf("domains = %q", got)
}
// An IPv6 zone may hold any text, commas included, so zoned addresses are
// dropped; entries are passed on in canonical form, mapped ones as IPv4.
if got := strings.Join(req.ScopeCIDRs, " "); got != "203.0.113.0/24 198.51.100.7 2001:db8::/32 203.0.113.0/24 10.1.0.0/16 198.51.100.8" {
t.Errorf("CIDRs = %q", got)
}
long := make([]string, MaxScopeBytes/200)
for i := range long {
long[i] = strings.Repeat("a", 240) + ".example"
}
if err := ValidateExecRequest(&ExecRequest{Argv: []string{"true"}, ScopeDomains: long}); !errors.Is(err, ErrBadRequest) {
t.Errorf("%d bytes of scope accepted: %v", joinedLen(long), err)
}
many := make([]string, MaxScopeEntries+1)
for i := range many {
many[i] = "a.example"
}
for _, req := range []ExecRequest{{ScopeDomains: many}, {ScopeCIDRs: many}} {
req.Argv = []string{"true"}
if err := ValidateExecRequest(&req); !errors.Is(err, ErrBadRequest) {
t.Errorf("%d scope entries accepted: %v", len(many), err)
}
}
}