refactor(traffic,intercept): use modern Go idioms

Mechanical modernization of the traffic, intercept, guard and egress packages with the gopls/go fix modernizers:
range over int, strings.SplitSeq, strings.Cut / CutPrefix,
slices.Contains / Sort / Backward, maps.Copy, min / max,
sync.WaitGroup.Go and t.Context in tests. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sisantaChhatoiandClaude Opus 5.5 committed 2026-12-03 02:08:01 +05:30
1 parent 9ae08ed457
commit 4295e366b2
26 files changed
+62 -99

No files matched your search

+2 -4
View File
@@ -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 {
+1 -4
View File
@@ -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
}
+1 -2
View File
@@ -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()
}
+3 -4
View File
@@ -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
}
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
}
}
+7 -11
View File
@@ -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
}
+3 -4
View File
@@ -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
}
+2 -6
View File
@@ -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
+1 -1
View File
@@ -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
}
+2 -6
View File
@@ -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
+1 -1
View File
@@ -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")
}
+4 -6
View File
@@ -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"}) {
+4 -4
View File
@@ -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
}
+1 -1
View File
@@ -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",
+1 -1
View File
@@ -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)
+2 -8
View File
@@ -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(`
+1 -4
View File
@@ -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(`
+3 -3
View File
@@ -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))))
}
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
+5 -6
View File
@@ -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)
+3 -5
View File
@@ -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()
+2 -2
View File
@@ -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)
+8 -10
View File
@@ -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)
}
+1 -2
View File
@@ -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