| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/sylvinus/agent-vm/internal/cage" |
| 16 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 17 | ) |
| 18 | |
| 19 | func monitorTimingRecords(t *testing.T, s *Server, kind string) []map[string]string { |
| 20 | t.Helper() |
| 21 | f, err := os.Open(filepath.Join(s.profile, "logs", "events.jsonl")) |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | defer f.Close() |
| 26 | var records []map[string]string |
| 27 | scanner := bufio.NewScanner(f) |
| 28 | for scanner.Scan() { |
| 29 | var event diagnostics.Event |
| 30 | if err := json.Unmarshal(scanner.Bytes(), &event); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | if event.Source != "network-monitor" { |
| 34 | continue |
| 35 | } |
| 36 | fields := make(map[string]string) |
| 37 | for _, field := range strings.Fields(event.Message) { |
| 38 | key, value, _ := strings.Cut(field, "=") |
| 39 | fields[key] = value |
| 40 | } |
| 41 | if fields["monitor"] == kind { |
| 42 | records = append(records, fields) |
| 43 | } |
| 44 | } |
| 45 | if err := scanner.Err(); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | return records |
| 49 | } |
| 50 | |
| 51 | func TestNetworkMonitorRecordsRepeatedLockSkips(t *testing.T) { |
| 52 | s := testServer(t) |
| 53 | s.ready = true |
| 54 | s.safety.VerifiedAt = time.Now().Add(-85 * time.Second) |
| 55 | s.safety.Gate = &cage.GateStatus{Mode: cage.GateOpen, Until: time.Now().Add(5 * time.Second)} |
| 56 | s.op.Lock() |
| 57 | defer s.op.Unlock() |
| 58 | ctx, cancel := context.WithTimeout(context.Background(), 5200*time.Millisecond) |
| 59 | defer cancel() |
| 60 | s.monitorNetwork(ctx) |
| 61 | records := monitorTimingRecords(t, s, "network") |
| 62 | if len(records) != 2 { |
| 63 | t.Fatalf("expected both skipped ticks, got %v", records) |
| 64 | } |
| 65 | for i, record := range records { |
| 66 | if record["result"] != "operation_lock_busy" || record["consecutive_lock_skips"] != strconv.Itoa(i+1) { |
| 67 | t.Fatalf("missing lock skip evidence: %v", record) |
| 68 | } |
| 69 | age, _ := strconv.Atoi(record["verified_age_ms"]) |
| 70 | if age < 85000 { |
| 71 | t.Fatalf("missing late verification age: %v", record) |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | func TestSafetyMonitorRunsWhileOperationLockIsHeld(t *testing.T) { |
| 77 | s := testServer(t) |
| 78 | s.ready = true |
| 79 | s.safety.VerifiedAt = time.Now() |
| 80 | s.op.Lock() |
| 81 | s.startMonitors() |
| 82 | deadline := time.Now().Add(2 * time.Second) |
| 83 | var found bool |
| 84 | for time.Now().Before(deadline) { |
| 85 | if _, err := os.Stat(filepath.Join(s.profile, "logs", "events.jsonl")); err == nil { |
| 86 | for _, record := range monitorTimingRecords(t, s, "safety") { |
| 87 | found = found || record["result"] == "not_due" |
| 88 | } |
| 89 | } |
| 90 | if found { |
| 91 | break |
| 92 | } |
| 93 | time.Sleep(10 * time.Millisecond) |
| 94 | } |
| 95 | s.op.Unlock() |
| 96 | s.closeBackground() |
| 97 | if !found { |
| 98 | t.Fatal("safety monitoring was blocked by an unrelated operation") |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | func TestConcurrentSafetyMonitorKeepsManualPause(t *testing.T) { |
| 103 | s, gate := grantedToolUpdateServer(t) |
| 104 | s.setJobForTest(Job{}) |
| 105 | s.safety.VerifiedAt = time.Now().Add(-time.Minute) |
| 106 | started := make(chan struct{}) |
| 107 | finished := make(chan struct{}) |
| 108 | go func() { |
| 109 | defer close(finished) |
| 110 | s.monitorSafetyWithProbe(func(ctx context.Context, _ cage.Config) (string, error) { |
| 111 | close(started) |
| 112 | <-ctx.Done() |
| 113 | return "", ctx.Err() |
| 114 | }) |
| 115 | }() |
| 116 | select { |
| 117 | case <-started: |
| 118 | case <-time.After(3 * time.Second): |
| 119 | t.Fatal("monitor did not start") |
| 120 | } |
| 121 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 122 | t.Error("overlapping monitor started a second probe") |
| 123 | return "", nil |
| 124 | }) |
| 125 | if err := s.pauseNetworkNow("user pause"); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | select { |
| 129 | case <-finished: |
| 130 | case <-time.After(3 * time.Second): |
| 131 | t.Fatal("paused monitor did not stop") |
| 132 | } |
| 133 | if gate.Status().Mode != cage.GateClosed { |
| 134 | t.Fatal("monitor reopened networking after manual pause") |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | func TestMonitorTimingAttributesSlowProbe(t *testing.T) { |
| 139 | s, gate := grantedToolUpdateServer(t) |
| 140 | s.setJobForTest(Job{}) |
| 141 | s.safety.VerifiedAt = time.Now().Add(-85 * time.Second) |
| 142 | s.monitorSafetyWithProbe(func(context.Context, cage.Config) (string, error) { |
| 143 | time.Sleep(30 * time.Millisecond) |
| 144 | return "", errors.New("synthetic probe failed token=private-probe-secret") |
| 145 | }) |
| 146 | if gate.Status().Mode != cage.GateClosed { |
| 147 | t.Fatal("failed probe retained an open gate") |
| 148 | } |
| 149 | records := monitorTimingRecords(t, s, "safety") |
| 150 | if len(records) != 1 { |
| 151 | t.Fatalf("missing safety round: %v", records) |
| 152 | } |
| 153 | record := records[0] |
| 154 | duration, err := strconv.Atoi(record["exit_ip_ms"]) |
| 155 | if err != nil || duration < 30 || record["result"] != "observation_failed" { |
| 156 | t.Fatalf("slow probe was not attributed: %v", record) |
| 157 | } |
| 158 | if _, present := record["guest_settings_ms"]; present { |
| 159 | t.Fatalf("recorded an unexecuted stage: %v", record) |
| 160 | } |
| 161 | data, err := os.ReadFile(filepath.Join(s.profile, "logs", "events.jsonl")) |
| 162 | if err != nil || strings.Contains(string(data), "private-probe-secret") { |
| 163 | t.Fatal("diagnostics could not be read or contained a probe secret") |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | func TestMonitorTimingRecordsRenewalAndSkips(t *testing.T) { |
| 168 | s, gate := grantedToolUpdateServer(t) |
| 169 | client, err := s.gateClient() |
| 170 | if err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | before := gate.Status() |
| 174 | s.finishSafetyMonitor(context.Background(), client, before, "192.0.2.1", "") |
| 175 | records := monitorTimingRecords(t, s, "renewal") |
| 176 | if len(records) != 1 || records[0]["result"] != "renewed" || records[0]["gate_renew_ms"] == "" || records[0]["safety_lock_ms"] == "" { |
| 177 | t.Fatalf("missing renewal timing: %v", records) |
| 178 | } |
| 179 | remaining, err := strconv.Atoi(records[0]["lease_remaining_end_ms"]) |
| 180 | if err != nil || remaining < 0 || remaining > int(cage.GateLease.Milliseconds()) { |
| 181 | t.Fatalf("invalid old lease margin: %v", records[0]) |
| 182 | } |
| 183 | s.monitorSafety() |
| 184 | s.networkPaused = true |
| 185 | s.monitorSafety() |
| 186 | records = monitorTimingRecords(t, s, "safety") |
| 187 | if len(records) != 2 || records[0]["result"] != "not_due" || records[1]["result"] != "network_paused" { |
| 188 | t.Fatalf("skip reasons were lost: %v", records) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func TestNetworkMonitorRecordsAllOuterStages(t *testing.T) { |
| 193 | s := testServer(t) |
| 194 | previous := physicalProxyInterface |
| 195 | physicalProxyInterface = func(context.Context) (string, error) { |
| 196 | time.Sleep(30 * time.Millisecond) |
| 197 | return "en0", nil |
| 198 | } |
| 199 | defer func() { physicalProxyInterface = previous }() |
| 200 | s.monitorNetworkTick() |
| 201 | records := monitorTimingRecords(t, s, "network") |
| 202 | if len(records) != 1 { |
| 203 | t.Fatalf("missing network round: %v", records) |
| 204 | } |
| 205 | for _, stage := range []string{"physical_interface", "proxy_health", "safety", "recovery", "subscriptions"} { |
| 206 | if records[0][stage+"_ms"] == "" { |
| 207 | t.Fatalf("missing %s timing: %v", stage, records[0]) |
| 208 | } |
| 209 | } |
| 210 | duration, err := strconv.Atoi(records[0]["physical_interface_ms"]) |
| 211 | if err != nil || duration < 30 { |
| 212 | t.Fatalf("slow interface check was not attributed: %v", records[0]) |
| 213 | } |
| 214 | } |