| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/google/uuid" |
| 14 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 16 | ) |
| 17 | |
| 18 | func TestExitProbeTimeoutKeepsExistingLeaseWithoutRenewing(t *testing.T) { |
| 19 | s, gate := grantedToolUpdateServer(t) |
| 20 | s.setJobForTest(Job{}) |
| 21 | s.safety.VerifiedAt = time.Now().Add(-time.Minute) |
| 22 | before := gate.Status() |
| 23 | verified := s.safety.VerifiedAt |
| 24 | for i := 0; i < 2; i++ { |
| 25 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 26 | return "", context.DeadlineExceeded |
| 27 | }) |
| 28 | after := gate.Status() |
| 29 | if after.Mode != cage.GateOpen || after.Until != before.Until || !s.safety.VerifiedAt.Equal(verified) { |
| 30 | t.Fatalf("timeout changed the existing lease: before=%+v after=%+v", before, after) |
| 31 | } |
| 32 | } |
| 33 | client, err := s.gateClient() |
| 34 | if err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | |
| 38 | |
| 39 | for !time.Now().Add(cage.GateLease).After(before.Until) { |
| 40 | time.Sleep(time.Millisecond) |
| 41 | } |
| 42 | s.finishSafetyMonitor(context.Background(), client, gate.Status(), "8.8.8.8", "") |
| 43 | if !gate.Status().Until.After(before.Until) || s.safety.monitorError != "" { |
| 44 | t.Fatalf("successful observation did not renew and clear the retry notice: before=%+v after=%+v monitorError=%q", before, gate.Status(), s.safety.monitorError) |
| 45 | } |
| 46 | s.safety.VerifiedAt = time.Now().Add(-time.Minute) |
| 47 | gate.Close("检查或监测授权已到期") |
| 48 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 49 | t.Fatal("expired gate must not probe or reopen") |
| 50 | return "", nil |
| 51 | }) |
| 52 | if gate.Status().Mode != cage.GateClosed || s.recovery.RunID == "" { |
| 53 | t.Fatal("expired lease did not remain closed and schedule recovery") |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestWindowsFastPacketReconnectSchedulesFreshCheck(t *testing.T) { |
| 58 | for _, tc := range []struct { |
| 59 | name, reason string |
| 60 | windows, paused, want bool |
| 61 | }{ |
| 62 | {"Windows packet reconnect", windowsPacketDisconnectedReason, true, false, true}, |
| 63 | {"user pause", windowsPacketDisconnectedReason, true, true, false}, |
| 64 | {"policy refusal", "当前出口不符合已保存的地区约束", true, false, false}, |
| 65 | {"other guest", windowsPacketDisconnectedReason, false, false, false}, |
| 66 | } { |
| 67 | t.Run(tc.name, func(t *testing.T) { |
| 68 | s, gate := grantedToolUpdateServer(t) |
| 69 | s.setJobForTest(Job{}) |
| 70 | if tc.windows { |
| 71 | instance := s.instanceDir() |
| 72 | s.windowsGuest = &guestos.WindowsProfile{VMID: uuid.New(), InstanceDirectory: instance} |
| 73 | } |
| 74 | s.ready, s.networkPaused = true, tc.paused |
| 75 | s.safety.VerifiedAt = time.Now().Add(-time.Minute) |
| 76 | gate.Close(tc.reason) |
| 77 | before := gate.Status() |
| 78 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 79 | t.Fatal("closed gate ran a monitor probe instead of scheduling a fresh check") |
| 80 | return "", nil |
| 81 | }) |
| 82 | if (s.recovery.RunID != "") != tc.want || gate.Status().Mode != cage.GateClosed { |
| 83 | t.Fatalf("recovery=%+v gate=%s want scheduled=%t", s.recovery, gate.Status().Mode, tc.want) |
| 84 | } |
| 85 | if tc.want && (s.recovery.RunID != before.RunID || s.recovery.Epoch != before.Epoch || s.recovery.Configuration != before.Configuration) { |
| 86 | t.Fatal("recovery was not bound to the observed closed connection") |
| 87 | } |
| 88 | }) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | func TestMacOSNetworkTickDispatchesRecoveryOnlyAfterSetup(t *testing.T) { |
| 93 | for _, tc := range []struct { |
| 94 | name, setupID string |
| 95 | wantJob bool |
| 96 | }{ |
| 97 | {"installed guest", "", true}, |
| 98 | {"setup pending", "pending", false}, |
| 99 | } { |
| 100 | t.Run(tc.name, func(t *testing.T) { |
| 101 | s := testServer(t) |
| 102 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", SetupID: tc.setupID} |
| 103 | s.ready = true |
| 104 | s.safety.VerifiedAt = time.Now() |
| 105 | s.recovery = networkRecovery{RunID: "isolated-retry", Next: time.Now().Add(-time.Second)} |
| 106 | |
| 107 | s.op.Lock() |
| 108 | s.monitorNetworkTick() |
| 109 | job := s.jobs.snapshot() |
| 110 | s.jobs.cancelRunning() |
| 111 | s.op.Unlock() |
| 112 | s.jobs.close() |
| 113 | if (job.Running && job.Kind == "network-recovery") != tc.wantJob { |
| 114 | t.Fatalf("recovery job = %+v, want queued = %t", job, tc.wantJob) |
| 115 | } |
| 116 | }) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | func TestMonitorLocationFailureSchedulesRecoveryButViolationDoesNot(t *testing.T) { |
| 121 | for _, policy := range []cage.ExitPolicy{ |
| 122 | {Mode: "static", IP: "8.8.8.8"}, |
| 123 | {Mode: "dynamic", Scope: "any"}, |
| 124 | {Mode: "dynamic", Scope: "country", CountryCode: "US"}, |
| 125 | } { |
| 126 | for _, condition := range []string{"location unavailable", "outside country", "mainland location", "mainland range", "user paused"} { |
| 127 | if condition == "outside country" && (policy.Mode == "static" || policy.Scope == "any") { |
| 128 | continue |
| 129 | } |
| 130 | t.Run(policy.Mode+"/"+policy.Scope+"/"+condition, func(t *testing.T) { |
| 131 | s := testServer(t) |
| 132 | proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 133 | if r.Method != http.MethodConnect { |
| 134 | t.Error("location bypassed proxy tunnel") |
| 135 | } |
| 136 | w.WriteHeader(http.StatusServiceUnavailable) |
| 137 | })) |
| 138 | defer proxy.Close() |
| 139 | cfg, _ := loadConfig(s.configPath) |
| 140 | cfg.ProxyURL = proxy.URL |
| 141 | cfg.ExitPolicy = policy |
| 142 | if err := writePrivate(s.configPath, cfg); err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | gate, err := cage.NewEgressGate(cfg) |
| 146 | if err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | if err := os.MkdirAll(s.instanceDir(), 0700); err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate) |
| 153 | if err != nil { |
| 154 | t.Fatal(err) |
| 155 | } |
| 156 | defer stop() |
| 157 | if err := gate.BeginCheck(); err != nil { |
| 158 | t.Fatal(err) |
| 159 | } |
| 160 | state := gate.Status() |
| 161 | report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "location-monitor", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()} |
| 162 | for _, id := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} { |
| 163 | report.Checks = append(report.Checks, cage.SafetyCheck{ID: id, Title: id, Critical: true, State: cage.CheckPassed, Evidence: "isolated fixture", CheckedAt: report.CreatedAt}) |
| 164 | } |
| 165 | if err := gate.Grant(report); err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | s.ready = true |
| 169 | s.safety.VerifiedAt = time.Now().Add(-time.Minute) |
| 170 | if condition == "mainland location" { |
| 171 | s.locations = map[string]Location{"8.8.8.8": {IP: "8.8.8.8", CountryCode: "CN", CheckedAt: time.Now()}} |
| 172 | } |
| 173 | if condition == "outside country" { |
| 174 | s.locations = map[string]Location{"8.8.8.8": {IP: "8.8.8.8", CountryCode: "JP", CheckedAt: time.Now()}} |
| 175 | } |
| 176 | if condition == "user paused" { |
| 177 | if err := s.pauseNetworkNow("user pause"); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | } |
| 181 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 182 | if condition == "user paused" { |
| 183 | t.Fatal("monitor probed while paused") |
| 184 | } |
| 185 | if condition == "mainland range" { |
| 186 | return "223.5.5.5", nil |
| 187 | } |
| 188 | return "8.8.8.8", nil |
| 189 | }) |
| 190 | if gate.Status().Mode != cage.GateClosed { |
| 191 | t.Fatal("unverified or paused network stayed open") |
| 192 | } |
| 193 | if (s.recovery.RunID != "") != (condition == "location unavailable") { |
| 194 | t.Fatalf("incorrect recovery admission for %s: %+v", condition, s.recovery) |
| 195 | } |
| 196 | }) |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func TestNetworkRecoveryAdmissionRequiresObservedPressureToDefer(t *testing.T) { |
| 202 | now := time.Now() |
| 203 | for _, tc := range []struct { |
| 204 | name string |
| 205 | status cage.ResourceStatus |
| 206 | wantJob bool |
| 207 | }{ |
| 208 | {"memory target could not be applied", cage.ResourceStatus{ObservedAt: now, Error: "内存目标未能应用,保持当前配置"}, true}, |
| 209 | {"failed sample retains stale guest pressure", cage.ResourceStatus{ObservedAt: now.Add(-time.Minute), Error: "资源采样暂时不可用,已暂停内存回收", Pressure: true}, true}, |
| 210 | {"current guest pressure", cage.ResourceStatus{ObservedAt: now, Pressure: true}, false}, |
| 211 | {"current host pressure", cage.ResourceStatus{HostPressure: true}, false}, |
| 212 | } { |
| 213 | t.Run(tc.name, func(t *testing.T) { |
| 214 | s, gate := failedMonitoringServer(t) |
| 215 | s.recovery.Next = time.Now().Add(-time.Second) |
| 216 | tc.status.Version, tc.status.UpdatedAt = 1, time.Now() |
| 217 | if err := writePrivate(filepath.Join(s.instanceDir(), "cage-resources.json"), tc.status); err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | |
| 221 | s.op.Lock() |
| 222 | s.recoverNetwork() |
| 223 | job := s.jobs.snapshot() |
| 224 | s.jobs.cancelRunning() |
| 225 | s.op.Unlock() |
| 226 | s.jobs.close() |
| 227 | if (job.Running && job.Kind == "network-recovery") != tc.wantJob || gate.Status().Mode != cage.GateClosed { |
| 228 | t.Fatalf("job = %+v, want admitted = %v while gate remains closed", job, tc.wantJob) |
| 229 | } |
| 230 | }) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | func failedMonitoringServer(t *testing.T) (*Server, *cage.EgressGate) { |
| 235 | s, gate := grantedToolUpdateServer(t) |
| 236 | s.setJobForTest(Job{}) |
| 237 | client, err := s.gateClient() |
| 238 | if err != nil { |
| 239 | t.Fatal(err) |
| 240 | } |
| 241 | s.finishSafetyObservation(context.Background(), client, gate.Status(), "", "guest observation timed out", true) |
| 242 | if gate.Status().Mode != cage.GateClosed || s.recovery.RunID == "" { |
| 243 | t.Fatal("temporary failure did not revoke and schedule") |
| 244 | } |
| 245 | return s, gate |
| 246 | } |
| 247 | |
| 248 | func TestNetworkRecoveryDoesNotReusePriorGrant(t *testing.T) { |
| 249 | s, gate := failedMonitoringServer(t) |
| 250 | expected := s.recovery |
| 251 | called := false |
| 252 | err := s.runNetworkRecovery(expected, func() error { |
| 253 | called = true |
| 254 | if gate.Status().Mode != cage.GateClosed { |
| 255 | t.Fatal("opened before full check") |
| 256 | } |
| 257 | return errors.New("new full check failed") |
| 258 | }) |
| 259 | if !called || err == nil || gate.Status().Mode != cage.GateClosed || s.recovery.Attempts != 1 || !s.recovery.Next.After(time.Now().Add(20*time.Second)) { |
| 260 | t.Fatal("failed check did not remain closed with backoff", err, s.recovery) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | func TestNetworkRecoveryHonorsInterveningChanges(t *testing.T) { |
| 265 | for _, change := range []string{"pause", "configuration", "new-check", "stop"} { |
| 266 | t.Run(change, func(t *testing.T) { |
| 267 | s, gate := failedMonitoringServer(t) |
| 268 | expected := s.recovery |
| 269 | switch change { |
| 270 | case "pause": |
| 271 | if err := s.pauseNetworkNow("user pause"); err != nil { |
| 272 | t.Fatal(err) |
| 273 | } |
| 274 | case "configuration": |
| 275 | cfg, _ := loadConfig(s.configPath) |
| 276 | cfg.Timezone = "Asia/Tokyo" |
| 277 | if err := writePrivate(s.configPath, cfg); err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | case "new-check": |
| 281 | if err := gate.BeginCheck(); err != nil { |
| 282 | t.Fatal(err) |
| 283 | } |
| 284 | case "stop": |
| 285 | s.closing = true |
| 286 | } |
| 287 | err := s.runNetworkRecovery(expected, func() error { t.Fatal("stale recovery ran"); return nil }) |
| 288 | if !errors.Is(err, context.Canceled) { |
| 289 | t.Fatal(err) |
| 290 | } |
| 291 | if s.recovery.RunID != "" { |
| 292 | t.Fatal("stale recovery retained") |
| 293 | } |
| 294 | }) |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | func TestNetworkRecoverySuccessfulFullCheckClearsRetry(t *testing.T) { |
| 299 | s, gate := failedMonitoringServer(t) |
| 300 | expected := s.recovery |
| 301 | err := s.runNetworkRecovery(expected, func() error { |
| 302 | if err := gate.BeginCheck(); err != nil { |
| 303 | return err |
| 304 | } |
| 305 | state := gate.Status() |
| 306 | report := *state.Report |
| 307 | report.CheckID = state.CheckID |
| 308 | report.ID = "fresh-recovery" |
| 309 | report.CreatedAt = time.Now() |
| 310 | for i := range report.Checks { |
| 311 | report.Checks[i].CheckedAt = report.CreatedAt |
| 312 | } |
| 313 | return gate.Grant(report) |
| 314 | }) |
| 315 | if err != nil || gate.Status().Mode != cage.GateOpen || s.recovery.RunID != "" { |
| 316 | t.Fatal(err, gate.Status().Mode, s.recovery) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func TestConfigurationMismatchDoesNotScheduleRecovery(t *testing.T) { |
| 321 | s, gate := grantedToolUpdateServer(t) |
| 322 | s.setJobForTest(Job{}) |
| 323 | state := gate.Status() |
| 324 | cfg, _ := loadConfig(s.configPath) |
| 325 | cfg.Timezone = "Asia/Tokyo" |
| 326 | if err := writePrivate(s.configPath, cfg); err != nil { |
| 327 | t.Fatal(err) |
| 328 | } |
| 329 | client, _ := s.gateClient() |
| 330 | s.finishSafetyObservation(context.Background(), client, state, "", "guest observation timed out", true) |
| 331 | if s.recovery.RunID != "" || gate.Status().Mode != cage.GateClosed { |
| 332 | t.Fatal("configuration change got transient recovery") |
| 333 | } |
| 334 | } |