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(`

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("