oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package webread
2
3import (
4 "bytes"
5 "compress/gzip"
6 "context"
7 "crypto/ecdsa"
8 "crypto/elliptic"
9 "crypto/rand"
10 "crypto/tls"
11 "crypto/x509"
12 "crypto/x509/pkix"
13 "encoding/binary"
14 "errors"
15 "fmt"
16 "hash/crc32"
17 "image"
18 "image/color"
19 "image/png"
20 "math/big"
21 "net"
22 "net/http"
23 "net/http/httptest"
24 "net/netip"
25 "os"
26 "path/filepath"
27 "strings"
28 "sync"
29 "testing"
30 "time"
31
32 "amadan.net/oficina/equipo/internal/websource"
33)
34
35// The rig serves every fake public address from two local test servers,
36// one TLS (port 443) and one plain (port 80). Lookups and dials are
37// injected: nothing here touches the real network.
38
39var (
40 certOnce sync.Once
41 certPool *x509.CertPool
42 certTLS tls.Certificate
43)
44
45func testCert(t testing.TB) (*x509.CertPool, tls.Certificate) {
46 certOnce.Do(func() {
47 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
48 if err != nil {
49 panic(err)
50 }
51 tmpl := &x509.Certificate{
52 SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "webread test"},
53 NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
54 DNSNames: []string{"*.example.com", "*.example.net", "*.example.org"},
55 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
56 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
57 BasicConstraintsValid: true, IsCA: true,
58 }
59 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
60 if err != nil {
61 panic(err)
62 }
63 c, _ := x509.ParseCertificate(der)
64 certPool = x509.NewCertPool()
65 certPool.AddCert(c)
66 certTLS = tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
67 })
68 return certPool, certTLS
69}
70
71type seen struct {
72 method, host, path string
73 header http.Header
74}
75
76type rig struct {
77 t *testing.T
78 secure, open *httptest.Server
79 mu sync.Mutex
80 answers map[string][][]netip.Addr
81 lookups map[string]int
82 dialed []string
83 requests []seen
84 d deps
85}
86
87func newRig(t *testing.T, mux *http.ServeMux) *rig {
88 t.Helper()
89 r := &rig{t: t, answers: map[string][][]netip.Addr{}, lookups: map[string]int{}}
90 record := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
91 r.mu.Lock()
92 r.requests = append(r.requests, seen{req.Method, req.Host, req.URL.RequestURI(), req.Header.Clone()})
93 r.mu.Unlock()
94 mux.ServeHTTP(w, req)
95 })
96 pool, cert := testCert(t)
97 r.secure = httptest.NewUnstartedServer(record)
98 r.secure.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
99 r.secure.StartTLS()
100 r.open = httptest.NewServer(record)
101 t.Cleanup(func() { r.secure.Close(); r.open.Close() })
102 r.d = defaults()
103 r.d.roots = pool
104 r.d.lookup = func(_ context.Context, host string) ([]netip.Addr, error) {
105 r.mu.Lock()
106 defer r.mu.Unlock()
107 all := r.answers[host]
108 if len(all) == 0 {
109 return nil, errors.New("no such host")
110 }
111 n := min(r.lookups[host], len(all)-1)
112 r.lookups[host]++
113 return all[n], nil
114 }
115 r.d.dial = func(ctx context.Context, network, address string) (net.Conn, error) {
116 r.mu.Lock()
117 r.dialed = append(r.dialed, address)
118 r.mu.Unlock()
119 ap, err := netip.ParseAddrPort(address)
120 if err != nil {
121 return nil, err
122 }
123 target := r.open.Listener.Addr().String()
124 if ap.Port() == 443 {
125 target = r.secure.Listener.Addr().String()
126 }
127 return (&net.Dialer{}).DialContext(ctx, network, target)
128 }
129 return r
130}
131
132// host makes name answer with each list of addresses in turn, the last
133// one from then on.
134func (r *rig) host(name string, answers ...string) {
135 var all [][]netip.Addr
136 for _, a := range answers {
137 var one []netip.Addr
138 for _, s := range strings.Split(a, ",") {
139 one = append(one, netip.MustParseAddr(s))
140 }
141 all = append(all, one)
142 }
143 r.answers[name] = all
144}
145
146func (r *rig) dials() []string {
147 r.mu.Lock()
148 defer r.mu.Unlock()
149 return append([]string(nil), r.dialed...)
150}
151
152func (r *rig) run(p Plan) (Manifest, string) {
153 r.t.Helper()
154 dir := r.t.TempDir()
155 m, err := fetch(context.Background(), p, dir, r.d)
156 if err != nil {
157 r.t.Fatalf("fetch: %v", err)
158 }
159 return m, dir
160}
161
162// testInventory is a confirmed inventory with a public prefix in each
163// family, apart from every address the tests dial, so both families'
164// egress is known.
165var testInventory = []netip.Prefix{netip.MustParsePrefix("81.2.69.0/24"), netip.MustParsePrefix("2a01:4f8:ffff::/48")}
166
167func plan(t testing.TB, urls ...string) Plan {
168 p := Plan{Inventory: append([]netip.Prefix(nil), testInventory...)}
169 for i, u := range urls {
170 p.Sources = append(p.Sources, Source{ID: fmt.Sprintf("s%d", i+1), URL: mustURL(t, u), Origin: OriginPaul})
171 }
172 return p
173}
174
175func entry(t *testing.T, m Manifest, id string) Entry {
176 t.Helper()
177 for _, e := range m.Log {
178 if e.Source == id {
179 return e
180 }
181 }
182 t.Fatalf("no log entry %s in %+v", id, m.Log)
183 return Entry{}
184}
185
186func pngOf(t testing.TB, w, h int) []byte {
187 img := image.NewRGBA(image.Rect(0, 0, w, h))
188 for i := range img.Pix {
189 img.Pix[i] = byte(i)
190 }
191 img.Set(0, 0, color.RGBA{255, 0, 0, 255})
192 var b bytes.Buffer
193 if err := png.Encode(&b, img); err != nil {
194 t.Fatal(err)
195 }
196 return b.Bytes()
197}
198
199// pngHeader claims w x h in a valid IHDR, with no pixel data behind it.
200func pngHeader(w, h uint32) []byte {
201 b := []byte("\x89PNG\r\n\x1a\n")
202 data := make([]byte, 13)
203 binary.BigEndian.PutUint32(data[0:], w)
204 binary.BigEndian.PutUint32(data[4:], h)
205 data[8], data[9] = 8, 6
206 chunk := append([]byte("IHDR"), data...)
207 b = binary.BigEndian.AppendUint32(b, 13)
208 b = append(b, chunk...)
209 b = binary.BigEndian.AppendUint32(b, crc32.ChecksumIEEE(chunk))
210 return append(b, make([]byte, 64)...)
211}
212
213func gz(t testing.TB, b []byte) []byte {
214 var out bytes.Buffer
215 w := gzip.NewWriter(&out)
216 w.Write(b)
217 w.Close()
218 return out.Bytes()
219}
220
221const public1, public2 = "151.101.1.1", "151.101.2.2"
222
223func TestFetchPageAndExpansion(t *testing.T) {
224 mux := http.NewServeMux()
225 logo := pngOf(t, 2100, 10)
226 mux.HandleFunc("/{$}", func(w http.ResponseWriter, _ *http.Request) {
227 http.SetCookie(w, &http.Cookie{Name: "session", Value: "abc"})
228 w.Header().Set("Content-Type", "text/html")
229 w.Header().Set("Content-Encoding", "gzip")
230 w.Write(gz(t, []byte(`<html><head><title>Shop</title><meta name="theme-color" content="#123456">
231<link rel="stylesheet" href="/a.css"><link rel="icon" href="/favicon.png"></head>
232<body><img src="/img/logo.png" alt="Shop logo"><p>Cuts and shaves.</p>
233<a href="/about">About</a><a href="/missing">Missing</a><a href="https://other.example.org/">x</a></body></html>`)))
234 })
235 mux.HandleFunc("/a.css", func(w http.ResponseWriter, _ *http.Request) {
236 w.Header().Set("Content-Type", "text/css")
237 w.Write([]byte("body { color: #123456 }"))
238 })
239 mux.HandleFunc("/favicon.png", func(w http.ResponseWriter, _ *http.Request) { w.Write(pngOf(t, 16, 16)) })
240 mux.HandleFunc("/img/logo.png", func(w http.ResponseWriter, _ *http.Request) { w.Write(logo) })
241 mux.HandleFunc("/about", func(w http.ResponseWriter, _ *http.Request) {
242 w.Write([]byte("<html><body><p>About us</p></body></html>"))
243 })
244 r := newRig(t, mux)
245 r.host("shop.example.com", public1)
246 m, dir := r.run(plan(t, "https://shop.example.com/"))
247
248 root := entry(t, m, "s1")
249 if root.Reason != "" || root.Status != 200 || root.Type != "text/html" || root.File == "" || root.Address != public1 || root.Origin != OriginPaul {
250 t.Fatalf("root %+v", root)
251 }
252 want := map[string]string{"s1.1": "text/css", "s1.2": "image/png", "s1.3": "image/png", "s1.4": "text/html"}
253 for id, typ := range want {
254 e := entry(t, m, id)
255 if e.Origin != OriginExpanded || e.Parent != "s1" || e.Type != typ || e.Reason != "" || e.SHA256 == "" {
256 t.Errorf("%s: %+v", id, e)
257 }
258 }
259 if e := entry(t, m, "s1.5"); e.Reason != ReasonStatus || e.Status != 404 {
260 t.Errorf("missing page: %+v", e)
261 }
262 for _, e := range m.Log {
263 if strings.Contains(e.URL, "other.example.org") {
264 t.Errorf("another host's link was fetched: %+v", e)
265 }
266 }
267 b, err := ReadBundle(dir)
268 if err != nil {
269 t.Fatal(err)
270 }
271 var text string
272 var scaled *BundleFile
273 for i, f := range b.Files {
274 if f.Source == "s1" {
275 text = string(f.Data)
276 }
277 if f.Source == "s1.3" {
278 scaled = &b.Files[i]
279 }
280 }
281 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") {
282 t.Errorf("page text:\n%s", text)
283 }
284 if scaled == nil || scaled.Kind != KindImage || scaled.Width != MaxEdge || scaled.Height != 9 || !bytes.HasPrefix(scaled.Data, []byte("\x89PNG")) {
285 t.Errorf("logo %+v", scaled)
286 }
287 for _, s := range r.requests {
288 h := s.header
289 if s.method != http.MethodGet || h.Get("User-Agent") != UserAgent || h.Get("Accept-Encoding") != "gzip" || h.Get("Accept") == "" {
290 t.Errorf("request %+v", s)
291 }
292 for _, k := range []string{"Cookie", "Referer", "Authorization"} {
293 if h.Get(k) != "" {
294 t.Errorf("%s sent on %s", k, s.path)
295 }
296 }
297 if s.host != "shop.example.com" {
298 t.Errorf("Host %q", s.host)
299 }
300 }
301}
302
303func TestRebindingSecondConnectionRefused(t *testing.T) {
304 mux := http.NewServeMux()
305 mux.HandleFunc("/{$}", func(w http.ResponseWriter, _ *http.Request) {
306 w.Write([]byte(`<html><link rel="stylesheet" href="/a.css"><p>hi</p></html>`))
307 })
308 mux.HandleFunc("/a.css", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("body{}")) })
309 r := newRig(t, mux)
310 // First answer public, second private: the second connection must not happen.
311 r.host("shop.example.com", public1, "10.0.0.7")
312 m, _ := r.run(plan(t, "https://shop.example.com/"))
313 if e := entry(t, m, "s1"); e.Reason != "" {
314 t.Fatalf("first fetch %+v", e)
315 }
316 if e := entry(t, m, "s1.1"); e.Reason != ReasonNotPublic || e.Address != "" {
317 t.Fatalf("rebound fetch %+v", e)
318 }
319 if d := r.dials(); len(d) != 1 || d[0] != public1+":443" {
320 t.Fatalf("dialed %v", d)
321 }
322}
323
324func TestRedirectTargetsRefused(t *testing.T) {
325 cases := []struct{ location, reason string }{
326 {"https://loop.example.net/", ReasonNotPublic},
327 {"https://ten.example.net/", ReasonNotPublic},
328 {"https://cgnat.example.net/", ReasonNotPublic},
329 {"https://metadata.example.net/latest/meta-data/", ReasonNotPublic},
330 {"https://mapped.example.net/", ReasonNotPublic},
331 {"https://mixed.example.net/", ReasonNotPublic},
332 {"https://site.example.net/", ReasonInventory},
333 {"https://127.0.0.1/", "ip_literal"},
334 {"http://10.0.0.1/", "ip_literal"},
335 {"https://169.254.169.254/", "ip_literal"},
336 {"https://[::ffff:10.0.0.1]/", "ip_literal"},
337 {"http://2130706433/", "ip_literal"},
338 {"https://box.tailnet-example.ts.net/", "host_refused"},
339 {"https://shop.example.com:8080/", "port_refused"},
340 {"https://shop.example.com:80/", "port_refused"},
341 {"http://shop.example.com/plain", ReasonDowngrade},
342 {"https://equipo.example.com/", ReasonHostRefused},
343 {"https://forge.example.com/", ReasonHostRefused},
344 {"ftp://shop.example.com/", "scheme_refused"},
345 {"", ReasonBadRedirect},
346 }
347 mux := http.NewServeMux()
348 for i, c := range cases {
349 mux.HandleFunc(fmt.Sprintf("/r%d", i), func(w http.ResponseWriter, _ *http.Request) {
350 if c.location != "" {
351 w.Header().Set("Location", c.location)
352 }
353 w.WriteHeader(http.StatusFound)
354 })
355 }
356 r := newRig(t, mux)
357 r.host("shop.example.com", public1)
358 r.host("loop.example.net", "127.0.0.1")
359 r.host("ten.example.net", "10.20.30.40")
360 r.host("cgnat.example.net", "100.64.0.1")
361 r.host("metadata.example.net", "169.254.169.254")
362 r.host("mapped.example.net", "::ffff:10.0.0.1")
363 r.host("mixed.example.net", public2+",127.0.0.1")
364 r.host("site.example.net", "151.101.9.9")
365 r.host("equipo.example.com", public2)
366 r.host("forge.example.com", public2)
367 var p Plan
368 for i := range cases {
369 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})
370 }
371 p.Inventory = []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")}
372 p.Instance, p.Forge = "equipo.example.com", "forge.example.com"
373 m, _ := r.run(p)
374 for i, c := range cases {
375 e := entry(t, m, fmt.Sprintf("s%d", i))
376 if e.Reason != c.reason || e.File != "" {
377 t.Errorf("redirect to %q: reason %q, want %q (%+v)", c.location, e.Reason, c.reason, e)
378 }
379 wantHops := 2 // the redirect, then its refused target
380 if c.reason == ReasonBadRedirect {
381 wantHops = 1
382 }
383 if len(e.Hops) != wantHops || e.Hops[0].Status != http.StatusFound || e.Hops[wantHops-1].Address != "" && wantHops == 2 {
384 t.Errorf("redirect to %q: hops %+v", c.location, e.Hops)
385 }
386 }
387 for _, d := range r.dials() {
388 if d != public1+":443" {
389 t.Errorf("dialed %s", d)
390 }
391 }
392}
393
394func TestSourcesRefusedBeforeConnecting(t *testing.T) {
395 r := newRig(t, http.NewServeMux())
396 r.host("site.example.net", "151.101.9.9")
397 r.host("equipo.example.com", public2)
398 p := plan(t, "https://site.example.net/", "https://equipo.example.com/")
399 p.Inventory = []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")}
400 p.Instance = "equipo.example.com"
401 m, _ := r.run(p)
402 if e := entry(t, m, "s1"); e.Reason != ReasonInventory {
403 t.Errorf("inventory source %+v", e)
404 }
405 if e := entry(t, m, "s2"); e.Reason != ReasonHostRefused {
406 t.Errorf("instance source %+v", e)
407 }
408 if d := r.dials(); len(d) != 0 {
409 t.Errorf("dialed %v", d)
410 }
411}
412
413func TestPlanRefusesHandBuiltSources(t *testing.T) {
414 ok := mustURL(t, "https://shop.example.com/")
415 for name, u := range map[string]websource.URL{
416 "decimal ip": {Scheme: "https", Host: "2130706433", Port: 443, EscapedPath: "/"},
417 "dotted ip": {Scheme: "https", Host: "127.0.0.1", Port: 443, EscapedPath: "/"},
418 "ts.net": {Scheme: "https", Host: "box.tailnet-example.ts.net", Port: 443, EscapedPath: "/"},
419 "port 8080": {Scheme: "https", Host: "shop.example.com", Port: 8080, EscapedPath: "/"},
420 "https on 80": {Scheme: "https", Host: "shop.example.com", Port: 80, EscapedPath: "/"},
421 "upper case": {Scheme: "https", Host: "Shop.example.com", Port: 443, EscapedPath: "/"},
422 "no path": {Scheme: "https", Host: "shop.example.com", Port: 443},
423 "bad path": {Scheme: "https", Host: "shop.example.com", Port: 443, EscapedPath: "/a b"},
424 } {
425 p := Plan{Sources: []Source{{ID: "s1", URL: u, Origin: OriginPaul}}}
426 if err := p.Validate(); !errors.Is(err, ErrPlan) {
427 t.Errorf("%s: %v", name, err)
428 }
429 }
430 for name, p := range map[string]Plan{
431 "no sources": {},
432 "duplicate id": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginPaul}, {ID: "a", URL: ok, Origin: OriginPaul}}},
433 "dotted id": {Sources: []Source{{ID: "a.1", URL: ok, Origin: OriginPaul}}},
434 "origin": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginExpanded}}},
435 "proposed query": {Sources: []Source{{ID: "a", URL: mustURL(t, "https://shop.example.com/?q=1"), Origin: OriginProposed}}},
436 "inventory": {Sources: []Source{{ID: "a", URL: ok, Origin: OriginPaul}}, Inventory: []netip.Prefix{netip.PrefixFrom(netip.MustParseAddr("10.1.2.3"), 8)}},
437 } {
438 if err := p.Validate(); !errors.Is(err, ErrPlan) {
439 t.Errorf("%s: %v", name, err)
440 }
441 }
442 dir := t.TempDir()
443 if _, err := fetch(context.Background(), Plan{}, dir, defaults()); !errors.Is(err, ErrPlan) {
444 t.Fatalf("fetch of an empty plan: %v", err)
445 }
446 if names, _ := os.ReadDir(dir); len(names) != 0 {
447 t.Fatalf("refused plan wrote %v", names)
448 }
449}
450
451func TestSizeAndTypeRefusals(t *testing.T) {
452 mux := http.NewServeMux()
453 serve := func(path, ctype, encoding string, body []byte) {
454 mux.HandleFunc(path, func(w http.ResponseWriter, _ *http.Request) {
455 if ctype != "" {
456 w.Header().Set("Content-Type", ctype)
457 }
458 if encoding != "" {
459 w.Header().Set("Content-Encoding", encoding)
460 }
461 w.Write(body)
462 })
463 }
464 serve("/text-bomb", "text/plain", "gzip", gz(t, bytes.Repeat([]byte("a"), MaxTextBytes+1)))
465 // Sniffed as an image, so only the decompressed-size cap stops it.
466 serve("/bomb", "image/png", "gzip", gz(t, append(pngHeader(10, 10), make([]byte, MaxImageBytes)...)))
467 serve("/pixels", "image/png", "", pngHeader(20000, 20000))
468 serve("/elf", "image/png", "", append([]byte("\x7fELF\x02\x01\x01"), make([]byte, 64)...))
469 serve("/webp", "image/webp", "", append([]byte("RIFF\x24\x00\x00\x00WEBPVP8 "), make([]byte, 64)...))
470 serve("/pdf", "text/plain", "", []byte("%PDF-1.7\n"))
471 serve("/brotli", "text/plain", "br", []byte("hello"))
472 serve("/html-said-png", "image/png", "", []byte("<!doctype html><title>t</title>"))
473 mux.HandleFunc("/declared", func(w http.ResponseWriter, _ *http.Request) {
474 w.Header().Set("Content-Length", fmt.Sprint(MaxImageBytes+1))
475 w.WriteHeader(200)
476 w.Write([]byte("short"))
477 })
478 mux.HandleFunc("/headers", func(w http.ResponseWriter, _ *http.Request) {
479 w.Header().Set("X-Big", strings.Repeat("h", MaxHeaderBytes))
480 w.Write([]byte("x"))
481 })
482 r := newRig(t, mux)
483 r.host("shop.example.com", public1)
484 paths := []string{"/text-bomb", "/bomb", "/pixels", "/elf", "/webp", "/pdf", "/brotli", "/html-said-png", "/declared", "/headers"}
485 want := []string{ReasonTooLarge, ReasonTooLarge, ReasonPixels, ReasonType, ReasonType, ReasonType, ReasonEncoding, "", ReasonTooLarge, ReasonTooLarge}
486 var urls []string
487 for _, p := range paths {
488 urls = append(urls, "https://shop.example.com"+p)
489 }
490 m, _ := r.run(plan(t, urls...))
491 for i, p := range paths {
492 e := entry(t, m, fmt.Sprintf("s%d", i+1))
493 if e.Reason != want[i] {
494 t.Errorf("%s: reason %q, want %q (%+v)", p, e.Reason, want[i], e)
495 }
496 if want[i] != "" && e.File != "" {
497 t.Errorf("%s: refused but kept %s", p, e.File)
498 }
499 }
500 if e := entry(t, m, "s1"); e.Bytes > MaxTextBytes+1 {
501 t.Errorf("text read on to %d bytes", e.Bytes)
502 }
503 if e := entry(t, m, "s5"); e.Type != "image/webp" {
504 t.Errorf("webp type %q", e.Type)
505 }
506 if e := entry(t, m, "s8"); e.Type != "text/html" || e.File == "" {
507 t.Errorf("html sent as png: %+v", e)
508 }
509 if e := entry(t, m, "s9"); e.Bytes != 0 {
510 t.Errorf("declared length read %d bytes", e.Bytes)
511 }
512}
513
514func TestTimeouts(t *testing.T) {
515 mux := http.NewServeMux()
516 mux.HandleFunc("/slow-body", func(w http.ResponseWriter, req *http.Request) {
517 w.Write([]byte("hello"))
518 w.(http.Flusher).Flush()
519 select {
520 case <-req.Context().Done():
521 case <-time.After(5 * time.Second):
522 }
523 })
524 mux.HandleFunc("/slow-head", func(w http.ResponseWriter, req *http.Request) {
525 select {
526 case <-req.Context().Done():
527 case <-time.After(5 * time.Second):
528 }
529 })
530 r := newRig(t, mux)
531 r.host("shop.example.com", public1)
532 r.d.request, r.d.firstByte = 300*time.Millisecond, 200*time.Millisecond
533 start := time.Now()
534 m, _ := r.run(plan(t, "https://shop.example.com/slow-body", "https://shop.example.com/slow-head"))
535 for _, id := range []string{"s1", "s2"} {
536 if e := entry(t, m, id); e.Reason != ReasonTimeout {
537 t.Errorf("%s: %+v", id, e)
538 }
539 }
540 if time.Since(start) > 3*time.Second {
541 t.Errorf("took %v", time.Since(start))
542 }
543 // The whole phase has its own deadline: every source left is refused.
544 r.d.overall = 100 * time.Millisecond
545 m, _ = r.run(plan(t, "https://shop.example.com/slow-head", "https://shop.example.com/slow-head"))
546 for _, id := range []string{"s1", "s2"} {
547 if e := entry(t, m, id); e.Reason != ReasonTimeout {
548 t.Errorf("overall %s: %+v", id, e)
549 }
550 }
551}
552
553func TestRedirectLimitAndBudget(t *testing.T) {
554 mux := http.NewServeMux()
555 mux.HandleFunc("/chain/{n}", func(w http.ResponseWriter, req *http.Request) {
556 var n int
557 fmt.Sscan(req.PathValue("n"), &n)
558 http.Redirect(w, req, fmt.Sprintf("/chain/%d", n+1), http.StatusMovedPermanently)
559 })
560 mux.HandleFunc("/hop/{n}", func(w http.ResponseWriter, req *http.Request) {
561 http.Redirect(w, req, "/ok/"+req.PathValue("n"), http.StatusFound)
562 })
563 mux.HandleFunc("/ok/{n}", func(w http.ResponseWriter, _ *http.Request) { w.Write(bytes.Repeat([]byte("x"), 600)) })
564 r := newRig(t, mux)
565 r.host("shop.example.com", public1)
566
567 m, _ := r.run(plan(t, "https://shop.example.com/chain/0"))
568 if e := entry(t, m, "s1"); e.Reason != ReasonRedirects || len(e.Hops) != MaxRedirects+1 {
569 t.Fatalf("chain %+v", e)
570 }
571
572 // Each source costs two requests: fifteen fit in thirty.
573 var urls []string
574 for i := range MaxSources {
575 urls = append(urls, fmt.Sprintf("https://shop.example.com/hop/%d", i))
576 }
577 r.dialed = nil
578 m, _ = r.run(plan(t, urls...))
579 for i := range MaxSources {
580 e := entry(t, m, fmt.Sprintf("s%d", i+1))
581 if (i < MaxRequests/2) != (e.Reason == "") || (i >= MaxRequests/2 && e.Reason != ReasonBudget) {
582 t.Errorf("source %d: %+v", i+1, e)
583 }
584 }
585 if n := len(r.dials()); n != MaxRequests {
586 t.Errorf("%d connections, want %d", n, MaxRequests)
587 }
588
589 // Bytes: one 600-byte page fits a 1,000-byte budget, the next does not.
590 r.d.maxBytes = 1000
591 m, _ = r.run(plan(t, "https://shop.example.com/ok/1", "https://shop.example.com/ok/2", "https://shop.example.com/ok/3"))
592 if e := entry(t, m, "s1"); e.Reason != "" || e.Bytes != 600 {
593 t.Errorf("first %+v", e)
594 }
595 for _, id := range []string{"s2", "s3"} {
596 if e := entry(t, m, id); e.Reason != ReasonBudget {
597 t.Errorf("%s %+v", id, e)
598 }
599 }
600}
601
602func TestTextBudget(t *testing.T) {
603 mux := http.NewServeMux()
604 mux.HandleFunc("/t/{n}", func(w http.ResponseWriter, _ *http.Request) {
605 w.Write(bytes.Repeat([]byte("word "), MaxPageText))
606 })
607 r := newRig(t, mux)
608 r.host("shop.example.com", public1)
609 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"))
610 for _, id := range []string{"s1", "s2", "s3"} {
611 if e := entry(t, m, id); e.Reason != "" || e.File == "" {
612 t.Errorf("%s %+v", id, e)
613 }
614 }
615 if e := entry(t, m, "s4"); e.Reason != ReasonTextBudget || e.File != "" {
616 t.Errorf("s4 %+v", e)
617 }
618 b, err := ReadBundle(dir)
619 if err != nil {
620 t.Fatal(err)
621 }
622 total := 0
623 for _, f := range b.Files {
624 if len(f.Data) > MaxPageText {
625 t.Errorf("%s: %d bytes", f.Name, len(f.Data))
626 }
627 total += len(f.Data)
628 }
629 if total > MaxTotalText {
630 t.Errorf("text total %d", total)
631 }
632}
633
634// The production dialer re-checks the socket address itself, whatever
635// the lookup said.
636func TestDialerControlRechecks(t *testing.T) {
637 ln, err := net.Listen("tcp", "127.0.0.1:0")
638 if err != nil {
639 t.Fatal(err)
640 }
641 defer ln.Close()
642 accepted := make(chan struct{}, 1)
643 go func() {
644 if c, err := ln.Accept(); err == nil {
645 accepted <- struct{}{}
646 c.Close()
647 }
648 }()
649 f := newFetcher(Plan{Inventory: []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24"), netip.MustParsePrefix("2a01:4f8:1:2::/64")}}, defaults())
650 c, err := f.dialer().DialContext(context.Background(), "tcp", ln.Addr().String())
651 if err == nil {
652 c.Close()
653 t.Fatal("dialled a loopback address")
654 }
655 if refusalOf(err) != ReasonNotPublic {
656 t.Fatalf("loopback dial: %v", err)
657 }
658 select {
659 case <-accepted:
660 t.Fatal("the listener accepted a connection")
661 case <-time.After(50 * time.Millisecond):
662 }
663 for addr, want := range map[string]string{
664 public1 + ":443": "", public1 + ":80": "", "[2606:4700::1]:443": "",
665 "151.101.9.9:443": ReasonInventory, "10.0.0.1:443": ReasonNotPublic, "[::ffff:10.0.0.1]:443": ReasonNotPublic,
666 "[::1]:443": ReasonNotPublic, public1 + ":22": "port_refused", "nonsense": ReasonNotPublic,
667 } {
668 if got := refusalOf(f.control("tcp", addr, nil)); got != want {
669 t.Errorf("control(%s) = %q, want %q", addr, got, want)
670 }
671 }
672}
673
674func TestFetchNeedsAnEmptyDirectory(t *testing.T) {
675 dir := t.TempDir()
676 os.WriteFile(filepath.Join(dir, "x"), nil, 0600)
677 if _, err := fetch(context.Background(), plan(t, "https://shop.example.com/"), dir, defaults()); err == nil {
678 t.Fatal("fetched into a used directory")
679 }
680}
681
682// A retry pass carries what earlier passes of the same step spent: the
683// requests, the bytes and the time come out of one budget, and the
684// manifest says what the step has used in all.
685func TestSpentCarriesOverToARetryPass(t *testing.T) {
686 mux := http.NewServeMux()
687 mux.HandleFunc("/ok/{n}", func(w http.ResponseWriter, _ *http.Request) { w.Write(bytes.Repeat([]byte("x"), 600)) })
688 r := newRig(t, mux)
689 r.host("shop.example.com", public1)
690 p := plan(t, "https://shop.example.com/ok/1", "https://shop.example.com/ok/2", "https://shop.example.com/ok/3")
691 p.Spent = &Spent{Requests: MaxRequests - 2, Bytes: 100, Millis: 1000}
692 m, _ := r.run(p)
693 for id, want := range map[string]string{"s1": "", "s2": "", "s3": ReasonBudget} {
694 if e := entry(t, m, id); e.Reason != want {
695 t.Errorf("%s: %+v", id, e)
696 }
697 }
698 if m.Used.Requests != MaxRequests || m.Used.Bytes != 100+1200 || m.Used.Millis < 1000 {
699 t.Fatalf("used %+v", m.Used)
700 }
701 // Bytes spent before count against this pass.
702 r.d.maxBytes = 1000
703 p = plan(t, "https://shop.example.com/ok/1")
704 p.Spent = &Spent{Bytes: 500}
705 if m, _ = r.run(p); entry(t, m, "s1").Reason != ReasonBudget {
706 t.Fatalf("bytes carried: %+v", m.Log)
707 }
708 // So does the time: a phase with nothing left fetches nothing.
709 r.d.maxBytes = MaxBytes
710 p.Spent = &Spent{Millis: OverallTimeout.Milliseconds()}
711 if m, _ = r.run(p); entry(t, m, "s1").Reason != ReasonTimeout {
712 t.Fatalf("time carried: %+v", m.Log)
713 }
714 // Out of bounds is refused.
715 for _, s := range []Spent{{Requests: -1}, {Requests: MaxRequests + 1}, {Bytes: -1}, {Bytes: MaxBytes + 1}, {Millis: -1}, {Millis: OverallTimeout.Milliseconds() + 1}} {
716 p.Spent = &s
717 if err := p.Validate(); err == nil {
718 t.Errorf("spent %+v accepted", s)
719 }
720 }
721}
722
723// TestFamilyUnknownRefused (Astra security finding 2): an address whose
724// family has no public prefix in the confirmed inventory is refused
725// before any connection, family_unknown: the site's egress in that
726// family is unknown. A tailnet or other non-public prefix does not make
727// a family known.
728func TestFamilyUnknownRefused(t *testing.T) {
729 r := newRig(t, func() *http.ServeMux {
730 mux := http.NewServeMux()
731 mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("hello")) })
732 return mux
733 }())
734 r.host("four.example.net", public1)
735 r.host("six.example.net", "2606:4700::1")
736 for name, c := range map[string]struct {
737 inventory []string
738 four, six string
739 wantDialed int
740 }{
741 "IPv4 known only": {[]string{"151.101.9.0/24"}, "", ReasonFamilyUnknown, 1},
742 "IPv6 known only": {[]string{"2a01:4f8:1:2::/64"}, ReasonFamilyUnknown, "", 1},
743 "both known": {[]string{"151.101.9.0/24", "2a01:4f8:1:2::/64"}, "", "", 2},
744 "a tailnet prefix": {[]string{"100.64.0.0/10", "2a01:4f8:1:2::/64"}, ReasonFamilyUnknown, "", 1},
745 "a ULA prefix only": {[]string{"151.101.9.0/24", "fd7a:115c:a1e0::/48"}, "", ReasonFamilyUnknown, 1},
746 } {
747 r.mu.Lock()
748 r.dialed = nil
749 r.mu.Unlock()
750 p := plan(t, "https://four.example.net/", "https://six.example.net/")
751 p.Inventory = nil
752 for _, s := range c.inventory {
753 p.Inventory = append(p.Inventory, netip.MustParsePrefix(s))
754 }
755 m, _ := r.run(p)
756 if e := entry(t, m, "s1"); e.Reason != c.four {
757 t.Errorf("%s: IPv4 site %+v", name, e)
758 }
759 if e := entry(t, m, "s2"); e.Reason != c.six {
760 t.Errorf("%s: IPv6 site %+v", name, e)
761 }
762 if d := r.dials(); len(d) != c.wantDialed {
763 t.Errorf("%s: dialed %v", name, d)
764 }
765 }
766 // The dial's Control hook applies the same rule.
767 f := newFetcher(Plan{Inventory: []netip.Prefix{netip.MustParsePrefix("151.101.9.0/24")}}, defaults())
768 if got := refusalOf(f.control("tcp", "[2606:4700::1]:443", nil)); got != ReasonFamilyUnknown {
769 t.Errorf("control on an unknown family: %q", got)
770 }
771}
772