// 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. Sent // says the request had been written to the connection before it failed; // false means nothing went out. type Refusal struct { Rule string Sent bool } 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} }