| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "os" |
| 12 | "reflect" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/miekg/dns" |
| 19 | "go.yaml.in/yaml/v3" |
| 20 | ) |
| 21 | |
| 22 | func writeDNSAnswer(t *testing.T, w http.ResponseWriter, r *http.Request, mutate func(*dns.Msg)) { |
| 23 | t.Helper() |
| 24 | if r.Method != "POST" || r.Header.Get("Content-Type") != "application/dns-message" || r.Header.Get("Accept") != "application/dns-message" { |
| 25 | t.Error("bootstrap changed its encrypted DNS request contract") |
| 26 | } |
| 27 | wire, _ := io.ReadAll(r.Body) |
| 28 | var q dns.Msg |
| 29 | if err := q.Unpack(wire); err != nil || len(q.Question) != 1 || q.Question[0].Qtype != dns.TypeA { |
| 30 | t.Error("invalid bootstrap question", err) |
| 31 | w.WriteHeader(400) |
| 32 | return |
| 33 | } |
| 34 | answer := new(dns.Msg) |
| 35 | answer.SetReply(&q) |
| 36 | answer.Answer = []dns.RR{&dns.A{Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, A: net.ParseIP("8.8.8.8").To4()}} |
| 37 | if mutate != nil { |
| 38 | mutate(answer) |
| 39 | } |
| 40 | wire, err := answer.Pack() |
| 41 | if err != nil { |
| 42 | t.Error(err) |
| 43 | } |
| 44 | w.Header().Set("Content-Type", "application/dns-message") |
| 45 | _, _ = w.Write(wire) |
| 46 | } |
| 47 | |
| 48 | func TestInfrastructureDNSDoesNotWaitForBlockedResolver(t *testing.T) { |
| 49 | started, canceled := make(chan struct{}), make(chan struct{}) |
| 50 | release := make(chan struct{}) |
| 51 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 52 | if r.URL.Path == "/blocked" { |
| 53 | _, _ = io.Copy(io.Discard, r.Body) |
| 54 | close(started) |
| 55 | select { |
| 56 | case <-r.Context().Done(): |
| 57 | close(canceled) |
| 58 | case <-release: |
| 59 | } |
| 60 | return |
| 61 | } |
| 62 | select { |
| 63 | case <-started: |
| 64 | case <-r.Context().Done(): |
| 65 | return |
| 66 | } |
| 67 | writeDNSAnswer(t, w, r, nil) |
| 68 | })) |
| 69 | defer server.Close() |
| 70 | defer close(release) |
| 71 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 72 | defer cancel() |
| 73 | ip, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/blocked", server.URL + "/working"}) |
| 74 | if err != nil || ip.String() != "8.8.8.8" { |
| 75 | t.Fatal("reachable resolver could not bypass blocked one", ip, err) |
| 76 | } |
| 77 | select { |
| 78 | case <-canceled: |
| 79 | case <-ctx.Done(): |
| 80 | t.Fatal("unused DNS query was not canceled") |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | func TestInfrastructureDNSRejectsInvalidAnswersAndTriesOtherResolver(t *testing.T) { |
| 85 | for _, tc := range []struct { |
| 86 | name string |
| 87 | mutate func(*dns.Msg) |
| 88 | }{ |
| 89 | {"wrong ID", func(m *dns.Msg) { m.Id++ }}, |
| 90 | {"not a reply", func(m *dns.Msg) { m.Response = false }}, |
| 91 | {"NXDOMAIN", func(m *dns.Msg) { m.Rcode = dns.RcodeNameError }}, |
| 92 | {"truncated", func(m *dns.Msg) { m.Truncated = true }}, |
| 93 | {"wrong question", func(m *dns.Msg) { m.Question[0].Name = "other.example." }}, |
| 94 | {"private IP", func(m *dns.Msg) { m.Answer[0].(*dns.A).A = net.ParseIP("127.0.0.1").To4() }}, |
| 95 | {"no answer", func(m *dns.Msg) { m.Answer = nil }}, |
| 96 | } { |
| 97 | t.Run(tc.name, func(t *testing.T) { |
| 98 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 99 | mutate := tc.mutate |
| 100 | if r.URL.Path == "/working" { |
| 101 | mutate = nil |
| 102 | } |
| 103 | writeDNSAnswer(t, w, r, mutate) |
| 104 | })) |
| 105 | defer server.Close() |
| 106 | ctx := context.Background() |
| 107 | if _, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/invalid"}); err == nil { |
| 108 | t.Fatal("invalid DNS response was accepted") |
| 109 | } |
| 110 | ip, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/invalid", server.URL + "/working"}) |
| 111 | if err != nil || ip.String() != "8.8.8.8" { |
| 112 | t.Fatal("valid DNS alternative failed", ip, err) |
| 113 | } |
| 114 | }) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | func TestInfrastructureDNSAllUnavailableAndCancellation(t *testing.T) { |
| 119 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 120 | w.WriteHeader(503) |
| 121 | })) |
| 122 | defer server.Close() |
| 123 | servers := []string{server.URL + "/one", server.URL + "/two"} |
| 124 | if ip, err := resolveInfrastructureWith(context.Background(), "example.com", server.Client(), servers); err == nil || ip.IsValid() || !strings.Contains(err.Error(), "未使用系统 DNS 回退") { |
| 125 | t.Fatal("all failed resolvers must fail closed", ip, err) |
| 126 | } |
| 127 | ctx, cancel := context.WithCancel(context.Background()) |
| 128 | cancel() |
| 129 | if _, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), servers); !errors.Is(err, context.Canceled) { |
| 130 | t.Fatal("cancellation was not preserved", err) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestRuntimeUsesRedundantBootstrapWithoutChangingBusinessDNS(t *testing.T) { |
| 135 | s, _ := Load(t.TempDir()) |
| 136 | if err := s.Import("test", "", []byte(testNodes), "source", 0, ""); err != nil { |
| 137 | t.Fatal(err) |
| 138 | } |
| 139 | s.Selected = s.Sources[0].Nodes[0].ID |
| 140 | wire, err := s.Runtime(t.TempDir()) |
| 141 | if err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | var config struct { |
| 145 | DNS struct { |
| 146 | Default []string `yaml:"default-nameserver"` |
| 147 | Proxy []string `yaml:"proxy-server-nameserver"` |
| 148 | Names []string `yaml:"nameserver"` |
| 149 | } `yaml:"dns"` |
| 150 | Rules []string `yaml:"rules"` |
| 151 | } |
| 152 | if err := yaml.Unmarshal(wire, &config); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | want := BootstrapDNSURLs() |
| 156 | if len(want) < 2 || !reflect.DeepEqual(config.DNS.Default, want) || !reflect.DeepEqual(config.DNS.Proxy, want) { |
| 157 | t.Fatal("node bootstrap did not receive both DNS services", config.DNS) |
| 158 | } |
| 159 | if !reflect.DeepEqual(config.DNS.Names, []string{"https://1.1.1.1/dns-query#" + Group}) || !reflect.DeepEqual(config.Rules, []string{"MATCH," + Group}) { |
| 160 | t.Fatal("bootstrap fallback changed business routing", config) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestInfrastructureDNSLiveIntegration(t *testing.T) { |
| 165 | if os.Getenv("CAGE_TEST_BOOTSTRAP") != "1" { |
| 166 | t.Skip("explicit host-network DNS test required") |
| 167 | } |
| 168 | tr := &http.Transport{Proxy: nil} |
| 169 | defer tr.CloseIdleConnections() |
| 170 | client := &http.Client{Transport: tr, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} |
| 171 | ip, err := resolveInfrastructureWith(context.Background(), "example.com", client, BootstrapDNSURLs()) |
| 172 | if err != nil || !publicIP(ip) { |
| 173 | t.Fatal("redundant encrypted DNS lookup failed", err) |
| 174 | } |
| 175 | |
| 176 | |
| 177 | for _, endpoint := range BootstrapDNSURLs() { |
| 178 | t.Run(endpoint, func(t *testing.T) { |
| 179 | ip, err := resolveInfrastructureWith(context.Background(), "example.com", client, []string{endpoint}) |
| 180 | if err != nil || !publicIP(ip) { |
| 181 | t.Log("DNS endpoint unavailable on this network", err) |
| 182 | return |
| 183 | } |
| 184 | t.Log("DNS endpoint returned a usable public IPv4") |
| 185 | }) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func TestHostSubscriptionUsesChosenProxyAndPinnedPublicIP(t *testing.T) { |
| 190 | resolver := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { writeDNSAnswer(t, w, r, nil) })) |
| 191 | defer resolver.Close() |
| 192 | origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 193 | if r.Host != "example.com" || r.TLS.ServerName != "example.com" { |
| 194 | t.Error("subscription authority or TLS name changed") |
| 195 | } |
| 196 | io.WriteString(w, "proxies: []") |
| 197 | })) |
| 198 | defer origin.Close() |
| 199 | for _, encrypted := range []bool{false, true} { |
| 200 | var dnsCalls, sourceCalls atomic.Int32 |
| 201 | proxy := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 202 | if r.Method != "CONNECT" { |
| 203 | http.Error(w, "unexpected proxy method", 400) |
| 204 | return |
| 205 | } |
| 206 | var upstream string |
| 207 | switch r.Host { |
| 208 | case resolver.Listener.Addr().String(): |
| 209 | upstream = r.Host |
| 210 | dnsCalls.Add(1) |
| 211 | case "8.8.8.8:443": |
| 212 | upstream = origin.Listener.Addr().String() |
| 213 | sourceCalls.Add(1) |
| 214 | default: |
| 215 | t.Errorf("unvalidated proxy destination %s", r.Host) |
| 216 | http.Error(w, "bad target", 400) |
| 217 | return |
| 218 | } |
| 219 | conn, err := net.Dial("tcp", upstream) |
| 220 | if err != nil { |
| 221 | t.Error(err) |
| 222 | return |
| 223 | } |
| 224 | defer conn.Close() |
| 225 | downstream, buf, err := w.(http.Hijacker).Hijack() |
| 226 | if err != nil { |
| 227 | t.Error(err) |
| 228 | return |
| 229 | } |
| 230 | defer downstream.Close() |
| 231 | buf.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n") |
| 232 | buf.Flush() |
| 233 | go io.Copy(conn, buf) |
| 234 | io.Copy(downstream, conn) |
| 235 | })) |
| 236 | if encrypted { |
| 237 | proxy.StartTLS() |
| 238 | } else { |
| 239 | proxy.Start() |
| 240 | } |
| 241 | defer proxy.Close() |
| 242 | addr, _ := url.Parse(proxy.URL) |
| 243 | host := origin.Client().Transport.(*http.Transport).Clone() |
| 244 | host.ForceAttemptHTTP2 = true |
| 245 | host.Proxy = http.ProxyURL(addr) |
| 246 | client := &http.Client{Transport: subscriptionHostTransport{host, []string{resolver.URL}}} |
| 247 | data, _, err := Fetch(t.Context(), client, "https://example.com/test-token") |
| 248 | if err != nil || string(data) != "proxies: []" || dnsCalls.Load() != 1 || sourceCalls.Load() != 1 { |
| 249 | t.Fatalf("encrypted=%v data=%q err=%v dns=%d source=%d", encrypted, data, err, dnsCalls.Load(), sourceCalls.Load()) |
| 250 | } |
| 251 | if _, _, err = Fetch(t.Context(), client, "https://127.0.0.1/private"); err == nil { |
| 252 | t.Fatal("private destination accepted") |
| 253 | } |
| 254 | } |
| 255 | } |