| 1 | |
| 2 | |
| 3 | package workbench |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "golang.org/x/sys/windows" |
| 18 | ) |
| 19 | |
| 20 | |
| 21 | |
| 22 | func TestWindowsNetworkProcessTree(t *testing.T) { |
| 23 | mode := os.Getenv("CAGE_TEST_WINDOWS_NETWORK_PROCESS_MODE") |
| 24 | if mode == "leaf" { |
| 25 | time.Sleep(5 * time.Minute) |
| 26 | return |
| 27 | } |
| 28 | executable, err := os.Executable() |
| 29 | if err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | if mode == "helper" { |
| 33 | if err := containWindowsNetworkProcess(); err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | child := exec.Command(executable, "-test.run=^TestWindowsNetworkProcessTree$") |
| 37 | child.Env = append(os.Environ(), "CAGE_TEST_WINDOWS_NETWORK_PROCESS_MODE=leaf") |
| 38 | child.Stdout, child.Stderr = io.Discard, io.Discard |
| 39 | if err := child.Start(); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | fmt.Fprintln(os.Stdout, child.Process.Pid) |
| 43 | time.Sleep(5 * time.Minute) |
| 44 | return |
| 45 | } |
| 46 | if os.Getenv("CAGE_TEST_WINDOWS_NETWORK_PROCESS_TREE") != "1" { |
| 47 | t.Skip("requires explicitly enabled native process-tree QA") |
| 48 | } |
| 49 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 50 | defer cancel() |
| 51 | helper := exec.CommandContext(ctx, executable, "-test.run=^TestWindowsNetworkProcessTree$") |
| 52 | helper.Env = append(os.Environ(), "CAGE_TEST_WINDOWS_NETWORK_PROCESS_MODE=helper") |
| 53 | helper.Stderr = os.Stderr |
| 54 | output, err := helper.StdoutPipe() |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if err := helper.Start(); err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | defer helper.Process.Kill() |
| 62 | line, err := bufio.NewReader(output).ReadString('\n') |
| 63 | id, parseErr := strconv.Atoi(strings.TrimSpace(line)) |
| 64 | if err != nil || parseErr != nil || id <= 0 || !processExists(id) { |
| 65 | t.Fatal("owned relay process was not observed") |
| 66 | } |
| 67 | leaf, err := windows.OpenProcess(windows.PROCESS_TERMINATE|windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, uint32(id)) |
| 68 | if err != nil { |
| 69 | t.Fatal(err) |
| 70 | } |
| 71 | defer windows.CloseHandle(leaf) |
| 72 | defer windows.TerminateProcess(leaf, 1) |
| 73 | if err := helper.Process.Kill(); err != nil { |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | _ = helper.Wait() |
| 77 | deadline := time.Now().Add(5 * time.Second) |
| 78 | var code uint32 |
| 79 | live := func() bool { return windows.GetExitCodeProcess(leaf, &code) != nil || code == 259 } |
| 80 | for live() && time.Now().Before(deadline) { |
| 81 | time.Sleep(25 * time.Millisecond) |
| 82 | } |
| 83 | if live() { |
| 84 | t.Fatal("owned relay survived its network helper") |
| 85 | } |
| 86 | } |