oficina / equipo Public

websource: one guarded client for lookups and services

internal/websource/guard is the instance's one client for the public
web: https on 443, websource.CheckHost (now exported), the deny list
(Config.Deny and WithDeny, every hop), every DNS answer public and
outside the confirmed inventory, the dial to the checked address with a
Control re-check, TLS to the host name, no proxy, cookies or keep-alive,
32 KiB headers, 2 MiB bodies after gzip, and per-policy time limits.
What a request may carry is its Policy: a lookup page (GET, up to 5
redirects, an http address tried once as https, no downgrade), a search
(no redirects, its Credential only on its own origin) or a service.
WithBeforeHop runs right before every hop. Refusals are rules; logs are
the rule and the registrable domain; no error carries a URL or a key. A
test binary dials nothing but its TestDial.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1d11ba289d183607f0149672b347d127f7c7d8c2 parent 7e6e979
4 files changed, +1,005 −2
  • internal/websource/guard/dial.go +315 −0
  • internal/websource/guard/guard.go +249 −0
  • internal/websource/guard/guard_test.go +434 −0
  • internal/websource/websource.go +7 −2
diff --git a/internal/websource/guard/dial.go b/internal/websource/guard/dial.go
new file mode 100644
index 00000000..0f1ae8e5
--- /dev/null
+++ b/internal/websource/guard/dial.go
@@ -0,0 +1,315 @@
+package guard
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "strings"
+ "syscall"
+
+ "amadan.net/oficina/equipo/internal/websource"
+)
+
+// allowedHeaders are the headers a caller may set, by policy; the guard
+// sets User-Agent, Accept and Accept-Encoding itself, and a search's
+// credential.
+var allowedHeaders = map[Policy][]string{
+ PolicyLookupPage: {},
+ PolicySearch: {"Content-Type"},
+ PolicyService: {"Authorization", "Content-Type", "Accept"},
+}
+
+// checkPolicy refuses a request outside the client's policy, before
+// anything is resolved or dialled.
+func (c *Client) checkPolicy(req *http.Request) error {
+ switch c.cfg.Policy {
+ case PolicyLookupPage:
+ if req.Method != http.MethodGet || req.Body != nil && req.Body != http.NoBody {
+ return Refusal{Rule: RulePolicy}
+ }
+ case PolicySearch, PolicyService:
+ if req.Method != http.MethodGet && req.Method != http.MethodPost {
+ return Refusal{Rule: RulePolicy}
+ }
+ }
+ for k := range req.Header {
+ ok := false
+ for _, a := range allowedHeaders[c.cfg.Policy] {
+ ok = ok || http.CanonicalHeaderKey(a) == http.CanonicalHeaderKey(k)
+ }
+ if !ok {
+ return Refusal{Rule: RulePolicy}
+ }
+ }
+ return nil
+}
+
+// Do makes req through every check, hop by hop, and reads the answer
+// within the limits. A refusal is a Refusal by rule; nothing returned
+// ever holds the URL, the query or a credential.
+func (c *Client) Do(ctx context.Context, req *http.Request) (*Response, error) {
+ if c.test && c.cfg.TestDial == nil {
+ // A test binary never dials the world.
+ return nil, Refusal{Rule: RuleUnavailable}
+ }
+ if err := c.checkPolicy(req); err != nil {
+ return nil, err
+ }
+ var body []byte
+ if req.Body != nil && req.Body != http.NoBody {
+ raw, err := io.ReadAll(io.LimitReader(req.Body, MaxBody+1))
+ if err != nil || len(raw) > MaxBody {
+ return nil, Refusal{Rule: RulePolicy}
+ }
+ body = raw
+ }
+ ctx, cancel := context.WithTimeout(ctx, c.cfg.Timeouts.Overall)
+ defer cancel()
+ u := *req.URL
+ method := req.Method
+ for hop := 0; ; hop++ {
+ if hop > c.cfg.Redirects {
+ return nil, c.refuse(RuleTooManyRedirect, u.Hostname())
+ }
+ if u.Scheme == "http" {
+ // An http address the person typed is tried once as https;
+ // a redirect down to http never.
+ if hop > 0 {
+ return nil, c.refuse(RuleDowngrade, u.Hostname())
+ }
+ u.Scheme = "https"
+ }
+ host, addrs, err := c.check(ctx, &u)
+ if err != nil {
+ return nil, err
+ }
+ if f := beforeHopOf(ctx); f != nil {
+ if err := f(ctx, host); err != nil {
+ return nil, err
+ }
+ }
+ res, err := c.send(ctx, method, u, body, req.Header, host, addrs)
+ if err != nil {
+ return nil, err
+ }
+ if res.Status < 300 || res.Status > 399 || res.Status == http.StatusNotModified {
+ res.FinalURL = u.String()
+ return res, nil
+ }
+ if c.cfg.Redirects == 0 {
+ return nil, c.refuse(RuleRedirect, host)
+ }
+ next, err := u.Parse(res.Header.Get("Location"))
+ if err != nil || res.Header.Get("Location") == "" {
+ return nil, c.refuse(RuleURL, host)
+ }
+ u, method, body = *next, http.MethodGet, nil
+ }
+}
+
+// check applies the per-hop checks to u, and resolves its host: every
+// answer must be public and outside the inventory.
+func (c *Client) check(ctx context.Context, u *url.URL) (string, []netip.Addr, error) {
+ host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")
+ switch {
+ case u.Scheme != "https":
+ return "", nil, c.refuse(RuleScheme, host)
+ case u.Port() != "" && u.Port() != "443":
+ return "", nil, c.refuse(RulePort, host)
+ case u.User != nil || u.Opaque != "" || len(u.String()) > MaxURL:
+ return "", nil, c.refuse(RuleURL, host)
+ }
+ if strings.HasPrefix(u.Host, "[") {
+ return "", nil, c.refuse(RuleIPLiteral, host)
+ }
+ if err := websource.CheckHost(host); err != nil {
+ if errors.Is(err, websource.ErrIPLiteral) {
+ return "", nil, c.refuse(RuleIPLiteral, host)
+ }
+ return "", nil, c.refuse(RuleHost, host)
+ }
+ for _, d := range append(append([]string(nil), c.cfg.Deny...), denyOf(ctx)...) {
+ d = strings.TrimSuffix(strings.ToLower(d), ".")
+ if d != "" && (host == d || strings.HasSuffix(host, "."+d)) {
+ return "", nil, c.refuse(RuleDenied, host)
+ }
+ }
+ if c.cfg.Inventory == nil || c.cfg.Inventory.Ready(ctx) != nil {
+ return "", nil, c.refuse(RuleUnconfirmed, host)
+ }
+ resolve := c.cfg.Resolve
+ if resolve == nil {
+ resolve = func(ctx context.Context, h string) ([]netip.Addr, error) {
+ return net.DefaultResolver.LookupNetIP(ctx, "ip", h)
+ }
+ }
+ addrs, err := resolve(ctx, host)
+ if err != nil || len(addrs) == 0 {
+ if ctx.Err() != nil {
+ return "", nil, c.refuse(RuleTimeout, host)
+ }
+ return "", nil, c.refuse(RuleUnavailable, host)
+ }
+ for _, a := range addrs {
+ if !websource.PublicAddress(a) {
+ return "", nil, c.refuse(RulePrivate, host)
+ }
+ if c.cfg.Inventory.Inside(a.Unmap()) {
+ return "", nil, c.refuse(RuleInventory, host)
+ }
+ }
+ return host, addrs, nil
+}
+
+// send makes one hop: a fresh connection to the checked address (the
+// socket's address checked again as it connects), TLS to host, no proxy,
+// no cookies, no keep-alive, the policy's headers, and the credential
+// only on its own origin. A 3xx comes back unread.
+func (c *Client) send(ctx context.Context, method string, u url.URL, body []byte, given http.Header, host string, addrs []netip.Addr) (*Response, error) {
+ target := netip.AddrPortFrom(addrs[0].Unmap(), 443).String()
+ var roots *x509.CertPool
+ if c.test {
+ target, roots = c.cfg.TestDial(host)
+ }
+ dialer := &net.Dialer{Timeout: c.cfg.Timeouts.Connect, Control: func(_, address string, _ syscall.RawConn) error {
+ if c.test {
+ return nil
+ }
+ ap, err := netip.ParseAddrPort(address)
+ if err != nil || !websource.PublicAddress(ap.Addr()) {
+ return Refusal{Rule: RulePrivate}
+ }
+ if c.cfg.Inventory.Inside(ap.Addr().Unmap()) {
+ return Refusal{Rule: RuleInventory}
+ }
+ return nil
+ }}
+ tr := &http.Transport{
+ Proxy: nil,
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, "tcp", target)
+ },
+ TLSClientConfig: &tls.Config{ServerName: host, RootCAs: roots, MinVersion: tls.VersionTLS12},
+ TLSHandshakeTimeout: c.cfg.Timeouts.Connect,
+ ResponseHeaderTimeout: c.cfg.Timeouts.FirstByte,
+ MaxResponseHeaderBytes: MaxHeaderBytes,
+ DisableKeepAlives: true,
+ DisableCompression: true,
+ }
+ defer tr.CloseIdleConnections()
+ client := &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ rctx, cancel := context.WithTimeout(ctx, c.cfg.Timeouts.Request)
+ defer cancel()
+ out := u
+ if cr := c.cfg.Credential; cr != nil && cr.Param != "" && origin(u) == cr.Origin {
+ q := out.Query()
+ q.Set(cr.Param, cr.Value)
+ out.RawQuery = q.Encode()
+ }
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(rctx, method, out.String(), rd)
+ if err != nil {
+ return nil, c.refuse(RuleURL, host)
+ }
+ for _, k := range allowedHeaders[c.cfg.Policy] {
+ if v := given.Get(k); v != "" {
+ req.Header.Set(k, v)
+ }
+ }
+ req.Header.Set("User-Agent", c.cfg.UserAgent)
+ if c.cfg.Policy != PolicyService || req.Header.Get("Accept") == "" {
+ req.Header.Set("Accept", "text/html,application/xhtml+xml,application/json,application/xml,text/plain;q=0.9,*/*;q=0.1")
+ }
+ req.Header.Set("Accept-Encoding", "gzip")
+ if cr := c.cfg.Credential; cr != nil && cr.Header != "" && origin(u) == cr.Origin {
+ req.Header.Set(cr.Header, cr.Value)
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ var r Refusal
+ switch {
+ case errors.As(err, &r):
+ return nil, c.refuse(r.Rule, host)
+ case rctx.Err() != nil || errors.Is(err, context.DeadlineExceeded):
+ return nil, c.refuse(RuleTimeout, host)
+ }
+ // Never err itself: a *url.Error prints the URL, and a search's
+ // key may ride in its query.
+ return nil, c.refuse(RuleUnavailable, host)
+ }
+ defer res.Body.Close()
+ resp := &Response{Status: res.StatusCode, Header: res.Header.Clone()}
+ if res.StatusCode >= 300 && res.StatusCode <= 399 {
+ return resp, nil
+ }
+ if res.ContentLength > c.cfg.Limit {
+ return nil, c.refuse(RuleTooLarge, host)
+ }
+ var rdr io.Reader = res.Body
+ if strings.EqualFold(res.Header.Get("Content-Encoding"), "gzip") {
+ gz, err := gzip.NewReader(res.Body)
+ if err != nil {
+ return nil, c.refuse(RuleUnavailable, host)
+ }
+ defer gz.Close()
+ rdr = gz
+ }
+ raw, err := io.ReadAll(io.LimitReader(rdr, c.cfg.Limit+1))
+ if err != nil {
+ if rctx.Err() != nil {
+ return nil, c.refuse(RuleTimeout, host)
+ }
+ return nil, c.refuse(RuleUnavailable, host)
+ }
+ if int64(len(raw)) > c.cfg.Limit {
+ return nil, c.refuse(RuleTooLarge, host)
+ }
+ resp.Body, resp.Type = raw, sniff(raw, res.Header.Get("Content-Type"))
+ return resp, nil
+}
+
+// origin is u's scheme and host.
+func origin(u url.URL) string { return u.Scheme + "://" + strings.ToLower(u.Host) }
+
+// sniff is a body's type from its bytes (the header only breaks a tie
+// between text kinds): html, text, json, xml, feed, or unsupported.
+func sniff(body []byte, header string) string {
+ head := bytes.TrimSpace(body[:min(len(body), 512)])
+ lower := bytes.ToLower(head)
+ switch {
+ case len(head) == 0:
+ return "text"
+ case bytes.HasPrefix(head, []byte("{")) || bytes.HasPrefix(head, []byte("[")):
+ return "json"
+ case bytes.Contains(lower, []byte("<rss")) || bytes.Contains(lower, []byte("<feed")):
+ return "feed"
+ case bytes.HasPrefix(lower, []byte("<?xml")):
+ if strings.Contains(header, "html") {
+ return "html"
+ }
+ return "xml"
+ }
+ switch kind := http.DetectContentType(body); {
+ case strings.HasPrefix(kind, "text/html"):
+ return "html"
+ case strings.HasPrefix(kind, "text/xml"):
+ return "xml"
+ case strings.HasPrefix(kind, "text/plain"):
+ if strings.Contains(header, "html") {
+ return "html"
+ }
+ return "text"
+ }
+ return "unsupported"
+}
diff --git a/internal/websource/guard/guard.go b/internal/websource/guard/guard.go
new file mode 100644
index 00000000..eae76ffd
--- /dev/null
+++ b/internal/websource/guard/guard.go
@@ -0,0 +1,249 @@
+// Package guard is the one guarded HTTP client the instance uses for the
+// public web: a lookup's page reads and searches (spec
+// 2026-11-26-assistant-abilities §4.3) and, once they land, services (MCP
+// §6.1). The network checks are the same for every caller: https on 443,
+// websource.CheckHost, the deny list, every DNS answer public and outside
+// the instance's inventory, the dial to the checked address with a
+// Control re-check, TLS to the host name, no proxy, no cookies, and size
+// and time limits. What a request may carry is the caller's Policy.
+//
+// Nothing here ever prints a URL, a query or a credential: a refusal is
+// its rule, and a log line is its rule and the host's registrable domain.
+package guard
+
+import (
+ "context"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/netip"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/net/publicsuffix"
+)
+
+// Inventory is the instance's own network (MCP plan Task 7): a request
+// may go nowhere inside it, and nowhere at all until it is confirmed.
+type Inventory interface {
+ // Ready is nil once the instance's prefixes are set and confirmed by
+ // an owner and nothing has drifted; ErrInventoryUnconfirmed otherwise.
+ Ready(ctx context.Context) error
+ // Inside reports whether a is within the confirmed prefixes.
+ Inside(a netip.Addr) bool
+}
+
+// ErrInventoryUnconfirmed: the instance's network isn't confirmed yet.
+var ErrInventoryUnconfirmed = errors.New("guard: instance inventory unconfirmed")
+
+// Policy is what a caller's requests may carry.
+type Policy int
+
+const (
+ // PolicyLookupPage: a page a lookup reads. GET only, the fixed
+ // headers, no credential, redirects allowed (Config.Redirects).
+ PolicyLookupPage Policy = iota + 1
+ // PolicySearch: a search backend's request. GET or POST with a JSON
+ // body, the fixed headers plus the bound Credential, no redirects.
+ PolicySearch
+ // PolicyService: a service's request (MCP). GET and POST,
+ // Authorization and Content-Type allowed, no redirects.
+ PolicyService
+)
+
+// Timeouts bound a request: connecting, the first byte, one request, and
+// everything a Do does (redirects included).
+type Timeouts struct {
+ Connect, FirstByte, Request, Overall time.Duration
+}
+
+// Lookup page reads' and searches' bounds (§4.3).
+var (
+ PageTimeouts = Timeouts{Connect: 5 * time.Second, FirstByte: 10 * time.Second, Request: 15 * time.Second, Overall: 25 * time.Second}
+ SearchTimeouts = Timeouts{Connect: 5 * time.Second, FirstByte: 10 * time.Second, Request: 10 * time.Second, Overall: 10 * time.Second}
+)
+
+// Size bounds (§4.3).
+const (
+ MaxHeaderBytes = 32 << 10
+ MaxBody = 2 << 20
+ MaxURL = 2 << 10
+ // MaxRedirects is the most hops a lookup page may follow.
+ MaxRedirects = 5
+)
+
+// Credential is a search backend's key, bound to the backend's origin:
+// it is added, as Header or as query parameter Param (exactly one), only
+// to a request whose origin is Origin exactly. It never prints.
+type Credential struct {
+ Origin, Header, Param, Value string
+}
+
+func (c Credential) String() string { return "credential(" + c.Origin + ")" }
+func (c Credential) GoString() string { return c.String() }
+func (c Credential) Format(f fmt.State, _ rune) { _, _ = f.Write([]byte(c.String())) }
+
+// Config is a client's configuration.
+type Config struct {
+ Policy Policy
+ // Deny are hosts refused exactly (and their subdomains): the
+ // instance's origin, Base's, oficina-connect's, the forge's.
+ Deny []string
+ Inventory Inventory
+ // Resolve is the resolver; nil is net.DefaultResolver.LookupNetIP.
+ Resolve func(ctx context.Context, host string) ([]netip.Addr, error)
+ Logger *slog.Logger
+ // TestDial maps a host to the test server it reaches and its roots.
+ // Honoured only in a test binary; in one, nothing else is dialled.
+ TestDial func(host string) (addrport string, roots *x509.CertPool)
+ // Redirects is how many redirects a request may follow: 0 answers a
+ // 3xx as Refusal{"redirect"}.
+ Redirects int
+ Timeouts Timeouts
+ UserAgent string
+ Credential *Credential
+ // Limit bounds a body, after decompression (0: MaxBody).
+ Limit int64
+}
+
+// Response is what Do read: the final status, headers and body, where
+// the last hop was, and the body's type as sniffed.
+type Response struct {
+ Status int
+ Header http.Header
+ Body []byte
+ FinalURL string
+ // Type is html, text, json, xml, feed or unsupported.
+ Type string
+}
+
+// Refusal is why a request was not made, or not finished: a stable rule,
+// safe to log and to store. It never holds an address or a value.
+type Refusal struct{ Rule string }
+
+func (r Refusal) Error() string { return "guard: refused: " + r.Rule }
+
+// The rules.
+const (
+ RuleScheme = "scheme"
+ RulePort = "port"
+ RuleHost = "host"
+ RuleIPLiteral = "ip_literal"
+ RuleDenied = "denied_host"
+ RulePrivate = "private_address"
+ RuleInventory = "inventory"
+ RuleUnconfirmed = "inventory_unconfirmed"
+ RuleRedirect = "redirect"
+ RuleTooManyRedirect = "too_many_redirects"
+ RuleDowngrade = "downgrade"
+ RuleTooLarge = "too_large"
+ RuleTimeout = "timeout"
+ RuleUnavailable = "unavailable"
+ RulePolicy = "policy"
+ RuleURL = "url"
+)
+
+// RuleOf is err's rule, "" when err is no Refusal.
+func RuleOf(err error) string {
+ var r Refusal
+ if errors.As(err, &r) {
+ return r.Rule
+ }
+ return ""
+}
+
+// Client is a guarded client.
+type Client struct {
+ cfg Config
+ test bool
+}
+
+// New is a client for c, or an error when c's policy or credential is
+// invalid.
+func New(c Config) (*Client, error) {
+ switch c.Policy {
+ case PolicyLookupPage, PolicySearch, PolicyService:
+ default:
+ return nil, errors.New("guard: unknown policy")
+ }
+ if c.Redirects < 0 || c.Redirects > MaxRedirects {
+ return nil, errors.New("guard: redirects out of range")
+ }
+ if c.Policy != PolicyLookupPage && c.Redirects != 0 {
+ return nil, errors.New("guard: only page reads follow redirects")
+ }
+ if cr := c.Credential; cr != nil {
+ if c.Policy != PolicySearch {
+ return nil, errors.New("guard: only searches carry a credential")
+ }
+ if (cr.Header == "") == (cr.Param == "") || cr.Value == "" || !strings.HasPrefix(cr.Origin, "https://") {
+ return nil, errors.New("guard: a credential needs an https origin, a value and one of header or param")
+ }
+ if c.Redirects != 0 {
+ return nil, errors.New("guard: a credential never follows a redirect")
+ }
+ }
+ if c.Timeouts == (Timeouts{}) {
+ c.Timeouts = PageTimeouts
+ if c.Policy == PolicySearch {
+ c.Timeouts = SearchTimeouts
+ }
+ }
+ if c.Limit <= 0 {
+ c.Limit = MaxBody
+ }
+ if c.UserAgent == "" {
+ c.UserAgent = "OficinaLookup/1"
+ }
+ if c.Logger == nil {
+ c.Logger = slog.New(slog.DiscardHandler)
+ }
+ return &Client{cfg: c, test: testing.Testing()}, nil
+}
+
+type denyKey struct{}
+type hopKey struct{}
+
+// WithDeny is ctx with hosts refused on every hop of a request made with
+// it, besides Config.Deny.
+func WithDeny(ctx context.Context, hosts []string) context.Context {
+ return context.WithValue(ctx, denyKey{}, append(append([]string(nil), denyOf(ctx)...), hosts...))
+}
+
+func denyOf(ctx context.Context) []string {
+ d, _ := ctx.Value(denyKey{}).([]string)
+ return d
+}
+
+// BeforeHop runs right before a hop is sent, with the host it goes to,
+// after its checks: an error stops the request with nothing sent.
+type BeforeHop func(ctx context.Context, host string) error
+
+// WithBeforeHop is ctx with f run before every hop of a request made
+// with it: the first and each redirect.
+func WithBeforeHop(ctx context.Context, f BeforeHop) context.Context {
+ return context.WithValue(ctx, hopKey{}, f)
+}
+
+func beforeHopOf(ctx context.Context) BeforeHop {
+ f, _ := ctx.Value(hopKey{}).(BeforeHop)
+ return f
+}
+
+// Registrable is host's registrable domain (example.co.uk for
+// www.example.co.uk), for logs; host itself when it has none.
+func Registrable(host string) string {
+ if d, err := publicsuffix.EffectiveTLDPlusOne(strings.ToLower(host)); err == nil {
+ return d
+ }
+ return host
+}
+
+// refuse logs a refusal by rule and registrable domain, and returns it.
+func (c *Client) refuse(rule, host string) error {
+ c.cfg.Logger.Info("guard: refused", "rule", rule, "domain", Registrable(host))
+ return Refusal{Rule: rule}
+}
diff --git a/internal/websource/guard/guard_test.go b/internal/websource/guard/guard_test.go
new file mode 100644
index 00000000..287a12e5
--- /dev/null
+++ b/internal/websource/guard/guard_test.go
@@ -0,0 +1,434 @@
+package guard
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "strings"
+ "sync"
+ "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, "<html><body>hello</body></html>")
+ 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": `<?xml version="1.0"?><rss><channel></channel></rss>`, "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)
+ }
+}
diff --git a/internal/websource/websource.go b/internal/websource/websource.go
index 67d82a41..8267431f 100644
--- a/internal/websource/websource.go
+++ b/internal/websource/websource.go
@@ -149,8 +149,13 @@ func fromParsed(raw string, p *url.URL) (URL, error) {
// refusedSuffixes are names that never leave the machine or the site.
var refusedSuffixes = []string{".localhost", ".local", ".internal", ".lan", ".home.arpa", ".arpa", ".ts.net", ".onion", ".test", ".invalid", ".example"}
-// checkHost applies §3.1's host rules to a lower-case host with its
-// trailing dot gone.
+// CheckHost applies §3.1's host rules to a lower-case host with its
+// trailing dot gone: a registered name whose last label has a letter, no
+// IP literal in any form, and none of the names that never leave the
+// machine or the site. The guarded client applies it to every hop.
+func CheckHost(host string) error { return checkHost(host) }
+
+// checkHost is CheckHost.
func checkHost(host string) error {
labels := strings.Split(host, ".")
numeric := true