diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go new file mode 100644 index 000000000..e0347845e --- /dev/null +++ b/internal/cli/main_test.go @@ -0,0 +1,397 @@ +package cli + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// userStateIsolatedEnv marks a process whose per-user directories have already +// 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"} + +// 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. 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. +// +// 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, 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 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)) +} + +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 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 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 marker := os.Getenv(userStateIsolatedEnv); isLivePackageRoot(marker) { + return marker, func() {}, nil + } + root, err := os.MkdirTemp("", "zero-cli-user-state-") + 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) } + fail := func(err error) (string, func(), error) { + cleanup() + return "", nil, err + } + for _, name := range packageHomeEnvNames { + if err := os.Setenv(name, root); err != nil { + return fail(fmt.Errorf("redirect %s: %w", name, err)) + } + } + for _, name := range packageClearedEnvNames { + if err := os.Unsetenv(name); err != nil { + 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.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 ( + 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() + resolvedRoot, err := filepath.EvalSymlinks(root) + if err != nil { + t.Fatalf("resolve %s: %v", root, err) + } + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + // 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)) +} + +// 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. 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") + } + 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) + } + } + for _, name := range everyPackageClearedEnvName { + if value, set := os.LookupEnv(name); set { + 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, + "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 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 everyPackageHomeEnvName { + t.Setenv(name, decoy) + } + for _, name := range everyPackageClearedEnvName { + t.Setenv(name, filepath.Join(decoy, "override")) + } + t.Setenv("ZERO_CRED_STORAGE", "keyring") + 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) + } + 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 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 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) + } +} + +// 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. 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) + } + defer parentCleanup() + + given := t.TempDir() + for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { + t.Setenv(name, given) + } + t.Setenv(userStateIsolatedEnv, parentRoot) + + root, cleanup, err := isolatePackageUserState() + if err != nil { + t.Fatal(err) + } + 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 cf1726e9a..de053b92d 100644 --- a/internal/cli/provider_adoption_test.go +++ b/internal/cli/provider_adoption_test.go @@ -77,6 +77,11 @@ 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 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"),