diff --git a/pkg/evaluator/provider/main_test.go b/pkg/evaluator/provider/main_test.go new file mode 100644 index 0000000000..94312d976e --- /dev/null +++ b/pkg/evaluator/provider/main_test.go @@ -0,0 +1,16 @@ +package provider + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/fake/main_test.go b/pkg/fake/main_test.go new file mode 100644 index 0000000000..c67505d539 --- /dev/null +++ b/pkg/fake/main_test.go @@ -0,0 +1,16 @@ +package fake + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/model/provider/anthropic/main_test.go b/pkg/model/provider/anthropic/main_test.go new file mode 100644 index 0000000000..c8c113024c --- /dev/null +++ b/pkg/model/provider/anthropic/main_test.go @@ -0,0 +1,16 @@ +package anthropic + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/model/provider/base/main_test.go b/pkg/model/provider/base/main_test.go new file mode 100644 index 0000000000..c7366326dd --- /dev/null +++ b/pkg/model/provider/base/main_test.go @@ -0,0 +1,16 @@ +package base + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/model/provider/dmr/main_test.go b/pkg/model/provider/dmr/main_test.go new file mode 100644 index 0000000000..6aaa5c477b --- /dev/null +++ b/pkg/model/provider/dmr/main_test.go @@ -0,0 +1,16 @@ +package dmr + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/model/provider/openai/main_test.go b/pkg/model/provider/openai/main_test.go new file mode 100644 index 0000000000..f4d2940932 --- /dev/null +++ b/pkg/model/provider/openai/main_test.go @@ -0,0 +1,16 @@ +package openai + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/remote/main_test.go b/pkg/remote/main_test.go new file mode 100644 index 0000000000..b702da58ca --- /dev/null +++ b/pkg/remote/main_test.go @@ -0,0 +1,16 @@ +package remote + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/runtime/harness_test.go b/pkg/runtime/harness_test.go index 3aaaf7430d..bca73f94d2 100644 --- a/pkg/runtime/harness_test.go +++ b/pkg/runtime/harness_test.go @@ -24,6 +24,7 @@ import ( "github.com/docker/docker-agent/pkg/session" "github.com/docker/docker-agent/pkg/session/sqlitestore" "github.com/docker/docker-agent/pkg/team" + "github.com/docker/docker-agent/pkg/testutil" "github.com/docker/docker-agent/pkg/tools" ) @@ -70,7 +71,7 @@ func TestMain(m *testing.M) { } paths.SetConfigDir(configDir) - code := m.Run() + code := testutil.RunWithTempHome(m.Run) paths.SetConfigDir("") _ = os.RemoveAll(configDir) @@ -78,6 +79,10 @@ func TestMain(m *testing.M) { os.Exit(code) } +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} + // useHarnessShim points PATH at the shared shim directory and sets the // stdout the named harness program ("codex" or "claude") emits when the // runtime invokes it. PATH is prepended, not replaced, so the shim can diff --git a/pkg/runtime/lazy_model_store_test.go b/pkg/runtime/lazy_model_store_test.go index 49fe59e345..63ee599306 100644 --- a/pkg/runtime/lazy_model_store_test.go +++ b/pkg/runtime/lazy_model_store_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "errors" + "path/filepath" "testing" "time" @@ -85,14 +86,17 @@ func TestLazyModelStore_DefersError(t *testing.T) { // unreachable. This exercises the exact store the request loop and session // compaction use in production. func TestLazyModelStore_GatesCustomProvider(t *testing.T) { - // Point the cache at an empty home so there is no on-disk catalog to fall - // back on: a cold start, as in a freshly-spawned pod. t.Setenv forbids + // Point the cache at an empty directory so there is no on-disk catalog to + // fall back on: a cold start, as in a freshly-spawned pod. t.Setenv forbids // t.Parallel, which is fine here. modelsdev.NewStore resolves the cache - // dir via os.UserCacheDir, which derives from HOME on macOS and from - // XDG_CACHE_HOME or HOME on Linux. + // dir via os.UserCacheDir, which follows HOME on macOS, %LocalAppData% on + // Windows and an absolute XDG_CACHE_HOME on Linux. RunWithTempHome sets + // those for the whole suite, so they must be overridden here too. home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("LocalAppData", filepath.Join(home, "AppData", "Local")) var store ModelStore = &lazyModelStore{} diff --git a/pkg/skills/cache_isolation_test.go b/pkg/skills/cache_isolation_test.go new file mode 100644 index 0000000000..593924ccda --- /dev/null +++ b/pkg/skills/cache_isolation_test.go @@ -0,0 +1,48 @@ +package skills + +import ( + "os" + "os/exec" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestSuiteCacheStaysInsideTempHome is the regression test for the review on +// #5018. TestLoadWithRemoteSources caches the remote skill under +// paths.GetCacheDir(), which follows %LocalAppData% on Windows and an absolute +// XDG_CACHE_HOME on Linux rather than HOME. Re-run it together with the +// isolation guard in a child process whose cache roots are preset outside the +// temporary home: the child suite must resolve its cache inside the temporary +// tree and leave the preset roots empty. +func TestSuiteCacheStaysInsideTempHome(t *testing.T) { + if testing.Short() { + t.Skip("re-runs the test binary") + } + + self, err := os.Executable() + require.NoError(t, err) + + preset := t.TempDir() + cmd := exec.CommandContext(t.Context(), self, + "-test.run=^(TestTempHomeIsolation|TestLoadWithRemoteSources)$", + "-test.count=1", + "-test.timeout=2m", + ) + // The child must create its own temporary home instead of inheriting the + // one this suite runs in; an empty marker value means "not set". The + // presets stand in for a developer's real cache root. + cmd.Env = append(os.Environ(), + "TESTUTIL_TEMP_HOME=", + "XDG_CACHE_HOME="+preset, + "LocalAppData="+preset, + ) + + output, err := cmd.CombinedOutput() + require.NoError(t, err, "child suite failed:\n%s", output) + + entries, err := os.ReadDir(preset) + require.NoError(t, err) + assert.Empty(t, entries, "child suite wrote into the preset cache root %q", preset) +} diff --git a/pkg/skills/main_test.go b/pkg/skills/main_test.go index 36c6fc3603..ba17a07175 100644 --- a/pkg/skills/main_test.go +++ b/pkg/skills/main_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/docker/docker-agent/pkg/httpclient" + "github.com/docker/docker-agent/pkg/testutil" ) // TestMain swaps the SSRF-safe HTTP client for the loopback-allowing @@ -16,7 +17,11 @@ func TestMain(m *testing.M) { skillsHTTPClient = httpclient.NewSafeClient(remoteHTTPTimeout, true) transport := http.DefaultTransport.(*http.Transport).Clone() skillsHTTPClient.Transport = transport - code := m.Run() + code := testutil.RunWithTempHome(m.Run) transport.CloseIdleConnections() os.Exit(code) } + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/telemetry/main_test.go b/pkg/telemetry/main_test.go new file mode 100644 index 0000000000..bd874ae953 --- /dev/null +++ b/pkg/telemetry/main_test.go @@ -0,0 +1,16 @@ +package telemetry + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +} diff --git a/pkg/testutil/cache_test.go b/pkg/testutil/cache_test.go new file mode 100644 index 0000000000..295ea1bcff --- /dev/null +++ b/pkg/testutil/cache_test.go @@ -0,0 +1,42 @@ +package testutil + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestCacheVariables pins the resolver input for every platform: these are +// the variables os.UserCacheDir (and therefore pkg/paths.GetCacheDir) reads. +func TestCacheVariables(t *testing.T) { + t.Parallel() + + home := t.TempDir() + windows := envValue{name: "LocalAppData", value: filepath.Join(home, "AppData", "Local")} + xdg := envValue{name: "XDG_CACHE_HOME", value: filepath.Join(home, ".cache")} + + tests := []struct { + goos string + want []envValue + }{ + {"windows", []envValue{windows}}, + {"linux", []envValue{xdg}}, + {"freebsd", []envValue{xdg}}, + // The macOS cache directory derives from HOME, which homeVariables + // already redirects. + {"darwin", nil}, + } + for _, tt := range tests { + t.Run(tt.goos, func(t *testing.T) { + t.Parallel() + + got := cacheVariables(tt.goos, home) + assert.Equal(t, tt.want, got) + for _, variable := range got { + assert.True(t, filepath.IsAbs(variable.value), "%s must be absolute", variable.name) + assert.True(t, withinDir(home, variable.value), "%s=%s must stay inside the temporary home", variable.name, variable.value) + } + }) + } +} diff --git a/pkg/testutil/home.go b/pkg/testutil/home.go index c299937961..47288e5517 100644 --- a/pkg/testutil/home.go +++ b/pkg/testutil/home.go @@ -3,15 +3,27 @@ package testutil import ( "os" + "path/filepath" "runtime" + "testing" + + "github.com/docker/docker-agent/pkg/paths" ) // tempHomeEnv marks a process tree that already runs with a temporary home. const tempHomeEnv = "TESTUTIL_TEMP_HOME" -// RunWithTempHome runs a test suite with the home directory pointing at an -// empty temporary directory, so tests neither read nor write the developer's -// configuration and data. Call it from TestMain. +// envValue is one environment variable assignment RunWithTempHome makes while +// a suite runs. +type envValue struct { + name string + value string +} + +// RunWithTempHome runs a test suite with the home directory and the effective +// cache root pointing at an empty temporary directory, so tests neither read +// nor write the developer's configuration, data, or cache. Call it from +// TestMain. func RunWithTempHome(run func() int) int { // A test binary re-executed as a helper keeps the home its parent gave it: // helpers often exit without returning, which would leak their own. @@ -29,6 +41,9 @@ func RunWithTempHome(run func() int) int { for _, name := range homeVariables(runtime.GOOS, os.Getenv("HOME")) { restores = append(restores, setenv(name, home)) } + for _, variable := range cacheVariables(runtime.GOOS, home) { + restores = append(restores, setenv(variable.name, variable.value)) + } defer func() { for _, restore := range restores { restore() @@ -38,6 +53,27 @@ func RunWithTempHome(run func() int) int { return run() } +// RequireTempHome fails unless the test binary runs under +// [RunWithTempHome]. State-touching packages call it from a test so that +// dropping the isolated TestMain fails loudly instead of writing to the +// developer's real home directory again. +// +// It also fails when the effective cache directory escapes the temporary +// home. The cache root does not always follow the home directory: Windows +// resolves it from %LocalAppData% and Linux from an absolute +// $XDG_CACHE_HOME, so a suite can keep writing the developer's cache while +// its home directory already looks isolated. +func RequireTempHome(tb testing.TB) { + tb.Helper() + home := os.Getenv(tempHomeEnv) + if home == "" { + tb.Fatal("tests must run with testutil.RunWithTempHome from TestMain") + } + if cache := paths.GetCacheDir(); !withinDir(home, cache) { + tb.Fatalf("cache directory %q is outside the temporary home %q: testutil.RunWithTempHome must isolate the effective cache root, not just HOME", cache, home) + } +} + // homeVariables lists the environment variables that locate the home // directory: the one os.UserHomeDir reads, plus HOME when it is set, because // pkg/path prefers it on every platform. @@ -53,6 +89,33 @@ func homeVariables(goos, home string) []string { } } +// cacheVariables lists the environment variables that locate the platform's +// cache root, with the values that keep it inside home. +// +// os.UserCacheDir — and therefore [paths.GetCacheDir] — does not always derive +// the cache root from the home directory: it reads %LocalAppData% on Windows +// and an absolute $XDG_CACHE_HOME when set on Linux/BSD. Changing HOME +// alone leaves those pointing at the developer's real cache. On macOS the +// cache lives under $HOME/Library/Caches, so changing HOME already covers it. +func cacheVariables(goos, home string) []envValue { + switch goos { + case "windows": + return []envValue{{name: "LocalAppData", value: filepath.Join(home, "AppData", "Local")}} + case "darwin", "ios": + return nil + default: + // A relative XDG_CACHE_HOME makes os.UserCacheDir fail, which would + // send pkg/paths.GetCacheDir to the shared system temporary directory. + return []envValue{{name: "XDG_CACHE_HOME", value: filepath.Join(home, ".cache")}} + } +} + +// withinDir reports whether path is dir or one of its descendants. +func withinDir(dir, path string) bool { + rel, err := filepath.Rel(dir, path) + return err == nil && filepath.IsLocal(rel) +} + // setenv sets an environment variable and returns a function that restores it. func setenv(name, value string) (restore func()) { previous, wasSet := os.LookupEnv(name) diff --git a/pkg/testutil/home_test.go b/pkg/testutil/home_test.go index 39efda7611..da61457495 100644 --- a/pkg/testutil/home_test.go +++ b/pkg/testutil/home_test.go @@ -29,6 +29,14 @@ func userHomeDir(t *testing.T) string { return home } +// requireInsideHome fails unless dir resolves inside home. +func requireInsideHome(t *testing.T, home, dir string) { + t.Helper() + rel, err := filepath.Rel(home, dir) + require.NoError(t, err) + assert.True(t, filepath.IsLocal(rel), "%q must resolve inside the temporary home %q", dir, home) +} + func TestRunWithTempHome(t *testing.T) { original := useHome(t) config := filepath.Join(original, ".config", "cagent", "config.yaml") @@ -46,6 +54,7 @@ func TestRunWithTempHome(t *testing.T) { assert.Equal(t, filepath.Join(home, ".config", "cagent"), paths.GetConfigDir()) assert.Equal(t, filepath.Join(home, ".cagent"), paths.GetDataDir()) + requireInsideHome(t, home, paths.GetCacheDir()) // pkg/path prefers HOME over os.UserHomeDir on every platform. expanded, err := pathx.ExpandHomeDir("~") @@ -117,6 +126,39 @@ func TestHomeVariables(t *testing.T) { assert.Equal(t, []string{"USERPROFILE", "HOME"}, homeVariables("windows", `C:\Users\me`)) } +// A developer can start a test run with the cache root preset outside the home +// directory (Windows %LocalAppData%, Linux $XDG_CACHE_HOME). RunWithTempHome +// must override it, otherwise suites keep writing the developer's cache while +// only their home directory looks isolated. +func TestRunWithTempHomeIsolatesPresetCache(t *testing.T) { + useHome(t) + preset := t.TempDir() + t.Setenv("XDG_CACHE_HOME", preset) + t.Setenv("LocalAppData", preset) + + var home, cache string + code := RunWithTempHome(func() int { + home = userHomeDir(t) + cache = paths.GetCacheDir() + require.NoError(t, os.MkdirAll(cache, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(cache, "written-by-suite"), nil, 0o600)) + return 0 + }) + + assert.Equal(t, 0, code) + require.NotEmpty(t, home) + requireInsideHome(t, home, cache) + + // The cache root variables are restored, so the next suite starts from + // the developer's values again. + assert.Equal(t, preset, os.Getenv("XDG_CACHE_HOME")) + assert.Equal(t, preset, os.Getenv("LocalAppData")) + + entries, err := os.ReadDir(preset) + require.NoError(t, err) + assert.Empty(t, entries, "suite wrote into the preset cache root %q", preset) +} + func TestSetenvRestoresUnsetVariable(t *testing.T) { const name = "TESTUTIL_UNSET_VARIABLE" t.Setenv(name, "") // Restores the variable after the test. diff --git a/pkg/tools/builtin/rag/main_test.go b/pkg/tools/builtin/rag/main_test.go new file mode 100644 index 0000000000..2c4a912c5e --- /dev/null +++ b/pkg/tools/builtin/rag/main_test.go @@ -0,0 +1,16 @@ +package rag + +import ( + "os" + "testing" + + "github.com/docker/docker-agent/pkg/testutil" +) + +func TestMain(m *testing.M) { + os.Exit(testutil.RunWithTempHome(m.Run)) +} + +func TestTempHomeIsolation(t *testing.T) { + testutil.RequireTempHome(t) +}