oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package guard
2
3import (
4 "bytes"
5 "compress/gzip"
6 "context"
7 "crypto/x509"
8 "errors"
9 "fmt"
10 "io"
11 "log/slog"
12 "net/http"
13 "net/http/httptest"
14 "net/netip"
15 "os"
16 "strings"
17 "sync"
18 "sync/atomic"
19 "testing"
20
21 "amadan.net/rastrillo/rastrillo/budget"
22)
23
24func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
25
26// inventory is a confirmed (or not) instance network.
27type inventory struct {
28 ready bool
29 inside []netip.Prefix
30}
31
32func (i inventory) Ready(context.Context) error {
33 if !i.ready {
34 return ErrInventoryUnconfirmed
35 }
36 return nil
37}
38
39func (i inventory) Inside(a netip.Addr) bool {
40 for _, p := range i.inside {
41 if p.Contains(a) {
42 return true
43 }
44 }
45 return false
46}
47
48// web is one TLS test server answering every *.example.com host by its
49// handler, with the resolver's answers per host and what each host got.
50type web struct {
51 srv *httptest.Server
52 mu sync.Mutex
53 answers map[string][]netip.Addr
54 got map[string][]*http.Request
55 handle map[string]http.HandlerFunc
56 logs bytes.Buffer
57}
58
59func newWeb(t *testing.T) *web {
60 t.Helper()
61 w := &web{answers: map[string][]netip.Addr{}, got: map[string][]*http.Request{}, handle: map[string]http.HandlerFunc{}}
62 w.srv = httptest.NewTLSServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
63 host := strings.Split(r.Host, ":")[0]
64 w.mu.Lock()
65 w.got[host] = append(w.got[host], r.Clone(context.Background()))
66 h := w.handle[host]
67 w.mu.Unlock()
68 if h == nil {
69 _, _ = io.WriteString(rw, "<html><body>hello</body></html>")
70 return
71 }
72 h(rw, r)
73 }))
74 t.Cleanup(w.srv.Close)
75 return w
76}
77
78func (w *web) on(host string, h http.HandlerFunc, addrs ...string) {
79 w.mu.Lock()
80 defer w.mu.Unlock()
81 w.handle[host] = h
82 if len(addrs) == 0 {
83 addrs = []string{"93.184.216.34"}
84 }
85 w.answers[host] = nil
86 for _, a := range addrs {
87 w.answers[host] = append(w.answers[host], netip.MustParseAddr(a))
88 }
89}
90
91func (w *web) requests(host string) []*http.Request {
92 w.mu.Lock()
93 defer w.mu.Unlock()
94 return w.got[host]
95}
96
97func (w *web) config(p Policy) Config {
98 roots := x509.NewCertPool()
99 roots.AddCert(w.srv.Certificate())
100 return Config{
101 Policy: p,
102 Deny: []string{"equipo.example.com"},
103 Inventory: inventory{ready: true, inside: []netip.Prefix{netip.MustParsePrefix("81.2.69.0/24")}},
104 Resolve: func(_ context.Context, host string) ([]netip.Addr, error) {
105 w.mu.Lock()
106 defer w.mu.Unlock()
107 if a, ok := w.answers[host]; ok {
108 return a, nil
109 }
110 return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
111 },
112 Logger: slog.New(slog.NewTextHandler(&w.logs, nil)),
113 TestDial: func(string) (string, *x509.CertPool) { return w.srv.Listener.Addr().String(), roots },
114 Redirects: MaxRedirects,
115 }
116}
117
118func get(t *testing.T, c *Client, ctx context.Context, raw string) (*Response, error) {
119 t.Helper()
120 req, err := http.NewRequest(http.MethodGet, raw, nil)
121 if err != nil {
122 t.Fatal(err)
123 }
124 return c.Do(ctx, req)
125}
126
127func mustNew(t *testing.T, cfg Config) *Client {
128 t.Helper()
129 c, err := New(cfg)
130 if err != nil {
131 t.Fatal(err)
132 }
133 return c
134}
135
136func redirect(to string) http.HandlerFunc {
137 return func(rw http.ResponseWriter, r *http.Request) { http.Redirect(rw, r, to, http.StatusFound) }
138}
139
140// Spec §10.1's list: every IP literal form, a private answer among public
141// ones, metadata, a redirect to a private address, https down to http, a
142// sixth redirect, .ts.net, the instance's own host, and the inventory.
143func TestFetchSSRF(t *testing.T) {
144 w := newWeb(t)
145 w.on("mixed.example.com", nil, "93.184.216.34", "10.1.2.3")
146 w.on("meta.example.com", nil, "169.254.169.254")
147 w.on("inside.example.com", nil, "81.2.69.7")
148 w.on("private.example.com", nil, "192.168.1.1")
149 w.on("hop.example.com", redirect("https://private.example.com/x"))
150 w.on("down.example.com", redirect("http://plain.example.com/x"))
151 for i := 0; i < 6; i++ {
152 w.on(fmt.Sprintf("r%d.example.com", i), redirect(fmt.Sprintf("https://r%d.example.com/", i+1)))
153 }
154 c := mustNew(t, w.config(PolicyLookupPage))
155 for raw, rule := range map[string]string{
156 "https://127.0.0.1/": RuleIPLiteral,
157 "https://[::1]/": RuleIPLiteral,
158 "https://0x7f.1/": RuleIPLiteral,
159 "https://2130706433/": RuleIPLiteral,
160 "https://localhost/": RuleHost,
161 "https://box.tail1.ts.net/": RuleHost,
162 "https://svc.internal/": RuleHost,
163 "https://equipo.example.com/": RuleDenied,
164 "https://x.equipo.example.com/": RuleDenied,
165 "https://mixed.example.com/": RulePrivate,
166 "https://meta.example.com/": RulePrivate,
167 "https://inside.example.com/": RuleInventory,
168 "https://hop.example.com/": RulePrivate,
169 "https://down.example.com/": RuleDowngrade,
170 "https://r0.example.com/": RuleTooManyRedirect,
171 "https://a.example.com:8443/": RulePort,
172 "ftp://a.example.com/": RuleScheme,
173 } {
174 if _, err := get(t, c, context.Background(), raw); RuleOf(err) != rule {
175 t.Errorf("%s: %v, want %s", raw, err, rule)
176 }
177 }
178 for _, h := range []string{"mixed.example.com", "meta.example.com", "inside.example.com", "private.example.com", "plain.example.com", "r6.example.com"} {
179 if n := len(w.requests(h)); n != 0 {
180 t.Errorf("%s got %d requests", h, n)
181 }
182 }
183 unready := w.config(PolicyLookupPage)
184 unready.Inventory = inventory{}
185 if _, err := get(t, mustNew(t, unready), context.Background(), "https://a.example.com/"); RuleOf(err) != RuleUnconfirmed {
186 t.Errorf("unconfirmed inventory: %v", err)
187 }
188 long := "https://a.example.com/" + strings.Repeat("a", MaxURL)
189 if _, err := get(t, c, context.Background(), long); RuleOf(err) != RuleURL {
190 t.Errorf("a URL over 2 KiB: %v", err)
191 }
192}
193
194// Sizes, decompression and types.
195func TestFetchBounds(t *testing.T) {
196 w := newWeb(t)
197 w.on("big.example.com", func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write(bytes.Repeat([]byte("a"), MaxBody+1)) })
198 w.on("bomb.example.com", func(rw http.ResponseWriter, _ *http.Request) {
199 var b bytes.Buffer
200 gz := gzip.NewWriter(&b)
201 _, _ = gz.Write(bytes.Repeat([]byte("a"), MaxBody+10))
202 _ = gz.Close()
203 rw.Header().Set("Content-Encoding", "gzip")
204 _, _ = rw.Write(b.Bytes())
205 })
206 w.on("headers.example.com", func(rw http.ResponseWriter, _ *http.Request) {
207 rw.Header().Set("X-Big", strings.Repeat("h", MaxHeaderBytes+1))
208 })
209 for host, body := range map[string]string{"json.example.com": `{"a":1}`, "feed.example.com": `<?xml version="1.0"?><rss><channel></channel></rss>`, "pdf.example.com": "%PDF-1.7 \x00\x01\x02", "text.example.com": "plain words"} {
210 body := body
211 w.on(host, func(rw http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(rw, body) })
212 }
213 c := mustNew(t, w.config(PolicyLookupPage))
214 for raw, rule := range map[string]string{"https://big.example.com/": RuleTooLarge, "https://bomb.example.com/": RuleTooLarge, "https://headers.example.com/": RuleUnavailable} {
215 if _, err := get(t, c, context.Background(), raw); RuleOf(err) != rule {
216 t.Errorf("%s: %v, want %s", raw, err, rule)
217 }
218 }
219 for host, want := range map[string]string{"a.example.com": "html", "json.example.com": "json", "feed.example.com": "feed", "pdf.example.com": "unsupported", "text.example.com": "text"} {
220 res, err := get(t, c, context.Background(), "https://"+host+"/")
221 if err != nil || res.Type != want {
222 t.Errorf("%s: %v %+v, want %s", host, err, res, want)
223 }
224 }
225}
226
227// No cookie, Authorization, Referer or proxy: a cookie set by one hop
228// isn't sent on the next, and HTTPS_PROXY is ignored.
229func TestNoCredentialsSent(t *testing.T) {
230 t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1")
231 w := newWeb(t)
232 w.on("c1.example.com", func(rw http.ResponseWriter, r *http.Request) {
233 http.SetCookie(rw, &http.Cookie{Name: "s", Value: "v"})
234 http.Redirect(rw, r, "https://c2.example.com/", http.StatusFound)
235 })
236 c := mustNew(t, w.config(PolicyLookupPage))
237 if _, err := get(t, c, context.Background(), "https://c1.example.com/"); err != nil {
238 t.Fatal(err)
239 }
240 for _, h := range []string{"c1.example.com", "c2.example.com"} {
241 for _, r := range w.requests(h) {
242 if r.Header.Get("Cookie") != "" || r.Header.Get("Authorization") != "" || r.Header.Get("Referer") != "" || r.Header.Get("User-Agent") != "OficinaLookup/1" {
243 t.Errorf("%s got %v", h, r.Header)
244 }
245 }
246 }
247 if len(w.requests("c2.example.com")) != 1 {
248 t.Error("the redirect wasn't followed")
249 }
250}
251
252// Services and searches follow no redirect.
253func TestRedirectsZeroForServices(t *testing.T) {
254 w := newWeb(t)
255 w.on("svc.example.com", redirect("https://elsewhere.example.com/"))
256 for _, p := range []Policy{PolicyService, PolicySearch} {
257 cfg := w.config(p)
258 cfg.Redirects = 0
259 if _, err := get(t, mustNew(t, cfg), context.Background(), "https://svc.example.com/"); RuleOf(err) != RuleRedirect {
260 t.Errorf("policy %d: %v", p, err)
261 }
262 }
263 if n := len(w.requests("elsewhere.example.com")); n != 0 {
264 t.Errorf("the redirect's target got %d", n)
265 }
266 cfg := w.config(PolicyService)
267 if _, err := New(cfg); err == nil {
268 t.Error("a service client with redirects")
269 }
270}
271
272const sentinel = "KEY-SENTINEL-4242"
273
274// A search key goes only to its backend's origin, never with a
275// redirect, and never prints.
276func TestCredentialBoundToOrigin(t *testing.T) {
277 w := newWeb(t)
278 w.on("search.example.com", redirect("https://evil.example.com/"))
279 cfg := w.config(PolicySearch)
280 cfg.Redirects = 0
281 cfg.Credential = &Credential{Origin: "https://search.example.com", Header: "Authorization", Value: "Bearer " + sentinel}
282 c := mustNew(t, cfg)
283 if _, err := get(t, c, context.Background(), "https://search.example.com/api"); RuleOf(err) != RuleRedirect {
284 t.Fatalf("302 from the backend: %v", err)
285 }
286 if got := w.requests("search.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "Bearer "+sentinel {
287 t.Errorf("the backend didn't get its key")
288 }
289 if n := len(w.requests("evil.example.com")); n != 0 {
290 t.Error("the redirect's target got a request")
291 }
292 if _, err := get(t, c, context.Background(), "https://other.example.com/"); err != nil {
293 t.Fatal(err)
294 }
295 if got := w.requests("other.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "" {
296 t.Error("another origin got the key")
297 }
298 bad := cfg
299 bad.Redirects = 1
300 if _, err := New(bad); err == nil {
301 t.Error("a credential with redirects")
302 }
303}
304
305// WithDeny's hosts are refused on every hop.
306func TestWithDenyEachHop(t *testing.T) {
307 w := newWeb(t)
308 w.on("start.example.com", redirect("https://app.example.com/"))
309 c := mustNew(t, w.config(PolicyLookupPage))
310 ctx := WithDeny(context.Background(), []string{"app.example.com"})
311 if _, err := get(t, c, ctx, "https://start.example.com/"); RuleOf(err) != RuleDenied {
312 t.Errorf("denied by redirect: %v", err)
313 }
314 if n := len(w.requests("app.example.com")); n != 0 {
315 t.Error("the denied host got a request")
316 }
317}
318
319// BeforeHop runs once per hop with that hop's host; an error on hop 2
320// means hop 2 is never sent.
321func TestBeforeHopEveryHop(t *testing.T) {
322 w := newWeb(t)
323 w.on("h1.example.com", redirect("https://h2.example.com/"))
324 c := mustNew(t, w.config(PolicyLookupPage))
325 var hosts []string
326 ctx := WithBeforeHop(context.Background(), func(_ context.Context, host string) error {
327 hosts = append(hosts, host)
328 if host == "h2.example.com" {
329 return errors.New("refused at hop 2")
330 }
331 return nil
332 })
333 if _, err := get(t, c, ctx, "https://h1.example.com/"); err == nil || err.Error() != "refused at hop 2" {
334 t.Errorf("err %v", err)
335 }
336 if strings.Join(hosts, ",") != "h1.example.com,h2.example.com" || len(w.requests("h2.example.com")) != 0 {
337 t.Errorf("hops %v, h2 got %d", hosts, len(w.requests("h2.example.com")))
338 }
339}
340
341// A page read is GET with nothing of the caller's; a search carries no
342// Authorization of the caller's: anything else is refused before a dial.
343func TestLookupPoliciesRefusePostAndAuthorization(t *testing.T) {
344 w := newWeb(t)
345 page := mustNew(t, w.config(PolicyLookupPage))
346 scfg := w.config(PolicySearch)
347 scfg.Redirects = 0
348 search := mustNew(t, scfg)
349 post, _ := http.NewRequest(http.MethodPost, "https://a.example.com/", strings.NewReader("x"))
350 if _, err := page.Do(context.Background(), post); RuleOf(err) != RulePolicy {
351 t.Errorf("POST through a page read: %v", err)
352 }
353 for _, c := range []*Client{page, search} {
354 req, _ := http.NewRequest(http.MethodGet, "https://a.example.com/", nil)
355 req.Header.Set("Authorization", "Bearer x")
356 if _, err := c.Do(context.Background(), req); RuleOf(err) != RulePolicy {
357 t.Errorf("Authorization through policy %d: %v", c.cfg.Policy, err)
358 }
359 }
360 if n := len(w.requests("a.example.com")); n != 0 {
361 t.Errorf("%d requests sent", n)
362 }
363}
364
365// A service's authenticated POST goes through.
366func TestServicePolicyAllowsAuthenticatedPost(t *testing.T) {
367 w := newWeb(t)
368 cfg := w.config(PolicyService)
369 cfg.Redirects = 0
370 req, _ := http.NewRequest(http.MethodPost, "https://svc.example.com/mcp", strings.NewReader(`{"a":1}`))
371 req.Header.Set("Authorization", "Bearer svc")
372 req.Header.Set("Content-Type", "application/json")
373 if _, err := mustNew(t, cfg).Do(context.Background(), req); err != nil {
374 t.Fatal(err)
375 }
376 if got := w.requests("svc.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "Bearer svc" || got[0].Method != http.MethodPost {
377 t.Errorf("service request %v", got)
378 }
379}
380
381// A credential never prints, and New refuses one with both or neither of
382// Header and Param; no guard error carries the value, even in a query.
383func TestCredentialRedacted(t *testing.T) {
384 cr := Credential{Origin: "https://search.example.com", Param: "api_key", Value: sentinel}
385 cfg := Config{Policy: PolicySearch, Credential: &cr}
386 for _, s := range []string{fmt.Sprintf("%v", cr), fmt.Sprintf("%+v", cr), fmt.Sprintf("%#v", cr), fmt.Sprintf("%v", cfg), fmt.Sprintf("%+v", &cfg)} {
387 if strings.Contains(s, sentinel) {
388 t.Errorf("printed: %s", s)
389 }
390 }
391 for _, bad := range []Credential{{Origin: cr.Origin, Value: "x"}, {Origin: cr.Origin, Header: "X", Param: "y", Value: "x"}} {
392 if _, err := New(Config{Policy: PolicySearch, Credential: &bad}); err == nil {
393 t.Errorf("New took %v", bad)
394 }
395 }
396 w := newWeb(t)
397 w.on("search.example.com", func(rw http.ResponseWriter, _ *http.Request) { panic(http.ErrAbortHandler) })
398 scfg := w.config(PolicySearch)
399 scfg.Redirects, scfg.Credential = 0, &cr
400 _, err := get(t, mustNew(t, scfg), context.Background(), "https://search.example.com/search?q=x")
401 if err == nil || strings.Contains(err.Error(), sentinel) || strings.Contains(fmt.Sprintf("%+v", err), sentinel) || strings.Contains(w.logs.String(), sentinel) {
402 t.Errorf("an error carried the key: %v", err)
403 }
404}
405
406// An http address is tried once as https.
407func TestHTTPTypedTriedAsHTTPSOnce(t *testing.T) {
408 w := newWeb(t)
409 res, err := get(t, mustNew(t, w.config(PolicyLookupPage)), context.Background(), "http://typed.example.com/page")
410 if err != nil || res.FinalURL != "https://typed.example.com/page" {
411 t.Errorf("%v %+v", err, res)
412 }
413}
414
415// In a test binary nothing is dialled without TestDial.
416func TestGuardNeverDialsInTests(t *testing.T) {
417 cfg := Config{Policy: PolicyLookupPage, Inventory: inventory{ready: true}, Redirects: MaxRedirects}
418 if _, err := get(t, mustNew(t, cfg), context.Background(), "https://a.example.com/"); RuleOf(err) != RuleUnavailable {
419 t.Errorf("%v", err)
420 }
421}
422
423// A refusal is logged by rule and registrable domain, never the path or
424// query.
425func TestRefusalLogsRuleAndDomainOnly(t *testing.T) {
426 w := newWeb(t)
427 w.on("deep.private.example.com", nil, "10.0.0.9")
428 if _, err := get(t, mustNew(t, w.config(PolicyLookupPage)), context.Background(), "https://deep.private.example.com/my/salary?q=secret"); RuleOf(err) != RulePrivate {
429 t.Fatal(err)
430 }
431 logs := w.logs.String()
432 if !strings.Contains(logs, "rule=private_address") || !strings.Contains(logs, "domain=example.com") || strings.Contains(logs, "salary") || strings.Contains(logs, "secret") || strings.Contains(logs, "deep.private") {
433 t.Errorf("log: %s", logs)
434 }
435}
436
437// flipInventory is an inventory that can stop being ready.
438type flipInventory struct{ off atomic.Bool }
439
440func (i *flipInventory) Ready(context.Context) error {
441 if i.off.Load() {
442 return ErrInventoryUnconfirmed
443 }
444 return nil
445}
446func (*flipInventory) Inside(netip.Addr) bool { return false }
447
448// The inventory stops being ready while a hop waits (its pace): the hop
449// is refused before its dial, and nothing is sent (Astra phase 3 round
450// 4, P2).
451func TestInventoryCheckedAfterTheWait(t *testing.T) {
452 w := newWeb(t)
453 cfg := w.config(PolicyLookupPage)
454 inv := &flipInventory{}
455 cfg.Inventory = inv
456 c := mustNew(t, cfg)
457 ctx := WithBeforeHop(context.Background(), func(context.Context, string) error {
458 inv.off.Store(true)
459 return nil
460 })
461 if _, err := get(t, c, ctx, "https://a.example.com/"); RuleOf(err) != RuleUnconfirmed {
462 t.Errorf("err %v", err)
463 }
464 if n := len(w.requests("a.example.com")); n != 0 {
465 t.Errorf("%d requests sent", n)
466 }
467}
468