| 1 | // Package guard is the one guarded HTTP client the instance uses for the |
| 2 | // public web: a lookup's page reads and searches (spec |
| 3 | // 2026-11-26-assistant-abilities §4.3) and, once they land, services (MCP |
| 4 | // §6.1). The network checks are the same for every caller: https on 443, |
| 5 | // websource.CheckHost, the deny list, every DNS answer public and outside |
| 6 | // the instance's inventory, the dial to the checked address with a |
| 7 | // Control re-check, TLS to the host name, no proxy, no cookies, and size |
| 8 | // and time limits. What a request may carry is the caller's Policy. |
| 9 | // |
| 10 | // Nothing here ever prints a URL, a query or a credential: a refusal is |
| 11 | // its rule, and a log line is its rule and the host's registrable domain. |
| 12 | package guard |
| 13 | |
| 14 | import ( |
| 15 | "context" |
| 16 | "crypto/x509" |
| 17 | "errors" |
| 18 | "fmt" |
| 19 | "log/slog" |
| 20 | "net/http" |
| 21 | "net/netip" |
| 22 | "strings" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "golang.org/x/net/publicsuffix" |
| 27 | ) |
| 28 | |
| 29 | // Inventory is the instance's own network (MCP plan Task 7): a request |
| 30 | // may go nowhere inside it, and nowhere at all until it is confirmed. |
| 31 | type Inventory interface { |
| 32 | // Ready is nil once the instance's prefixes are set and confirmed by |
| 33 | // an owner and nothing has drifted; ErrInventoryUnconfirmed otherwise. |
| 34 | Ready(ctx context.Context) error |
| 35 | // Inside reports whether a is within the confirmed prefixes. |
| 36 | Inside(a netip.Addr) bool |
| 37 | } |
| 38 | |
| 39 | // ErrInventoryUnconfirmed: the instance's network isn't confirmed yet. |
| 40 | var ErrInventoryUnconfirmed = errors.New("guard: instance inventory unconfirmed") |
| 41 | |
| 42 | // Policy is what a caller's requests may carry. |
| 43 | type Policy int |
| 44 | |
| 45 | const ( |
| 46 | // PolicyLookupPage: a page a lookup reads. GET only, the fixed |
| 47 | // headers, no credential, redirects allowed (Config.Redirects). |
| 48 | PolicyLookupPage Policy = iota + 1 |
| 49 | // PolicySearch: a search backend's request. GET or POST with a JSON |
| 50 | // body, the fixed headers plus the bound Credential, no redirects. |
| 51 | PolicySearch |
| 52 | // PolicyService: a service's request (MCP). GET and POST, |
| 53 | // Authorization and Content-Type allowed, no redirects. |
| 54 | PolicyService |
| 55 | ) |
| 56 | |
| 57 | // Timeouts bound a request: connecting, the first byte, one request, and |
| 58 | // everything a Do does (redirects included). |
| 59 | type Timeouts struct { |
| 60 | Connect, FirstByte, Request, Overall time.Duration |
| 61 | } |
| 62 | |
| 63 | // Lookup page reads' and searches' bounds (§4.3). |
| 64 | var ( |
| 65 | PageTimeouts = Timeouts{Connect: 5 * time.Second, FirstByte: 10 * time.Second, Request: 15 * time.Second, Overall: 25 * time.Second} |
| 66 | SearchTimeouts = Timeouts{Connect: 5 * time.Second, FirstByte: 10 * time.Second, Request: 10 * time.Second, Overall: 10 * time.Second} |
| 67 | ) |
| 68 | |
| 69 | // Size bounds (§4.3). |
| 70 | const ( |
| 71 | MaxHeaderBytes = 32 << 10 |
| 72 | MaxBody = 2 << 20 |
| 73 | MaxURL = 2 << 10 |
| 74 | // MaxRedirects is the most hops a lookup page may follow. |
| 75 | MaxRedirects = 5 |
| 76 | ) |
| 77 | |
| 78 | // Credential is a search backend's key, bound to the backend's origin: |
| 79 | // it is added, as Header or as query parameter Param (exactly one), only |
| 80 | // to a request whose origin is Origin exactly. It never prints. |
| 81 | type Credential struct { |
| 82 | Origin, Header, Param, Value string |
| 83 | } |
| 84 | |
| 85 | func (c Credential) String() string { return "credential(" + c.Origin + ")" } |
| 86 | func (c Credential) GoString() string { return c.String() } |
| 87 | func (c Credential) Format(f fmt.State, _ rune) { _, _ = f.Write([]byte(c.String())) } |
| 88 | |
| 89 | // Config is a client's configuration. |
| 90 | type Config struct { |
| 91 | Policy Policy |
| 92 | // Deny are hosts refused exactly (and their subdomains): the |
| 93 | // instance's origin, Base's, oficina-connect's, the forge's. |
| 94 | Deny []string |
| 95 | Inventory Inventory |
| 96 | // Resolve is the resolver; nil is net.DefaultResolver.LookupNetIP. |
| 97 | Resolve func(ctx context.Context, host string) ([]netip.Addr, error) |
| 98 | Logger *slog.Logger |
| 99 | // TestDial maps a host to the test server it reaches and its roots. |
| 100 | // Honoured only in a test binary; in one, nothing else is dialled. |
| 101 | TestDial func(host string) (addrport string, roots *x509.CertPool) |
| 102 | // Redirects is how many redirects a request may follow: 0 answers a |
| 103 | // 3xx as Refusal{"redirect"}. |
| 104 | Redirects int |
| 105 | Timeouts Timeouts |
| 106 | UserAgent string |
| 107 | Credential *Credential |
| 108 | // Limit bounds a body, after decompression (0: MaxBody). |
| 109 | Limit int64 |
| 110 | } |
| 111 | |
| 112 | // Response is what Do read: the final status, headers and body, where |
| 113 | // the last hop was, and the body's type as sniffed. |
| 114 | type Response struct { |
| 115 | Status int |
| 116 | Header http.Header |
| 117 | Body []byte |
| 118 | FinalURL string |
| 119 | // Type is html, text, json, xml, feed or unsupported. |
| 120 | Type string |
| 121 | } |
| 122 | |
| 123 | // Refusal is why a request was not made, or not finished: a stable rule, |
| 124 | // safe to log and to store. It never holds an address or a value. Sent |
| 125 | // says the request had been written to the connection before it failed; |
| 126 | // false means nothing went out. |
| 127 | type Refusal struct { |
| 128 | Rule string |
| 129 | Sent bool |
| 130 | } |
| 131 | |
| 132 | func (r Refusal) Error() string { return "guard: refused: " + r.Rule } |
| 133 | |
| 134 | // The rules. |
| 135 | const ( |
| 136 | RuleScheme = "scheme" |
| 137 | RulePort = "port" |
| 138 | RuleHost = "host" |
| 139 | RuleIPLiteral = "ip_literal" |
| 140 | RuleDenied = "denied_host" |
| 141 | RulePrivate = "private_address" |
| 142 | RuleInventory = "inventory" |
| 143 | RuleUnconfirmed = "inventory_unconfirmed" |
| 144 | RuleRedirect = "redirect" |
| 145 | RuleTooManyRedirect = "too_many_redirects" |
| 146 | RuleDowngrade = "downgrade" |
| 147 | RuleTooLarge = "too_large" |
| 148 | RuleTimeout = "timeout" |
| 149 | RuleUnavailable = "unavailable" |
| 150 | RulePolicy = "policy" |
| 151 | RuleURL = "url" |
| 152 | ) |
| 153 | |
| 154 | // RuleOf is err's rule, "" when err is no Refusal. |
| 155 | func RuleOf(err error) string { |
| 156 | var r Refusal |
| 157 | if errors.As(err, &r) { |
| 158 | return r.Rule |
| 159 | } |
| 160 | return "" |
| 161 | } |
| 162 | |
| 163 | // Client is a guarded client. |
| 164 | type Client struct { |
| 165 | cfg Config |
| 166 | test bool |
| 167 | } |
| 168 | |
| 169 | // New is a client for c, or an error when c's policy or credential is |
| 170 | // invalid. |
| 171 | func New(c Config) (*Client, error) { |
| 172 | switch c.Policy { |
| 173 | case PolicyLookupPage, PolicySearch, PolicyService: |
| 174 | default: |
| 175 | return nil, errors.New("guard: unknown policy") |
| 176 | } |
| 177 | if c.Redirects < 0 || c.Redirects > MaxRedirects { |
| 178 | return nil, errors.New("guard: redirects out of range") |
| 179 | } |
| 180 | if c.Policy != PolicyLookupPage && c.Redirects != 0 { |
| 181 | return nil, errors.New("guard: only page reads follow redirects") |
| 182 | } |
| 183 | if cr := c.Credential; cr != nil { |
| 184 | if c.Policy != PolicySearch { |
| 185 | return nil, errors.New("guard: only searches carry a credential") |
| 186 | } |
| 187 | if (cr.Header == "") == (cr.Param == "") || cr.Value == "" || !strings.HasPrefix(cr.Origin, "https://") { |
| 188 | return nil, errors.New("guard: a credential needs an https origin, a value and one of header or param") |
| 189 | } |
| 190 | if c.Redirects != 0 { |
| 191 | return nil, errors.New("guard: a credential never follows a redirect") |
| 192 | } |
| 193 | } |
| 194 | if c.Timeouts == (Timeouts{}) { |
| 195 | c.Timeouts = PageTimeouts |
| 196 | if c.Policy == PolicySearch { |
| 197 | c.Timeouts = SearchTimeouts |
| 198 | } |
| 199 | } |
| 200 | if c.Limit <= 0 { |
| 201 | c.Limit = MaxBody |
| 202 | } |
| 203 | if c.UserAgent == "" { |
| 204 | c.UserAgent = "OficinaLookup/1" |
| 205 | } |
| 206 | if c.Logger == nil { |
| 207 | c.Logger = slog.New(slog.DiscardHandler) |
| 208 | } |
| 209 | return &Client{cfg: c, test: testing.Testing()}, nil |
| 210 | } |
| 211 | |
| 212 | type denyKey struct{} |
| 213 | type hopKey struct{} |
| 214 | |
| 215 | // WithDeny is ctx with hosts refused on every hop of a request made with |
| 216 | // it, besides Config.Deny. |
| 217 | func WithDeny(ctx context.Context, hosts []string) context.Context { |
| 218 | return context.WithValue(ctx, denyKey{}, append(append([]string(nil), denyOf(ctx)...), hosts...)) |
| 219 | } |
| 220 | |
| 221 | func denyOf(ctx context.Context) []string { |
| 222 | d, _ := ctx.Value(denyKey{}).([]string) |
| 223 | return d |
| 224 | } |
| 225 | |
| 226 | // BeforeHop runs right before a hop is sent, with the host it goes to, |
| 227 | // after its checks: an error stops the request with nothing sent. |
| 228 | type BeforeHop func(ctx context.Context, host string) error |
| 229 | |
| 230 | // WithBeforeHop is ctx with f run before every hop of a request made |
| 231 | // with it: the first and each redirect. |
| 232 | func WithBeforeHop(ctx context.Context, f BeforeHop) context.Context { |
| 233 | return context.WithValue(ctx, hopKey{}, f) |
| 234 | } |
| 235 | |
| 236 | func beforeHopOf(ctx context.Context) BeforeHop { |
| 237 | f, _ := ctx.Value(hopKey{}).(BeforeHop) |
| 238 | return f |
| 239 | } |
| 240 | |
| 241 | // Registrable is host's registrable domain (example.co.uk for |
| 242 | // www.example.co.uk), for logs; host itself when it has none. |
| 243 | func Registrable(host string) string { |
| 244 | if d, err := publicsuffix.EffectiveTLDPlusOne(strings.ToLower(host)); err == nil { |
| 245 | return d |
| 246 | } |
| 247 | return host |
| 248 | } |
| 249 | |
| 250 | // refuse logs a refusal by rule and registrable domain, and returns it. |
| 251 | func (c *Client) refuse(rule, host string) error { |
| 252 | c.cfg.Logger.Info("guard: refused", "rule", rule, "domain", Registrable(host)) |
| 253 | return Refusal{Rule: rule} |
| 254 | } |
| 255 | |