| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/sylvinus/agent-vm/internal/cage" |
| 20 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 21 | ) |
| 22 | |
| 23 | const primaryLocationJSON = `{"success":true,"ip":"8.8.8.8","country":"United States","country_code":"US","region":"California","city":"Mountain View","timezone":{"id":"America/Los_Angeles"}}` |
| 24 | const backupLocationJSON = `{"ip":"8.8.8.8","country":"United States","country_code":"US","region":"California","region_code":"CA","city":"Mountain View","timezone":"America/Los_Angeles"}` |
| 25 | |
| 26 | func locationResponse(status int, body string) *http.Response { |
| 27 | return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))} |
| 28 | } |
| 29 | |
| 30 | func TestLocationFallbackUsesMeasuredIP(t *testing.T) { |
| 31 | for _, tc := range []struct { |
| 32 | name string |
| 33 | status int |
| 34 | body string |
| 35 | }{ |
| 36 | {"connection interrupted", 0, ""}, |
| 37 | {"timed out", -1, ""}, |
| 38 | {"rate limited", 429, ""}, |
| 39 | {"unavailable", 503, ""}, |
| 40 | {"malformed", 200, "not json"}, |
| 41 | {"rejected", 200, strings.Replace(primaryLocationJSON, `"success":true`, `"success":false`, 1)}, |
| 42 | {"wrong IP", 200, strings.Replace(primaryLocationJSON, "8.8.8.8", "9.9.9.9", 1)}, |
| 43 | {"missing country", 200, strings.Replace(primaryLocationJSON, `"US"`, `""`, 1)}, |
| 44 | {"invalid timezone", 200, strings.Replace(primaryLocationJSON, "America/Los_Angeles", "Not/AZone", 1)}, |
| 45 | } { |
| 46 | t.Run(tc.name, func(t *testing.T) { |
| 47 | var hosts []string |
| 48 | client := &http.Client{Timeout: 50 * time.Millisecond, Transport: browserTransport(func(r *http.Request) (*http.Response, error) { |
| 49 | hosts = append(hosts, r.URL.Host) |
| 50 | if r.URL.Scheme != "https" || r.Method != "GET" || r.Header.Get("User-Agent") != "Cage-network-check/1" { |
| 51 | t.Fatal("lookup changed its fixed HTTPS request contract") |
| 52 | } |
| 53 | switch r.URL.Host { |
| 54 | case "ipwho.is": |
| 55 | if r.URL.Path != "/8.8.8.8" { |
| 56 | t.Fatal("primary did not query measured IP") |
| 57 | } |
| 58 | if tc.status == 0 { |
| 59 | return nil, errors.New("private transport detail") |
| 60 | } |
| 61 | if tc.status == -1 { |
| 62 | <-r.Context().Done() |
| 63 | return nil, r.Context().Err() |
| 64 | } |
| 65 | return locationResponse(tc.status, tc.body), nil |
| 66 | case "api.ip.sb": |
| 67 | if r.URL.Path != "/geoip/8.8.8.8" { |
| 68 | t.Fatal("fallback did not query measured IP") |
| 69 | } |
| 70 | return locationResponse(200, backupLocationJSON), nil |
| 71 | default: |
| 72 | t.Fatal("unexpected location provider") |
| 73 | return nil, errors.New("unexpected host") |
| 74 | } |
| 75 | })} |
| 76 | loc, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")) |
| 77 | if err != nil || loc.IP != "8.8.8.8" || loc.CountryCode != "US" || loc.RegionCode != "CA" || loc.Timezone != "America/Los_Angeles" || loc.SuggestedLocale != "en_US.UTF-8" || loc.CheckedAt.IsZero() { |
| 78 | t.Fatalf("fallback location: %+v, %v", loc, err) |
| 79 | } |
| 80 | if strings.Join(hosts, ",") != "ipwho.is,api.ip.sb" { |
| 81 | t.Fatalf("incorrect fallback order: %v", hosts) |
| 82 | } |
| 83 | }) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | func TestLocationFallbackStaysOnConfiguredProxy(t *testing.T) { |
| 88 | targets := make(chan string, 2) |
| 89 | proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 90 | if r.Method != http.MethodConnect { |
| 91 | t.Error("location query did not establish a proxy tunnel") |
| 92 | } |
| 93 | targets <- r.Host |
| 94 | w.WriteHeader(http.StatusBadGateway) |
| 95 | })) |
| 96 | defer proxy.Close() |
| 97 | cfg := cage.DefaultConfig() |
| 98 | cfg.ProxyURL = proxy.URL |
| 99 | if _, err := probeLocationForIP(context.Background(), cfg, "8.8.8.8"); err == nil { |
| 100 | t.Fatal("rejected proxy requests produced a location") |
| 101 | } |
| 102 | for _, want := range []string{"ipwho.is:443", "api.ip.sb:443"} { |
| 103 | select { |
| 104 | case target := <-targets: |
| 105 | if target != want { |
| 106 | t.Fatal("unexpected proxy destination", target) |
| 107 | } |
| 108 | default: |
| 109 | t.Fatal("location provider bypassed configured proxy", want) |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | func TestSuccessfulPrimaryLocationDoesNotQueryBackup(t *testing.T) { |
| 115 | client := &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { |
| 116 | if r.URL.Host != "ipwho.is" { |
| 117 | t.Fatal("backup queried despite valid primary") |
| 118 | } |
| 119 | return locationResponse(200, primaryLocationJSON), nil |
| 120 | })} |
| 121 | if _, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | func TestLocationRejectsInvalidBackupAndKeepsErrorsPrivate(t *testing.T) { |
| 127 | for _, body := range []string{ |
| 128 | strings.Replace(backupLocationJSON, "8.8.8.8", "9.9.9.9", 1), |
| 129 | strings.Replace(backupLocationJSON, "America/Los_Angeles", "Local", 1), |
| 130 | strings.Replace(backupLocationJSON, "America/Los_Angeles", "", 1), |
| 131 | strings.Replace(backupLocationJSON, `"US"`, `""`, 1), |
| 132 | } { |
| 133 | client := &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { |
| 134 | if r.URL.Host == "ipwho.is" { |
| 135 | return nil, errors.New("private-secret") |
| 136 | } |
| 137 | return locationResponse(200, body), nil |
| 138 | })} |
| 139 | loc, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")) |
| 140 | if err == nil || loc != (Location{}) || strings.Contains(err.Error(), "private-secret") || !strings.Contains(err.Error(), "位置查询均失败") { |
| 141 | t.Fatalf("invalid backup accepted or error leaked: %+v, %v", loc, err) |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | func TestLocationCancellationStopsFallback(t *testing.T) { |
| 147 | ctx, cancel := context.WithCancel(context.Background()) |
| 148 | defer cancel() |
| 149 | calls := 0 |
| 150 | client := &http.Client{Transport: browserTransport(func(*http.Request) (*http.Response, error) { |
| 151 | calls++ |
| 152 | cancel() |
| 153 | return nil, context.Canceled |
| 154 | })} |
| 155 | _, err := lookupLocation(ctx, client, net.ParseIP("8.8.8.8")) |
| 156 | if !errors.Is(err, context.Canceled) || calls != 1 { |
| 157 | t.Fatal("canceled lookup continued to fallback", calls, err) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestLocationProvidersLiveIntegration(t *testing.T) { |
| 162 | path := os.Getenv("CAGE_TEST_CONFIG") |
| 163 | if path == "" { |
| 164 | t.Skip("explicit proxy profile required") |
| 165 | } |
| 166 | cfg, err := cage.Load(path) |
| 167 | if err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | if core := os.Getenv("CAGE_TEST_CORE"); core != "" { |
| 171 | cfg = isolatedLocationProxy(t, path, core, cfg) |
| 172 | } |
| 173 | egress, err := cage.NewEgress(cfg) |
| 174 | if err != nil { |
| 175 | t.Fatal(err) |
| 176 | } |
| 177 | transport := &http.Transport{Proxy: nil, DialContext: egress.DialContext} |
| 178 | defer transport.CloseIdleConnections() |
| 179 | client := &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} |
| 180 | t.Run("measured exit", func(t *testing.T) { |
| 181 | loc, err := probeLocation(context.Background(), cfg) |
| 182 | if err != nil || loc.IP == "" || loc.Timezone == "" { |
| 183 | t.Fatal("measured-exit location lookup failed", err) |
| 184 | } |
| 185 | }) |
| 186 | for _, policy := range []cage.ExitPolicy{ |
| 187 | {Mode: "static", Scope: "country"}, |
| 188 | {Mode: "dynamic", Scope: "any"}, |
| 189 | } { |
| 190 | t.Run("manual settings "+policy.Mode, func(t *testing.T) { |
| 191 | manual := cfg |
| 192 | manual.ExitPolicy = policy |
| 193 | manual.Timezone, manual.Locale, manual.BrowserLanguage = "Asia/Shanghai", "zh_CN.UTF-8", "zh-CN" |
| 194 | loc, err := probeEnvironmentLocation(context.Background(), manual, Preferences{}) |
| 195 | if err != nil || loc.IP == "" || loc.Timezone == "" || loc.CountryCode == "" { |
| 196 | t.Fatal("manual settings skipped mandatory country evidence", err) |
| 197 | } |
| 198 | if manual.Timezone != "Asia/Shanghai" || manual.Locale != "zh_CN.UTF-8" || manual.BrowserLanguage != "zh-CN" { |
| 199 | t.Fatal("manual settings changed during probe") |
| 200 | } |
| 201 | }) |
| 202 | } |
| 203 | t.Run("manual settings retain country verification", func(t *testing.T) { |
| 204 | restricted := cfg |
| 205 | restricted.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "country", CountryCode: "US"} |
| 206 | loc, err := probeEnvironmentLocation(context.Background(), restricted, Preferences{}) |
| 207 | if err != nil || loc.CountryCode == "" || loc.Timezone == "" { |
| 208 | t.Fatal("manual settings skipped required country lookup", err) |
| 209 | } |
| 210 | }) |
| 211 | t.Run("manual settings persist through validated save", func(t *testing.T) { |
| 212 | s := testServer(t) |
| 213 | store, err := managedproxy.Load(filepath.Dir(path)) |
| 214 | if err != nil { |
| 215 | t.Fatal("cannot load test source") |
| 216 | } |
| 217 | endpoint, _ := url.Parse(cfg.ProxyURL) |
| 218 | store.Port, _ = strconv.Atoi(endpoint.Port()) |
| 219 | store.Auth, _ = endpoint.User.Password() |
| 220 | if err := store.Save(s.profile); err != nil { |
| 221 | t.Fatal("cannot save isolated proxy source") |
| 222 | } |
| 223 | before := cfg |
| 224 | before.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "any"} |
| 225 | if err := writePrivate(s.configPath, before); err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | if err := before.RequireManagedProxy(s.profile); err != nil { |
| 229 | t.Fatal("test proxy source is not applied") |
| 230 | } |
| 231 | after := before |
| 232 | after.Timezone, after.Locale, after.BrowserLanguage = "Asia/Tokyo", "ja_JP.UTF-8", "ja-JP" |
| 233 | preferences := Preferences{Keyboard: "mac"} |
| 234 | if err := s.apply(savedProfile{Config: after, Preferences: preferences}, true); err != nil { |
| 235 | t.Fatal("validated manual settings save failed", err) |
| 236 | } |
| 237 | saved, err := cage.Load(s.configPath) |
| 238 | if err != nil || saved.Timezone != after.Timezone || saved.Locale != after.Locale || saved.BrowserLanguage != after.BrowserLanguage || saved.ExitPolicy != before.ExitPolicy { |
| 239 | t.Fatal("manual settings were not persisted or exit rule changed") |
| 240 | } |
| 241 | if s.preferences.AutoTimezone || s.preferences.AutoLanguage { |
| 242 | t.Fatal("manual mode was not applied") |
| 243 | } |
| 244 | }) |
| 245 | for _, host := range []string{"ipwho.is", "api.ip.sb"} { |
| 246 | t.Run(host, func(t *testing.T) { |
| 247 | only := *client |
| 248 | only.Transport = browserTransport(func(r *http.Request) (*http.Response, error) { |
| 249 | if r.URL.Host != host { |
| 250 | return nil, errors.New("only testing " + host) |
| 251 | } |
| 252 | return transport.RoundTrip(r) |
| 253 | }) |
| 254 | if _, err := lookupLocation(context.Background(), &only, net.ParseIP("8.8.8.8")); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | }) |
| 258 | } |
| 259 | t.Run("forced primary failure", func(t *testing.T) { |
| 260 | fallbackClient := *client |
| 261 | fallbackClient.Transport = browserTransport(func(r *http.Request) (*http.Response, error) { |
| 262 | if r.URL.Host == "ipwho.is" { |
| 263 | return nil, errors.New("simulated primary outage") |
| 264 | } |
| 265 | return transport.RoundTrip(r) |
| 266 | }) |
| 267 | if _, err := lookupLocation(context.Background(), &fallbackClient, net.ParseIP("8.8.8.8")); err != nil { |
| 268 | t.Fatal("real backup through selected proxy failed", err) |
| 269 | } |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | func isolatedLocationProxy(t *testing.T, configPath, core string, cfg cage.Config) cage.Config { |
| 276 | t.Helper() |
| 277 | store, err := managedproxy.Load(filepath.Dir(configPath)) |
| 278 | if err != nil { |
| 279 | t.Fatal("cannot load test proxy source") |
| 280 | } |
| 281 | if node, ok := store.Find(store.Selected); ok { |
| 282 | server, _ := node.Config["server"].(string) |
| 283 | t.Logf("Selected test node requires domain bootstrap: %t", net.ParseIP(server) == nil) |
| 284 | } |
| 285 | listener, err := net.Listen("tcp4", "127.0.0.1:0") |
| 286 | if err != nil { |
| 287 | t.Fatal(err) |
| 288 | } |
| 289 | store.Port = listener.Addr().(*net.TCPAddr).Port |
| 290 | _ = listener.Close() |
| 291 | store.Auth = managedproxy.Token() |
| 292 | profile := t.TempDir() |
| 293 | wire, err := store.Runtime(profile) |
| 294 | if err != nil { |
| 295 | t.Fatal("cannot generate isolated core config", err) |
| 296 | } |
| 297 | name, err := managedproxy.PhysicalInterface(context.Background()) |
| 298 | if err != nil { |
| 299 | t.Fatal(err) |
| 300 | } |
| 301 | wire, err = managedproxy.BindInterface(wire, name) |
| 302 | if err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | socketDir := filepath.Dir(managedproxy.Socket(profile)) |
| 306 | if err := os.MkdirAll(socketDir, 0700); err != nil { |
| 307 | t.Fatal(err) |
| 308 | } |
| 309 | t.Cleanup(func() { _ = os.RemoveAll(socketDir) }) |
| 310 | file := filepath.Join(managedproxy.Dir(profile), "config.yaml") |
| 311 | if err := managedproxy.Write(file, wire); err != nil { |
| 312 | t.Fatal(err) |
| 313 | } |
| 314 | log, err := os.OpenFile(filepath.Join(profile, "core.log"), os.O_CREATE|os.O_WRONLY, 0600) |
| 315 | if err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | t.Cleanup(func() { _ = log.Close() }) |
| 319 | validate := exec.Command(core, "-t", "-d", managedproxy.Dir(profile), "-f", file) |
| 320 | validate.Stdout, validate.Stderr = log, log |
| 321 | if err := validate.Run(); err != nil { |
| 322 | t.Fatal("bundled core rejected generated config") |
| 323 | } |
| 324 | cmd := exec.Command(core, "-d", managedproxy.Dir(profile), "-f", file) |
| 325 | cmd.Stdout, cmd.Stderr = log, log |
| 326 | if err := cmd.Start(); err != nil { |
| 327 | t.Fatal("cannot start isolated core") |
| 328 | } |
| 329 | done := make(chan error, 1) |
| 330 | go func() { done <- cmd.Wait() }() |
| 331 | t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) |
| 332 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 333 | defer cancel() |
| 334 | for { |
| 335 | if managedproxy.Running(ctx, profile, store) { |
| 336 | cfg.ProxyURL = store.Endpoint() |
| 337 | return cfg |
| 338 | } |
| 339 | select { |
| 340 | case <-ctx.Done(): |
| 341 | t.Fatal("isolated proxy did not become ready") |
| 342 | case <-time.After(50 * time.Millisecond): |
| 343 | } |
| 344 | } |
| 345 | } |