| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "strings" |
| 15 | "sync/atomic" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "golang.org/x/sys/unix" |
| 20 | ) |
| 21 | |
| 22 | |
| 23 | |
| 24 | func TestLinuxBundledProxyLifecycle(t *testing.T) { |
| 25 | if os.Getenv("CAGE_LINUX_INTEGRATION") != "1" { |
| 26 | t.Skip("requires a bundled Linux mihomo and host network interfaces") |
| 27 | } |
| 28 | profile := t.TempDir() |
| 29 | s, err := Load(profile) |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | listener, err := net.Listen("tcp4", "127.0.0.1:0") |
| 34 | if err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | s.Port = listener.Addr().(*net.TCPAddr).Port |
| 38 | listener.Close() |
| 39 | var targetRequests, proxyRequests atomic.Int32 |
| 40 | target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 41 | targetRequests.Add(1) |
| 42 | w.Header().Set("Connection", "close") |
| 43 | _, _ = io.WriteString(w, "local-target-response") |
| 44 | })) |
| 45 | defer target.Close() |
| 46 | targetAddress := strings.TrimPrefix(target.URL, "http://") |
| 47 | upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 48 | proxyRequests.Add(1) |
| 49 | if r.Method != http.MethodConnect || r.Host != targetAddress { |
| 50 | t.Errorf("upstream received unexpected request %s %q", r.Method, r.Host) |
| 51 | http.Error(w, "refused", http.StatusForbidden) |
| 52 | return |
| 53 | } |
| 54 | remote, err := net.DialTimeout("tcp4", targetAddress, time.Second) |
| 55 | if err != nil { |
| 56 | http.Error(w, "target unavailable", http.StatusBadGateway) |
| 57 | return |
| 58 | } |
| 59 | defer remote.Close() |
| 60 | client, buffered, err := w.(http.Hijacker).Hijack() |
| 61 | if err != nil { |
| 62 | return |
| 63 | } |
| 64 | defer client.Close() |
| 65 | _, _ = io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n") |
| 66 | go func() { _, _ = io.Copy(remote, buffered); _ = remote.Close() }() |
| 67 | _, _ = io.Copy(client, remote) |
| 68 | })) |
| 69 | defer upstream.Close() |
| 70 | upstreamPort := upstream.Listener.Addr().(*net.TCPAddr).Port |
| 71 | if err := s.Import("local smoke node", "", []byte(fmt.Sprintf("proxies:\n - {name: smoke, type: http, server: 127.0.0.1, port: %d}\n", upstreamPort)), "smoke", 0, ""); err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | s.Selected = s.Sources[0].Nodes[0].ID |
| 75 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 76 | defer cancel() |
| 77 | t.Cleanup(func() { |
| 78 | if err := Stop(profile); err != nil { |
| 79 | t.Error(err) |
| 80 | } |
| 81 | }) |
| 82 | readRecord := func() linuxCoreRecord { |
| 83 | t.Helper() |
| 84 | b, err := os.ReadFile(linuxCoreRecordPath(profile)) |
| 85 | var record linuxCoreRecord |
| 86 | if err != nil || json.Unmarshal(b, &record) != nil { |
| 87 | t.Fatal("missing proxy process record", err) |
| 88 | } |
| 89 | return record |
| 90 | } |
| 91 | if err := Start(ctx, profile, s); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | first := readRecord() |
| 95 | if !Running(ctx, profile, s) { |
| 96 | t.Fatal("bundled core did not expose its authenticated local state") |
| 97 | } |
| 98 | if info, err := os.Stat(Socket(profile)); err != nil || info.Mode().Perm() != 0600 { |
| 99 | t.Fatal("proxy control socket is not private", err) |
| 100 | } |
| 101 | if err := Start(ctx, profile, s); err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | if readRecord() != first { |
| 105 | t.Fatal("idempotent start replaced the running core") |
| 106 | } |
| 107 | proxyURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", s.Port)) |
| 108 | proxyURL.User = url.UserPassword("cage", s.Auth) |
| 109 | transport := &http.Transport{Proxy: http.ProxyURL(proxyURL), DisableKeepAlives: true} |
| 110 | defer transport.CloseIdleConnections() |
| 111 | client := &http.Client{Transport: transport, Timeout: 5 * time.Second} |
| 112 | res, err := client.Get(target.URL + "/cage-linux-smoke") |
| 113 | if err != nil { |
| 114 | t.Fatal("selected proxy did not carry the request", err) |
| 115 | } |
| 116 | body, err := io.ReadAll(res.Body) |
| 117 | res.Body.Close() |
| 118 | if err != nil || string(body) != "local-target-response" || proxyRequests.Load() != 1 || targetRequests.Load() != 1 { |
| 119 | t.Fatal("request bypassed the selected proxy", err) |
| 120 | } |
| 121 | upstream.Close() |
| 122 | res, err = client.Get(target.URL + "/cage-linux-smoke") |
| 123 | if err == nil { |
| 124 | body, _ = io.ReadAll(res.Body) |
| 125 | res.Body.Close() |
| 126 | if res.StatusCode == http.StatusOK || strings.Contains(string(body), "local-target-response") { |
| 127 | t.Fatal("core fell back to direct after the upstream stopped") |
| 128 | } |
| 129 | } |
| 130 | if targetRequests.Load() != 1 { |
| 131 | t.Fatal("target was contacted directly after the upstream stopped") |
| 132 | } |
| 133 | if err := Stop(profile); err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | if Running(ctx, profile, s) { |
| 137 | t.Fatal("core still responds after stop") |
| 138 | } |
| 139 | if _, err := os.Stat(linuxCoreRecordPath(profile)); !os.IsNotExist(err) { |
| 140 | t.Fatal("stop retained its process record", err) |
| 141 | } |
| 142 | if err := Start(ctx, profile, s); err != nil { |
| 143 | t.Fatal("could not restart bundled core", err) |
| 144 | } |
| 145 | if readRecord() == first { |
| 146 | t.Fatal("restart reused the old process identity") |
| 147 | } |
| 148 | second := readRecord() |
| 149 | fd, err := unix.PidfdOpen(second.PID, 0) |
| 150 | if err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | defer unix.Close(fd) |
| 154 | if err := unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | if n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, 5000); err != nil || n == 0 { |
| 158 | t.Fatal("core did not exit after simulated crash", err) |
| 159 | } |
| 160 | if err := Start(ctx, profile, s); err != nil { |
| 161 | t.Fatal("stale record prevented restart after a core crash", err) |
| 162 | } |
| 163 | if readRecord() == second || !Running(ctx, profile, s) { |
| 164 | t.Fatal("core did not recover after a crash") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestLinuxCoreStopPinsAndChecksProcessIdentity(t *testing.T) { |
| 169 | cmd := exec.Command("sleep", "60") |
| 170 | if err := cmd.Start(); err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | done := make(chan struct{}) |
| 174 | go func() { _ = cmd.Wait(); close(done) }() |
| 175 | t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) |
| 176 | record, err := identifyLinuxCore(cmd.Process.Pid) |
| 177 | if err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | stale := record |
| 181 | stale.Started++ |
| 182 | if err := stopLinuxProcess(stale, record.Executable); err != nil { |
| 183 | t.Fatal("stale record prevented recovery", err) |
| 184 | } |
| 185 | if err := unix.Kill(cmd.Process.Pid, 0); err != nil { |
| 186 | t.Fatal("stopped a process with a different identity", err) |
| 187 | } |
| 188 | if err := stopLinuxProcess(record, "/proc/self/exe"); err == nil { |
| 189 | t.Fatal("accepted a different executable") |
| 190 | } |
| 191 | previousBoot := record |
| 192 | previousBoot.BootID = "a-previous-boot" |
| 193 | if err := stopLinuxProcess(previousBoot, record.Executable); err != nil { |
| 194 | t.Fatal("could not discard previous boot record", err) |
| 195 | } |
| 196 | if err := unix.Kill(cmd.Process.Pid, 0); err != nil { |
| 197 | t.Fatal("stopped a process referenced by a previous boot", err) |
| 198 | } |
| 199 | if err := stopLinuxProcess(record, record.Executable); err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | select { |
| 203 | case <-done: |
| 204 | case <-time.After(2 * time.Second): |
| 205 | t.Fatal("proxy process was not reaped") |
| 206 | } |
| 207 | if err := stopLinuxProcess(record, record.Executable); err != nil { |
| 208 | t.Fatal("stopping an exited process should succeed", err) |
| 209 | } |
| 210 | } |