From 2407d9aba97ea392bf866a7b87b8f6898607290d Mon Sep 17 00:00:00 2001 From: Vasanthdev2004 Date: Sat, 28 Nov 2026 16:17:04 +0530 Subject: [PATCH 1/3] test(cli): run the whole package against a throwaway user state Tests in this package drive the root command, which fills whatever a test leaves out with the production wiring and loads user config, hooks, plugins and stores from the per-user directories. Only the tests that call isolateCLIUserState redirected them. The rest ran against the developer's own: with a user-level hooks.json in place, one run of the package executed those hooks more than two thousand times, and a hooks file that only says enabled:false fails a test that never mentions it. Replace the base directories once in TestMain, before any test runs, and clear the two overrides that outrank them. A test that starts this test binary again as a child keeps the roots it was given, through a marker in the environment. isolateCLIUserState stays for tests that need a root of their own. Fixes #1249. --- internal/cli/main_test.go | 213 +++++++++++++++++++++++++ internal/cli/provider_adoption_test.go | 4 + 2 files changed, 217 insertions(+) create mode 100644 internal/cli/main_test.go diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go new file mode 100644 index 000000000..74cf7d00b --- /dev/null +++ b/internal/cli/main_test.go @@ -0,0 +1,213 @@ +package cli + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +// userStateIsolatedEnv marks a process whose per-user directories have already +// been replaced. A test that starts this test binary again as a child inherits +// it and keeps the parent's root. A test that hands a child its own +// environment sets it too, so the child keeps the roots it was given. +const userStateIsolatedEnv = "ZERO_TEST_CLI_USER_STATE_ISOLATED" + +// userStateOverrideEnvNames outrank the base directories: an inherited value +// would send the sandbox grants file and the Windows sandbox home back to the +// developer's real ones whatever the base directories say. +var userStateOverrideEnvNames = []string{"ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME"} + +// packageUserStateRoot is the throwaway root TestMain put behind every +// per-user base directory, or empty in a child that was already isolated. +var packageUserStateRoot string + +// TestMain runs every test in this package against a throwaway per-user root. +// +// THE DEFAULT HAS TO BE ISOLATED, NOT THE EXCEPTION. Tests here drive the root +// command, and the root command fills whatever a test leaves out with the +// production wiring: it loads user config, user hooks, plugins and stores from +// the per-user directories. A test that redirects none of them runs against the +// developer's own. With a user-level hooks.json in place, one run of this +// package executed those hooks more than two thousand times, and a hooks file +// that merely says enabled:false is enough to fail a test that never mentions +// it. isolateCLIUserState fixes that for the tests that call it, and there are +// several hundred that do not. +// +// So the base directories are replaced once, before anything runs. A test that +// needs its own root still calls isolateCLIUserState or t.Setenv, which +// override this for that test and restore it afterwards. +func TestMain(m *testing.M) { + os.Exit(runPackageTests(m.Run)) +} + +func runPackageTests(run func() int) int { + root, cleanup, err := isolatePackageUserState() + if err != nil { + fmt.Fprintf(os.Stderr, "isolate the package from the user's own state: %v\n", err) + return 1 + } + defer cleanup() + packageUserStateRoot = root + return run() +} + +// isolatePackageUserState replaces the per-user base directories of this +// process with one new throwaway root and clears the overrides that outrank +// them. It returns the root and a function that removes it. In a process that +// is already marked as isolated it changes nothing and returns an empty root. +func isolatePackageUserState() (string, func(), error) { + if os.Getenv(userStateIsolatedEnv) != "" { + return "", func() {}, nil + } + root, err := os.MkdirTemp("", "zero-cli-user-state-") + if err != nil { + return "", nil, fmt.Errorf("create the root: %w", err) + } + cleanup := func() { _ = os.RemoveAll(root) } + for _, name := range userStateEnvNames { + if err := os.Setenv(name, root); err != nil { + cleanup() + return "", nil, fmt.Errorf("redirect %s: %w", name, err) + } + } + for _, name := range userStateOverrideEnvNames { + if err := os.Unsetenv(name); err != nil { + cleanup() + return "", nil, fmt.Errorf("clear %s: %w", name, err) + } + } + if err := os.Setenv(userStateIsolatedEnv, "1"); err != nil { + cleanup() + return "", nil, fmt.Errorf("mark the process as isolated: %w", err) + } + return root, cleanup, nil +} + +// everyUserStateEnvName is written out here on purpose. Reusing the list the +// setup walks would let a name dropped from that list go unnoticed. +var everyUserStateEnvName = []string{ + "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", + "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", +} + +// everyUserStateOverrideEnvName is written out for the same reason. +var everyUserStateOverrideEnvName = []string{"ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME"} + +func pathIsUnder(t *testing.T, root, path string) bool { + t.Helper() + resolvedRoot, err := filepath.EvalSymlinks(root) + if err != nil { + t.Fatalf("resolve %s: %v", root, err) + } + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + resolved = path + } + rel, err := filepath.Rel(resolvedRoot, resolved) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// THE PACKAGE DEFAULT IS PINNED HERE, so removing TestMain fails a test +// instead of quietly sending several hundred tests back to the developer's own +// directories. +// +// It reads the environment a test starts with, before any t.Setenv, and checks +// each base directory against the root TestMain created. It also asks Go for +// the three directories it derives from them, because those are what the +// production code resolves on each platform. +func TestPackageRunsAgainstAThrowawayUserState(t *testing.T) { + if packageUserStateRoot == "" { + t.Fatal("TestMain did not replace the per-user directories for this package") + } + for _, name := range everyUserStateEnvName { + if value := os.Getenv(name); value == "" || !pathIsUnder(t, packageUserStateRoot, value) { + t.Errorf("%s = %q, want a path under the package root %q", name, value, packageUserStateRoot) + } + } + for _, name := range everyUserStateOverrideEnvName { + if value, set := os.LookupEnv(name); set { + t.Errorf("%s = %q is still set; it outranks the base directories", name, value) + } + } + for name, resolve := range map[string]func() (string, error){ + "os.UserHomeDir": os.UserHomeDir, + "os.UserConfigDir": os.UserConfigDir, + "os.UserCacheDir": os.UserCacheDir, + } { + if path, err := resolve(); err != nil || !pathIsUnder(t, packageUserStateRoot, path) { + t.Errorf("%s() = %q, %v; want a path under %q", name, path, err, packageUserStateRoot) + } + } +} + +// THE SETUP ITSELF, AGAINST AN ENVIRONMENT THAT POINTS SOMEWHERE ELSE. +// +// A decoy directory stands in for the developer's own behind every base +// directory, and both overrides are set, which the machines that run this +// suite never have. After the setup nothing may still name the decoy, the +// overrides must be gone, and the process must be marked so that a child does +// not do it all again. The removal function must take the root away. +func TestIsolatePackageUserStateReplacesEveryDirectoryAndClearsTheOverrides(t *testing.T) { + decoy := t.TempDir() + for _, name := range everyUserStateEnvName { + t.Setenv(name, decoy) + } + for _, name := range everyUserStateOverrideEnvName { + t.Setenv(name, filepath.Join(decoy, "override")) + } + t.Setenv(userStateIsolatedEnv, "") + + root, cleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) + } + if root == "" || pathIsUnder(t, decoy, root) { + t.Fatalf("root = %q, want a new directory outside %q", root, decoy) + } + for _, name := range everyUserStateEnvName { + if value := os.Getenv(name); !pathIsUnder(t, root, value) { + t.Errorf("%s = %q, want a path under the new root %q", name, value, root) + } + } + for _, name := range everyUserStateOverrideEnvName { + if value, set := os.LookupEnv(name); set { + t.Errorf("%s = %q is still set", name, value) + } + } + if os.Getenv(userStateIsolatedEnv) == "" { + t.Errorf("%s is not set; a child started by a test would isolate itself again", userStateIsolatedEnv) + } + cleanup() + if _, err := os.Stat(root); !os.IsNotExist(err) { + t.Errorf("the root %q is still there after cleanup: %v", root, err) + } +} + +// A PROCESS THAT IS ALREADY ISOLATED IS LEFT ALONE. +// +// Some tests start this test binary again as a child and hand it its own +// directories, and two such children have to share them. Replacing the +// directories again in the child would give each its own empty root. +func TestIsolatePackageUserStateLeavesAnIsolatedProcessAlone(t *testing.T) { + given := t.TempDir() + for _, name := range everyUserStateEnvName { + t.Setenv(name, given) + } + t.Setenv(userStateIsolatedEnv, "1") + + root, cleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) + } + defer cleanup() + if root != "" { + t.Fatalf("root = %q, want none: the process was already isolated", root) + } + for _, name := range everyUserStateEnvName { + if value := os.Getenv(name); value != given { + t.Errorf("%s = %q, want the directory it was given, %q", name, value, given) + } + } +} diff --git a/internal/cli/provider_adoption_test.go b/internal/cli/provider_adoption_test.go index cf1726e9a..dc7659cbf 100644 --- a/internal/cli/provider_adoption_test.go +++ b/internal/cli/provider_adoption_test.go @@ -77,6 +77,10 @@ func TestLocalAdoptionSavesAndReloadsEligibleModel(t *testing.T) { cmd.Dir = root cmd.Env = []string{ "ZERO_TEST_LOCAL_ADOPTION=1", "ZERO_CRED_STORAGE=encrypted-file", + // The child is this test binary again. It is handed its own roots + // below and both invocations must share them, so tell the package + // setup not to replace them a second time. + userStateIsolatedEnv + "=1", "HOME=" + root, "USERPROFILE=" + root, "XDG_CONFIG_HOME=" + filepath.Join(root, "config"), "XDG_CACHE_HOME=" + filepath.Join(root, "cache"), From ebdd97a81c7742a3e3789d5ca7dee193ba59b6bd Mon Sep 17 00:00:00 2001 From: Vasanthdev2004 Date: Sat, 28 Nov 2026 17:10:00 +0530 Subject: [PATCH 2/3] test(cli): clear the overrides instead of setting them, and keep credentials in a file The first version pointed all eight directory variables at the package root. Two tests failed on macOS. The config directory there honours XDG_CONFIG_HOME before HOME, and the specialist tests redirect only HOME, so a package-wide XDG_CONFIG_HOME outranked the directory each of them chose and they shared one. And a redirected home has no keychain, so a test that saves a key could not. Make the process look like a machine with an empty home and nothing overriding it: redirect HOME, USERPROFILE, APPDATA and LOCALAPPDATA, remove the XDG variables and the two sandbox overrides, and keep credentials in a file under the root. Export the root in its physical spelling so a path derived from it compares equal to one the system reports. --- internal/cli/main_test.go | 158 ++++++++++++++++++++++++-------------- 1 file changed, 100 insertions(+), 58 deletions(-) diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go index 74cf7d00b..017b007d5 100644 --- a/internal/cli/main_test.go +++ b/internal/cli/main_test.go @@ -14,10 +14,20 @@ import ( // environment sets it too, so the child keeps the roots it was given. const userStateIsolatedEnv = "ZERO_TEST_CLI_USER_STATE_ISOLATED" -// userStateOverrideEnvNames outrank the base directories: an inherited value -// would send the sandbox grants file and the Windows sandbox home back to the -// developer's real ones whatever the base directories say. -var userStateOverrideEnvNames = []string{"ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME"} +// packageHomeEnvNames are the directories every platform derives the per-user +// paths from when nothing overrides them. They are pointed at the package root. +var packageHomeEnvNames = []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA"} + +// packageClearedEnvNames outrank the directories above, so an inherited value +// would send a path straight back to the developer's own. They are removed, +// not pointed at the root: a machine with none of them set is what the tests +// were written against, and several redirect only the directory their platform +// starts from. Setting XDG_CONFIG_HOME for everyone would outrank a test that +// moves HOME on macOS, where the config directory honours it first. +var packageClearedEnvNames = []string{ + "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", + "ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME", +} // packageUserStateRoot is the throwaway root TestMain put behind every // per-user base directory, or empty in a child that was already isolated. @@ -28,16 +38,16 @@ var packageUserStateRoot string // THE DEFAULT HAS TO BE ISOLATED, NOT THE EXCEPTION. Tests here drive the root // command, and the root command fills whatever a test leaves out with the // production wiring: it loads user config, user hooks, plugins and stores from -// the per-user directories. A test that redirects none of them runs against the -// developer's own. With a user-level hooks.json in place, one run of this -// package executed those hooks more than two thousand times, and a hooks file -// that merely says enabled:false is enough to fail a test that never mentions -// it. isolateCLIUserState fixes that for the tests that call it, and there are -// several hundred that do not. +// the per-user directories, and saves credentials to the keychain. A test that +// redirects none of them runs against the developer's own. With a user-level +// hooks.json in place, one run of this package executed those hooks more than +// two thousand times, and a hooks file that merely says enabled:false is enough +// to fail a test that never mentions it. isolateCLIUserState fixes that for the +// tests that call it, and there are several hundred that do not. // -// So the base directories are replaced once, before anything runs. A test that -// needs its own root still calls isolateCLIUserState or t.Setenv, which -// override this for that test and restore it afterwards. +// So the process starts out looking like a machine with an empty home and no +// overrides. A test that needs its own root still calls isolateCLIUserState or +// t.Setenv, which override this for that test and restore it afterwards. func TestMain(m *testing.M) { os.Exit(runPackageTests(m.Run)) } @@ -53,10 +63,11 @@ func runPackageTests(run func() int) int { return run() } -// isolatePackageUserState replaces the per-user base directories of this -// process with one new throwaway root and clears the overrides that outrank -// them. It returns the root and a function that removes it. In a process that -// is already marked as isolated it changes nothing and returns an empty root. +// isolatePackageUserState points the home directories of this process at one +// new throwaway root, removes the variables that outrank them, and keeps +// credentials in a file under that root. It returns the root and a function +// that removes it. In a process that is already marked as isolated it changes +// nothing and returns an empty root. func isolatePackageUserState() (string, func(), error) { if os.Getenv(userStateIsolatedEnv) != "" { return "", func() {}, nil @@ -65,35 +76,47 @@ func isolatePackageUserState() (string, func(), error) { if err != nil { return "", nil, fmt.Errorf("create the root: %w", err) } + // The physical spelling, so a path derived from it compares equal to one + // the system reports: the temporary directory is reached through a link on + // macOS and through a short name on some Windows machines. + if resolved, err := filepath.EvalSymlinks(root); err == nil { + root = resolved + } cleanup := func() { _ = os.RemoveAll(root) } - for _, name := range userStateEnvNames { + fail := func(err error) (string, func(), error) { + cleanup() + return "", nil, err + } + for _, name := range packageHomeEnvNames { if err := os.Setenv(name, root); err != nil { - cleanup() - return "", nil, fmt.Errorf("redirect %s: %w", name, err) + return fail(fmt.Errorf("redirect %s: %w", name, err)) } } - for _, name := range userStateOverrideEnvNames { + for _, name := range packageClearedEnvNames { if err := os.Unsetenv(name); err != nil { - cleanup() - return "", nil, fmt.Errorf("clear %s: %w", name, err) + return fail(fmt.Errorf("clear %s: %w", name, err)) } } + // Credentials resolve keychain-first. A redirected home has no keychain, and + // a test key has no business in the real one. + if err := os.Setenv("ZERO_CRED_STORAGE", "encrypted-file"); err != nil { + return fail(fmt.Errorf("keep credentials in a file: %w", err)) + } if err := os.Setenv(userStateIsolatedEnv, "1"); err != nil { - cleanup() - return "", nil, fmt.Errorf("mark the process as isolated: %w", err) + return fail(fmt.Errorf("mark the process as isolated: %w", err)) } return root, cleanup, nil } -// everyUserStateEnvName is written out here on purpose. Reusing the list the -// setup walks would let a name dropped from that list go unnoticed. -var everyUserStateEnvName = []string{ - "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", - "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", -} - -// everyUserStateOverrideEnvName is written out for the same reason. -var everyUserStateOverrideEnvName = []string{"ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME"} +// The names are written out again here on purpose. Reusing the lists the setup +// walks would let a name dropped from them go unnoticed. +var ( + everyPackageHomeEnvName = []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA"} + everyPackageClearedEnvName = []string{ + "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", + "ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME", + } +) func pathIsUnder(t *testing.T, root, path string) bool { t.Helper() @@ -103,7 +126,9 @@ func pathIsUnder(t *testing.T, root, path string) bool { } resolved, err := filepath.EvalSymlinks(path) if err != nil { - resolved = path + // The path does not exist yet. The root is exported in its physical + // spelling, so a path built from it already has the right prefix. + resolved = filepath.Clean(path) } rel, err := filepath.Rel(resolvedRoot, resolved) return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) @@ -113,24 +138,30 @@ func pathIsUnder(t *testing.T, root, path string) bool { // instead of quietly sending several hundred tests back to the developer's own // directories. // -// It reads the environment a test starts with, before any t.Setenv, and checks -// each base directory against the root TestMain created. It also asks Go for -// the three directories it derives from them, because those are what the -// production code resolves on each platform. +// It reads the environment a test starts with, before any t.Setenv. It also +// asks Go for the three directories it derives from that environment, because +// those are what the production code resolves on each platform, and on a new +// root they do not exist yet. func TestPackageRunsAgainstAThrowawayUserState(t *testing.T) { if packageUserStateRoot == "" { t.Fatal("TestMain did not replace the per-user directories for this package") } - for _, name := range everyUserStateEnvName { - if value := os.Getenv(name); value == "" || !pathIsUnder(t, packageUserStateRoot, value) { - t.Errorf("%s = %q, want a path under the package root %q", name, value, packageUserStateRoot) + if resolved, err := filepath.EvalSymlinks(packageUserStateRoot); err != nil || resolved != packageUserStateRoot { + t.Fatalf("the package root is %q and resolves to %q, %v; it must be exported in its physical spelling", packageUserStateRoot, resolved, err) + } + for _, name := range everyPackageHomeEnvName { + if value := os.Getenv(name); value != packageUserStateRoot { + t.Errorf("%s = %q, want the package root %q", name, value, packageUserStateRoot) } } - for _, name := range everyUserStateOverrideEnvName { + for _, name := range everyPackageClearedEnvName { if value, set := os.LookupEnv(name); set { - t.Errorf("%s = %q is still set; it outranks the base directories", name, value) + t.Errorf("%s = %q is still set; it outranks the home directories", name, value) } } + if got := os.Getenv("ZERO_CRED_STORAGE"); got != "encrypted-file" { + t.Errorf("ZERO_CRED_STORAGE = %q, want credentials kept in a file", got) + } for name, resolve := range map[string]func() (string, error){ "os.UserHomeDir": os.UserHomeDir, "os.UserConfigDir": os.UserConfigDir, @@ -144,19 +175,21 @@ func TestPackageRunsAgainstAThrowawayUserState(t *testing.T) { // THE SETUP ITSELF, AGAINST AN ENVIRONMENT THAT POINTS SOMEWHERE ELSE. // -// A decoy directory stands in for the developer's own behind every base -// directory, and both overrides are set, which the machines that run this -// suite never have. After the setup nothing may still name the decoy, the -// overrides must be gone, and the process must be marked so that a child does -// not do it all again. The removal function must take the root away. -func TestIsolatePackageUserStateReplacesEveryDirectoryAndClearsTheOverrides(t *testing.T) { +// A decoy directory stands in for the developer's own behind every home +// directory and every override, and credential storage is set to the keychain, +// which the machines that run this suite never have all at once. After the +// setup nothing may still name the decoy, the overrides must be gone, and the +// process must be marked so that a child does not do it all again. The removal +// function must take the root away. +func TestIsolatePackageUserStateReplacesTheHomeAndClearsTheOverrides(t *testing.T) { decoy := t.TempDir() - for _, name := range everyUserStateEnvName { + for _, name := range everyPackageHomeEnvName { t.Setenv(name, decoy) } - for _, name := range everyUserStateOverrideEnvName { + for _, name := range everyPackageClearedEnvName { t.Setenv(name, filepath.Join(decoy, "override")) } + t.Setenv("ZERO_CRED_STORAGE", "keyring") t.Setenv(userStateIsolatedEnv, "") root, cleanup, err := isolatePackageUserState() @@ -166,16 +199,22 @@ func TestIsolatePackageUserStateReplacesEveryDirectoryAndClearsTheOverrides(t *t if root == "" || pathIsUnder(t, decoy, root) { t.Fatalf("root = %q, want a new directory outside %q", root, decoy) } - for _, name := range everyUserStateEnvName { - if value := os.Getenv(name); !pathIsUnder(t, root, value) { - t.Errorf("%s = %q, want a path under the new root %q", name, value, root) + if resolved, err := filepath.EvalSymlinks(root); err != nil || resolved != root { + t.Errorf("root = %q resolves to %q, %v; want the physical spelling", root, resolved, err) + } + for _, name := range everyPackageHomeEnvName { + if value := os.Getenv(name); value != root { + t.Errorf("%s = %q, want the new root %q", name, value, root) } } - for _, name := range everyUserStateOverrideEnvName { + for _, name := range everyPackageClearedEnvName { if value, set := os.LookupEnv(name); set { t.Errorf("%s = %q is still set", name, value) } } + if got := os.Getenv("ZERO_CRED_STORAGE"); got != "encrypted-file" { + t.Errorf("ZERO_CRED_STORAGE = %q, want credentials kept in a file", got) + } if os.Getenv(userStateIsolatedEnv) == "" { t.Errorf("%s is not set; a child started by a test would isolate itself again", userStateIsolatedEnv) } @@ -192,7 +231,10 @@ func TestIsolatePackageUserStateReplacesEveryDirectoryAndClearsTheOverrides(t *t // directories again in the child would give each its own empty root. func TestIsolatePackageUserStateLeavesAnIsolatedProcessAlone(t *testing.T) { given := t.TempDir() - for _, name := range everyUserStateEnvName { + for _, name := range everyPackageHomeEnvName { + t.Setenv(name, given) + } + for _, name := range everyPackageClearedEnvName { t.Setenv(name, given) } t.Setenv(userStateIsolatedEnv, "1") @@ -205,7 +247,7 @@ func TestIsolatePackageUserStateLeavesAnIsolatedProcessAlone(t *testing.T) { if root != "" { t.Fatalf("root = %q, want none: the process was already isolated", root) } - for _, name := range everyUserStateEnvName { + for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { if value := os.Getenv(name); value != given { t.Errorf("%s = %q, want the directory it was given, %q", name, value, given) } From a36d047954519716a909b07b908c0fdc0dd9884a Mon Sep 17 00:00:00 2001 From: Vasanthdev2004 Date: Thu, 3 Dec 2026 20:08:03 +0530 Subject: [PATCH 3/3] test(cli): ignore an isolation marker the package setup did not write Any non-empty ZERO_TEST_CLI_USER_STATE_ISOLATED skipped the package setup, so a value exported in a shell or left in a CI environment ran the whole package against the developer's own directories. The marker now carries the root the setup created, and the setup writes a stamp file into that root. A marker counts only when it is an absolute path to a root that still holds the stamp. Any other value is ignored and the process isolates itself as if the marker were absent. A child of an isolated run gets the parent's root back and leaves it in place. --- internal/cli/main_test.go | 192 +++++++++++++++++++++---- internal/cli/provider_adoption_test.go | 7 +- 2 files changed, 171 insertions(+), 28 deletions(-) diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go index 017b007d5..e0347845e 100644 --- a/internal/cli/main_test.go +++ b/internal/cli/main_test.go @@ -3,17 +3,28 @@ package cli import ( "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" ) // userStateIsolatedEnv marks a process whose per-user directories have already -// been replaced. A test that starts this test binary again as a child inherits -// it and keeps the parent's root. A test that hands a child its own -// environment sets it too, so the child keeps the roots it was given. +// been replaced. Its value is the package root the setup created. A test that +// starts this test binary again as a child inherits it and keeps the parent's +// root. A test that hands a child its own environment passes it on too, so the +// child keeps the directories it was given. +// +// The marker only counts while it names a root that still holds +// packageRootStamp. Any other value, such as "1" exported in a shell or the +// path of a root that has been removed, is ignored and the process isolates +// itself as usual. Skipping the setup on a value nobody checked would run the +// whole package against the developer's own directories. const userStateIsolatedEnv = "ZERO_TEST_CLI_USER_STATE_ISOLATED" +// packageRootStamp is the file the setup writes into each root it creates. +const packageRootStamp = "zero-cli-test-package-root" + // packageHomeEnvNames are the directories every platform derives the per-user // paths from when nothing overrides them. They are pointed at the package root. var packageHomeEnvNames = []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA"} @@ -30,7 +41,8 @@ var packageClearedEnvNames = []string{ } // packageUserStateRoot is the throwaway root TestMain put behind every -// per-user base directory, or empty in a child that was already isolated. +// per-user base directory. In a child that was already isolated it is the root +// of the run that started it. var packageUserStateRoot string // TestMain runs every test in this package against a throwaway per-user root. @@ -45,9 +57,11 @@ var packageUserStateRoot string // to fail a test that never mentions it. isolateCLIUserState fixes that for the // tests that call it, and there are several hundred that do not. // -// So the process starts out looking like a machine with an empty home and no -// overrides. A test that needs its own root still calls isolateCLIUserState or -// t.Setenv, which override this for that test and restore it afterwards. +// So the process starts out looking like a machine with an empty home and none +// of the directory overrides above. Zero's overrides for single files and +// stores, such as ZERO_OAUTH_TOKENS_PATH or ZERO_MODELS_CACHE_PATH, are not +// touched here. A test that needs its own root still calls isolateCLIUserState +// or t.Setenv, which override this for that test and restore it afterwards. func TestMain(m *testing.M) { os.Exit(runPackageTests(m.Run)) } @@ -66,11 +80,11 @@ func runPackageTests(run func() int) int { // isolatePackageUserState points the home directories of this process at one // new throwaway root, removes the variables that outrank them, and keeps // credentials in a file under that root. It returns the root and a function -// that removes it. In a process that is already marked as isolated it changes -// nothing and returns an empty root. +// that removes it. In a child of an isolated run it changes nothing and returns +// the parent's root with a function that leaves it in place. func isolatePackageUserState() (string, func(), error) { - if os.Getenv(userStateIsolatedEnv) != "" { - return "", func() {}, nil + if marker := os.Getenv(userStateIsolatedEnv); isLivePackageRoot(marker) { + return marker, func() {}, nil } root, err := os.MkdirTemp("", "zero-cli-user-state-") if err != nil { @@ -102,12 +116,26 @@ func isolatePackageUserState() (string, func(), error) { if err := os.Setenv("ZERO_CRED_STORAGE", "encrypted-file"); err != nil { return fail(fmt.Errorf("keep credentials in a file: %w", err)) } - if err := os.Setenv(userStateIsolatedEnv, "1"); err != nil { + if err := os.WriteFile(filepath.Join(root, packageRootStamp), nil, 0o600); err != nil { + return fail(fmt.Errorf("stamp the root: %w", err)) + } + if err := os.Setenv(userStateIsolatedEnv, root); err != nil { return fail(fmt.Errorf("mark the process as isolated: %w", err)) } return root, cleanup, nil } +// isLivePackageRoot reports whether path is a root the setup created and has +// not removed yet. The setup exports an absolute path. A relative one would +// depend on the directory a child happens to start in, so it never counts. +func isLivePackageRoot(path string) bool { + if !filepath.IsAbs(path) { + return false + } + _, err := os.Lstat(filepath.Join(path, packageRootStamp)) + return err == nil +} + // The names are written out again here on purpose. Reusing the lists the setup // walks would let a name dropped from them go unnoticed. var ( @@ -149,6 +177,9 @@ func TestPackageRunsAgainstAThrowawayUserState(t *testing.T) { if resolved, err := filepath.EvalSymlinks(packageUserStateRoot); err != nil || resolved != packageUserStateRoot { t.Fatalf("the package root is %q and resolves to %q, %v; it must be exported in its physical spelling", packageUserStateRoot, resolved, err) } + if got := os.Getenv(userStateIsolatedEnv); got != packageUserStateRoot || !isLivePackageRoot(got) { + t.Errorf("%s = %q, want the live package root %q so a child keeps it", userStateIsolatedEnv, got, packageUserStateRoot) + } for _, name := range everyPackageHomeEnvName { if value := os.Getenv(name); value != packageUserStateRoot { t.Errorf("%s = %q, want the package root %q", name, value, packageUserStateRoot) @@ -215,41 +246,152 @@ func TestIsolatePackageUserStateReplacesTheHomeAndClearsTheOverrides(t *testing. if got := os.Getenv("ZERO_CRED_STORAGE"); got != "encrypted-file" { t.Errorf("ZERO_CRED_STORAGE = %q, want credentials kept in a file", got) } - if os.Getenv(userStateIsolatedEnv) == "" { - t.Errorf("%s is not set; a child started by a test would isolate itself again", userStateIsolatedEnv) + if got := os.Getenv(userStateIsolatedEnv); got != root || !isLivePackageRoot(got) { + t.Errorf("%s = %q, want the live root %q; a child started by a test would isolate itself again", userStateIsolatedEnv, got, root) } cleanup() if _, err := os.Stat(root); !os.IsNotExist(err) { t.Errorf("the root %q is still there after cleanup: %v", root, err) } + if isLivePackageRoot(root) { + t.Errorf("the removed root %q still counts as live", root) + } } -// A PROCESS THAT IS ALREADY ISOLATED IS LEFT ALONE. +// pointUserStateAt sets every home directory to home and every override to a +// path under it, the way a developer's own environment might. +func pointUserStateAt(t *testing.T, home string) { + t.Helper() + for _, name := range everyPackageHomeEnvName { + t.Setenv(name, home) + } + for _, name := range everyPackageClearedEnvName { + t.Setenv(name, filepath.Join(home, "override")) + } +} + +// A CHILD OF AN ISOLATED RUN IS LEFT ALONE. // // Some tests start this test binary again as a child and hand it its own // directories, and two such children have to share them. Replacing the -// directories again in the child would give each its own empty root. -func TestIsolatePackageUserStateLeavesAnIsolatedProcessAlone(t *testing.T) { - given := t.TempDir() - for _, name := range everyPackageHomeEnvName { - t.Setenv(name, given) +// directories again in the child would give each its own empty root. The +// child must not remove the parent's root either. +func TestIsolatePackageUserStateLeavesAChildOfAnIsolatedRunAlone(t *testing.T) { + pointUserStateAt(t, t.TempDir()) + t.Setenv(userStateIsolatedEnv, "") + parentRoot, parentCleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) } - for _, name := range everyPackageClearedEnvName { + defer parentCleanup() + + given := t.TempDir() + for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { t.Setenv(name, given) } - t.Setenv(userStateIsolatedEnv, "1") + t.Setenv(userStateIsolatedEnv, parentRoot) root, cleanup, err := isolatePackageUserState() if err != nil { t.Fatal(err) } - defer cleanup() - if root != "" { - t.Fatalf("root = %q, want none: the process was already isolated", root) + if root != parentRoot { + t.Fatalf("root = %q, want the parent's root %q: the process was already isolated", root, parentRoot) } for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { if value := os.Getenv(name); value != given { t.Errorf("%s = %q, want the directory it was given, %q", name, value, given) } } + cleanup() + if !isLivePackageRoot(parentRoot) { + t.Errorf("the child removed the parent's root %q", parentRoot) + } +} + +// A MARKER THE SETUP DID NOT WRITE IS IGNORED. +// +// The marker skips the whole setup, so a value that merely looks set, exported +// in a shell or copied from a log, must not be enough. With any of these the +// process has to be isolated exactly as if the marker were absent. +func TestIsolatePackageUserStateIgnoresAMarkerItDidNotWrite(t *testing.T) { + removedRoot := func(t *testing.T) string { + t.Setenv(userStateIsolatedEnv, "") + root, cleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) + } + cleanup() + return root + } + for name, marker := range map[string]func(t *testing.T) string{ + "a flag value": func(*testing.T) string { return "1" }, + "a relative path to a stamped root": func(t *testing.T) string { + t.Chdir(t.TempDir()) + if err := os.Mkdir("root", 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join("root", packageRootStamp), nil, 0o600); err != nil { + t.Fatal(err) + } + return "root" + }, + "a directory the setup never made": func(t *testing.T) string { return t.TempDir() }, + "the root of a run that has finished": removedRoot, + } { + t.Run(name, func(t *testing.T) { + decoy := t.TempDir() + pointUserStateAt(t, decoy) + value := marker(t) + pointUserStateAt(t, decoy) + t.Setenv(userStateIsolatedEnv, value) + + root, cleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) + } + defer cleanup() + if root == "" || root == value || pathIsUnder(t, decoy, root) { + t.Fatalf("root = %q with the marker %q, want a new root outside %q", root, value, decoy) + } + for _, name := range everyPackageHomeEnvName { + if got := os.Getenv(name); got != root { + t.Errorf("%s = %q, want the new root %q", name, got, root) + } + } + for _, name := range everyPackageClearedEnvName { + if got, set := os.LookupEnv(name); set { + t.Errorf("%s = %q is still set", name, got) + } + } + if got := os.Getenv(userStateIsolatedEnv); got != root { + t.Errorf("%s = %q, want the new root %q", userStateIsolatedEnv, got, root) + } + }) + } +} + +// THE SAME THROUGH TestMain, the way a developer would hit it: the package run +// starts with the marker already exported and every directory pointing at a +// decoy. The child runs the test that pins the package default, which fails +// if the setup was skipped. +func TestPackageRunIgnoresAMarkerFromTheOutsideEnvironment(t *testing.T) { + decoy := t.TempDir() + cmd := exec.Command(os.Args[0], "-test.run=^TestPackageRunsAgainstAThrowawayUserState$", "-test.v") + // The parent's own setup already put ZERO_CRED_STORAGE in os.Environ, so + // set it back to the keychain: the child has to get the file from its setup. + cmd.Env = append(os.Environ(), userStateIsolatedEnv+"=1", "ZERO_CRED_STORAGE=keyring") + for _, name := range everyPackageHomeEnvName { + cmd.Env = append(cmd.Env, name+"="+decoy) + } + for _, name := range everyPackageClearedEnvName { + cmd.Env = append(cmd.Env, name+"="+filepath.Join(decoy, "override")) + } + output, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("the package run with %s=1 in its environment failed: %v\n%s", userStateIsolatedEnv, err, output) + } + if !strings.Contains(string(output), "--- PASS: TestPackageRunsAgainstAThrowawayUserState") { + t.Fatalf("the child did not run the package check:\n%s", output) + } } diff --git a/internal/cli/provider_adoption_test.go b/internal/cli/provider_adoption_test.go index dc7659cbf..de053b92d 100644 --- a/internal/cli/provider_adoption_test.go +++ b/internal/cli/provider_adoption_test.go @@ -78,9 +78,10 @@ func TestLocalAdoptionSavesAndReloadsEligibleModel(t *testing.T) { cmd.Env = []string{ "ZERO_TEST_LOCAL_ADOPTION=1", "ZERO_CRED_STORAGE=encrypted-file", // The child is this test binary again. It is handed its own roots - // below and both invocations must share them, so tell the package - // setup not to replace them a second time. - userStateIsolatedEnv + "=1", + // below and both invocations must share them, so pass on the + // package root, which tells the package setup not to replace them a + // second time. + userStateIsolatedEnv + "=" + packageUserStateRoot, "HOME=" + root, "USERPROFILE=" + root, "XDG_CONFIG_HOME=" + filepath.Join(root, "config"), "XDG_CACHE_HOME=" + filepath.Join(root, "cache"),