Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

Fix Codex task MULTICA_TOKEN passthrough (ZIC-82)

ZIce910671b1853f
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a38aa61498..b317a8e4ab 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4261,6 +4261,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
agentCustomEnv = task.Agent.CustomEnv
}
layerCustomEnvAndHermesHome(agentEnv, agentCustomEnv, env.HermesHome, d.logger)
+ if err := configureCodexTaskShellEnvironment(provider, env.CodexHome, os.Environ(), agentEnv, d.logger); err != nil {
+ return TaskResult{}, err
+ }
backend, err := agent.New(provider, agent.Config{
ExecutablePath: entry.Path,
CLIVersion: resolvedVersion,
@@ -5388,6 +5391,27 @@ func layerCustomEnvAndHermesHome(agentEnv, customEnv map[string]string, overlayH
}
}
+// configureCodexTaskShellEnvironment writes the managed shell policy only
+// after the task and agent custom environment are fully assembled. This makes
+// the allowlist reflect the child environment that will actually be launched,
+// including platform-specific essentials and non-secret custom_env values.
+// Failure is fatal: launching with an unowned or malformed policy could either
+// drop the task-scoped token again or expose inherited daemon credentials.
+func configureCodexTaskShellEnvironment(provider, codexHome string, inherited []string, agentEnv map[string]string, logger *slog.Logger) error {
+ if provider != "codex" {
+ return nil
+ }
+ if strings.TrimSpace(codexHome) == "" {
+ return errors.New("configure Codex shell environment: task CODEX_HOME is missing")
+ }
+ includeOnly := execenv.CodexShellEnvAllowlist(inherited, agentEnv)
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := execenv.EnsureCodexShellEnvPolicyConfig(configPath, includeOnly, logger); err != nil {
+ return fmt.Errorf("configure Codex shell environment: %w", err)
+ }
+ return nil
+}
+
func defaultArgsForProvider(cfg Config, provider string) []string {
var args []string
switch provider {
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 6cd0e81a06..dd26c173aa 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -240,6 +240,63 @@ func TestLayerCustomEnvAndHermesHome(t *testing.T) {
}
}
+func TestConfigureCodexTaskShellEnvironment(t *testing.T) {
+ t.Parallel()
+
+ t.Run("non-Codex runtime is unchanged", func(t *testing.T) {
+ t.Parallel()
+ codexHome := t.TempDir()
+ if err := configureCodexTaskShellEnvironment("claude", codexHome, nil, nil, slog.Default()); err != nil {
+ t.Fatalf("configureCodexTaskShellEnvironment: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(codexHome, "config.toml")); !os.IsNotExist(err) {
+ t.Fatalf("non-Codex runtime unexpectedly wrote config.toml: %v", err)
+ }
+ })
+
+ t.Run("Codex policy uses platform and explicit task environment", func(t *testing.T) {
+ t.Parallel()
+ codexHome := t.TempDir()
+ inherited := []string{
+ "SystemRoot=C:\\Windows",
+ "USERPROFILE=C:\\Users\\test",
+ "OPENAI_API_KEY=host-secret",
+ "MULTICA_LLM_API_KEY=daemon-secret",
+ }
+ agentEnv := map[string]string{
+ "CUSTOM_FLAG": "enabled",
+ "MULTICA_SERVER_URL": "https://task.example",
+ "MULTICA_TOKEN": "mat_task",
+ }
+ if err := configureCodexTaskShellEnvironment("codex", codexHome, inherited, agentEnv, slog.Default()); err != nil {
+ t.Fatalf("configureCodexTaskShellEnvironment: %v", err)
+ }
+ data, err := os.ReadFile(filepath.Join(codexHome, "config.toml"))
+ if err != nil {
+ t.Fatalf("read config.toml: %v", err)
+ }
+ config := string(data)
+ for _, want := range []string{"SystemRoot", "USERPROFILE", "CUSTOM_FLAG", "MULTICA_SERVER_URL", "MULTICA_TOKEN"} {
+ if !strings.Contains(config, want) {
+ t.Errorf("config.toml missing %q:\n%s", want, config)
+ }
+ }
+ for _, unwanted := range []string{"OPENAI_API_KEY", "MULTICA_LLM_API_KEY", "MULTICA_*"} {
+ if strings.Contains(config, unwanted) {
+ t.Errorf("config.toml unexpectedly contains %q:\n%s", unwanted, config)
+ }
+ }
+ })
+
+ t.Run("Codex without task home fails closed", func(t *testing.T) {
+ t.Parallel()
+ err := configureCodexTaskShellEnvironment("codex", "", nil, map[string]string{"MULTICA_TOKEN": "mat_task"}, slog.Default())
+ if err == nil || !strings.Contains(err.Error(), "CODEX_HOME is missing") {
+ t.Fatalf("error = %v, want missing CODEX_HOME", err)
+ }
+ })
+}
+
func TestTaskScopedAuthToken(t *testing.T) {
t.Parallel()
diff --git a/server/internal/daemon/execenv/codex_shell_env.go b/server/internal/daemon/execenv/codex_shell_env.go
new file mode 100644
index 0000000000..4a21b242ea
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_shell_env.go
@@ -0,0 +1,287 @@
+package execenv
+
+import (
+ "bytes"
+ "fmt"
+ "log/slog"
+ "os"
+ "regexp"
+ "sort"
+ "strings"
+
+ "github.com/pelletier/go-toml/v2"
+ "github.com/pelletier/go-toml/v2/unstable"
+)
+
+// Codex filters environment variables before running shell tool subprocesses.
+// Its default secret guard drops names containing KEY, SECRET, or TOKEN, so a
+// daemon-spawned Codex process can have MULTICA_TOKEN while `multica issue ...`
+// inside a shell tool does not. The daemon therefore owns the shell policy in
+// each task's isolated Codex home.
+const (
+ shellEnvironmentPolicyKey = "shell_environment_policy"
+ multicaShellEnvBeginMarker = "# BEGIN multica-managed shell-environment (do not edit; regenerated by daemon)"
+ multicaShellEnvEndMarker = "# END multica-managed shell-environment"
+)
+
+var shellEnvBlockRe = regexp.MustCompile(
+ `(?ms)^` + regexp.QuoteMeta(multicaShellEnvBeginMarker) +
+ `.*?^` + regexp.QuoteMeta(multicaShellEnvEndMarker) + `\n*`)
+
+type codexShellEnvironmentPolicy struct {
+ Inherit string `toml:"inherit"`
+ IgnoreDefaultExcludes bool `toml:"ignore_default_excludes"`
+ IncludeOnly []string `toml:"include_only"`
+}
+
+type tomlByteRange struct {
+ start int
+ end int
+}
+
+// CodexShellEnvAllowlist returns exact (not glob) environment names for the
+// managed shell policy.
+//
+// Inherited process variables keep Codex's documented default filtering for
+// names containing KEY, SECRET, or TOKEN. Inherited MULTICA_* variables are
+// always dropped because they belong to the daemon process, not necessarily to
+// this task. Explicit MULTICA_* values are safe to include because daemon.go
+// blocklists that namespace from agent custom_env and constructs those values
+// from the current task. Non-secret explicit custom_env values keep their
+// existing shell visibility; secret-looking custom_env remains filtered just
+// as it was under Codex's default policy.
+func CodexShellEnvAllowlist(inherited []string, explicit map[string]string) []string {
+ // Codex's glob matching is case-insensitive. De-duplicate on the same basis
+ // so Windows Path/PATH aliases cannot create ambiguous policy entries.
+ allowed := make(map[string]string, len(inherited)+len(explicit))
+ add := func(key string, isExplicit bool) {
+ if key == "" {
+ return
+ }
+ upper := strings.ToUpper(key)
+ if strings.HasPrefix(upper, "MULTICA_") {
+ if !isExplicit {
+ return
+ }
+ } else if codexDefaultExcludesEnvKey(upper) {
+ return
+ }
+ allowed[upper] = key
+ }
+
+ for _, entry := range inherited {
+ key, _, ok := strings.Cut(entry, "=")
+ if !ok {
+ continue
+ }
+ add(key, false)
+ }
+ for key := range explicit {
+ add(key, true)
+ }
+
+ keys := make([]string, 0, len(allowed))
+ for _, key := range allowed {
+ keys = append(keys, key)
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ return strings.ToUpper(keys[i]) < strings.ToUpper(keys[j])
+ })
+ return keys
+}
+
+func codexDefaultExcludesEnvKey(upperKey string) bool {
+ return strings.Contains(upperKey, "KEY") ||
+ strings.Contains(upperKey, "SECRET") ||
+ strings.Contains(upperKey, "TOKEN")
+}
+
+func renderMulticaShellEnvBlock(includeOnly []string) (string, error) {
+ policy, err := toml.Marshal(codexShellEnvironmentPolicy{
+ Inherit: "all",
+ IgnoreDefaultExcludes: true,
+ IncludeOnly: includeOnly,
+ })
+ if err != nil {
+ return "", fmt.Errorf("render shell_environment_policy: %w", err)
+ }
+
+ var b strings.Builder
+ b.WriteString(multicaShellEnvBeginMarker)
+ b.WriteByte('\n')
+ b.WriteString("[")
+ b.WriteString(shellEnvironmentPolicyKey)
+ b.WriteString("]\n")
+ b.Write(bytes.TrimRight(policy, "\n"))
+ b.WriteByte('\n')
+ b.WriteString(multicaShellEnvEndMarker)
+ b.WriteByte('\n')
+ return b.String(), nil
+}
+
+// stripUserShellEnvPolicy removes complete TOML expressions that define a
+// shell_environment_policy, including root dotted/inline values, quoted table
+// forms, nested set tables, and profile overlays. It deliberately preserves
+// comments and every unrelated expression byte-for-byte.
+func stripUserShellEnvPolicy(content []byte) ([]byte, error) {
+ if len(bytes.TrimSpace(content)) == 0 {
+ return content, nil
+ }
+
+ // The iterative parser exposes source ranges but does not enforce all TOML
+ // semantic rules (for example duplicate definitions). Validate with the
+ // stable decoder first so a malformed user config is never partially
+ // rewritten into a different malformed config.
+ var decoded map[string]any
+ if err := toml.Unmarshal(content, &decoded); err != nil {
+ return nil, fmt.Errorf("parse config.toml before shell environment update: %w", err)
+ }
+
+ var parser unstable.Parser
+ parser.Reset(content)
+ var currentTable []string
+ ranges := make([]tomlByteRange, 0, 8)
+ for parser.NextExpression() {
+ expr := parser.Expression()
+ keys := tomlNodeKeys(expr)
+ switch expr.Kind {
+ case unstable.Table, unstable.ArrayTable:
+ currentTable = keys
+ if isCodexShellEnvPolicyPath(keys) {
+ r, err := tomlTableHeaderLineRange(content, expr)
+ if err != nil {
+ return nil, err
+ }
+ ranges = append(ranges, r)
+ }
+ case unstable.KeyValue:
+ fullKey := make([]string, 0, len(currentTable)+len(keys))
+ fullKey = append(fullKey, currentTable...)
+ fullKey = append(fullKey, keys...)
+ if isCodexShellEnvPolicyPath(fullKey) {
+ start := int(expr.Raw.Offset)
+ ranges = append(ranges, tomlByteRange{start: start, end: start + int(expr.Raw.Length)})
+ }
+ }
+ }
+ if err := parser.Error(); err != nil {
+ return nil, fmt.Errorf("parse config.toml shell environment expressions: %w", err)
+ }
+ return removeTOMLByteRanges(content, ranges)
+}
+
+func tomlNodeKeys(node *unstable.Node) []string {
+ it := node.Key()
+ keys := make([]string, 0, 4)
+ for it.Next() {
+ keys = append(keys, string(it.Node().Data))
+ }
+ return keys
+}
+
+func isCodexShellEnvPolicyPath(keys []string) bool {
+ if len(keys) > 0 && keys[0] == shellEnvironmentPolicyKey {
+ return true
+ }
+ return len(keys) >= 3 && keys[0] == "profiles" && keys[2] == shellEnvironmentPolicyKey
+}
+
+func tomlTableHeaderLineRange(content []byte, table *unstable.Node) (tomlByteRange, error) {
+ it := table.Key()
+ if !it.Next() {
+ return tomlByteRange{}, errorsForInvalidShellEnvTOML("table header has no key")
+ }
+ offset := int(it.Node().Raw.Offset)
+ if offset < 0 || offset > len(content) {
+ return tomlByteRange{}, errorsForInvalidShellEnvTOML("table key range is outside config")
+ }
+ start := bytes.LastIndexByte(content[:offset], '\n') + 1
+ end := len(content)
+ if newline := bytes.IndexByte(content[offset:], '\n'); newline >= 0 {
+ end = offset + newline + 1
+ }
+ return tomlByteRange{start: start, end: end}, nil
+}
+
+func errorsForInvalidShellEnvTOML(detail string) error {
+ return fmt.Errorf("parse config.toml shell environment expressions: %s", detail)
+}
+
+func removeTOMLByteRanges(content []byte, ranges []tomlByteRange) ([]byte, error) {
+ if len(ranges) == 0 {
+ return append([]byte(nil), content...), nil
+ }
+ sort.Slice(ranges, func(i, j int) bool {
+ if ranges[i].start == ranges[j].start {
+ return ranges[i].end < ranges[j].end
+ }
+ return ranges[i].start < ranges[j].start
+ })
+
+ merged := make([]tomlByteRange, 0, len(ranges))
+ for _, r := range ranges {
+ if r.start < 0 || r.end < r.start || r.end > len(content) {
+ return nil, errorsForInvalidShellEnvTOML("expression range is outside config")
+ }
+ if len(merged) > 0 && r.start <= merged[len(merged)-1].end {
+ if r.end > merged[len(merged)-1].end {
+ merged[len(merged)-1].end = r.end
+ }
+ continue
+ }
+ merged = append(merged, r)
+ }
+
+ var out bytes.Buffer
+ previous := 0
+ for _, r := range merged {
+ out.Write(content[previous:r.start])
+ previous = r.end
+ }
+ out.Write(content[previous:])
+ return out.Bytes(), nil
+}
+
+// EnsureCodexShellEnvPolicyConfig replaces every user/profile shell policy in
+// the task-local config with one validated daemon-managed policy. The source
+// config in the user's shared Codex home is never modified.
+func EnsureCodexShellEnvPolicyConfig(configPath string, includeOnly []string, logger *slog.Logger) error {
+ data, err := os.ReadFile(configPath)
+ if err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("read config.toml: %w", err)
+ }
+
+ withoutManaged := []byte(shellEnvBlockRe.ReplaceAllString(string(data), ""))
+ stripped, err := stripUserShellEnvPolicy(withoutManaged)
+ if err != nil {
+ return err
+ }
+ block, err := renderMulticaShellEnvBlock(includeOnly)
+ if err != nil {
+ return err
+ }
+
+ base := strings.TrimRight(string(stripped), " \t\r\n")
+ updated := block
+ if base != "" {
+ updated = base + "\n\n" + block
+ }
+ var validated map[string]any
+ if err := toml.Unmarshal([]byte(updated), &validated); err != nil {
+ return fmt.Errorf("validate generated config.toml shell environment policy: %w", err)
+ }
+
+ if updated == string(data) {
+ return nil
+ }
+ if err := os.WriteFile(configPath, []byte(updated), 0o644); err != nil {
+ return fmt.Errorf("write config.toml: %w", err)
+ }
+ if logger != nil {
+ logger.Debug("codex shell environment: wrote managed shell_environment_policy",
+ "config_path", configPath,
+ "include_count", len(includeOnly),
+ )
+ }
+ return nil
+}
diff --git a/server/internal/daemon/execenv/codex_shell_env_test.go b/server/internal/daemon/execenv/codex_shell_env_test.go
new file mode 100644
index 0000000000..5404bf85a2
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_shell_env_test.go
@@ -0,0 +1,252 @@
+package execenv
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/pelletier/go-toml/v2"
+)
+
+func assertValidToml(t *testing.T, content string) {
+ t.Helper()
+ var parsed map[string]any
+ if err := toml.Unmarshal([]byte(content), &parsed); err != nil {
+ t.Fatalf("generated config.toml is invalid: %v\n---\n%s", err, content)
+ }
+}
+
+func parsedShellEnvPolicy(t *testing.T, content string) codexShellEnvironmentPolicy {
+ t.Helper()
+ var parsed struct {
+ Policy codexShellEnvironmentPolicy `toml:"shell_environment_policy"`
+ }
+ if err := toml.Unmarshal([]byte(content), &parsed); err != nil {
+ t.Fatalf("parse generated config.toml: %v\n---\n%s", err, content)
+ }
+ return parsed.Policy
+}
+
+func TestCodexShellEnvAllowlistUsesExactTaskAndSafeInheritedNames(t *testing.T) {
+ t.Parallel()
+
+ inherited := []string{
+ "PATH=/usr/bin",
+ "SystemRoot=C:\\Windows",
+ "COMSPEC=C:\\Windows\\System32\\cmd.exe",
+ "PATHEXT=.COM;.EXE;.BAT;.CMD",
+ "USERPROFILE=C:\\Users\\test",
+ "APPDATA=C:\\Users\\test\\AppData\\Roaming",
+ "LOCALAPPDATA=C:\\Users\\test\\AppData\\Local",
+ "LANG=en_US.UTF-8",
+ "HTTPS_PROXY=http://proxy.example",
+ "SSL_CERT_FILE=/etc/ssl/cert.pem",
+ "SDKROOT=/opt/sdk",
+ "OPENAI_API_KEY=host-secret",
+ "GH_TOKEN=host-secret",
+ "MULTICA_LLM_API_KEY=daemon-secret",
+ "MULTICA_SERVER_URL=https://wrong.example",
+ }
+ explicit := map[string]string{
+ "MULTICA_TOKEN": "mat_task",
+ "MULTICA_SERVER_URL": "https://task.example",
+ "CUSTOM_FLAG": "enabled",
+ "ANTHROPIC_API_KEY": "agent-secret",
+ }
+
+ got := CodexShellEnvAllowlist(inherited, explicit)
+ want := []string{
+ "APPDATA",
+ "COMSPEC",
+ "CUSTOM_FLAG",
+ "HTTPS_PROXY",
+ "LANG",
+ "LOCALAPPDATA",
+ "MULTICA_SERVER_URL",
+ "MULTICA_TOKEN",
+ "PATH",
+ "PATHEXT",
+ "SDKROOT",
+ "SSL_CERT_FILE",
+ "SystemRoot",
+ "USERPROFILE",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("CodexShellEnvAllowlist() = %#v, want %#v", got, want)
+ }
+}
+
+func TestEnsureCodexShellEnvPolicyConfigReplacesAllLegalPolicyForms(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ existing string
+ kept []string
+ removed []string
+ }{
+ {
+ name: "root dotted multiline arrays",
+ existing: `# keep root comment
+model = "gpt-5.6"
+shell_environment_policy.inherit = "none"
+shell_environment_policy.include_only = [
+ "PATH", # old item comment
+ "HOME",
+]
+shell_environment_policy.exclude = [
+ "AWS_*",
+]
+
+[features]
+foo = true
+`,
+ kept: []string{"# keep root comment", `model = "gpt-5.6"`, "[features]", "foo = true"},
+ removed: []string{"old item comment", `"AWS_*"`},
+ },
+ {
+ name: "quoted table and comments",
+ existing: `model = "gpt-5.6"
+
+["shell_environment_policy"] # legal quoted table
+# policy-local comment remains harmless
+inherit = "none"
+include_only = [
+ "PATH",
+ "HOME",
+]
+set = { FOO = "bar", MULTICA_TOKEN = "stale" }
+
+[features]
+# keep feature comment
+foo = true
+`,
+ kept: []string{`model = "gpt-5.6"`, "# policy-local comment remains harmless", "# keep feature comment", "[features]", "foo = true"},
+ removed: []string{"legal quoted table", `FOO = "bar"`, `MULTICA_TOKEN = "stale"`},
+ },
+ {
+ name: "inline root and profile policies",
+ existing: `shell_environment_policy = { inherit = "none", include_only = ["PATH"] }
+
+[profiles.work]
+model = "gpt-5.6"
+shell_environment_policy = { inherit = "core", exclude = ["AWS_*"] }
+
+[features]
+foo = true
+
+[tools]
+shell_environment_policy = "unrelated key with the same name"
+`,
+ kept: []string{"[profiles.work]", `model = "gpt-5.6"`, "[features]", "foo = true", "[tools]", `shell_environment_policy = "unrelated key with the same name"`},
+ removed: []string{`inherit = "none"`, `inherit = "core"`, `"AWS_*"`},
+ },
+ {
+ name: "nested profile policy tables",
+ existing: `[profiles.work]
+model = "gpt-5.6"
+
+[profiles.work.shell_environment_policy]
+include_only = [
+ "PATH",
+]
+
+[profiles.work.shell_environment_policy.set]
+FOO = "bar"
+
+[features]
+foo = true
+`,
+ kept: []string{"[profiles.work]", `model = "gpt-5.6"`, "[features]", "foo = true"},
+ removed: []string{"[profiles.work.shell_environment_policy]", "[profiles.work.shell_environment_policy.set]", `FOO = "bar"`},
+ },
+ }
+
+ includeOnly := []string{"CUSTOM_FLAG", "MULTICA_SERVER_URL", "MULTICA_TOKEN", "PATH", "SystemRoot"}
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ configPath := filepath.Join(t.TempDir(), "config.toml")
+ if err := os.WriteFile(configPath, []byte(tt.existing), 0o644); err != nil {
+ t.Fatalf("write config.toml: %v", err)
+ }
+
+ if err := EnsureCodexShellEnvPolicyConfig(configPath, includeOnly, testLogger()); err != nil {
+ t.Fatalf("EnsureCodexShellEnvPolicyConfig: %v", err)
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config.toml: %v", err)
+ }
+ s := string(data)
+ assertValidToml(t, s)
+ for _, want := range tt.kept {
+ if !strings.Contains(s, want) {
+ t.Errorf("lost unrelated content %q:\n%s", want, s)
+ }
+ }
+ for _, unwanted := range tt.removed {
+ if strings.Contains(s, unwanted) {
+ t.Errorf("stale policy content %q remains:\n%s", unwanted, s)
+ }
+ }
+ if strings.Contains(s, `"MULTICA_*"`) {
+ t.Fatalf("managed policy must not use a MULTICA_* wildcard:\n%s", s)
+ }
+ if n := strings.Count(s, "[shell_environment_policy]"); n != 1 {
+ t.Fatalf("expected exactly one managed policy table, got %d:\n%s", n, s)
+ }
+ policy := parsedShellEnvPolicy(t, s)
+ if policy.Inherit != "all" || !policy.IgnoreDefaultExcludes {
+ t.Fatalf("unexpected managed policy: %#v", policy)
+ }
+ if !reflect.DeepEqual(policy.IncludeOnly, includeOnly) {
+ t.Fatalf("include_only = %#v, want %#v", policy.IncludeOnly, includeOnly)
+ }
+ })
+ }
+}
+
+func TestEnsureCodexShellEnvPolicyConfigRejectsInvalidInputWithoutWriting(t *testing.T) {
+ t.Parallel()
+
+ configPath := filepath.Join(t.TempDir(), "config.toml")
+ existing := []byte("model = [\n")
+ if err := os.WriteFile(configPath, existing, 0o644); err != nil {
+ t.Fatalf("write config.toml: %v", err)
+ }
+ if err := EnsureCodexShellEnvPolicyConfig(configPath, []string{"MULTICA_TOKEN", "PATH"}, testLogger()); err == nil {
+ t.Fatal("expected malformed input to fail")
+ }
+ got, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config.toml: %v", err)
+ }
+ if !reflect.DeepEqual(got, existing) {
+ t.Fatalf("invalid input was modified: got %q, want %q", got, existing)
+ }
+}
+
+func TestEnsureCodexShellEnvPolicyConfigIsIdempotent(t *testing.T) {
+ t.Parallel()
+ configPath := filepath.Join(t.TempDir(), "config.toml")
+ includeOnly := []string{"MULTICA_SERVER_URL", "MULTICA_TOKEN", "PATH"}
+
+ for i := 0; i < 3; i++ {
+ if err := EnsureCodexShellEnvPolicyConfig(configPath, includeOnly, testLogger()); err != nil {
+ t.Fatalf("pass %d: %v", i, err)
+ }
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config.toml: %v", err)
+ }
+ s := string(data)
+ assertValidToml(t, s)
+ if n := strings.Count(s, multicaShellEnvBeginMarker); n != 1 {
+ t.Fatalf("expected exactly one managed block, got %d:\n%s", n, s)
+ }
+}
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 89de2d2682..aa80313821 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -749,7 +749,10 @@ func mergeEnv(base []string, extra map[string]string) []string {
env := make([]string, 0, len(base)+len(extra))
for _, entry := range base {
key, _, _ := strings.Cut(entry, "=")
- if isFilteredChildEnvKey(key) {
+ // MULTICA_* in the daemon's own environment is not task context. Drop
+ // the inherited namespace for every backend and append only the values
+ // daemon.go explicitly assembled for this task below.
+ if isFilteredChildEnvKey(key) || strings.HasPrefix(strings.ToUpper(key), "MULTICA_") {
continue
}
env = append(env, entry)
diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.go
index 7b0a263134..6d397d2df6 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -589,7 +589,13 @@ func TestMergeEnvFiltersClaudeCodeVars(t *testing.T) {
"CLAUDE_CODE_GIT_BASH_PATH=C:\\Program Files\\Git\\bin\\bash.exe",
"CLAUDE_CODE_USE_BEDROCK=1",
"CLAUDE_CODE_TMPDIR=/custom/tmp",
- }, map[string]string{"FOO": "bar"})
+ "MULTICA_LLM_API_KEY=daemon-secret",
+ "MULTICA_SERVER_URL=https://daemon.example",
+ }, map[string]string{
+ "FOO": "bar",
+ "MULTICA_SERVER_URL": "https://task.example",
+ "MULTICA_TOKEN": "mat_task",
+ })
// Internal runtime/session markers must be stripped so the child does not
// inherit the parent's identity or transport.
@@ -599,6 +605,8 @@ func TestMergeEnvFiltersClaudeCodeVars(t *testing.T) {
"CLAUDE_CODE_EXECPATH=/opt/claude",
"CLAUDE_CODE_SESSION_ID=abc123",
"CLAUDE_CODE_SSE_PORT=9999",
+ "MULTICA_LLM_API_KEY=daemon-secret",
+ "MULTICA_SERVER_URL=https://daemon.example",
}
for _, entry := range env {
for _, banned := range filteredOut {
@@ -635,6 +643,9 @@ func TestMergeEnvFiltersClaudeCodeVars(t *testing.T) {
if !found["FOO=bar"] {
t.Fatalf("expected extra env var to be appended, got %v", env)
}
+ if !found["MULTICA_SERVER_URL=https://task.example"] || !found["MULTICA_TOKEN=mat_task"] {
+ t.Fatalf("expected explicit task MULTICA_* values to be appended, got %v", env)
+ }
}
func TestBuildEnvAppendsExtras(t *testing.T) {
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 456d8f4848..b9a43f2ee5 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -157,6 +157,17 @@ func hasManagedCodexMcpConfig(raw json.RawMessage) bool {
// `$CODEX_HOME/config.toml`.
var codexManagedMcpConfigKeyRe = regexp.MustCompile(`^\s*mcp_servers(?:\s*\.|\s*=|\s*$)`)
+// A daemon-managed shell_environment_policy must also win over profile and
+// custom-arg overrides. Match root and profile policy keys without catching an
+// unrelated table field that happens to use the same final key name.
+const (
+ codexShellEnvPolicyKeyPattern = `(?:shell_environment_policy|"shell_environment_policy"|'shell_environment_policy')`
+ codexProfileNameKeyPattern = `(?:[A-Za-z0-9_-]+|"[^"]+"|'[^']+')`
+)
+
+var codexManagedShellEnvConfigKeyRe = regexp.MustCompile(
+ `^\s*(?:` + codexShellEnvPolicyKeyPattern + `|profiles\s*\.\s*` + codexProfileNameKeyPattern + `\s*\.\s*` + codexShellEnvPolicyKeyPattern + `)\s*(?:\.|=|$)`)
+
// filterCodexCustomConfigOverrides drops `-c mcp_servers.…=` and
// `--config mcp_servers.…=` entries from custom args. Codex's `-c` is
// last-wins (verified against codex-cli 0.132.0), so without this filter a
@@ -166,6 +177,16 @@ var codexManagedMcpConfigKeyRe = regexp.MustCompile(`^\s*mcp_servers(?:\s*\.|\s*
// to write into it are dropped with a warning rather than allowed to win.
// Other `-c`/`--config` keys (e.g. `-c model="o3"`) pass through unchanged.
func filterCodexCustomConfigOverrides(args []string, logger *slog.Logger) []string {
+ return filterCodexConfigOverrides(args, codexManagedMcpConfigKeyRe, "mcp_servers", logger)
+}
+
+func filterCodexShellEnvConfigOverrides(args []string, logger *slog.Logger) []string {
+ return filterCodexConfigOverrides(args, codexManagedShellEnvConfigKeyRe, shellEnvironmentPolicyConfigNamespace, logger)
+}
+
+const shellEnvironmentPolicyConfigNamespace = "shell_environment_policy"
+
+func filterCodexConfigOverrides(args []string, managedKeyRe *regexp.Regexp, namespace string, logger *slog.Logger) []string {
if len(args) == 0 {
return args
}
@@ -185,17 +206,16 @@ func filterCodexCustomConfigOverrides(args []string, logger *slog.Logger) []stri
if !hasInlineValue && i+1 < len(args) {
value = args[i+1]
}
- if codexManagedMcpConfigKeyRe.MatchString(value) {
+ if managedKeyRe.MatchString(value) {
if logger != nil {
- // Log the key only, never the value — mcp_servers.<name>.env
- // is allowed to carry secrets and the whole point of moving
- // this to config.toml is to keep raw values out of logs/argv.
+ // Log the key only, never the value. Managed config values
+ // may contain secrets and must stay out of logs/argv.
key := value
if eqIdx := strings.Index(value, "="); eqIdx >= 0 {
key = value[:eqIdx]
}
- logger.Warn("custom_args: blocked mcp_servers override; daemon manages this via CODEX_HOME/config.toml",
- "flag", flag, "key", strings.TrimSpace(key))
+ logger.Warn("custom_args: blocked managed Codex config override",
+ "namespace", namespace, "flag", flag, "key", strings.TrimSpace(key))
}
if !hasInlineValue && i+1 < len(args) {
i++ // skip the value arg
@@ -656,7 +676,8 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// echoed into the daemon's `agent command` log line below, so any
// inline env-bearing TOML would defeat the redaction. Writing through
// config.toml at 0o600 keeps the secret values out of argv and logs.
- if codexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"]); codexHome != "" {
+ codexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])
+ if codexHome != "" {
if err := ensureCodexMcpConfig(filepath.Join(codexHome, "config.toml"), opts.McpConfig, b.cfg.Logger); err != nil {
// Fail closed when we can't materialise the managed config.
// Warning-and-launching would silently fall back to the
@@ -676,6 +697,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
return nil, fmt.Errorf("codex: mcp_config is set but CODEX_HOME env var is not configured; cannot apply managed MCP")
}
+ if codexHome != "" {
+ // The daemon owns shell_environment_policy in the task-local config.
+ // Codex -c/--config overrides are last-wins, so remove user-provided
+ // root or profile policy overrides before building the final argv.
+ opts.ExtraArgs = filterCodexShellEnvConfigOverrides(opts.ExtraArgs, b.cfg.Logger)
+ opts.CustomArgs = filterCodexShellEnvConfigOverrides(opts.CustomArgs, b.cfg.Logger)
+ }
codexArgs := buildCodexArgs(opts, b.cfg.Logger)
cmd := exec.CommandContext(runCtx, execPath, codexArgs...)
hideAgentWindow(cmd)
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 5b8bb32ffd..a3cdafed3e 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -2716,6 +2716,46 @@ func TestFilterCodexCustomConfigOverridesDropsMcpServers(t *testing.T) {
}
}
+func TestFilterCodexShellEnvConfigOverrides(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ in []string
+ want []string
+ }{
+ {
+ name: "root policy override",
+ in: []string{"-c", `shell_environment_policy.include_only=["PATH"]`, "-c", `model="o3"`},
+ want: []string{"-c", `model="o3"`},
+ },
+ {
+ name: "profile policy override",
+ in: []string{`--config=profiles.work.shell_environment_policy.ignore_default_excludes=false`, "--sandbox", "workspace-write"},
+ want: []string{"--sandbox", "workspace-write"},
+ },
+ {
+ name: "quoted policy key",
+ in: []string{"--config", `profiles.work."shell_environment_policy".inherit="none"`},
+ want: []string{},
+ },
+ {
+ name: "unrelated override survives",
+ in: []string{"-c", `model="o3"`, "-c", `profiles.work.model="gpt-5.6"`, "-c", `tools.shell_environment_policy="metadata"`},
+ want: []string{"-c", `model="o3"`, "-c", `profiles.work.model="gpt-5.6"`, "-c", `tools.shell_environment_policy="metadata"`},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got := filterCodexShellEnvConfigOverrides(tc.in, slog.Default())
+ if !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("filterCodexShellEnvConfigOverrides(%v) = %v, want %v", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
func TestEnsureCodexMcpConfigEmptyClearsBlock(t *testing.T) {
t.Parallel()