package webread import ( "bytes" "compress/gzip" "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/binary" "errors" "fmt" "hash/crc32" "image" "image/color" "image/png" "math/big" "net" "net/http" "net/http/httptest" "net/netip" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/websource" ) // The rig serves every fake public address from two local test servers, // one TLS (port 443) and one plain (port 80). Lookups and dials are // injected: nothing here touches the real network. var ( certOnce sync.Once certPool *x509.CertPool certTLS tls.Certificate ) func testCert(t testing.TB) (*x509.CertPool, tls.Certificate) { certOnce.Do(func() { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "webread test"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), DNSNames: []string{"*.example.com", "*.example.net", "*.example.org"}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true, } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) if err != nil { panic(err) } c, _ := x509.ParseCertificate(der) certPool = x509.NewCertPool() certPool.AddCert(c) certTLS = tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} }) return certPool, certTLS } type seen struct { method, host, path string header http.Header } type rig struct { t *testing.T secure, open *httptest.Server mu sync.Mutex answers map[string][][]netip.Addr lookups map[string]int dialed []string requests []seen d deps } func newRig(t *testing.T, mux *http.ServeMux) *rig { t.Helper() r := &rig{t: t, answers: map[string][][]netip.Addr{}, lookups: map[string]int{}} record := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { r.mu.Lock() r.requests = append(r.requests, seen{req.Method, req.Host, req.URL.RequestURI(), req.Header.Clone()}) r.mu.Unlock() mux.ServeHTTP(w, req) }) pool, cert := testCert(t) r.secure = httptest.NewUnstartedServer(record) r.secure.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} r.secure.StartTLS() r.open = httptest.NewServer(record) t.Cleanup(func() { r.secure.Close(); r.open.Close() }) r.d = defaults() r.d.roots = pool r.d.lookup = func(_ context.Context, host string) ([]netip.Addr, error) { r.mu.Lock() defer r.mu.Unlock() all := r.answers[host] if len(all) == 0 { return nil, errors.New("no such host") } n := min(r.lookups[host], len(all)-1) r.lookups[host]++ return all[n], nil } r.d.dial = func(ctx context.Context, network, address string) (net.Conn, error) { r.mu.Lock() r.dialed = append(r.dialed, address) r.mu.Unlock() ap, err := netip.ParseAddrPort(address) if err != nil { return nil, err } target := r.open.Listener.Addr().String() if ap.Port() == 443 { target = r.secure.Listener.Addr().String() } return (&net.Dialer{}).DialContext(ctx, network, target) } return r } // host makes name answer with each list of addresses in turn, the last // one from then on. func (r *rig) host(name string, answers ...string) { var all [][]netip.Addr for _, a := range answers { var one []netip.Addr for _, s := range strings.Split(a, ",") { one = append(one, netip.MustParseAddr(s)) } all = append(all, one) } r.answers[name] = all } func (r *rig) dials() []string { r.mu.Lock() defer r.mu.Unlock() return append([]string(nil), r.dialed...) } func (r *rig) run(p Plan) (Manifest, string) { r.t.Helper() dir := r.t.TempDir() m, err := fetch(context.Background(), p, dir, r.d) if err != nil { r.t.Fatalf("fetch: %v", err) } return m, dir } // testInventory is a confirmed inventory with a public prefix in each // family, apart from every address the tests dial, so both families' // egress is known. var testInventory = []netip.Prefix{netip.MustParsePrefix("81.2.69.0/24"), netip.MustParsePrefix("2a01:4f8:ffff::/48")} func plan(t testing.TB, urls ...string) Plan { p := Plan{Inventory: append([]netip.Prefix(nil), testInventory...)} for i, u := range urls { p.Sources = append(p.Sources, Source{ID: fmt.Sprintf("s%d", i+1), URL: mustURL(t, u), Origin: OriginPaul}) } return p } func entry(t *testing.T, m Manifest, id string) Entry { t.Helper() for _, e := range m.Log { if e.Source == id { return e } } t.Fatalf("no log entry %s in %+v", id, m.Log) return Entry{} } func pngOf(t testing.TB, w, h int) []byte { img := image.NewRGBA(image.Rect(0, 0, w, h)) for i := range img.Pix { img.Pix[i] = byte(i) } img.Set(0, 0, color.RGBA{255, 0, 0, 255}) var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } // pngHeader claims w x h in a valid IHDR, with no pixel data behind it. func pngHeader(w, h uint32) []byte { b := []byte("\x89PNG\r\n\x1a\n") data := make([]byte, 13) binary.BigEndian.PutUint32(data[0:], w) binary.BigEndian.PutUint32(data[4:], h) data[8], data[9] = 8, 6 chunk := append([]byte("IHDR"), data...) b = binary.BigEndian.AppendUint32(b, 13) b = append(b, chunk...) b = binary.BigEndian.AppendUint32(b, crc32.ChecksumIEEE(chunk)) return append(b, make([]byte, 64)...) } func gz(t testing.TB, b []byte) []byte { var out bytes.Buffer w := gzip.NewWriter(&out) w.Write(b) w.Close() return out.Bytes() } const public1, public2 = "151.101.1.1", "151.101.2.2" func TestFetchPageAndExpansion(t *testing.T) { mux := http.NewServeMux() logo := pngOf(t, 2100, 10) mux.HandleFunc("/{$}", func(w http.ResponseWriter, _ *http.Request) { http.SetCookie(w, &http.Cookie{Name: "session", Value: "abc"}) w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Encoding", "gzip") w.Write(gz(t, []byte(`Shop Shop logo

Cuts and shaves.

AboutMissingx`))) }) mux.HandleFunc("/a.css", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/css") w.Write([]byte("body { color: #123456 }")) }) mux.HandleFunc("/favicon.png", func(w http.ResponseWriter, _ *http.Request) { w.Write(pngOf(t, 16, 16)) }) mux.HandleFunc("/img/logo.png", func(w http.ResponseWriter, _ *http.Request) { w.Write(logo) }) mux.HandleFunc("/about", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("

About us

")) }) r := newRig(t, mux) r.host("shop.example.com", public1) m, dir := r.run(plan(t, "https://shop.example.com/")) root := entry(t, m, "s1") if root.Reason != "" || root.Status != 200 || root.Type != "text/html" || root.File == "" || root.Address != public1 || root.Origin != OriginPaul { t.Fatalf("root %+v", root) } want := map[string]string{"s1.1": "text/css", "s1.2": "image/png", "s1.3": "image/png", "s1.4": "text/html"} for id, typ := range want { e := entry(t, m, id) if e.Origin != OriginExpanded || e.Parent != "s1" || e.Type != typ || e.Reason != "" || e.SHA256 == "" { t.Errorf("%s: %+v", id, e) } } if e := entry(t, m, "s1.5"); e.Reason != ReasonStatus || e.Status != 404 { t.Errorf("missing page: %+v", e) } for _, e := range m.Log { if strings.Contains(e.URL, "other.example.org") { t.Errorf("another host's link was fetched: %+v", e) } } b, err := ReadBundle(dir) if err != nil { t.Fatal(err) } var text string var scaled *BundleFile for i, f := range b.Files { if f.Source == "s1" { text = string(f.Data) } if f.Source == "s1.3" { scaled = &b.Files[i] } } if !strings.Contains(text, "Title: Shop") || !strings.Contains(text, "theme-color: #123456") || !strings.Contains(text, "Cuts and shaves.") || !strings.Contains(text, "https://shop.example.com/about") { t.Errorf("page text:\n%s", text) } if scaled == nil || scaled.Kind != KindImage || scaled.Width != MaxEdge || scaled.Height != 9 || !bytes.HasPrefix(scaled.Data, []byte("\x89PNG")) { t.Errorf("logo %+v", scaled) } for _, s := range r.requests { h := s.header if s.method != http.MethodGet || h.Get("User-Agent") != UserAgent || h.Get("Accept-Encoding") != "gzip" || h.Get("Accept") == "" { t.Errorf("request %+v", s) } for _, k := range []string{"Cookie", "Referer", "Authorization"} { if h.Get(k) != "" { t.Errorf("%s sent on %s", k, s.path) } } if s.host != "shop.example.com" { t.Errorf("Host %q", s.host) } } } func TestRebindingSecondConnectionRefused(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/{$}", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`

hi

`)) }) mux.HandleFunc("/a.css", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("body{}")) }) r := newRig(t, mux) // First answer public, second private: the second connection must not happen. r.host("shop.example.com", public1, "10.0.0.7") m, _ := r.run(plan(t, "https://shop.example.com/")) if e := entry(t, m, "s1"); e.Reason != "" { t.Fatalf("first fetch %+v", e) } if e := entry(t, m, "s1.1"); e.Reason != ReasonNotPublic || e.Address != "" { t.Fatalf("rebound fetch %+v", e) } if d := r.dials(); len(d) != 1 || d[0] != public1+":443" { t.Fatalf("dialed %v", d) } } func TestRedirectTargetsRefused(t *testing.T) { cases := []struct{ location, reason string }{ {"https://loop.example.net/", ReasonNotPublic}, {"https://ten.example.net/", ReasonNotPublic}, {"https://cgnat.example.net/", ReasonNotPublic}, {"https://metadata.example.net/latest/meta-data/", ReasonNotPublic}, {"https://mapped.example.net/", ReasonNotPublic}, {"https://mixed.example.net/", ReasonNotPublic}, {"https://site.example.net/", ReasonInventory}, {"https://127.0.0.1/", "ip_literal"}, {"http://10.0.0.1/", "ip_literal"}, {"https://169.254.169.254/", "ip_literal"}, {"https://[::ffff:10.0.0.1]/", "ip_literal"}, {"http://2130706433/", "ip_literal"}, {"https://box.tailnet-example.ts.net/", "host_refused"}, {"https://shop.example.com:8080/", "port_refused"}, {"https://shop.example.com:80/", "port_refused"}, {"http://shop.example.com/plain", ReasonDowngrade}, {"https://equipo.example.com/", ReasonHostRefused}, {"https://forge.example.com/", ReasonHostRefused}, {"ftp://shop.example.com/", "scheme_refused"}, {"", ReasonBadRedirect}, } mux := http.NewServeMux() for i, c := range cases { mux.HandleFunc(fmt.Sprintf("/r%d", i), func(w http.ResponseWriter, _ *http.Request) { if c.location != "" { w.Header().Set("Location", c.location) } w.WriteHeader(http.StatusFound) }) } r := newRig(t, mux) r.host("shop.example.com", public1) r.host("loop.example.net", "127.0.0.1") r.host("ten.example.net", "10.20.30.40") r.host("cgnat.example.net", "100.64.0.1") r.host("metadata.example.net", "169.254.169.254") r.host("mapped.example.net", "::ffff:10.0.0.1") r.host("mixed.example.net", public2+",127.0.0.1") r.host("site.example.net", "151.101.9.9") r.host("equipo.example.com", public2) r.host("forge.example.com", public2) var p Plan for i := range cases { p.Sources = append(p.Sources, Source{ID: fmt.Sprintf("s%d", i), URL: mustURL(t, fmt.Sprintf("https://shop.example.com/r%d", i)), Origin: OriginPaul}) } p.Inventory = []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")} p.Instance, p.Forge = "equipo.example.com", "forge.example.com" m, _ := r.run(p) for i, c := range cases { e := entry(t, m, fmt.Sprintf("s%d", i)) if e.Reason != c.reason || e.File != "" { t.Errorf("redirect to %q: reason %q, want %q (%+v)", c.location, e.Reason, c.reason, e) } wantHops := 2 // the redirect, then its refused target if c.reason == ReasonBadRedirect { wantHops = 1 } if len(e.Hops) != wantHops || e.Hops[0].Status != http.StatusFound || e.Hops[wantHops-1].Address != "" && wantHops == 2 { t.Errorf("redirect to %q: hops %+v", c.location, e.Hops) } } for _, d := range r.dials() { if d != public1+":443" { t.Errorf("dialed %s", d) } } } func TestSourcesRefusedBeforeConnecting(t *testing.T) { r := newRig(t, http.NewServeMux()) r.host("site.example.net", "151.101.9.9") r.host("equipo.example.com", public2) p := plan(t, "https://site.example.net/", "https://equipo.example.com/") p.Inventory = []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")} p.Instance = "equipo.example.com" m, _ := r.run(p) if e := entry(t, m, "s1"); e.Reason != ReasonInventory { t.Errorf("inventory source %+v", e) } if e := entry(t, m, "s2"); e.Reason != ReasonHostRefused { t.Errorf("instance source %+v", e) } if d := r.dials(); len(d) != 0 { t.Errorf("dialed %v", d) } } func TestPlanRefusesHandBuiltSources(t *testing.T) { ok := mustURL(t, "https://shop.example.com/") for name, u := range map[string]websource.URL{ "decimal ip": {Scheme: "https", Host: "2130706433", Port: 443, EscapedPath: "/"}, "dotted ip": {Scheme: "https", Host: "127.0.0.1", Port: 443, EscapedPath: "/"}, "ts.net": {Scheme: "https", Host: "box.tailnet-example.ts.net", Port: 443, EscapedPath: "/"}, "port 8080": {Scheme: "https", Host: "shop.example.com", Port: 8080, EscapedPath: "/"}, "https on 80": {Scheme: "https", Host: "shop.example.com", Port: 80, EscapedPath: "/"}, "upper case": {Scheme: "https", Host: "Shop.example.com", Port: 443, EscapedPath: "/"}, "no path": {Scheme: "https", Host: "shop.example.com", Port: 443}, "bad path": {Scheme: "https", Host: "shop.example.com", Port: 443, EscapedPath: "/a b"}, } { p := Plan{Sources: []Source{{ID: "s1", URL: u, Origin: OriginPaul}}} if err := p.Validate(); !errors.Is(err, ErrPlan) { t.Errorf("%s: %v", name, err) } } for name, p := range map[string]Plan{ "no sources": {}, "duplicate id": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginPaul}, {ID: "a", URL: ok, Origin: OriginPaul}}}, "dotted id": {Sources: []Source{{ID: "a.1", URL: ok, Origin: OriginPaul}}}, "origin": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginExpanded}}}, "proposed query": {Sources: []Source{{ID: "a", URL: mustURL(t, "https://shop.example.com/?q=1"), Origin: OriginProposed}}}, "inventory": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginPaul}}, Inventory: []netip.Prefix{netip.PrefixFrom(netip.MustParseAddr("10.1.2.3"), 8)}}, } { if err := p.Validate(); !errors.Is(err, ErrPlan) { t.Errorf("%s: %v", name, err) } } dir := t.TempDir() if _, err := fetch(context.Background(), Plan{}, dir, defaults()); !errors.Is(err, ErrPlan) { t.Fatalf("fetch of an empty plan: %v", err) } if names, _ := os.ReadDir(dir); len(names) != 0 { t.Fatalf("refused plan wrote %v", names) } } func TestSizeAndTypeRefusals(t *testing.T) { mux := http.NewServeMux() serve := func(path, ctype, encoding string, body []byte) { mux.HandleFunc(path, func(w http.ResponseWriter, _ *http.Request) { if ctype != "" { w.Header().Set("Content-Type", ctype) } if encoding != "" { w.Header().Set("Content-Encoding", encoding) } w.Write(body) }) } serve("/text-bomb", "text/plain", "gzip", gz(t, bytes.Repeat([]byte("a"), MaxTextBytes+1))) // Sniffed as an image, so only the decompressed-size cap stops it. serve("/bomb", "image/png", "gzip", gz(t, append(pngHeader(10, 10), make([]byte, MaxImageBytes)...))) serve("/pixels", "image/png", "", pngHeader(20000, 20000)) serve("/elf", "image/png", "", append([]byte("\x7fELF\x02\x01\x01"), make([]byte, 64)...)) serve("/webp", "image/webp", "", append([]byte("RIFF\x24\x00\x00\x00WEBPVP8 "), make([]byte, 64)...)) serve("/pdf", "text/plain", "", []byte("%PDF-1.7\n")) serve("/brotli", "text/plain", "br", []byte("hello")) serve("/html-said-png", "image/png", "", []byte("t")) mux.HandleFunc("/declared", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Length", fmt.Sprint(MaxImageBytes+1)) w.WriteHeader(200) w.Write([]byte("short")) }) mux.HandleFunc("/headers", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("X-Big", strings.Repeat("h", MaxHeaderBytes)) w.Write([]byte("x")) }) r := newRig(t, mux) r.host("shop.example.com", public1) paths := []string{"/text-bomb", "/bomb", "/pixels", "/elf", "/webp", "/pdf", "/brotli", "/html-said-png", "/declared", "/headers"} want := []string{ReasonTooLarge, ReasonTooLarge, ReasonPixels, ReasonType, ReasonType, ReasonType, ReasonEncoding, "", ReasonTooLarge, ReasonTooLarge} var urls []string for _, p := range paths { urls = append(urls, "https://shop.example.com"+p) } m, _ := r.run(plan(t, urls...)) for i, p := range paths { e := entry(t, m, fmt.Sprintf("s%d", i+1)) if e.Reason != want[i] { t.Errorf("%s: reason %q, want %q (%+v)", p, e.Reason, want[i], e) } if want[i] != "" && e.File != "" { t.Errorf("%s: refused but kept %s", p, e.File) } } if e := entry(t, m, "s1"); e.Bytes > MaxTextBytes+1 { t.Errorf("text read on to %d bytes", e.Bytes) } if e := entry(t, m, "s5"); e.Type != "image/webp" { t.Errorf("webp type %q", e.Type) } if e := entry(t, m, "s8"); e.Type != "text/html" || e.File == "" { t.Errorf("html sent as png: %+v", e) } if e := entry(t, m, "s9"); e.Bytes != 0 { t.Errorf("declared length read %d bytes", e.Bytes) } } func TestTimeouts(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/slow-body", func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("hello")) w.(http.Flusher).Flush() select { case <-req.Context().Done(): case <-time.After(5 * time.Second): } }) mux.HandleFunc("/slow-head", func(w http.ResponseWriter, req *http.Request) { select { case <-req.Context().Done(): case <-time.After(5 * time.Second): } }) r := newRig(t, mux) r.host("shop.example.com", public1) r.d.request, r.d.firstByte = 300*time.Millisecond, 200*time.Millisecond start := time.Now() m, _ := r.run(plan(t, "https://shop.example.com/slow-body", "https://shop.example.com/slow-head")) for _, id := range []string{"s1", "s2"} { if e := entry(t, m, id); e.Reason != ReasonTimeout { t.Errorf("%s: %+v", id, e) } } if time.Since(start) > 3*time.Second { t.Errorf("took %v", time.Since(start)) } // The whole phase has its own deadline: every source left is refused. r.d.overall = 100 * time.Millisecond m, _ = r.run(plan(t, "https://shop.example.com/slow-head", "https://shop.example.com/slow-head")) for _, id := range []string{"s1", "s2"} { if e := entry(t, m, id); e.Reason != ReasonTimeout { t.Errorf("overall %s: %+v", id, e) } } } func TestRedirectLimitAndBudget(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/chain/{n}", func(w http.ResponseWriter, req *http.Request) { var n int fmt.Sscan(req.PathValue("n"), &n) http.Redirect(w, req, fmt.Sprintf("/chain/%d", n+1), http.StatusMovedPermanently) }) mux.HandleFunc("/hop/{n}", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/ok/"+req.PathValue("n"), http.StatusFound) }) mux.HandleFunc("/ok/{n}", func(w http.ResponseWriter, _ *http.Request) { w.Write(bytes.Repeat([]byte("x"), 600)) }) r := newRig(t, mux) r.host("shop.example.com", public1) m, _ := r.run(plan(t, "https://shop.example.com/chain/0")) if e := entry(t, m, "s1"); e.Reason != ReasonRedirects || len(e.Hops) != MaxRedirects+1 { t.Fatalf("chain %+v", e) } // Each source costs two requests: fifteen fit in thirty. var urls []string for i := range MaxSources { urls = append(urls, fmt.Sprintf("https://shop.example.com/hop/%d", i)) } r.dialed = nil m, _ = r.run(plan(t, urls...)) for i := range MaxSources { e := entry(t, m, fmt.Sprintf("s%d", i+1)) if (i < MaxRequests/2) != (e.Reason == "") || (i >= MaxRequests/2 && e.Reason != ReasonBudget) { t.Errorf("source %d: %+v", i+1, e) } } if n := len(r.dials()); n != MaxRequests { t.Errorf("%d connections, want %d", n, MaxRequests) } // Bytes: one 600-byte page fits a 1,000-byte budget, the next does not. r.d.maxBytes = 1000 m, _ = r.run(plan(t, "https://shop.example.com/ok/1", "https://shop.example.com/ok/2", "https://shop.example.com/ok/3")) if e := entry(t, m, "s1"); e.Reason != "" || e.Bytes != 600 { t.Errorf("first %+v", e) } for _, id := range []string{"s2", "s3"} { if e := entry(t, m, id); e.Reason != ReasonBudget { t.Errorf("%s %+v", id, e) } } } func TestTextBudget(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/t/{n}", func(w http.ResponseWriter, _ *http.Request) { w.Write(bytes.Repeat([]byte("word "), MaxPageText)) }) r := newRig(t, mux) r.host("shop.example.com", public1) m, dir := r.run(plan(t, "https://shop.example.com/t/1", "https://shop.example.com/t/2", "https://shop.example.com/t/3", "https://shop.example.com/t/4")) for _, id := range []string{"s1", "s2", "s3"} { if e := entry(t, m, id); e.Reason != "" || e.File == "" { t.Errorf("%s %+v", id, e) } } if e := entry(t, m, "s4"); e.Reason != ReasonTextBudget || e.File != "" { t.Errorf("s4 %+v", e) } b, err := ReadBundle(dir) if err != nil { t.Fatal(err) } total := 0 for _, f := range b.Files { if len(f.Data) > MaxPageText { t.Errorf("%s: %d bytes", f.Name, len(f.Data)) } total += len(f.Data) } if total > MaxTotalText { t.Errorf("text total %d", total) } } // The production dialer re-checks the socket address itself, whatever // the lookup said. func TestDialerControlRechecks(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer ln.Close() accepted := make(chan struct{}, 1) go func() { if c, err := ln.Accept(); err == nil { accepted <- struct{}{} c.Close() } }() f := newFetcher(Plan{Inventory: []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24"), netip.MustParsePrefix("2a01:4f8:1:2::/64")}}, defaults()) c, err := f.dialer().DialContext(context.Background(), "tcp", ln.Addr().String()) if err == nil { c.Close() t.Fatal("dialled a loopback address") } if refusalOf(err) != ReasonNotPublic { t.Fatalf("loopback dial: %v", err) } select { case <-accepted: t.Fatal("the listener accepted a connection") case <-time.After(50 * time.Millisecond): } for addr, want := range map[string]string{ public1 + ":443": "", public1 + ":80": "", "[2606:4700::1]:443": "", "151.101.9.9:443": ReasonInventory, "10.0.0.1:443": ReasonNotPublic, "[::ffff:10.0.0.1]:443": ReasonNotPublic, "[::1]:443": ReasonNotPublic, public1 + ":22": "port_refused", "nonsense": ReasonNotPublic, } { if got := refusalOf(f.control("tcp", addr, nil)); got != want { t.Errorf("control(%s) = %q, want %q", addr, got, want) } } } func TestFetchNeedsAnEmptyDirectory(t *testing.T) { dir := t.TempDir() os.WriteFile(filepath.Join(dir, "x"), nil, 0600) if _, err := fetch(context.Background(), plan(t, "https://shop.example.com/"), dir, defaults()); err == nil { t.Fatal("fetched into a used directory") } } // A retry pass carries what earlier passes of the same step spent: the // requests, the bytes and the time come out of one budget, and the // manifest says what the step has used in all. func TestSpentCarriesOverToARetryPass(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/ok/{n}", func(w http.ResponseWriter, _ *http.Request) { w.Write(bytes.Repeat([]byte("x"), 600)) }) r := newRig(t, mux) r.host("shop.example.com", public1) p := plan(t, "https://shop.example.com/ok/1", "https://shop.example.com/ok/2", "https://shop.example.com/ok/3") p.Spent = &Spent{Requests: MaxRequests - 2, Bytes: 100, Millis: 1000} m, _ := r.run(p) for id, want := range map[string]string{"s1": "", "s2": "", "s3": ReasonBudget} { if e := entry(t, m, id); e.Reason != want { t.Errorf("%s: %+v", id, e) } } if m.Used.Requests != MaxRequests || m.Used.Bytes != 100+1200 || m.Used.Millis < 1000 { t.Fatalf("used %+v", m.Used) } // Bytes spent before count against this pass. r.d.maxBytes = 1000 p = plan(t, "https://shop.example.com/ok/1") p.Spent = &Spent{Bytes: 500} if m, _ = r.run(p); entry(t, m, "s1").Reason != ReasonBudget { t.Fatalf("bytes carried: %+v", m.Log) } // So does the time: a phase with nothing left fetches nothing. r.d.maxBytes = MaxBytes p.Spent = &Spent{Millis: OverallTimeout.Milliseconds()} if m, _ = r.run(p); entry(t, m, "s1").Reason != ReasonTimeout { t.Fatalf("time carried: %+v", m.Log) } // Out of bounds is refused. for _, s := range []Spent{{Requests: -1}, {Requests: MaxRequests + 1}, {Bytes: -1}, {Bytes: MaxBytes + 1}, {Millis: -1}, {Millis: OverallTimeout.Milliseconds() + 1}} { p.Spent = &s if err := p.Validate(); err == nil { t.Errorf("spent %+v accepted", s) } } } // TestFamilyUnknownRefused (Astra security finding 2): an address whose // family has no public prefix in the confirmed inventory is refused // before any connection, family_unknown: the site's egress in that // family is unknown. A tailnet or other non-public prefix does not make // a family known. func TestFamilyUnknownRefused(t *testing.T) { r := newRig(t, func() *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("hello")) }) return mux }()) r.host("four.example.net", public1) r.host("six.example.net", "2606:4700::1") for name, c := range map[string]struct { inventory []string four, six string wantDialed int }{ "IPv4 known only": {[]string{"151.101.9.0/24"}, "", ReasonFamilyUnknown, 1}, "IPv6 known only": {[]string{"2a01:4f8:1:2::/64"}, ReasonFamilyUnknown, "", 1}, "both known": {[]string{"151.101.9.0/24", "2a01:4f8:1:2::/64"}, "", "", 2}, "a tailnet prefix": {[]string{"100.64.0.0/10", "2a01:4f8:1:2::/64"}, ReasonFamilyUnknown, "", 1}, "a ULA prefix only": {[]string{"151.101.9.0/24", "fd7a:115c:a1e0::/48"}, "", ReasonFamilyUnknown, 1}, } { r.mu.Lock() r.dialed = nil r.mu.Unlock() p := plan(t, "https://four.example.net/", "https://six.example.net/") p.Inventory = nil for _, s := range c.inventory { p.Inventory = append(p.Inventory, netip.MustParsePrefix(s)) } m, _ := r.run(p) if e := entry(t, m, "s1"); e.Reason != c.four { t.Errorf("%s: IPv4 site %+v", name, e) } if e := entry(t, m, "s2"); e.Reason != c.six { t.Errorf("%s: IPv6 site %+v", name, e) } if d := r.dials(); len(d) != c.wantDialed { t.Errorf("%s: dialed %v", name, d) } } // The dial's Control hook applies the same rule. f := newFetcher(Plan{Inventory: []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")}}, defaults()) if got := refusalOf(f.control("tcp", "[2606:4700::1]:443", nil)); got != ReasonFamilyUnknown { t.Errorf("control on an unknown family: %q", got) } }