Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 95 additions & 7 deletions internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,12 +516,24 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep
if key == "FULLSEND_DIR" {
return absFullsendDir
}
// Refuse OIDC credential vars so ${VAR} expansion in harness
// YAML cannot leak mint-usable credentials (#5832).
if oidcDenyKeys[key] {
return ""
}
return os.Getenv(key)
}
lookup := func(key string) (string, bool) {
if key == "FULLSEND_DIR" {
return absFullsendDir, true
}
// Refuse OIDC credential vars (#5832).
Comment thread
ifireball marked this conversation as resolved.
Resolved
Comment thread
ifireball marked this conversation as resolved.
Resolved
// Unlike expander (which silently returns "" to produce an empty
// expansion), lookup returns false so ValidateRunnerEnvWith treats
// the reference as an unresolvable variable and fails validation.
if oidcDenyKeys[key] {
return "", false
}
return os.LookupEnv(key)
}
if err := h.ValidateRunnerEnvWith(lookup); err != nil {
Expand Down Expand Up @@ -698,7 +710,8 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep
preflightCtx, preflightCancel := context.WithTimeout(ctx, preflightCheckTimeout)
defer preflightCancel()
preflightCmd := exec.CommandContext(preflightCtx, "sh", "-c", h.ValidationLoop.PreflightCheck)
preflightCmd.Env = append(os.Environ(), envToList(h.RunnerEnv)...)
// Use childScriptEnv to strip OIDC credential vars (#5832).
preflightCmd.Env = childScriptEnv(h.RunnerEnv, "")
preflightOut, preflightErr := preflightCmd.CombinedOutput()
if preflightErr != nil {
printer.StepFail("Preflight dependency check failed")
Expand Down Expand Up @@ -1613,7 +1626,9 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep
// failure sets it to false and continues (skipping step 9e),
Comment thread
ifireball marked this conversation as resolved.
Resolved
// while success sets it to true immediately above. Pass the
// repo dir directly.
valCmd.Env = append(os.Environ(), validationEnv(h, hostRepositoryDownloadDir, runDir)...)
// Strip OIDC credential vars from the full composed env so keys
// injected via h.RunnerEnv are also removed (#5832).
valCmd.Env = stripOIDCEnv(append(os.Environ(), validationEnv(h, hostRepositoryDownloadDir, runDir)...))
valOut, valErr := valCmd.CombinedOutput()

if valErr == nil {
Expand Down Expand Up @@ -1879,11 +1894,30 @@ func setupFetchService(ctx context.Context, treeFetcher gitfetch.TreeFetchFunc,
// Keys that don't match are skipped to prevent shell injection.
var validEnvKeyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)

// oidcDenyKeys lists OIDC credential env vars that must not leak into
// user-controlled or sandbox-visible contexts. The parent harness process
// retains these for mintAgentToken and OIDC token refresh; stripping them
Comment thread
ifireball marked this conversation as resolved.
Resolved
// from child scripts, expanders, and sandbox injection prevents user code
// and LLM sessions from minting additional tokens. See #5832, ADR 0073.
//
// MAINTENANCE: when new OIDC-related credential env vars are introduced
// (e.g. by mint infrastructure changes), add them here. By convention the
// vars use ACTIONS_ID_TOKEN_ or FULLSEND_GCP_OIDC_ prefixes. Every
// expansion site in this file consults this map, so a single addition
// propagates to all deny checks.
var oidcDenyKeys = map[string]bool{
"ACTIONS_ID_TOKEN_REQUEST_URL": true,
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": true,
"FULLSEND_GCP_OIDC_URL": true,
"FULLSEND_GCP_OIDC_AUTH_FILE": true,
}

// reservedSandboxKeys are infrastructure env vars that env.sandbox must not
// shadow. These are set by the runner in bootstrapEnv and overriding them
// from harness YAML could break sandbox operation, or are security-sensitive
// vars that could influence sandbox execution (e.g. shared library injection,
// auto-sourced shell startup files).
// auto-sourced shell startup files). OIDC credential vars from oidcDenyKeys
// are merged in by init() to prevent re-injection into the sandbox (#5832).
// NOTE: keep in sync with bootstrapEnv exports below for FULLSEND_* keys.
var reservedSandboxKeys = map[string]bool{
"PATH": true,
Expand All @@ -1901,6 +1935,14 @@ var reservedSandboxKeys = map[string]bool{
"FULLSEND_TARGET_REPO_DIR": true,
}

func init() {
// Merge OIDC credential vars into reservedSandboxKeys so a future
// addition to oidcDenyKeys automatically blocks sandbox injection.
for k := range oidcDenyKeys {
reservedSandboxKeys[k] = true
}
}

// buildSandboxEnvLines generates export lines for env.sandbox values (ADR 0055).
// Values have already been expanded by the caller. Each value is single-quoted
// with internal single quotes escaped. Keys that are not valid shell identifiers
Expand Down Expand Up @@ -2018,7 +2060,9 @@ func bootstrapEnv(sandboxName, remoteRepositoryDir string, h *harness.Harness, r

// Copy host files into the sandbox.
for _, hf := range h.HostFiles {
hostPath := os.ExpandEnv(hf.Src)
// Use safeExpandEnv instead of os.ExpandEnv to refuse OIDC
// credential vars in host_files src path expansion (#5832).
hostPath := safeExpandEnv(hf.Src)
if hostPath == "" {
if hf.Optional {
continue
Expand Down Expand Up @@ -2080,14 +2124,32 @@ func bootstrapEnv(sandboxName, remoteRepositoryDir string, h *harness.Harness, r
return nil
}

// safeExpandEnv expands ${VAR} references like os.ExpandEnv but refuses
// OIDC credential vars (oidcDenyKeys), expanding them to empty. Use this
// instead of os.ExpandEnv at any site where the expanded value may reach
// user-controlled or sandbox-visible contexts. See #5832.
func safeExpandEnv(s string) string {
return os.Expand(s, func(key string) string {
if oidcDenyKeys[key] {
return ""
}
return os.Getenv(key)
})
}

// shellSafeExpandEnv expands ${VAR} references in text using the host
// environment, escaping characters that are special inside double quotes
// (", $, `, \) so the result is safe to source as a shell script.
// Templates use the standard export FOO="${FOO}" pattern; this function
// ensures substituted values cannot break out of the double-quote context.
// OIDC credential vars are refused (expand to empty) to prevent leaking
// mint-usable credentials into sandbox-bound files (#5832).
// Fixes #408, #615.
func shellSafeExpandEnv(text string) string {
return os.Expand(text, func(key string) string {
if oidcDenyKeys[key] {
return ""
}
return escapeForDoubleQuotes(os.Getenv(key))
})
}
Expand Down Expand Up @@ -2155,7 +2217,9 @@ func postLoopValidationSweep(h *harness.Harness, runDir string, runCount int, cu
printer.StepStart(fmt.Sprintf("Post-loop validation (iteration %d): %s", i, h.ValidationLoop.Script))
valCmd := exec.Command(h.ValidationLoop.Script)
valCmd.Dir = iterDir
valCmd.Env = append(os.Environ(), validationEnv(h, "", runDir)...)
// Strip OIDC credential vars from the full composed env so keys
// injected via h.RunnerEnv are also removed (#5832).
valCmd.Env = stripOIDCEnv(append(os.Environ(), validationEnv(h, "", runDir)...))
valOut, valErr := valCmd.CombinedOutput()

if valErr == nil {
Expand All @@ -2171,6 +2235,21 @@ func postLoopValidationSweep(h *harness.Harness, runDir string, runCount int, cu
return sweepResult{passed: false, repoExtractedOK: currentRepoExtractedOK}
}

// stripOIDCEnv returns a copy of env with OIDC credential entries removed.
// Use this to filter os.Environ() slices in contexts where childScriptEnv is
// not applicable (e.g., validation scripts that compose their env differently).
// See #5832.
func stripOIDCEnv(env []string) []string {
result := make([]string, 0, len(env))
for _, e := range env {
if i := strings.IndexByte(e, '='); i > 0 && oidcDenyKeys[e[:i]] {
continue
}
result = append(result, e)
}
return result
}

// envToList converts a map of env vars to a sorted list of KEY=VALUE strings.
// toTelemetryMetrics maps fullsend's aggregate run metrics onto the telemetry
// summary metrics — the same numbers already written to metrics.json, no new
Expand Down Expand Up @@ -2349,13 +2428,22 @@ func runPreScript(h *harness.Harness, runDir, traceparent string, printer *ui.Pr
// match, so a stale value would shadow fullsend's own, and fullsend's trace
// identity never derives from runner_env (issue #2779). An empty traceparent
// (telemetry disabled) is omitted rather than emitted blank.
//
// OIDC credential vars (oidcDenyKeys) are stripped so user-authored pre/post
// scripts and validation/preflight commands cannot mint their own tokens.
// The parent harness process retains them for mintAgentToken. See #5832.
func childScriptEnv(runnerEnv map[string]string, traceparent string) []string {
merged := append(os.Environ(), envToList(runnerEnv)...)
env := make([]string, 0, len(merged)+1)
for _, e := range merged {
if !strings.HasPrefix(e, "TRACEPARENT=") {
env = append(env, e)
if strings.HasPrefix(e, "TRACEPARENT=") {
continue
}
// Strip OIDC credential vars from child script env (#5832).
if i := strings.IndexByte(e, '='); i > 0 && oidcDenyKeys[e[:i]] {
continue
}
env = append(env, e)
}
if traceparent != "" {
env = append(env, "TRACEPARENT="+traceparent)
Expand Down
119 changes: 119 additions & 0 deletions internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1838,6 +1838,125 @@ func TestShellSafeExpandEnv_ShellRoundtrip(t *testing.T) {
}
}

// TestShellSafeExpandEnv_RefusesOIDCVars verifies that OIDC credential vars
// expand to empty in host_files templates so they cannot leak into sandbox-bound
// files (#5832).
func TestShellSafeExpandEnv_RefusesOIDCVars(t *testing.T) {
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://oidc.example.com")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "secret-token")
t.Setenv("FULLSEND_GCP_OIDC_URL", "https://gcp.example.com")
t.Setenv("FULLSEND_GCP_OIDC_AUTH_FILE", "/tmp/auth.json")
t.Setenv("SAFE_VAR", "allowed-value")

template := `export A="${ACTIONS_ID_TOKEN_REQUEST_URL}"
export B="${ACTIONS_ID_TOKEN_REQUEST_TOKEN}"
export C="${FULLSEND_GCP_OIDC_URL}"
export D="${FULLSEND_GCP_OIDC_AUTH_FILE}"
export E="${SAFE_VAR}"`

got := shellSafeExpandEnv(template)

assert.Contains(t, got, `export A=""`, "OIDC var must expand to empty")
assert.Contains(t, got, `export B=""`, "OIDC var must expand to empty")
assert.Contains(t, got, `export C=""`, "OIDC var must expand to empty")
assert.Contains(t, got, `export D=""`, "OIDC var must expand to empty")
assert.Contains(t, got, `export E="allowed-value"`, "non-OIDC var must expand normally")
}

// TestSafeExpandEnv_RefusesOIDCVars verifies that safeExpandEnv refuses OIDC
// credential vars (expanding them to empty) while passing other vars through
// unchanged. This covers the host_files src path expansion site (#5832).
func TestSafeExpandEnv_RefusesOIDCVars(t *testing.T) {
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://oidc.example.com")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "secret-token")
t.Setenv("FULLSEND_GCP_OIDC_URL", "https://gcp.example.com")
t.Setenv("FULLSEND_GCP_OIDC_AUTH_FILE", "/tmp/auth.json")
t.Setenv("SAFE_VAR", "allowed-value")

// OIDC vars must expand to empty.
assert.Equal(t, "", safeExpandEnv("${ACTIONS_ID_TOKEN_REQUEST_URL}"))
assert.Equal(t, "", safeExpandEnv("${ACTIONS_ID_TOKEN_REQUEST_TOKEN}"))
assert.Equal(t, "", safeExpandEnv("${FULLSEND_GCP_OIDC_URL}"))
assert.Equal(t, "", safeExpandEnv("${FULLSEND_GCP_OIDC_AUTH_FILE}"))

// Non-OIDC vars must expand normally.
assert.Equal(t, "allowed-value", safeExpandEnv("${SAFE_VAR}"))

// Mixed usage: OIDC part disappears, safe part remains.
assert.Equal(t, "/prefix//suffix", safeExpandEnv("/prefix/${FULLSEND_GCP_OIDC_AUTH_FILE}/suffix"))
}

// TestReservedSandboxKeys_IncludesOIDCVars verifies that OIDC credential vars
// are in reservedSandboxKeys so env.sandbox cannot inject them (#5832).
func TestReservedSandboxKeys_IncludesOIDCVars(t *testing.T) {
for _, key := range []string{
"ACTIONS_ID_TOKEN_REQUEST_URL",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
"FULLSEND_GCP_OIDC_URL",
"FULLSEND_GCP_OIDC_AUTH_FILE",
} {
assert.True(t, reservedSandboxKeys[key], "reservedSandboxKeys must include %s", key)
}
}

// TestBuildSandboxEnvLines_SkipsOIDCVars verifies that OIDC credential vars
// in env.sandbox are rejected by buildSandboxEnvLines (#5832).
func TestBuildSandboxEnvLines_SkipsOIDCVars(t *testing.T) {
h := &harness.Harness{
Agent: "agents/test.md",
Role: "test",
Env: &harness.EnvConfig{
Sandbox: map[string]string{
"CUSTOM_VAR": "allowed",
"ACTIONS_ID_TOKEN_REQUEST_URL": "https://stolen.example.com",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "stolen-token",
"FULLSEND_GCP_OIDC_URL": "https://stolen-gcp.example.com",
"FULLSEND_GCP_OIDC_AUTH_FILE": "/tmp/stolen-auth.json",
},
},
}
lines := buildSandboxEnvLines(h)
require.Len(t, lines, 1)
assert.Equal(t, "export CUSTOM_VAR='allowed'", lines[0])
}

// TestStripOIDCEnv verifies that stripOIDCEnv removes OIDC credential entries
// from an env slice while preserving all other entries (#5832).
func TestStripOIDCEnv(t *testing.T) {
env := []string{
"PATH=/usr/bin",
"ACTIONS_ID_TOKEN_REQUEST_URL=https://oidc.example.com",
"HOME=/home/user",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN=secret",
"FULLSEND_GCP_OIDC_URL=https://gcp.example.com",
"FULLSEND_GCP_OIDC_AUTH_FILE=/tmp/auth.json",
"SAFE_VAR=value",
}

result := stripOIDCEnv(env)

assert.Equal(t, []string{
"PATH=/usr/bin",
"HOME=/home/user",
"SAFE_VAR=value",
}, result)
}

// TestOIDCDenyKeys_Completeness verifies that all four OIDC credential vars
// are present in oidcDenyKeys (#5832).
func TestOIDCDenyKeys_Completeness(t *testing.T) {
expected := []string{
"ACTIONS_ID_TOKEN_REQUEST_URL",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
"FULLSEND_GCP_OIDC_URL",
"FULLSEND_GCP_OIDC_AUTH_FILE",
}
for _, key := range expected {
assert.True(t, oidcDenyKeys[key], "oidcDenyKeys must include %s", key)
}
assert.Len(t, oidcDenyKeys, len(expected), "oidcDenyKeys must contain exactly %d keys", len(expected))
}

func TestNeedsCrossCompilation(t *testing.T) {
result := needsCrossCompilation()
if runtime.GOOS == "linux" {
Expand Down
71 changes: 71 additions & 0 deletions internal/cli/telemetry_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,77 @@ func TestChildScriptEnv_PreservesTracestate(t *testing.T) {
assert.True(t, found, "TRACESTATE must pass through to child scripts")
}

// TestChildScriptEnv_StripsOIDCVars verifies that OIDC credential vars
// are stripped from the child script environment so user-authored
// pre/post scripts cannot mint their own tokens (#5832).
func TestChildScriptEnv_StripsOIDCVars(t *testing.T) {
// Set OIDC vars in the process environment.
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://oidc.example.com")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "secret-token")
t.Setenv("FULLSEND_GCP_OIDC_URL", "https://gcp.example.com")
t.Setenv("FULLSEND_GCP_OIDC_AUTH_FILE", "/tmp/auth.json")
t.Setenv("SAFE_VAR", "should-survive")

env := childScriptEnv(map[string]string{"RUNNER_VAR": "present"}, "")

for _, e := range env {
key := e
if i := strings.IndexByte(e, '='); i > 0 {
key = e[:i]
}
assert.False(t, key == "ACTIONS_ID_TOKEN_REQUEST_URL", "OIDC var must be stripped")
assert.False(t, key == "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "OIDC var must be stripped")
assert.False(t, key == "FULLSEND_GCP_OIDC_URL", "OIDC var must be stripped")
assert.False(t, key == "FULLSEND_GCP_OIDC_AUTH_FILE", "OIDC var must be stripped")
}

// Non-OIDC vars must survive.
hasSafe, hasRunner := false, false
for _, e := range env {
if e == "SAFE_VAR=should-survive" {
hasSafe = true
}
if e == "RUNNER_VAR=present" {
hasRunner = true
}
}
assert.True(t, hasSafe, "non-OIDC process env var must survive")
assert.True(t, hasRunner, "RunnerEnv var must survive")
}

// TestChildScriptEnv_StripsOIDCFromRunnerEnv verifies that OIDC credential
// vars injected via RunnerEnv are also stripped (#5832).
func TestChildScriptEnv_StripsOIDCFromRunnerEnv(t *testing.T) {
runnerEnv := map[string]string{
"ACTIONS_ID_TOKEN_REQUEST_URL": "https://injected.example.com",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "injected-token",
"FULLSEND_GCP_OIDC_URL": "https://injected-gcp.example.com",
"FULLSEND_GCP_OIDC_AUTH_FILE": "/tmp/injected-auth.json",
"LEGIT_VAR": "allowed",
}

env := childScriptEnv(runnerEnv, "")

for _, e := range env {
key := e
if i := strings.IndexByte(e, '='); i > 0 {
key = e[:i]
}
assert.False(t, key == "ACTIONS_ID_TOKEN_REQUEST_URL", "OIDC var from RunnerEnv must be stripped")
assert.False(t, key == "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "OIDC var from RunnerEnv must be stripped")
assert.False(t, key == "FULLSEND_GCP_OIDC_URL", "OIDC var from RunnerEnv must be stripped")
assert.False(t, key == "FULLSEND_GCP_OIDC_AUTH_FILE", "OIDC var from RunnerEnv must be stripped")
}

hasLegit := false
for _, e := range env {
if e == "LEGIT_VAR=allowed" {
hasLegit = true
}
}
assert.True(t, hasLegit, "non-OIDC RunnerEnv var must survive")
}

func TestAgentSpanStartAttrs(t *testing.T) {
attrs := agentSpanStartAttrs(3, "code")
require.Len(t, attrs, 3)
Expand Down
Loading