package guard
import (
"bytes"
"compress/gzip"
"context"
"crypto/x509"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"amadan.net/rastrillo/rastrillo/budget"
)
func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
// inventory is a confirmed (or not) instance network.
type inventory struct {
ready bool
inside []netip.Prefix
}
func (i inventory) Ready(context.Context) error {
if !i.ready {
return ErrInventoryUnconfirmed
}
return nil
}
func (i inventory) Inside(a netip.Addr) bool {
for _, p := range i.inside {
if p.Contains(a) {
return true
}
}
return false
}
// web is one TLS test server answering every *.example.com host by its
// handler, with the resolver's answers per host and what each host got.
type web struct {
srv *httptest.Server
mu sync.Mutex
answers map[string][]netip.Addr
got map[string][]*http.Request
handle map[string]http.HandlerFunc
logs bytes.Buffer
}
func newWeb(t *testing.T) *web {
t.Helper()
w := &web{answers: map[string][]netip.Addr{}, got: map[string][]*http.Request{}, handle: map[string]http.HandlerFunc{}}
w.srv = httptest.NewTLSServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
host := strings.Split(r.Host, ":")[0]
w.mu.Lock()
w.got[host] = append(w.got[host], r.Clone(context.Background()))
h := w.handle[host]
w.mu.Unlock()
if h == nil {
_, _ = io.WriteString(rw, "
hello")
return
}
h(rw, r)
}))
t.Cleanup(w.srv.Close)
return w
}
func (w *web) on(host string, h http.HandlerFunc, addrs ...string) {
w.mu.Lock()
defer w.mu.Unlock()
w.handle[host] = h
if len(addrs) == 0 {
addrs = []string{"93.184.216.34"}
}
w.answers[host] = nil
for _, a := range addrs {
w.answers[host] = append(w.answers[host], netip.MustParseAddr(a))
}
}
func (w *web) requests(host string) []*http.Request {
w.mu.Lock()
defer w.mu.Unlock()
return w.got[host]
}
func (w *web) config(p Policy) Config {
roots := x509.NewCertPool()
roots.AddCert(w.srv.Certificate())
return Config{
Policy: p,
Deny: []string{"equipo.example.com"},
Inventory: inventory{ready: true, inside: []netip.Prefix{netip.MustParsePrefix("81.2.69.0/24")}},
Resolve: func(_ context.Context, host string) ([]netip.Addr, error) {
w.mu.Lock()
defer w.mu.Unlock()
if a, ok := w.answers[host]; ok {
return a, nil
}
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
},
Logger: slog.New(slog.NewTextHandler(&w.logs, nil)),
TestDial: func(string) (string, *x509.CertPool) { return w.srv.Listener.Addr().String(), roots },
Redirects: MaxRedirects,
}
}
func get(t *testing.T, c *Client, ctx context.Context, raw string) (*Response, error) {
t.Helper()
req, err := http.NewRequest(http.MethodGet, raw, nil)
if err != nil {
t.Fatal(err)
}
return c.Do(ctx, req)
}
func mustNew(t *testing.T, cfg Config) *Client {
t.Helper()
c, err := New(cfg)
if err != nil {
t.Fatal(err)
}
return c
}
func redirect(to string) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { http.Redirect(rw, r, to, http.StatusFound) }
}
// Spec ยง10.1's list: every IP literal form, a private answer among public
// ones, metadata, a redirect to a private address, https down to http, a
// sixth redirect, .ts.net, the instance's own host, and the inventory.
func TestFetchSSRF(t *testing.T) {
w := newWeb(t)
w.on("mixed.example.com", nil, "93.184.216.34", "10.1.2.3")
w.on("meta.example.com", nil, "169.254.169.254")
w.on("inside.example.com", nil, "81.2.69.7")
w.on("private.example.com", nil, "192.168.1.1")
w.on("hop.example.com", redirect("https://private.example.com/x"))
w.on("down.example.com", redirect("http://plain.example.com/x"))
for i := 0; i < 6; i++ {
w.on(fmt.Sprintf("r%d.example.com", i), redirect(fmt.Sprintf("https://r%d.example.com/", i+1)))
}
c := mustNew(t, w.config(PolicyLookupPage))
for raw, rule := range map[string]string{
"https://127.0.0.1/": RuleIPLiteral,
"https://[::1]/": RuleIPLiteral,
"https://0x7f.1/": RuleIPLiteral,
"https://2130706433/": RuleIPLiteral,
"https://localhost/": RuleHost,
"https://box.tail1.ts.net/": RuleHost,
"https://svc.internal/": RuleHost,
"https://equipo.example.com/": RuleDenied,
"https://x.equipo.example.com/": RuleDenied,
"https://mixed.example.com/": RulePrivate,
"https://meta.example.com/": RulePrivate,
"https://inside.example.com/": RuleInventory,
"https://hop.example.com/": RulePrivate,
"https://down.example.com/": RuleDowngrade,
"https://r0.example.com/": RuleTooManyRedirect,
"https://a.example.com:8443/": RulePort,
"ftp://a.example.com/": RuleScheme,
} {
if _, err := get(t, c, context.Background(), raw); RuleOf(err) != rule {
t.Errorf("%s: %v, want %s", raw, err, rule)
}
}
for _, h := range []string{"mixed.example.com", "meta.example.com", "inside.example.com", "private.example.com", "plain.example.com", "r6.example.com"} {
if n := len(w.requests(h)); n != 0 {
t.Errorf("%s got %d requests", h, n)
}
}
unready := w.config(PolicyLookupPage)
unready.Inventory = inventory{}
if _, err := get(t, mustNew(t, unready), context.Background(), "https://a.example.com/"); RuleOf(err) != RuleUnconfirmed {
t.Errorf("unconfirmed inventory: %v", err)
}
long := "https://a.example.com/" + strings.Repeat("a", MaxURL)
if _, err := get(t, c, context.Background(), long); RuleOf(err) != RuleURL {
t.Errorf("a URL over 2 KiB: %v", err)
}
}
// Sizes, decompression and types.
func TestFetchBounds(t *testing.T) {
w := newWeb(t)
w.on("big.example.com", func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write(bytes.Repeat([]byte("a"), MaxBody+1)) })
w.on("bomb.example.com", func(rw http.ResponseWriter, _ *http.Request) {
var b bytes.Buffer
gz := gzip.NewWriter(&b)
_, _ = gz.Write(bytes.Repeat([]byte("a"), MaxBody+10))
_ = gz.Close()
rw.Header().Set("Content-Encoding", "gzip")
_, _ = rw.Write(b.Bytes())
})
w.on("headers.example.com", func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("X-Big", strings.Repeat("h", MaxHeaderBytes+1))
})
for host, body := range map[string]string{"json.example.com": `{"a":1}`, "feed.example.com": ``, "pdf.example.com": "%PDF-1.7 \x00\x01\x02", "text.example.com": "plain words"} {
body := body
w.on(host, func(rw http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(rw, body) })
}
c := mustNew(t, w.config(PolicyLookupPage))
for raw, rule := range map[string]string{"https://big.example.com/": RuleTooLarge, "https://bomb.example.com/": RuleTooLarge, "https://headers.example.com/": RuleUnavailable} {
if _, err := get(t, c, context.Background(), raw); RuleOf(err) != rule {
t.Errorf("%s: %v, want %s", raw, err, rule)
}
}
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"} {
res, err := get(t, c, context.Background(), "https://"+host+"/")
if err != nil || res.Type != want {
t.Errorf("%s: %v %+v, want %s", host, err, res, want)
}
}
}
// No cookie, Authorization, Referer or proxy: a cookie set by one hop
// isn't sent on the next, and HTTPS_PROXY is ignored.
func TestNoCredentialsSent(t *testing.T) {
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1")
w := newWeb(t)
w.on("c1.example.com", func(rw http.ResponseWriter, r *http.Request) {
http.SetCookie(rw, &http.Cookie{Name: "s", Value: "v"})
http.Redirect(rw, r, "https://c2.example.com/", http.StatusFound)
})
c := mustNew(t, w.config(PolicyLookupPage))
if _, err := get(t, c, context.Background(), "https://c1.example.com/"); err != nil {
t.Fatal(err)
}
for _, h := range []string{"c1.example.com", "c2.example.com"} {
for _, r := range w.requests(h) {
if r.Header.Get("Cookie") != "" || r.Header.Get("Authorization") != "" || r.Header.Get("Referer") != "" || r.Header.Get("User-Agent") != "OficinaLookup/1" {
t.Errorf("%s got %v", h, r.Header)
}
}
}
if len(w.requests("c2.example.com")) != 1 {
t.Error("the redirect wasn't followed")
}
}
// Services and searches follow no redirect.
func TestRedirectsZeroForServices(t *testing.T) {
w := newWeb(t)
w.on("svc.example.com", redirect("https://elsewhere.example.com/"))
for _, p := range []Policy{PolicyService, PolicySearch} {
cfg := w.config(p)
cfg.Redirects = 0
if _, err := get(t, mustNew(t, cfg), context.Background(), "https://svc.example.com/"); RuleOf(err) != RuleRedirect {
t.Errorf("policy %d: %v", p, err)
}
}
if n := len(w.requests("elsewhere.example.com")); n != 0 {
t.Errorf("the redirect's target got %d", n)
}
cfg := w.config(PolicyService)
if _, err := New(cfg); err == nil {
t.Error("a service client with redirects")
}
}
const sentinel = "KEY-SENTINEL-4242"
// A search key goes only to its backend's origin, never with a
// redirect, and never prints.
func TestCredentialBoundToOrigin(t *testing.T) {
w := newWeb(t)
w.on("search.example.com", redirect("https://evil.example.com/"))
cfg := w.config(PolicySearch)
cfg.Redirects = 0
cfg.Credential = &Credential{Origin: "https://search.example.com", Header: "Authorization", Value: "Bearer " + sentinel}
c := mustNew(t, cfg)
if _, err := get(t, c, context.Background(), "https://search.example.com/api"); RuleOf(err) != RuleRedirect {
t.Fatalf("302 from the backend: %v", err)
}
if got := w.requests("search.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "Bearer "+sentinel {
t.Errorf("the backend didn't get its key")
}
if n := len(w.requests("evil.example.com")); n != 0 {
t.Error("the redirect's target got a request")
}
if _, err := get(t, c, context.Background(), "https://other.example.com/"); err != nil {
t.Fatal(err)
}
if got := w.requests("other.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "" {
t.Error("another origin got the key")
}
bad := cfg
bad.Redirects = 1
if _, err := New(bad); err == nil {
t.Error("a credential with redirects")
}
}
// WithDeny's hosts are refused on every hop.
func TestWithDenyEachHop(t *testing.T) {
w := newWeb(t)
w.on("start.example.com", redirect("https://app.example.com/"))
c := mustNew(t, w.config(PolicyLookupPage))
ctx := WithDeny(context.Background(), []string{"app.example.com"})
if _, err := get(t, c, ctx, "https://start.example.com/"); RuleOf(err) != RuleDenied {
t.Errorf("denied by redirect: %v", err)
}
if n := len(w.requests("app.example.com")); n != 0 {
t.Error("the denied host got a request")
}
}
// BeforeHop runs once per hop with that hop's host; an error on hop 2
// means hop 2 is never sent.
func TestBeforeHopEveryHop(t *testing.T) {
w := newWeb(t)
w.on("h1.example.com", redirect("https://h2.example.com/"))
c := mustNew(t, w.config(PolicyLookupPage))
var hosts []string
ctx := WithBeforeHop(context.Background(), func(_ context.Context, host string) error {
hosts = append(hosts, host)
if host == "h2.example.com" {
return errors.New("refused at hop 2")
}
return nil
})
if _, err := get(t, c, ctx, "https://h1.example.com/"); err == nil || err.Error() != "refused at hop 2" {
t.Errorf("err %v", err)
}
if strings.Join(hosts, ",") != "h1.example.com,h2.example.com" || len(w.requests("h2.example.com")) != 0 {
t.Errorf("hops %v, h2 got %d", hosts, len(w.requests("h2.example.com")))
}
}
// A page read is GET with nothing of the caller's; a search carries no
// Authorization of the caller's: anything else is refused before a dial.
func TestLookupPoliciesRefusePostAndAuthorization(t *testing.T) {
w := newWeb(t)
page := mustNew(t, w.config(PolicyLookupPage))
scfg := w.config(PolicySearch)
scfg.Redirects = 0
search := mustNew(t, scfg)
post, _ := http.NewRequest(http.MethodPost, "https://a.example.com/", strings.NewReader("x"))
if _, err := page.Do(context.Background(), post); RuleOf(err) != RulePolicy {
t.Errorf("POST through a page read: %v", err)
}
for _, c := range []*Client{page, search} {
req, _ := http.NewRequest(http.MethodGet, "https://a.example.com/", nil)
req.Header.Set("Authorization", "Bearer x")
if _, err := c.Do(context.Background(), req); RuleOf(err) != RulePolicy {
t.Errorf("Authorization through policy %d: %v", c.cfg.Policy, err)
}
}
if n := len(w.requests("a.example.com")); n != 0 {
t.Errorf("%d requests sent", n)
}
}
// A service's authenticated POST goes through.
func TestServicePolicyAllowsAuthenticatedPost(t *testing.T) {
w := newWeb(t)
cfg := w.config(PolicyService)
cfg.Redirects = 0
req, _ := http.NewRequest(http.MethodPost, "https://svc.example.com/mcp", strings.NewReader(`{"a":1}`))
req.Header.Set("Authorization", "Bearer svc")
req.Header.Set("Content-Type", "application/json")
if _, err := mustNew(t, cfg).Do(context.Background(), req); err != nil {
t.Fatal(err)
}
if got := w.requests("svc.example.com"); len(got) != 1 || got[0].Header.Get("Authorization") != "Bearer svc" || got[0].Method != http.MethodPost {
t.Errorf("service request %v", got)
}
}
// A credential never prints, and New refuses one with both or neither of
// Header and Param; no guard error carries the value, even in a query.
func TestCredentialRedacted(t *testing.T) {
cr := Credential{Origin: "https://search.example.com", Param: "api_key", Value: sentinel}
cfg := Config{Policy: PolicySearch, Credential: &cr}
for _, s := range []string{fmt.Sprintf("%v", cr), fmt.Sprintf("%+v", cr), fmt.Sprintf("%#v", cr), fmt.Sprintf("%v", cfg), fmt.Sprintf("%+v", &cfg)} {
if strings.Contains(s, sentinel) {
t.Errorf("printed: %s", s)
}
}
for _, bad := range []Credential{{Origin: cr.Origin, Value: "x"}, {Origin: cr.Origin, Header: "X", Param: "y", Value: "x"}} {
if _, err := New(Config{Policy: PolicySearch, Credential: &bad}); err == nil {
t.Errorf("New took %v", bad)
}
}
w := newWeb(t)
w.on("search.example.com", func(rw http.ResponseWriter, _ *http.Request) { panic(http.ErrAbortHandler) })
scfg := w.config(PolicySearch)
scfg.Redirects, scfg.Credential = 0, &cr
_, err := get(t, mustNew(t, scfg), context.Background(), "https://search.example.com/search?q=x")
if err == nil || strings.Contains(err.Error(), sentinel) || strings.Contains(fmt.Sprintf("%+v", err), sentinel) || strings.Contains(w.logs.String(), sentinel) {
t.Errorf("an error carried the key: %v", err)
}
}
// An http address is tried once as https.
func TestHTTPTypedTriedAsHTTPSOnce(t *testing.T) {
w := newWeb(t)
res, err := get(t, mustNew(t, w.config(PolicyLookupPage)), context.Background(), "http://typed.example.com/page")
if err != nil || res.FinalURL != "https://typed.example.com/page" {
t.Errorf("%v %+v", err, res)
}
}
// In a test binary nothing is dialled without TestDial.
func TestGuardNeverDialsInTests(t *testing.T) {
cfg := Config{Policy: PolicyLookupPage, Inventory: inventory{ready: true}, Redirects: MaxRedirects}
if _, err := get(t, mustNew(t, cfg), context.Background(), "https://a.example.com/"); RuleOf(err) != RuleUnavailable {
t.Errorf("%v", err)
}
}
// A refusal is logged by rule and registrable domain, never the path or
// query.
func TestRefusalLogsRuleAndDomainOnly(t *testing.T) {
w := newWeb(t)
w.on("deep.private.example.com", nil, "10.0.0.9")
if _, err := get(t, mustNew(t, w.config(PolicyLookupPage)), context.Background(), "https://deep.private.example.com/my/salary?q=secret"); RuleOf(err) != RulePrivate {
t.Fatal(err)
}
logs := w.logs.String()
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") {
t.Errorf("log: %s", logs)
}
}
// flipInventory is an inventory that can stop being ready.
type flipInventory struct{ off atomic.Bool }
func (i *flipInventory) Ready(context.Context) error {
if i.off.Load() {
return ErrInventoryUnconfirmed
}
return nil
}
func (*flipInventory) Inside(netip.Addr) bool { return false }
// The inventory stops being ready while a hop waits (its pace): the hop
// is refused before its dial, and nothing is sent (Astra phase 3 round
// 4, P2).
func TestInventoryCheckedAfterTheWait(t *testing.T) {
w := newWeb(t)
cfg := w.config(PolicyLookupPage)
inv := &flipInventory{}
cfg.Inventory = inv
c := mustNew(t, cfg)
ctx := WithBeforeHop(context.Background(), func(context.Context, string) error {
inv.off.Store(true)
return nil
})
if _, err := get(t, c, ctx, "https://a.example.com/"); RuleOf(err) != RuleUnconfirmed {
t.Errorf("err %v", err)
}
if n := len(w.requests("a.example.com")); n != 0 {
t.Errorf("%d requests sent", n)
}
}