package hub_test import ( "bytes" "encoding/json" "io" "net/http" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) // A probe that starts with a backlog sends resolv.conf in the same batch as // the egress lines (or right before them). The hub must apply the files first: // DNS to a resolver listed in that resolv.conf is not "dns_bypass". A probe // that never sent resolv.conf is the control: the same line is a finding. // Regression: the 2.0.0 cutover opened two false dns_bypass incidents. func TestEgressFilesAppliedBeforeLines(t *testing.T) { dir := t.TempDir() hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)} hp.start() defer func() { hp.stop() }() base := "http://" + hp.addr push := func(name, token string, b wire.Batch) { t.Helper() post := func(path string, v any) { t.Helper() body, _ := json.Marshal(v) req, _ := http.NewRequest("POST", base+path, bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) req.Header.Set(wire.HeaderProbe, name) req.Header.Set("Content-Type", "application/json") res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } out, _ := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode != 200 { t.Fatalf("%s %s: %d %s", name, path, res.StatusCode, out) } } post(wire.PathHello, wire.Hello{Proto: wire.Proto, Name: name, Version: "test", Sources: []string{wire.SrcEgress}}) post(wire.PathPush, b) } line := func(host string) wire.Line { ts := time.Now().UTC().Format("2006-01-02T15:04:05+00:00") txt := ts + " " + host + " kernel: URUTAU-EGRESS: IN= OUT=eth0 SRC=192.0.2.10 DST=153.92.2.6 PROTO=UDP SPT=40000 DPT=53\n" return wire.Line{Src: wire.SrcEgress, Text: txt, End: wire.Pos{Inode: 7, Offset: int64(len(txt))}} } tokens := map[string]string{} for _, n := range []string{"withresolv", "noresolv"} { code, b := hp.send("POST", "/api/v1/probes", map[string]string{"name": n}) var o struct{ Token string } if code != 201 || json.Unmarshal(b, &o) != nil { t.Fatalf("create %s: %d %s", n, code, b) } tokens[n] = o.Token } resolv := wire.File{Name: wire.FileResolv, Data: "nameserver 1.1.1.1\nnameserver 153.92.2.6\n"} // the file comes AFTER the line inside the batch, as the probe may queue them push("withresolv", tokens["withresolv"], wire.Batch{Seq: 1, Sent: time.Now().UnixMilli(), Lines: []wire.Line{line("withresolv")}, Files: []wire.File{resolv}}) push("noresolv", tokens["noresolv"], wire.Batch{Seq: 1, Sent: time.Now().UnixMilli(), Lines: []wire.Line{line("noresolv")}}) bypass := func(host string) bool { _, b := hp.send("GET", "/api/v1/egress?range=1h&host="+host, nil) return strings.Contains(string(b), `"dns_bypass"`) } waitFor(t, "control probe reports dns_bypass", 15*time.Second, func() bool { return bypass("noresolv") }) if bypass("withresolv") { t.Fatal("DNS to a resolver listed in the probe's resolv.conf was reported as dns_bypass") } }