package scripts_test import ( "context" "errors" "fmt" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" "testing" "time" "gopkg.in/yaml.v3" ) type artifactRootScenario struct { Env map[string]string Phases []struct { Name string Always bool Actions []map[string]string } } // Exercise whole action copies, including the runner's quoted environment // prefix. No real cleanup executable is reachable in the test's stub PATH. func TestTestopsArtifactRootGuards(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("POSIX shell controls") } dir := os.Getenv("TESTOPS_SCENARIO_DIR") if dir == "" { dir = filepath.Join(repoRoot(t), "testops", "scenarios") } files, err := filepath.Glob(filepath.Join(dir, "*.yaml")) if err != nil { t.Fatal(err) } guarded, uninstalls := 0, 0 for _, path := range files { raw, err := os.ReadFile(path) if err != nil { t.Fatal(err) } var scenario artifactRootScenario if err := yaml.Unmarshal(raw, &scenario); err != nil { t.Fatalf("%s: %v", path, err) } if _, exists := scenario.Env["artifact_root"]; !exists { continue } for _, phase := range scenario.Phases { for index, action := range phase.Actions { cmd := action["cmd"] if action["action"] != "exec" { continue } usesRoot := strings.Contains(cmd, "{{ artifact_root }}") for key, value := range action { if strings.HasPrefix(key, "env.") && strings.Contains(value, "{{ artifact_root }}") { usesRoot = true } } needsGuard := usesRoot && (phase.Always || strings.Contains(cmd, "rm -") || strings.Contains(cmd, "case ")) if !needsGuard { continue } guarded++ if phase.Always && strings.Contains(cmd, "uninstall-k8s-alpha.sh") { uninstalls++ } name := fmt.Sprintf("%s/%s/%d", filepath.Base(path), phase.Name, index) t.Run(name, func(t *testing.T) { checkArtifactRootAction(t, action) }) } } } if guarded < 24 || uninstalls != 6 { t.Fatalf("coverage: guarded actions=%d, always uninstalls=%d; want >=24 and 6", guarded, uninstalls) } } func checkArtifactRootAction(t *testing.T, action map[string]string) { t.Helper() work := t.TempDir() bin := filepath.Join(work, "bin") if err := os.Mkdir(bin, 0o755); err != nil { t.Fatal(err) } if _, overridesPath := action["env.PATH"]; overridesPath { t.Fatal("cleanup controls must retain their stub-only PATH") } if err := os.Symlink("/bin/sh", filepath.Join(bin, "sh")); err != nil { t.Fatal(err) } if err := os.Symlink("/bin/cat", filepath.Join(bin, "cat")); err != nil { t.Fatal(err) } // Make the uncordon branch real in the supported-root control. nodeFile := filepath.Join(work, "g15d-k8s", "guard-test-node-loss-survival", "demo", "cordoned-primary-node.txt") if err := os.MkdirAll(filepath.Dir(nodeFile), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(nodeFile, []byte("node-test\n"), 0o644); err != nil { t.Fatal(err) } trace := filepath.Join(work, "cleanup-started") for _, name := range []string{"rm", "mkdir", "kubectl", "helm", "sudo", "nvme", "iscsiadm", "bash", "touch", "go"} { stub := "#!/bin/sh\nprintf '%s %s\\n' '" + name + "' \"$*\" >> \"$GUARD_TRACE\"\nexit 0\n" if err := os.WriteFile(filepath.Join(bin, name), []byte(stub), 0o755); err != nil { t.Fatal(err) } } bad := []string{"", "/", "relative/dir", "/srv/with space", "/srv/*", "/srv/x\n", "/srv/'$(touch injected)'", "/srv/x'; touch injected; '"} for index, root := range bad { t.Run(fmt.Sprintf("invalid-%d", index), func(t *testing.T) { _ = os.Remove(trace) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "bash", "-c", renderArtifactRootAction(action, root, work)) cmd.Dir = work cmd.Env = append(os.Environ(), "PATH="+bin, "GUARD_TRACE="+trace) out, err := cmd.CombinedOutput() if ctx.Err() != nil { t.Fatalf("invalid-root control expired: %v; %s", ctx.Err(), out) } var exit *exec.ExitError if !errors.As(err, &exit) { t.Fatalf("invalid-root command did not complete with a refusal: %v; %s", err, out) } if exit.ExitCode() != 2 { t.Errorf("invalid root %q: exit=%d want2; %s", root, exit.ExitCode(), out) } if raw, readErr := os.ReadFile(trace); readErr == nil || !os.IsNotExist(readErr) { t.Fatalf("invalid root %q started cleanup: %q (read=%v)", root, raw, readErr) } }) } // A real supported path must reach the original action, not a blanket // refusal. Every complete body must finish and leave a command witness. _ = os.Remove(trace) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "bash", "-c", renderArtifactRootAction(action, work, work)) cmd.Dir = work cmd.Env = append(os.Environ(), "PATH="+bin, "GUARD_TRACE="+trace) out, err := cmd.CombinedOutput() if ctx.Err() != nil || err != nil { t.Fatalf("supported root command did not complete: %v (context=%v); %s", err, ctx.Err(), out) } witness, err := os.ReadFile(trace) if err != nil || len(witness) == 0 { t.Fatalf("supported root did not reach its action: %v; %s", err, out) } for _, target := range []string{"scripts/run-phase129-nvme-k8s-mounted-restage-gate.sh", "scripts/uninstall-k8s-alpha.sh"} { if strings.Contains(action["cmd"], target) && !strings.Contains(string(witness), "bash "+target+" ") { t.Fatalf("missing script witness %s: %s", target, witness) } } if strings.Contains(action["cmd"], "kubectl uncordon") { for _, target := range []string{"kubectl uncordon node-test", "kubectl get node node-test"} { if !strings.Contains(string(witness), target) { t.Fatalf("missing node-file witness %s: %s", target, witness) } } } } func renderArtifactRootAction(action map[string]string, root, product string) string { render := strings.NewReplacer("{{ artifact_root }}", root, "{{ product_root }}", product, "{{ run_id }}", "guard-test") var keys []string for key := range action { if strings.HasPrefix(key, "env.") { keys = append(keys, key) } } sort.Strings(keys) var prefix strings.Builder for _, key := range keys { fmt.Fprintf(&prefix, "%s=%s ", strings.TrimPrefix(key, "env."), artifactShellQuote(render.Replace(action[key]))) } // The runner applies env.* to the complete command through sh -c. return prefix.String() + "sh -c " + artifactShellQuote(render.Replace(action["cmd"])) } func artifactShellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" }