diff --git a/egress/current_test.go b/egress/current_test.go index 3a18aaad..5b18e844 100644 --- a/egress/current_test.go +++ b/egress/current_test.go @@ -20,9 +20,7 @@ func TestSetProfileConcurrentAndConsistent(t *testing.T) { names := []string{"off", "quiet", "balanced", "aggressive"} var wg sync.WaitGroup for i := range 8 { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for j := range 200 { p, _ := ProfileByName(names[(i+j)%len(names)]) SetProfile(p) @@ -32,7 +30,7 @@ func TestSetProfileConcurrentAndConsistent(t *testing.T) { } _ = CurrentProfile() } - }() + }) } wg.Wait() for _, name := range names { diff --git a/egress/egress.go b/egress/egress.go index 68fd0df4..d96a2560 100644 --- a/egress/egress.go +++ b/egress/egress.go @@ -266,10 +266,7 @@ func (g *Governor) reserve(h *hostState) time.Duration { func (g *Governor) backoff(h http.Header, attempt int) (d time.Duration, ok bool) { v := strings.TrimSpace(h.Get("Retry-After")) if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 0 { - maxSec := int64(g.p.MaxDelay / time.Second) - if maxSec < 0 { - maxSec = 0 - } + maxSec := max(int64(g.p.MaxDelay/time.Second), 0) if n > maxSec { return 0, false } diff --git a/egress/egress_test.go b/egress/egress_test.go index 4b9c7095..213ad5c8 100644 --- a/egress/egress_test.go +++ b/egress/egress_test.go @@ -62,8 +62,7 @@ func do(t *testing.T, g *Governor, ctx context.Context, method, u string) (int, func parallel(n int, f func(i int)) { var wg sync.WaitGroup for i := range n { - wg.Add(1) - go func() { defer wg.Done(); f(i) }() + wg.Go(func() { f(i) }) } wg.Wait() } diff --git a/guard/guard.go b/guard/guard.go index d8738bea..a676854a 100644 --- a/guard/guard.go +++ b/guard/guard.go @@ -11,6 +11,7 @@ import ( "context" "encoding/json" "fmt" + "maps" "net" "regexp" "strconv" @@ -294,7 +295,7 @@ func (d *ruleDecision) consider(dec intercept.Decision, tool string, input []byt // ask was carried by a request this call created, so it needs no prompt of its // own. func (g *Guard) requestTargets(ctx context.Context, scope intercept.TargetScope, ev hook.Event, unpinned []intercept.TargetRequest, ask *intercept.Decision) (res intercept.TargetResult, merged bool) { - for pass := 0; pass < targetPasses; pass++ { + for range targetPasses { if res = g.gate.RequestTargets(ctx, scope, ev.ToolName, ev.Input, unpinned, ask); res.Code != "" { return res, merged } @@ -413,9 +414,7 @@ func (g *Guard) Attributions() map[string]int { g.mu.Lock() defer g.mu.Unlock() out := make(map[string]int, len(g.attrib)) - for k, v := range g.attrib { - out[k] = v - } + maps.Copy(out, g.attrib) return out } diff --git a/guard/target_gate_test.go b/guard/target_gate_test.go index ef458e3f..75ab67c1 100644 --- a/guard/target_gate_test.go +++ b/guard/target_gate_test.go @@ -141,7 +141,7 @@ func TestTargetOnlyGuardRecordsBlocksOnly(t *testing.T) { {"add_intent", `{"summary":"probe https://app.example.com/"}`}, {"shell_send", `{"text":"nc 203.0.113.7 22\n"}`}, {"ExecuteExtraTool", `{"tool_name":"mcp__scan__run","params":{"target":"203.0.113.7"}}`}, } - for round := 0; round < 50; round++ { + for range 50 { for _, c := range calls { if block, msg := pre(g, ctx, c.tool, c.input); block { t.Fatalf("%s blocked: %s", c.tool, msg) diff --git a/intercept/alwaysallow_denylist.go b/intercept/alwaysallow_denylist.go index 1fdb4723..fd502bd5 100644 --- a/intercept/alwaysallow_denylist.go +++ b/intercept/alwaysallow_denylist.go @@ -36,7 +36,7 @@ var alwaysAllowDenylist = func() map[string]bool { "iptables ip6tables nft ufw mount umount swapoff shutdown reboot poweroff halt init telinit crontab " + "insmod rmmod modprobe", } { - for _, name := range strings.Fields(group) { + for name := range strings.FieldsSeq(group) { m[name] = true } } diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go index 1ff824f9..e2ed7e11 100644 --- a/intercept/argv_compound.go +++ b/intercept/argv_compound.go @@ -281,7 +281,7 @@ func hasAssignPrefix(s string) bool { if eq <= 0 { return false } - for i := 0; i < eq; i++ { + for i := range eq { c := s[i] isLetter := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' isDigit := c >= '0' && c <= '9' @@ -339,8 +339,7 @@ func shellDashCPayload(args []callWord) (string, bool) { } if strings.HasPrefix(tok, "--") { name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName, val := name[:eq], name[eq+1:] + if flagName, val, ok := strings.Cut(name, "="); ok { if flagName == "command" { return val, true } @@ -486,8 +485,7 @@ func envMatchesArgv(rule []string, args []callWord, depth int) bool { } if strings.HasPrefix(tok, "--") { name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName, val := name[:eq], name[eq+1:] + if flagName, val, ok := strings.Cut(name, "="); ok { if flagName == "split-string" && checkSplitString(val) { return true } @@ -645,8 +643,7 @@ func flockMatchesArgv(rule []string, args []callWord, depth int) bool { } if strings.HasPrefix(tok, "--") { name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName, val := name[:eq], name[eq+1:] + if flagName, val, ok := strings.Cut(name, "="); ok { if flagName == "command" { if depth < argvMaxNestedPayloads && bashCommandMatchesArgv(rule, val, depth+1) { return true @@ -743,9 +740,9 @@ func flockMatchesArgv(rule []string, args []callWord, depth int) bool { } return false } - if strings.HasPrefix(tok, "--command=") { + if after, ok := strings.CutPrefix(tok, "--command="); ok { if depth < argvMaxNestedPayloads { - return bashCommandMatchesArgv(rule, strings.TrimPrefix(tok, "--command="), depth+1) + return bashCommandMatchesArgv(rule, after, depth+1) } return false } @@ -1012,8 +1009,7 @@ func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { } if strings.HasPrefix(tok, "--") { name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName := name[:eq] + if flagName, _, ok := strings.Cut(name, "="); ok { if spec.stopLong[flagName] { return } diff --git a/intercept/intercept.go b/intercept/intercept.go index 6980d572..a8043357 100644 --- a/intercept/intercept.go +++ b/intercept/intercept.go @@ -19,6 +19,7 @@ import ( "log/slog" "net" "regexp" + "slices" "strconv" "strings" "sync" @@ -548,10 +549,8 @@ func (i *Interceptor) getSettingChoice(key, def string, allowed ...string) strin return def } v = strings.TrimSpace(v) - for _, a := range allowed { - if v == a { - return v - } + if slices.Contains(allowed, v) { + return v } return def } diff --git a/intercept/persistence.go b/intercept/persistence.go index ed12f473..aefeb7ab 100644 --- a/intercept/persistence.go +++ b/intercept/persistence.go @@ -2,6 +2,7 @@ package intercept import ( "encoding/json" + "slices" "strings" ) @@ -20,12 +21,7 @@ var PersistenceTools = []string{ // IsPersistenceTool reports whether name is one of PersistenceTools. func IsPersistenceTool(name string) bool { - for _, t := range PersistenceTools { - if t == name { - return true - } - } - return false + return slices.Contains(PersistenceTools, name) } // MatchPersistence decides a call of a persistence tool from the loaded rules. Any diff --git a/intercept/target.go b/intercept/target.go index 9ba90f02..7c22bb94 100644 --- a/intercept/target.go +++ b/intercept/target.go @@ -165,7 +165,7 @@ func validHostname(h string) bool { if len(h) > 253 { return false } - for _, label := range strings.Split(h, ".") { + for label := range strings.SplitSeq(h, ".") { if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { return false } diff --git a/intercept/target_gate.go b/intercept/target_gate.go index bc451311..e2b05270 100644 --- a/intercept/target_gate.go +++ b/intercept/target_gate.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/netip" + "slices" "sort" "strings" "time" @@ -524,12 +525,7 @@ func exemptionHolds(ct *checkedTarget) bool { if ct.Kind != TargetDomain || ct.err != nil || len(ct.ips) == 0 { return false } - for _, ip := range ct.ips { - if voidsExemption(ip) { - return false - } - } - return true + return !slices.ContainsFunc(ct.ips, voidsExemption) } // coveringPin returns the pin that covers the resolved addresses: the first diff --git a/intercept/target_gate_pg_test.go b/intercept/target_gate_pg_test.go index 2b8590a2..eb350d8b 100644 --- a/intercept/target_gate_pg_test.go +++ b/intercept/target_gate_pg_test.go @@ -180,7 +180,7 @@ func TestExemptionFirstUseLoggedOnce(t *testing.T) { t.Fatal(err) } - for n := 0; n < 3; n++ { + for range 3 { mustPass(t, "stored exemption", ic, scope, "https://pypi.org/simple/") mustPass(t, "derived exemption", ic, scope, "https://llm.example.net/v1/models") } diff --git a/intercept/target_gate_test.go b/intercept/target_gate_test.go index e07f2986..ae810f26 100644 --- a/intercept/target_gate_test.go +++ b/intercept/target_gate_test.go @@ -423,14 +423,12 @@ func TestResolverCacheTTLAndCollapse(t *testing.T) { // Concurrent lookups for one host collapse into one. g.res.hold = make(chan struct{}) var wg sync.WaitGroup - for n := 0; n < 8; n++ { - wg.Add(1) - go func() { - defer wg.Done() + for range 8 { + wg.Go(func() { if res, err := cache.lookup(context.Background(), "app.example.com", false); err != nil || !slices.Equal(res.ips, []string{"203.0.113.7"}) { t.Errorf("lookup = %+v, %v", res, err) } - }() + }) } eventually(t, "the shared lookup", func() bool { return g.res.lookups("app.example.com") == 1 }) time.Sleep(20 * time.Millisecond) @@ -1010,7 +1008,7 @@ func TestPinFirstUseLoggedOncePerVersion(t *testing.T) { g := newGate(t) g.res.set("app.example.com", "203.0.113.7") g.store.approve(g.requests("first", g.fetch(appURL))) - for n := 0; n < 3; n++ { + for range 3 { g.passes("pinned", g.fetch(appURL)) } if got := g.store.outcomes(); !slices.Equal(got, []string{"allowed/pin_match"}) { diff --git a/traffic/har.go b/traffic/har.go index 98681b08..49bb6f43 100644 --- a/traffic/har.go +++ b/traffic/har.go @@ -885,11 +885,11 @@ FROM exchange_bodies WHERE id=?`, id).Scan(&reqHead, &reqBody, &reqBlob, &respHe } func splitLegacyHTTP(raw []byte) (string, []byte) { - if idx := bytes.Index(raw, []byte("\r\n\r\n")); idx >= 0 { - return string(raw[:idx]), raw[idx+4:] + if before, after, ok := bytes.Cut(raw, []byte("\r\n\r\n")); ok { + return string(before), after } - if idx := bytes.Index(raw, []byte("\n\n")); idx >= 0 { - return string(raw[:idx]), raw[idx+2:] + if before, after, ok := bytes.Cut(raw, []byte("\n\n")); ok { + return string(before), after } return string(raw), nil } diff --git a/traffic/hookvm/vm_test.go b/traffic/hookvm/vm_test.go index 1e15ca61..465ac69c 100644 --- a/traffic/hookvm/vm_test.go +++ b/traffic/hookvm/vm_test.go @@ -479,7 +479,7 @@ func OnRequest(req *Request) error { } inputBody := []byte(`{"z":"last","a":"first","m":"mid","b":"second","k":"fifth"}`) var firstHeader, firstHash string - for run := 0; run < 20; run++ { + for run := range 20 { req := &Request{ Scheme: "https", Host: "example.test", Port: "443", Method: "POST", Path: "/api", diff --git a/traffic/host_ts_index_test.go b/traffic/host_ts_index_test.go index 312e4ff8..ff48dde1 100644 --- a/traffic/host_ts_index_test.go +++ b/traffic/host_ts_index_test.go @@ -48,7 +48,7 @@ func BenchmarkHostSearch(b *testing.B) { if err != nil { b.Fatal(err) } - for i := 0; i < 50000; i++ { + for i := range 50000 { host := "big.example" if i%10 == 0 { host = fmt.Sprintf("h%d.example", i%200) diff --git a/traffic/raw_tcp.go b/traffic/raw_tcp.go index 4baeebb0..6f49b462 100644 --- a/traffic/raw_tcp.go +++ b/traffic/raw_tcp.go @@ -131,10 +131,7 @@ func (t *Traffic) RecordRawTCPStream(rec RawTCPCapture, previewBytes int) (strin if ended.IsZero() || ended.Before(started) { ended = started } - durMs := ended.Sub(started).Milliseconds() - if durMs < 0 { - durMs = 0 - } + durMs := max(ended.Sub(started).Milliseconds(), 0) c2sPrev, c2sBlob := t.spillRawDir(rec.C2SData, previewBytes) s2cPrev, s2cBlob := t.spillRawDir(rec.S2CData, previewBytes) @@ -243,10 +240,7 @@ func (t *Traffic) ListRawTCPStreams(f RawTCPFilter) ([]RawTCPStream, int, error) if limit > 500 { limit = 500 } - offset := f.Offset - if offset < 0 { - offset = 0 - } + offset := max(f.Offset, 0) qArgs := append(append([]any{}, args...), limit, offset) rows, err := t.db.Query(` diff --git a/traffic/raw_udp.go b/traffic/raw_udp.go index e10d295d..97faf8f9 100644 --- a/traffic/raw_udp.go +++ b/traffic/raw_udp.go @@ -156,10 +156,7 @@ func (t *Traffic) ListRawUDPDatagrams(f RawUDPFilter) ([]RawUDPDatagram, int, er if limit > 500 { limit = 500 } - offset := f.Offset - if offset < 0 { - offset = 0 - } + offset := max(f.Offset, 0) qArgs := append(append([]any{}, args...), limit, offset) rows, err := t.db.Query(` diff --git a/traffic/reclaim_test.go b/traffic/reclaim_test.go index 794317d8..c07dc9ee 100644 --- a/traffic/reclaim_test.go +++ b/traffic/reclaim_test.go @@ -14,7 +14,7 @@ import ( // the test stays fast; the FTS side is covered by TestReclaimMergesFTSTombstones. func bulkRecord(tr *Traffic, host string, n, size int) { body := []byte(strings.Repeat("A", size)) - for i := 0; i < n; i++ { + for i := range n { tr.record(newFlow(host, "GET", fmt.Sprintf("/blob/%d", i), nil, body, withRespType("application/octet-stream"))) } @@ -78,9 +78,9 @@ func TestReclaimMergesFTSTombstones(t *testing.T) { } // Deleted in batches, which is what leaves tombstones spread over many // segments rather than emptying the index in one shot. - for round := 0; round < 4; round++ { + for round := range 4 { host := fmt.Sprintf("fts%d.example.com", round) - for i := 0; i < 20; i++ { + for i := range 20 { tr.record(newFlow(host, "GET", fmt.Sprintf("/p/%d", i), nil, []byte(strings.Repeat("secret token chinese body padding ", 200)))) } diff --git a/traffic/replay.go b/traffic/replay.go index ee45571b..8dc00f90 100644 --- a/traffic/replay.go +++ b/traffic/replay.go @@ -210,7 +210,7 @@ func (t *Traffic) Replay(ctx context.Context, req ReplayRequest) (ReplayResult, if http.CanonicalHeaderKey(strings.TrimSpace(h.Name)) != "Connection" { continue } - for _, token := range strings.Split(h.Value, ",") { + for token := range strings.SplitSeq(h.Value, ",") { if token = strings.TrimSpace(token); token != "" { connectionNamed[http.CanonicalHeaderKey(token)] = true } diff --git a/traffic/rewrite/engine.go b/traffic/rewrite/engine.go index a187adc8..80e9872d 100644 --- a/traffic/rewrite/engine.go +++ b/traffic/rewrite/engine.go @@ -288,7 +288,7 @@ func (r *compiledRule) matchBody(st *state) bool { // lists in Connection: that header is hop-by-hop for this exchange. func (r *compiledRule) writesConnectionHeader(h http.Header) bool { for _, v := range h.Values("Connection") { - for _, token := range strings.Split(v, ",") { + for token := range strings.SplitSeq(v, ",") { name := http.CanonicalHeaderKey(strings.TrimSpace(token)) if name != "" && slices.ContainsFunc(r.actions, func(a compiledAction) bool { return a.name == name }) { return true diff --git a/traffic/rewrite_flow_test.go b/traffic/rewrite_flow_test.go index 97b40598..4df13a18 100644 --- a/traffic/rewrite_flow_test.go +++ b/traffic/rewrite_flow_test.go @@ -12,6 +12,7 @@ import ( "fmt" "io" "log" + "maps" "net" "net/http" "net/http/httptest" @@ -175,9 +176,7 @@ func sendThrough(t *testing.T, tr *Traffic, proxyURL, method, target, body strin if err != nil { t.Fatal(err) } - for k, vs := range header { - req.Header[k] = vs - } + maps.Copy(req.Header, header) resp, err := proxyClient(t, tr, proxyURL).Do(req) if err != nil { t.Fatal(err) @@ -570,7 +569,7 @@ func TestSnapshotSweepDebounce(t *testing.T) { tb.reserve(key(1), live) tb.tick() // first sweep: none before start := tb.sweeps.Load() - for i := 0; i < 100; i++ { + for range 100 { tb.requestSweep() tb.tick() } @@ -616,7 +615,7 @@ func TestSnapshotSweeperStopsOnClose(t *testing.T) { // capacity tombstone stands for the flow. func TestSnapshotCapacityTombstone(t *testing.T) { tb := newSnapTable() - for i := 0; i < maxSnapEntries; i++ { + for i := range maxSnapEntries { e, _ := liveEntry(1) if !tb.reserve(key(i), e) { t.Fatalf("reservation %d failed", i) @@ -638,7 +637,7 @@ func TestSnapshotCapacityTombstone(t *testing.T) { // The 64 MiB budget bounds the entries too. tb = newSnapTable() - for i := 0; i < 64; i++ { + for i := range 64 { e, _ := liveEntry(1 << 20) if !tb.reserve(key(i), e) { t.Fatalf("reservation %d failed", i) diff --git a/traffic/socks5_test.go b/traffic/socks5_test.go index a705c2cb..ed7e77a4 100644 --- a/traffic/socks5_test.go +++ b/traffic/socks5_test.go @@ -29,9 +29,7 @@ func startEchoServer(t *testing.T, network, addr string) (net.Listener, *atomic. } var accepted atomic.Int32 var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { c, err := ln.Accept() if err != nil { @@ -45,7 +43,7 @@ func startEchoServer(t *testing.T, network, addr string) (net.Listener, *atomic. _, _ = io.Copy(conn, conn) }(c) } - }() + }) t.Cleanup(func() { _ = ln.Close() wg.Wait() @@ -855,7 +853,7 @@ func TestRawTCPAtomicBlobSpillConcurrent(t *testing.T) { const workers = 8 var wg sync.WaitGroup hashes := make([]string, workers) - for i := 0; i < workers; i++ { + for i := range workers { wg.Add(1) go func(idx int) { defer wg.Done() diff --git a/traffic/stream_direction_test.go b/traffic/stream_direction_test.go index cfbfe1ad..7c508149 100644 --- a/traffic/stream_direction_test.go +++ b/traffic/stream_direction_test.go @@ -13,7 +13,7 @@ import ( func directionStream(t *testing.T, pairs int) (*Traffic, string) { t.Helper() tr, s, f := unitStream(t, "direction.test") - for i := 0; i < pairs; i++ { + for i := range pairs { addWS(f, true, websocket.TextMessage, []byte("q"+string(rune('0'+i)))) addWS(f, false, websocket.TextMessage, []byte("a"+string(rune('0'+i)))) } @@ -74,7 +74,7 @@ func TestStreamMessagesByDirectionRejectsUnknown(t *testing.T) { // A filtered page keeps the meta row, so dropped messages are never hidden. func TestStreamMessagesByDirectionKeepsMetaRow(t *testing.T) { tr, s, f := unitStream(t, "direction-meta.test") - for i := 0; i < maxStreamMessages+4; i++ { + for i := range maxStreamMessages + 4 { addWS(f, i%2 == 0, websocket.TextMessage, []byte("m")) } s.WebSocketMessage(f) diff --git a/traffic/stream_test.go b/traffic/stream_test.go index 96e62634..9cf9e301 100644 --- a/traffic/stream_test.go +++ b/traffic/stream_test.go @@ -345,7 +345,7 @@ func TestStreamPayloadTruncatedToLimit(t *testing.T) { func TestStreamMessageLimitStoresOneMetaRow(t *testing.T) { tr, s, f := unitStream(t, "count.test") - for i := 0; i < maxStreamMessages+5; i++ { + for i := range maxStreamMessages + 5 { addWS(f, i%2 == 0, websocket.TextMessage, []byte("m")) } s.WebSocketMessage(f) @@ -382,7 +382,7 @@ func TestStreamByteLimitStoresOneMetaRow(t *testing.T) { } kept := int(maxStreamBytes / cost) n := kept + 1 - for i := 0; i < n; i++ { + for range n { addWS(f, false, websocket.BinaryMessage, chunk) } s.WebSocketMessage(f) @@ -532,7 +532,7 @@ func TestWebSocketSurvivesRecordingFailure(t *testing.T) { if err := tr.DB().Close(); err != nil { t.Fatal(err) } - for i := 0; i < 3; i++ { + for i := range 3 { msg := fmt.Sprintf("after-%d", i) if err := c.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil { t.Fatalf("write %s: %v", msg, err) @@ -557,7 +557,7 @@ func TestWebSocketConcurrentDirections(t *testing.T) { } defer c.Close() go func() { - for i := 0; i < n; i++ { + for i := range n { if c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("s-%d", i))) != nil { return } @@ -576,17 +576,15 @@ func TestWebSocketConcurrentDirections(t *testing.T) { t.Fatal(err) } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < n; i++ { + wg.Go(func() { + for i := range n { if err := c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("c-%d", i))); err != nil { t.Errorf("write: %v", err) return } } - }() - for i := 0; i < n; i++ { + }) + for i := range n { if _, _, err := c.ReadMessage(); err != nil { t.Fatalf("read %d: %v", i, err) } diff --git a/traffic/traffic.go b/traffic/traffic.go index 23ffebdc..e43024fb 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -1983,8 +1983,7 @@ func writeHostDeleteStageJournal(path string, journal hostDeleteStageJournal) er // first, and drops the staging directory once everything is home. func restoreTrees(stageDir string, moves []stagedTrafficPath) error { var errs []error - for i := len(moves) - 1; i >= 0; i-- { - move := moves[i] + for _, move := range slices.Backward(moves) { if _, err := os.Lstat(move.source); err == nil { errs = append(errs, fmt.Errorf("restore destination already exists: %s", move.source)) continue