Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): keep the runtime owner's Reasonix deny rules in a task (MUL-6021) (#6764)
Bohan Jiange0d0b3815342
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex be555e9a6c..a2556c3c60 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5872,6 +5872,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot idefer d.unmarkActiveStore(store)}}+ // Reasonix locates its user config from the environment (REASONIX_HOME, and+ // the platform config dirs behind it), which an agent's custom_env may+ // re-point or clear. The per-task reasonix.toml has to restate the+ // permissions from whichever config the child ends up loading, so the deny+ // rules the runtime owner set there survive the task-scoped config that+ // overrides them — hence the same sanitized env the child is launched with.+ var reasonixEnv map[string]string+ if provider == "reasonix" {+ reasonixEnv = sanitizeAgentEnv(agentEnvOverrides)+ }// Guard this task's per-issue Codex session store from the GC for the whole// task, starting before Prepare/Reuse mounts it — so a prune that samples the// store's stale (pre-remount) mtime cannot reclaim it out from under a resume@@ -5899,6 +5909,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,HermesMemoryStore: hermesMemoryStore,+ ReasonixEnv: reasonixEnv,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,})@@ -5924,6 +5935,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,HermesMemoryStore: hermesMemoryStore,+ ReasonixEnv: reasonixEnv,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex b048426e6b..051c6afe28 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -86,6 +86,12 @@ type PrepareParams struct {// blocklisted keys) used to expand ${VAR} in Hermes external_dirs so it// matches what the Hermes child process actually sees. Only used for hermes.HermesEnv map[string]string+ // ReasonixEnv is the sanitized agent custom_env, layered over the daemon's+ // own environment exactly as the child's env is built. The per-task+ // reasonix.toml restates the permissions from the user config that env+ // resolves to, so an agent that re-points (or clears) REASONIX_HOME moves the+ // daemon's read with it. Only used for reasonix.+ ReasonixEnv map[string]string// CodexCustomArgs are the effective Codex CLI args this task launches with// (daemon defaults + profile-fixed + per-agent custom_args). Only the// Windows sandbox decision reads them, to honor a `-c windows.sandbox=...`@@ -408,7 +414,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {// reasonix.toml. Degraded, not fatal: without it the task still runs under// the backend's fail-closed question handling.if params.Provider == "reasonix" {- if err := writeReasonixProjectConfig(workDir, manifest, logger); err != nil {+ if err := writeReasonixProjectConfig(workDir, params.ReasonixEnv, manifest, logger); err != nil {logger.Warn("execenv: write reasonix project config failed", "error", err)}}@@ -501,6 +507,9 @@ type ReuseParams struct {HermesSourceMustExist boolHermesEnv map[string]stringHermesMemoryStore string+ // ReasonixEnv mirrors PrepareParams.ReasonixEnv on reuse so the rewritten+ // reasonix.toml keeps restating the owner's current permissions.+ ReasonixEnv map[string]string// CodexCustomArgs mirrors PrepareParams.CodexCustomArgs on reuse so the// Windows sandbox decision honors a `-c windows.sandbox=...` override here// too (MUL-4957).@@ -634,7 +643,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {// prior run's reasonix.toml, so without this the next turn would run with// the tool available again.if params.Provider == "reasonix" {- if err := writeReasonixProjectConfig(params.WorkDir, manifest, logger); err != nil {+ if err := writeReasonixProjectConfig(params.WorkDir, params.ReasonixEnv, manifest, logger); err != nil {logger.Warn("execenv: refresh reasonix project config failed", "error", err)}}diff --git a/server/internal/daemon/execenv/reasonix_permissions.go b/server/internal/daemon/execenv/reasonix_permissions.goindex 51cddcb8f7..98623c483e 100644--- a/server/internal/daemon/execenv/reasonix_permissions.go+++ b/server/internal/daemon/execenv/reasonix_permissions.go@@ -3,8 +3,12 @@ package execenvimport ("errors""fmt"+ "io/fs""log/slog"+ "os""path/filepath"++ "github.com/pelletier/go-toml/v2")// reasonixProjectConfigFile is Reasonix's project-scoped config. Reasonix@@ -14,7 +18,15 @@ import (// interactive sessions alone.const reasonixProjectConfigFile = "reasonix.toml"-// reasonixProjectConfig turns off Reasonix's `ask` tool for the task.+// reasonixUserConfigFile is the runtime owner's own Reasonix config; where it+// lives is resolved in reasonix_user_config.go. It is never written to — the+// daemon only reads the permissions the owner set there.+const reasonixUserConfigFile = "config.toml"++// reasonixAskTool is the Reasonix tool the per-task config denies.+const reasonixAskTool = "ask"++// reasonixProjectConfigHeader precedes the rendered [permissions] table.//// `ask` puts a multiple-choice question to a human mid-turn. An unattended task// has no human: Reasonix wires an asker for every ACP session, so the runtime's@@ -29,37 +41,142 @@ const reasonixProjectConfigFile = "reasonix.toml"// decide against the same policy — where a tool-call hook would only ever reach// the executor. The model gets "denied by permission policy" back as an ordinary// tool result and keeps working.-//-// Deny is a replacing list, not an additive one: for the duration of a task in-// this workdir this is the effective deny list, so a deny rule in the runtime-// owner's global config does not apply here. That is a deliberate, accepted-// widening of what the agent may run in a task workdir — not something the-// daemon's other constraints (--workspace-only, the ACP permission policy) make-// equivalent. Extending the global list instead would mean parsing the runtime-// owner's config to restate it, which is its own failure mode.-const reasonixProjectConfig = `# Managed by Multica. Written per task, removed when the task env is cleaned up.+const reasonixProjectConfigHeader = `# Managed by Multica. Written per task, removed when the task env is cleaned up.# Edits are not preserved.+#+# [permissions] restates the runtime owner's own table from the Reasonix user+# config, with the ask tool added to deny: no human can answer a question in an+# unattended task, and an unanswered question cancels the Reasonix turn. Denying+# the tool instead lets the model take its own decision and keep going.-[permissions]-# No human can answer a question in an unattended task, and an unanswered-# question cancels the Reasonix turn. Denying the tool instead lets the model-# take its own decision and keep going.-deny = ["ask"]`-// writeReasonixProjectConfig lays down the per-task reasonix.toml in workDir.+// reasonixOwnerPermissions returns the [permissions] table the runtime owner+// configured, or nil when there is no config or no such table. An unreadable or+// unparseable config is an error: the caller must not write a permissions table+// it could not derive from the owner's, because the project file replaces the+// owner's rules rather than adding to them.+func reasonixOwnerPermissions(path string) (map[string]any, error) {+ if path == "" {+ return nil, nil+ }+ data, err := os.ReadFile(path)+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ if err != nil {+ return nil, fmt.Errorf("read reasonix user config %s: %w", path, err)+ }+ var cfg map[string]any+ if err := toml.Unmarshal(data, &cfg); err != nil {+ return nil, fmt.Errorf("parse reasonix user config %s: %w", path, err)+ }+ raw, ok := cfg["permissions"]+ if !ok || raw == nil {+ return nil, nil+ }+ perms, ok := raw.(map[string]any)+ if !ok {+ return nil, fmt.Errorf("reasonix user config %s: [permissions] is %T, want a table", path, raw)+ }+ return perms, nil+}++// withReasonixAskDenied copies the owner's permissions table and adds `ask` to+// its deny list. The whole table is carried over, not just deny: the project+// file overrides what it declares, so restating every key the owner set is what+// keeps their policy intact whether Reasonix merges these layers per key or per+// table.+func withReasonixAskDenied(ownerPermissions map[string]any) (map[string]any, error) {+ deny, err := reasonixDenyList(ownerPermissions["deny"])+ if err != nil {+ return nil, err+ }+ merged := make(map[string]any, len(ownerPermissions)+1)+ for k, v := range ownerPermissions {+ merged[k] = v+ }+ for _, rule := range deny {+ if rule == reasonixAskTool {+ merged["deny"] = deny+ return merged, nil+ }+ }+ merged["deny"] = append(deny, reasonixAskTool)+ return merged, nil+}++// reasonixDenyList reads the owner's deny rules as strings. A shape this cannot+// restate faithfully is an error rather than a silent reset to ["ask"], which+// would drop every rule the owner wrote.+func reasonixDenyList(raw any) ([]string, error) {+ if raw == nil {+ return nil, nil+ }+ entries, ok := raw.([]any)+ if !ok {+ return nil, fmt.Errorf("reasonix user config: [permissions] deny is %T, want an array of strings", raw)+ }+ rules := make([]string, 0, len(entries)+1)+ for _, entry := range entries {+ rule, ok := entry.(string)+ if !ok {+ return nil, fmt.Errorf("reasonix user config: [permissions] deny entry is %T, want a string", entry)+ }+ rules = append(rules, rule)+ }+ return rules, nil+}++// reasonixProjectConfig renders the task's reasonix.toml from the owner's config+// at userConfigPath (which need not exist).+func reasonixProjectConfig(userConfigPath string) ([]byte, error) {+ ownerPermissions, err := reasonixOwnerPermissions(userConfigPath)+ if err != nil {+ return nil, err+ }+ permissions, err := withReasonixAskDenied(ownerPermissions)+ if err != nil {+ return nil, err+ }+ body, err := toml.Marshal(map[string]any{"permissions": permissions})+ if err != nil {+ return nil, fmt.Errorf("encode reasonix project config: %w", err)+ }+ return append([]byte(reasonixProjectConfigHeader), body...), nil+}++// writeReasonixProjectConfig lays down the per-task reasonix.toml in workDir,+// denying the `ask` tool on top of the runtime owner's own permissions.+// taskEnv is the agent's sanitized custom_env, which decides — together with the+// daemon's own environment — which user config the Reasonix child will load+// (reasonix_user_config.go).//// A reasonix.toml that came with the repository is left untouched: sidecar// cleanup is a pure deletion of paths the daemon created, so it must never// overwrite user content. That case is a warning rather than a failure — the// task still runs, `ask` stays available, and a question that does arrive hits// the existing fail-closed permission handling in the reasonix backend.-func writeReasonixProjectConfig(workDir string, manifest *sidecarManifest, logger *slog.Logger) error {+//+// The same holds when the owner's config cannot be read or restated: the daemon+// writes nothing rather than a table that silently drops their deny rules.+func writeReasonixProjectConfig(workDir string, taskEnv map[string]string, manifest *sidecarManifest, logger *slog.Logger) error {if workDir == "" {return nil}+ userConfig := reasonixEnv(taskEnv).userConfigLoadPath()+ content, err := reasonixProjectConfig(userConfig)+ if err != nil {+ if logger != nil {+ logger.Warn("execenv: cannot restate the reasonix user permissions; leaving the task without a project config — the reasonix ask tool stays enabled for this task",+ "user_config", userConfig,+ "error", err,+ )+ }+ return nil+ }path := filepath.Join(workDir, reasonixProjectConfigFile)- err := recordWriteFile(path, []byte(reasonixProjectConfig), 0o644, manifest)+ err = recordWriteFile(path, content, 0o644, manifest)if errors.Is(err, errPathPreExists) {if logger != nil {logger.Warn("execenv: project reasonix.toml already exists; leaving it untouched — the reasonix ask tool stays enabled for this task",diff --git a/server/internal/daemon/execenv/reasonix_permissions_test.go b/server/internal/daemon/execenv/reasonix_permissions_test.goindex 228feafc03..bbf2172fc5 100644--- a/server/internal/daemon/execenv/reasonix_permissions_test.go+++ b/server/internal/daemon/execenv/reasonix_permissions_test.go@@ -3,10 +3,54 @@ package execenvimport ("os""path/filepath"+ "slices""strings""testing"++ "github.com/pelletier/go-toml/v2")+// reasonixEnvWith writes a Reasonix user config.toml into a fresh home and+// returns the task env pointing at it, so a test never reads the machine's real+// Reasonix config.+func reasonixEnvWith(t *testing.T, config string) map[string]string {+ t.Helper()+ home := t.TempDir()+ if config != "" {+ if err := os.WriteFile(filepath.Join(home, reasonixUserConfigFile), []byte(config), 0o600); err != nil {+ t.Fatalf("seed reasonix user config: %v", err)+ }+ }+ return map[string]string{"REASONIX_HOME": home}+}++// assertTaskDenyList checks the deny rules in a written per-task reasonix.toml.+func assertTaskDenyList(t *testing.T, path string, want []string) {+ t.Helper()+ if got := taskDenyList(t, path); !slices.Equal(got, want) {+ t.Fatalf("deny = %v, want %v", got, want)+ }+}++// taskDenyList decodes the deny rules from a written per-task reasonix.toml.+func taskDenyList(t *testing.T, path string) []string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", reasonixProjectConfigFile, err)+ }+ var cfg struct {+ Permissions struct {+ Deny []string `toml:"deny"`+ Allow []string `toml:"allow"`+ } `toml:"permissions"`+ }+ if err := toml.Unmarshal(data, &cfg); err != nil {+ t.Fatalf("parse written %s: %v\n%s", reasonixProjectConfigFile, err, data)+ }+ return cfg.Permissions.Deny+}+func TestPrepareDeniesReasonixAskTool(t *testing.T) {t.Parallel()env, err := Prepare(PrepareParams{@@ -15,6 +59,7 @@ func TestPrepareDeniesReasonixAskTool(t *testing.T) {TaskID: "b1b2c3d4-e5f6-7890-abcd-ef1234567890",AgentName: "Reasonix Agent",Provider: "reasonix",+ ReasonixEnv: reasonixEnvWith(t, ""),Task: TaskContextForEnv{IssueID: "b1b2c3d4-e5f6-7890-abcd-ef1234567890"},}, testLogger())if err != nil {@@ -23,12 +68,8 @@ func TestPrepareDeniesReasonixAskTool(t *testing.T) {defer env.Cleanup(true)configPath := filepath.Join(env.WorkDir, reasonixProjectConfigFile)- data, err := os.ReadFile(configPath)- if err != nil {- t.Fatalf("read %s: %v", reasonixProjectConfigFile, err)- }- if !strings.Contains(string(data), "[permissions]") || !strings.Contains(string(data), `deny = ["ask"]`) {- t.Fatalf("project config does not deny ask:\n%s", data)+ if got := taskDenyList(t, configPath); !slices.Equal(got, []string{"ask"}) {+ t.Fatalf("deny = %v, want [ask]", got)}// The sidecar is daemon-owned state, so CleanupSidecars must take it back@@ -49,6 +90,7 @@ func TestReuseRewritesReasonixAskDeny(t *testing.T) {TaskID: "c1b2c3d4-e5f6-7890-abcd-ef1234567890",AgentName: "Reasonix Agent",Provider: "reasonix",+ ReasonixEnv: reasonixEnvWith(t, "[permissions]\ndeny = [\"bash\"]\n"),Task: TaskContextForEnv{IssueID: "c1b2c3d4-e5f6-7890-abcd-ef1234567890"},}env, err := Prepare(params, testLogger())@@ -64,17 +106,107 @@ func TestReuseRewritesReasonixAskDeny(t *testing.T) {WorkspacesRoot: params.WorkspacesRoot,WorkDir: env.WorkDir,Provider: "reasonix",+ ReasonixEnv: params.ReasonixEnv,Task: params.Task,}, testLogger())if reused == nil {t.Fatal("Reuse returned nil")}- data, err := os.ReadFile(filepath.Join(reused.WorkDir, reasonixProjectConfigFile))+ got := taskDenyList(t, filepath.Join(reused.WorkDir, reasonixProjectConfigFile))+ if !slices.Equal(got, []string{"bash", "ask"}) {+ t.Fatalf("deny after reuse = %v, want [bash ask]", got)+ }+}++// TestReasonixProjectConfigMergesOwnerPermissions is the regression test for the+// task config replacing the runtime owner's deny list instead of extending it:+// a global `deny = ["bash"]` must still deny bash inside the task.+func TestReasonixProjectConfigMergesOwnerPermissions(t *testing.T) {+ t.Parallel()+ env := reasonixEnvWith(t, `[permissions]+deny = ["bash", "config_write"]+allow = ["read"]++[model]+default = "some-model"+`)+ workDir := t.TempDir()++ if err := writeReasonixProjectConfig(workDir, env, &sidecarManifest{}, testLogger()); err != nil {+ t.Fatalf("writeReasonixProjectConfig: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(workDir, reasonixProjectConfigFile))if err != nil {- t.Fatalf("read %s after reuse: %v", reasonixProjectConfigFile, err)+ t.Fatalf("read %s: %v", reasonixProjectConfigFile, err)+ }+ var cfg struct {+ Permissions struct {+ Deny []string `toml:"deny"`+ Allow []string `toml:"allow"`+ } `toml:"permissions"`+ }+ if err := toml.Unmarshal(data, &cfg); err != nil {+ t.Fatalf("parse written %s: %v\n%s", reasonixProjectConfigFile, err, data)+ }+ if !slices.Equal(cfg.Permissions.Deny, []string{"bash", "config_write", "ask"}) {+ t.Fatalf("deny = %v, want the owner's rules plus ask", cfg.Permissions.Deny)+ }+ // The rest of the owner's table is restated too: the project file overrides+ // what it declares, so dropping allow here would widen the task as well.+ if !slices.Equal(cfg.Permissions.Allow, []string{"read"}) {+ t.Fatalf("allow = %v, want the owner's [read]", cfg.Permissions.Allow)+ }+ // Only permissions are restated; unrelated owner settings stay in their own+ // config, where the task still inherits them.+ if strings.Contains(string(data), "some-model") {+ t.Fatalf("project config copied unrelated owner settings:\n%s", data)}- if !strings.Contains(string(data), `deny = ["ask"]`) {- t.Fatalf("reused task lost the ask deny rule:\n%s", data)+}++// TestReasonixProjectConfigKeepsOwnerAskDeny checks the already-denied case: the+// merge must not append a duplicate rule.+func TestReasonixProjectConfigKeepsOwnerAskDeny(t *testing.T) {+ t.Parallel()+ env := reasonixEnvWith(t, "[permissions]\ndeny = [\"ask\", \"bash\"]\n")+ workDir := t.TempDir()++ if err := writeReasonixProjectConfig(workDir, env, &sidecarManifest{}, testLogger()); err != nil {+ t.Fatalf("writeReasonixProjectConfig: %v", err)+ }+ got := taskDenyList(t, filepath.Join(workDir, reasonixProjectConfigFile))+ if !slices.Equal(got, []string{"ask", "bash"}) {+ t.Fatalf("deny = %v, want the owner's list unchanged", got)+ }+}++// TestReasonixProjectConfigSkipsUnreadableOwnerConfig covers the fail-closed+// path: a config the daemon cannot restate must leave the task without a+// project config rather than with one that drops the owner's rules.+func TestReasonixProjectConfigSkipsUnreadableOwnerConfig(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ config string+ }{+ {name: "malformed toml", config: "[permissions\ndeny = "},+ {name: "deny is not an array", config: "[permissions]\ndeny = \"bash\"\n"},+ {name: "deny holds a table", config: "[permissions]\ndeny = [{ tool = \"bash\" }]\n"},+ {name: "permissions is not a table", config: "permissions = \"strict\"\n"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ workDir := t.TempDir()+ manifest := &sidecarManifest{}+ if err := writeReasonixProjectConfig(workDir, reasonixEnvWith(t, tc.config), manifest, testLogger()); err != nil {+ t.Fatalf("writeReasonixProjectConfig: %v", err)+ }+ if _, err := os.Stat(filepath.Join(workDir, reasonixProjectConfigFile)); !os.IsNotExist(err) {+ t.Fatalf("wrote a project config from an owner config it could not restate (stat err = %v)", err)+ }+ if len(manifest.Files) != 0 {+ t.Fatalf("manifest recorded a file it did not write: %+v", manifest.Files)+ }+ })}}@@ -92,7 +224,7 @@ func TestReasonixProjectConfigKeepsRepositoryFile(t *testing.T) {// reports success so the task still runs (with ask enabled, caught by the// backend's fail-closed question handling).manifest := &sidecarManifest{}- if err := writeReasonixProjectConfig(workDir, manifest, testLogger()); err != nil {+ if err := writeReasonixProjectConfig(workDir, reasonixEnvWith(t, ""), manifest, testLogger()); err != nil {t.Fatalf("writeReasonixProjectConfig: %v", err)}data, err := os.ReadFile(configPath)diff --git a/server/internal/daemon/execenv/reasonix_user_config.go b/server/internal/daemon/execenv/reasonix_user_config.gonew file mode 100644index 0000000000..085f391ac2--- /dev/null+++ b/server/internal/daemon/execenv/reasonix_user_config.go@@ -0,0 +1,278 @@+package execenv++import (+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+)++// Finding the runtime owner's Reasonix config is not a best-effort lookup: the+// per-task reasonix.toml replaces whatever [permissions] the owner set, so a+// config the daemon fails to find is a deny list the task silently drops. The+// file has to be the one the Reasonix child will actually load, on every+// platform and for every way the owner can move it.+//+// So the resolution below is a port of Reasonix's own (internal/config/paths.go+// in DeepSeek-Reasonix, v2), not an approximation of it:+//+// - REASONIX_HOME wins, after ${VAR} / ${VAR:-default} expansion, ~ handling,+// and absolute-path normalization.+// - Without it, the home is %AppData%\reasonix on Windows (falling back to+// %USERPROFILE%\AppData\Roaming\reasonix) and ~/.reasonix everywhere else.+// - config.toml under that home is the primary path. When it does not exist+// AND REASONIX_HOME is unset, Reasonix reads the legacy OS-support and XDG+// locations instead — so the daemon has to look there too.+//+// Divergence here is a security bug, not a cosmetic one. Keep this in step with+// upstream.++// reasonixGOOS is runtime.GOOS, overridable so tests can cover the Windows+// resolution from any runner. Never assigned outside tests.+var reasonixGOOS = runtime.GOOS++// reasonixVarRef matches ${VAR} and ${VAR:-default}, mirroring Reasonix's+// ExpandVars.+var reasonixVarRef = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}`)++// reasonixEnv is the environment the task's Reasonix child will see: the+// agent's custom_env (already stripped of daemon-blocklisted keys) layered over+// the daemon's own environment, the way the agent process builds its child env.+//+// Presence is what makes this a map rather than a single home string: an agent+// that sets REASONIX_HOME="" has overridden it to empty, which sends the child+// back to the platform default — reading the daemon's own REASONIX_HOME there+// would point at a different config than the one the task runs against.+type reasonixEnv map[string]string++// lookup resolves one variable the way the child would: the agent's override+// when it declared one, else the daemon's own environment.+func (e reasonixEnv) lookup(name string) string {+ if v, ok := e[name]; ok {+ return v+ }+ if reasonixGOOS == "windows" {+ // Windows environment names are case-insensitive, and so is os.Getenv+ // there; an agent that wrote "APPDATA" still overrides "AppData".+ for k, v := range e {+ if strings.EqualFold(k, name) {+ return v+ }+ }+ }+ return os.Getenv(name)+}++// expandVars substitutes ${VAR} / ${VAR:-default}. An unset OR empty variable+// takes the default, matching Reasonix.+func (e reasonixEnv) expandVars(s string) string {+ if !strings.Contains(s, "${") {+ return s+ }+ return reasonixVarRef.ReplaceAllStringFunc(s, func(match string) string {+ groups := reasonixVarRef.FindStringSubmatch(match)+ if value := e.lookup(groups[1]); value != "" {+ return value+ }+ if groups[2] != "" {+ return groups[3]+ }+ return ""+ })+}++// cleanDir reads a directory-valued variable the way Reasonix's cleanEnvDir+// does: trim, expand, resolve a leading ~, make absolute, clean.+func (e reasonixEnv) cleanDir(name string) string {+ dir := strings.TrimSpace(e.lookup(name))+ if dir == "" {+ return ""+ }+ dir = e.expandVars(dir)+ if dir == "~" {+ if home := e.userHomeDir(); home != "" {+ dir = home+ }+ } else if strings.HasPrefix(dir, "~/") || strings.HasPrefix(dir, `~\`) {+ if home := e.userHomeDir(); home != "" {+ dir = filepath.Join(home, dir[2:])+ }+ }+ if !filepath.IsAbs(dir) {+ if abs, err := filepath.Abs(dir); err == nil {+ dir = abs+ }+ }+ return filepath.Clean(dir)+}++// userHomeDir ports os.UserHomeDir against the child's env.+func (e reasonixEnv) userHomeDir() string {+ if reasonixGOOS == "windows" {+ return e.lookup("USERPROFILE")+ }+ return e.lookup("HOME")+}++// userConfigDir ports os.UserConfigDir against the child's env.+func (e reasonixEnv) userConfigDir() string {+ switch reasonixGOOS {+ case "windows":+ return e.lookup("AppData")+ case "darwin", "ios":+ home := e.userHomeDir()+ if home == "" {+ return ""+ }+ return filepath.Join(home, "Library", "Application Support")+ default:+ if dir := e.lookup("XDG_CONFIG_HOME"); dir != "" {+ if !filepath.IsAbs(dir) {+ return "" // os.UserConfigDir rejects a relative XDG_CONFIG_HOME+ }+ return dir+ }+ home := e.userHomeDir()+ if home == "" {+ return ""+ }+ return filepath.Join(home, ".config")+ }+}++// isolatedHome is Reasonix's IsolatedHomeDir: a non-empty REASONIX_HOME marks a+// self-contained runtime, which switches off every legacy fallback below.+func (e reasonixEnv) isolatedHome() string {+ return e.cleanDir("REASONIX_HOME")+}++// homeDir is Reasonix's reasonixHomeDir.+func (e reasonixEnv) homeDir() string {+ if dir := e.isolatedHome(); dir != "" {+ return dir+ }+ if reasonixGOOS == "windows" {+ if dir := e.userConfigDir(); dir != "" {+ return filepath.Join(dir, "reasonix")+ }+ if home := e.userHomeDir(); home != "" {+ return filepath.Join(home, "AppData", "Roaming", "reasonix")+ }+ return ""+ }+ if home := e.userHomeDir(); home != "" {+ return filepath.Join(home, ".reasonix")+ }+ if dir := e.userConfigDir(); dir != "" {+ return filepath.Join(dir, "reasonix")+ }+ return ""+}++// userConfigPath is the primary config.toml under the Reasonix home.+func (e reasonixEnv) userConfigPath() string {+ dir := e.homeDir()+ if dir == "" {+ return ""+ }+ return filepath.Join(dir, reasonixUserConfigFile)+}++// legacyOSSupportDir is the pre-Reasonix-home OS app-support directory, empty+// when REASONIX_HOME isolates the runtime or when it is the home already.+func (e reasonixEnv) legacyOSSupportDir() string {+ if e.isolatedHome() != "" {+ return ""+ }+ dir := e.userConfigDir()+ if dir == "" {+ return ""+ }+ path := filepath.Join(dir, "reasonix")+ if current := e.homeDir(); current != "" && reasonixSamePath(path, current) {+ return ""+ }+ return path+}++// legacyUserConfigPath is the legacy OS app-support config.toml.+func (e reasonixEnv) legacyUserConfigPath() string {+ dir := e.legacyOSSupportDir()+ if dir == "" {+ return ""+ }+ path := filepath.Join(dir, reasonixUserConfigFile)+ if primary := e.userConfigPath(); primary != "" && reasonixSamePath(path, primary) {+ return ""+ }+ return path+}++// legacyXDGConfigPaths are the deprecated XDG locations, Unix-only and only+// while REASONIX_HOME is unset.+func (e reasonixEnv) legacyXDGConfigPaths() []string {+ if e.isolatedHome() != "" || reasonixGOOS == "windows" {+ return nil+ }+ seen := map[string]bool{}+ var paths []string+ add := func(path string) {+ if path == "" {+ return+ }+ path = filepath.Clean(path)+ if seen[path] {+ return+ }+ seen[path] = true+ paths = append(paths, path)+ }+ if dir := e.cleanDir("XDG_CONFIG_HOME"); dir != "" {+ add(filepath.Join(dir, "reasonix", reasonixUserConfigFile))+ }+ if home := e.userHomeDir(); home != "" {+ add(filepath.Join(home, ".config", "reasonix", reasonixUserConfigFile))+ }+ return paths+}++// userConfigLoadPath is the config.toml the child will read: the primary path+// when it exists, else the first legacy location that does, else the primary+// path again (which simply does not exist yet). Ports userConfigLoadPath.+func (e reasonixEnv) userConfigLoadPath() string {+ primary := e.userConfigPath()+ if primary == "" {+ return e.legacyUserConfigPath()+ }+ if _, err := os.Stat(primary); err == nil {+ return primary+ }+ if legacy := e.legacyUserConfigPath(); legacy != "" {+ if _, err := os.Stat(legacy); err == nil {+ return legacy+ }+ }+ for _, legacy := range e.legacyXDGConfigPaths() {+ if legacy == "" || reasonixSamePath(legacy, primary) {+ continue+ }+ if _, err := os.Stat(legacy); err == nil {+ return legacy+ }+ }+ return primary+}++func reasonixSamePath(a, b string) bool {+ if a == "" || b == "" {+ return false+ }+ if abs, err := filepath.Abs(a); err == nil {+ a = abs+ }+ if abs, err := filepath.Abs(b); err == nil {+ b = abs+ }+ return filepath.Clean(a) == filepath.Clean(b)+}diff --git a/server/internal/daemon/execenv/reasonix_user_config_test.go b/server/internal/daemon/execenv/reasonix_user_config_test.gonew file mode 100644index 0000000000..d710958ede--- /dev/null+++ b/server/internal/daemon/execenv/reasonix_user_config_test.go@@ -0,0 +1,169 @@+package execenv++import (+ "os"+ "path/filepath"+ "testing"+)++// setReasonixGOOS pins the platform the resolver targets so the Windows and+// macOS paths are covered from any runner. These tests are deliberately NOT+// parallel: Go resumes parallel tests only once every serial test has finished,+// so the global stays consistent for the parallel reasonix tests.+func setReasonixGOOS(t *testing.T, goos string) {+ t.Helper()+ previous := reasonixGOOS+ reasonixGOOS = goos+ t.Cleanup(func() { reasonixGOOS = previous })+}++// TestReasonixUserConfigPathWindows pins the Windows resolution: %AppData% is+// the home root, NOT %USERPROFILE%\.reasonix. Reading the wrong file there means+// reading no owner permissions at all, and the task config would then replace+// the rules the child actually loads.+func TestReasonixUserConfigPathWindows(t *testing.T) {+ setReasonixGOOS(t, "windows")++ appData := t.TempDir()+ profile := t.TempDir()+ env := reasonixEnv{"REASONIX_HOME": "", "AppData": appData, "USERPROFILE": profile}+ if got, want := env.userConfigLoadPath(), filepath.Join(appData, "reasonix", reasonixUserConfigFile); got != want {+ t.Fatalf("windows config path = %q, want %q", got, want)+ }++ // %AppData% missing: Reasonix falls back to the Roaming path under the+ // profile, still not to a dot-directory.+ env = reasonixEnv{"REASONIX_HOME": "", "AppData": "", "USERPROFILE": profile}+ want := filepath.Join(profile, "AppData", "Roaming", "reasonix", reasonixUserConfigFile)+ if got := env.userConfigLoadPath(); got != want {+ t.Fatalf("windows config path without AppData = %q, want %q", got, want)+ }++ // An agent may write the variable in any case; Windows env lookups do not+ // care, so neither may this one.+ env = reasonixEnv{"REASONIX_HOME": "", "APPDATA": appData, "USERPROFILE": profile}+ if got, want := env.userConfigLoadPath(), filepath.Join(appData, "reasonix", reasonixUserConfigFile); got != want {+ t.Fatalf("windows config path with APPDATA spelling = %q, want %q", got, want)+ }+}++// TestReasonixUserConfigPathHonorsExplicitEmptyOverride is the presence-aware+// case: an agent that sets REASONIX_HOME="" sends its child back to the platform+// default, so the daemon must not keep reading its own REASONIX_HOME.+func TestReasonixUserConfigPathHonorsExplicitEmptyOverride(t *testing.T) {+ setReasonixGOOS(t, "linux")+ daemonHome := t.TempDir()+ t.Setenv("REASONIX_HOME", daemonHome)+ t.Setenv("XDG_CONFIG_HOME", "")++ userHome := t.TempDir()+ cleared := reasonixEnv{"REASONIX_HOME": "", "HOME": userHome}+ if got, want := cleared.userConfigLoadPath(), filepath.Join(userHome, ".reasonix", reasonixUserConfigFile); got != want {+ t.Fatalf("path with an explicitly cleared override = %q, want the platform default %q", got, want)+ }++ // No entry at all means the child inherits the daemon's own variable.+ inherited := reasonixEnv{"HOME": userHome}+ if got, want := inherited.userConfigLoadPath(), filepath.Join(daemonHome, reasonixUserConfigFile); got != want {+ t.Fatalf("path without an override = %q, want the daemon's home %q", got, want)+ }+}++// TestReasonixUserConfigPathExpandsOverride covers the forms Reasonix accepts in+// REASONIX_HOME: ${VAR} / ${VAR:-default}, a leading ~, surrounding whitespace,+// and a relative path.+func TestReasonixUserConfigPathExpandsOverride(t *testing.T) {+ setReasonixGOOS(t, "linux")+ home := t.TempDir()+ root := t.TempDir()+ cwd, err := os.Getwd()+ if err != nil {+ t.Fatalf("getwd: %v", err)+ }++ for _, tc := range []struct {+ name string+ override string+ want string+ }{+ {name: "tilde", override: "~/rx", want: filepath.Join(home, "rx")},+ {name: "variable", override: "${RX_ROOT}/rx", want: filepath.Join(root, "rx")},+ {name: "variable default", override: "${RX_UNSET:-" + root + "/fallback}", want: filepath.Join(root, "fallback")},+ {name: "whitespace", override: " " + root + "/spaced ", want: filepath.Join(root, "spaced")},+ {name: "relative", override: "relative-rx", want: filepath.Join(cwd, "relative-rx")},+ } {+ t.Run(tc.name, func(t *testing.T) {+ env := reasonixEnv{"REASONIX_HOME": tc.override, "HOME": home, "RX_ROOT": root}+ if got, want := env.userConfigLoadPath(), filepath.Join(tc.want, reasonixUserConfigFile); got != want {+ t.Fatalf("config path = %q, want %q", got, want)+ }+ })+ }+}++// TestReasonixUserConfigPathFallsBackToLegacy covers the compatibility lookup:+// with no REASONIX_HOME and no config under the current home, Reasonix reads the+// legacy OS-support location, then the XDG one — and so must the daemon.+func TestReasonixUserConfigPathFallsBackToLegacy(t *testing.T) {+ setReasonixGOOS(t, "darwin")+ ownerConfig := "[permissions]\ndeny = [\"bash\"]\n"++ home := t.TempDir()+ legacyOS := filepath.Join(home, "Library", "Application Support", "reasonix", reasonixUserConfigFile)+ mustWrite(t, legacyOS, ownerConfig)+ env := reasonixEnv{"REASONIX_HOME": "", "HOME": home, "XDG_CONFIG_HOME": ""}+ if got := env.userConfigLoadPath(); got != legacyOS {+ t.Fatalf("config path = %q, want the legacy OS-support config %q", got, legacyOS)+ }++ // Only the XDG copy exists.+ home = t.TempDir()+ legacyXDG := filepath.Join(home, ".config", "reasonix", reasonixUserConfigFile)+ mustWrite(t, legacyXDG, ownerConfig)+ env = reasonixEnv{"REASONIX_HOME": "", "HOME": home, "XDG_CONFIG_HOME": ""}+ if got := env.userConfigLoadPath(); got != legacyXDG {+ t.Fatalf("config path = %q, want the legacy XDG config %q", got, legacyXDG)+ }++ // The primary config wins whenever it exists.+ primary := filepath.Join(home, ".reasonix", reasonixUserConfigFile)+ mustWrite(t, primary, ownerConfig)+ if got := env.userConfigLoadPath(); got != primary {+ t.Fatalf("config path = %q, want the primary config %q", got, primary)+ }+}++// TestReasonixUserConfigPathIsolatesExplicitHome pins Reasonix's isolation rule:+// once REASONIX_HOME is set, no legacy location is consulted, even when one+// holds a config.+func TestReasonixUserConfigPathIsolatesExplicitHome(t *testing.T) {+ setReasonixGOOS(t, "darwin")+ home := t.TempDir()+ mustWrite(t, filepath.Join(home, "Library", "Application Support", "reasonix", reasonixUserConfigFile), "[permissions]\ndeny = [\"bash\"]\n")+ mustWrite(t, filepath.Join(home, ".config", "reasonix", reasonixUserConfigFile), "[permissions]\ndeny = [\"bash\"]\n")++ isolated := t.TempDir()+ env := reasonixEnv{"REASONIX_HOME": isolated, "HOME": home, "XDG_CONFIG_HOME": ""}+ if got, want := env.userConfigLoadPath(), filepath.Join(isolated, reasonixUserConfigFile); got != want {+ t.Fatalf("config path = %q, want the isolated home's %q", got, want)+ }+}++// TestReasonixProjectConfigMergesLegacyOwnerConfig is the end-to-end version of+// the fallback: a deny list that only lives in a legacy location still has to+// reach the task config.+func TestReasonixProjectConfigMergesLegacyOwnerConfig(t *testing.T) {+ setReasonixGOOS(t, "darwin")+ home := t.TempDir()+ mustWrite(t,+ filepath.Join(home, "Library", "Application Support", "reasonix", reasonixUserConfigFile),+ "[permissions]\ndeny = [\"bash\"]\n",+ )++ workDir := t.TempDir()+ env := map[string]string{"REASONIX_HOME": "", "HOME": home, "XDG_CONFIG_HOME": ""}+ if err := writeReasonixProjectConfig(workDir, env, &sidecarManifest{}, testLogger()); err != nil {+ t.Fatalf("writeReasonixProjectConfig: %v", err)+ }+ assertTaskDenyList(t, filepath.Join(workDir, reasonixProjectConfigFile), []string{"bash", "ask"})+}