refactor: pre-cleanup.

This commit is contained in:
sam committed 2026-08-06 01:40:15 +10:00
1 parent 0ceab9d897
commit e10cbbc92c
53 files changed
+3596 -648

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
package webfetch
import (
"context"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/tools"
)
// ToolName is the registry name of the fetch tool.
const ToolName = "web_fetch"
// Tool builds the registry entry for cfg, or nil when the fetcher is
// disabled. Returning nil rather than an entry that always refuses keeps a
// capability the operator turned off out of the model's tool list entirely --
// an advertised tool that never works costs a round trip to discover.
func Tool(cfg Config) *tools.ToolEntry {
if !cfg.Enabled {
return nil
}
client := New(cfg)
return &tools.ToolEntry{
Name: ToolName,
Toolset: "web",
Description: "Fetch a web page or API response over http/https and return its readable text. " +
"HTML is reduced to text; JSON, XML and plain text are returned as received. " +
"Use it to read documentation, changelogs, issues or any URL the user provides.",
// Reading a URL has no side effect on this host, so it is safe to
// run alongside other reads.
Classification: tools.ClassIdempotent,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"url": map[string]any{
"type": "string",
"description": "Absolute http:// or https:// URL to fetch.",
},
"raw": map[string]any{
"type": "boolean",
"description": "Return the response body unchanged instead of extracting readable text from HTML. Defaults to false.",
},
},
"required": []any{"url"},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
target, _ := input["url"].(string)
if strings.TrimSpace(target) == "" {
return nil, fmt.Errorf("%s: url is required", ToolName)
}
raw, _ := input["raw"].(bool)
body, err := client.Fetch(ctx, target, raw)
if err != nil {
return nil, fmt.Errorf("%s: %w", ToolName, err)
}
return body, nil
},
}
}
+352
View File
@@ -0,0 +1,352 @@
// Package webfetch retrieves a URL on the model's behalf and returns readable
// text.
//
// The interesting part is not the fetch, it is the refusals. archied runs on a
// host where the Docker API, NATS and its own dashboard answer on private
// addresses, and the URL it is asked to fetch arrives in chat -- an untrusted
// path, since a forge issue body or an inbound email can end up quoted into a
// turn. So the address is vetted at dial time rather than by inspecting the
// URL: a name that looks public can resolve to a private address, and only the
// resolved address tells the truth.
package webfetch
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/net/html"
)
const (
// maxRedirects bounds a redirect chain. Each hop is re-vetted by the
// dialer, so this only stops a loop from spending the timeout.
maxRedirects = 5
// statusExcerpt is how much of a failed response body is quoted back.
// Enough to tell an API error message from an HTML error page.
statusExcerpt = 200
)
// Config controls the fetcher. The zero value is disabled.
type Config struct {
// Enabled advertises the tool. When false, Tool returns nil so the
// model is never shown a capability the operator turned off.
Enabled bool
// Timeout bounds one fetch, redirects included.
Timeout time.Duration
// MaxBytes bounds how much of a response body is read.
MaxBytes int64
// AllowPrivateNetworks permits loopback, private, link-local and
// carrier-grade-NAT addresses. Off by default: leaving it off is what
// keeps the daemon's own control surfaces out of reach.
AllowPrivateNetworks bool
}
// Client fetches URLs under a Config.
type Client struct {
cfg Config
http *http.Client
}
// New builds a Client whose transport refuses disallowed addresses at dial
// time.
func New(cfg Config) *Client {
c := &Client{cfg: cfg}
transport := &http.Transport{
DialContext: c.dialContext,
TLSHandshakeTimeout: cfg.Timeout,
ResponseHeaderTimeout: cfg.Timeout,
DisableKeepAlives: true,
}
c.http = &http.Client{
Transport: transport,
Timeout: cfg.Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("stopped after %d redirects", maxRedirects)
}
return checkScheme(req.URL)
},
}
return c
}
// Fetch retrieves rawURL and returns its readable content. When raw is true
// the body is returned as received rather than reduced to text.
func (c *Client) Fetch(ctx context.Context, rawURL string, raw bool) (string, error) {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil {
return "", fmt.Errorf("invalid url %q: %w", rawURL, err)
}
if err := checkScheme(parsed); err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return "", fmt.Errorf("build request: %w", err)
}
// Some sites serve a different, poorer page to an unidentified client,
// and a few refuse one outright.
req.Header.Set("User-Agent", "archie-webfetch/1.0 (+https://github.com/samcharles93/archie-core)")
req.Header.Set("Accept", "text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.1")
resp, err := c.http.Do(req)
if err != nil {
return "", unwrapFetchError(err)
}
defer resp.Body.Close()
body, truncated, err := c.readBody(resp)
if err != nil {
return "", err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("%s returned %d %s: %s",
parsed.Redacted(), resp.StatusCode, http.StatusText(resp.StatusCode), excerpt(body))
}
mediaType := contentType(resp)
rendered, err := render(mediaType, body, raw, len(body))
if err != nil {
return "", err
}
if truncated {
rendered += fmt.Sprintf("\n\n[webfetch: response truncated at %d bytes]", c.cfg.MaxBytes)
}
return rendered, nil
}
// readBody reads at most MaxBytes, reporting whether more was available.
func (c *Client) readBody(resp *http.Response) (string, bool, error) {
limit := c.cfg.MaxBytes
if limit <= 0 {
limit = 1 << 20
}
// One byte past the limit distinguishes "exactly at the limit" from
// "there was more".
data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
if err != nil {
return "", false, fmt.Errorf("read response: %w", err)
}
if int64(len(data)) > limit {
return string(data[:limit]), true, nil
}
return string(data), false, nil
}
// render turns a body into what the model sees, refusing anything that is not
// text. Returning binary would spend the context window on bytes the model
// cannot read.
func render(mediaType, body string, raw bool, size int) (string, error) {
switch {
case raw:
return body, nil
case mediaType == "text/html", mediaType == "application/xhtml+xml":
return htmlToText(body), nil
case strings.HasPrefix(mediaType, "text/"),
mediaType == "application/json",
mediaType == "application/xml",
strings.HasSuffix(mediaType, "+json"),
strings.HasSuffix(mediaType, "+xml"):
return body, nil
default:
return "", fmt.Errorf("refusing %s (%d bytes): only text, html, json and xml are readable", mediaType, size)
}
}
// contentType returns the media type without parameters, defaulting to plain
// text when the server sends nothing.
func contentType(resp *http.Response) string {
raw := resp.Header.Get("Content-Type")
if raw == "" {
return "text/plain"
}
if i := strings.IndexByte(raw, ';'); i >= 0 {
raw = raw[:i]
}
return strings.ToLower(strings.TrimSpace(raw))
}
// excerpt quotes the start of a failed response so the model can tell an API
// error message from a generic error page.
func excerpt(body string) string {
body = strings.TrimSpace(body)
if len(body) <= statusExcerpt {
return body
}
return body[:statusExcerpt] + "..."
}
// checkScheme allows only http and https. Anything else -- file:, data:,
// gopher: -- reaches something that is not a web server.
func checkScheme(u *url.URL) error {
switch u.Scheme {
case "http", "https":
return nil
case "":
return fmt.Errorf("url %q has no scheme: give an absolute http:// or https:// url", u.String())
default:
return fmt.Errorf("refusing scheme %q: only http and https are fetched", u.Scheme)
}
}
// unwrapFetchError strips the url.Error wrapper so the refusal the dialer or
// the redirect check produced is what the model reads, rather than being
// buried behind Go's transport prose.
func unwrapFetchError(err error) error {
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr.Err != nil {
return urlErr.Err
}
return err
}
// dialContext resolves the host and refuses addresses the daemon must not be
// talked into reaching, then dials a vetted address directly.
//
// Vetting here rather than on the URL is the whole point: between a pre-flight
// check and the connection, a name can resolve to something else. Dialing the
// address that was actually approved closes that window.
func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid address %q: %w", addr, err)
}
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
dialer := &net.Dialer{Timeout: c.cfg.Timeout}
var refused []string
for _, ip := range ips {
if !c.addressAllowed(ip.IP) {
refused = append(refused, ip.IP.String())
continue
}
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.IP.String(), port))
if err == nil {
return conn, nil
}
}
if len(refused) > 0 {
return nil, fmt.Errorf(
"refusing to connect to %s: it resolves to the private or loopback address %s, which is where this host's own services live; set tools.web_fetch.allow_private_networks to permit it",
host, strings.Join(refused, ", "))
}
return nil, fmt.Errorf("could not connect to %s", host)
}
// addressAllowed reports whether an address may be reached.
func (c *Client) addressAllowed(ip net.IP) bool {
if c.cfg.AllowPrivateNetworks {
return true
}
switch {
case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(),
ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(),
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
return false
case isCarrierGradeNAT(ip):
return false
default:
return true
}
}
// isCarrierGradeNAT reports whether ip is in 100.64.0.0/10, which net.IP has
// no predicate for and which routes to infrastructure rather than the public
// internet.
func isCarrierGradeNAT(ip net.IP) bool {
v4 := ip.To4()
return v4 != nil && v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127
}
// blockedElements hold text that is markup machinery rather than content.
var blockedElements = map[string]bool{
"script": true, "style": true, "noscript": true,
"head": true, "template": true, "svg": true,
}
// htmlToText reduces a document to the text a reader would see. It is
// deliberately simple: the goal is to spend the context window on prose
// instead of markup, not to reproduce a browser.
func htmlToText(body string) string {
doc, err := html.Parse(strings.NewReader(body))
if err != nil {
// Unparseable markup still has readable text in it; handing back
// the raw document beats returning nothing.
return body
}
var b strings.Builder
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && blockedElements[n.Data] {
return
}
if n.Type == html.TextNode {
if text := strings.TrimSpace(n.Data); text != "" {
b.WriteString(text)
b.WriteByte(' ')
}
}
for child := n.FirstChild; child != nil; child = child.NextSibling {
walk(child)
}
// Block-level elements end a line so headings and paragraphs do not
// run together into one wall of text.
if n.Type == html.ElementNode && breaksLine(n.Data) {
b.WriteByte('\n')
}
}
walk(doc)
return collapseBlankLines(b.String())
}
// breaksLine reports whether an element should end the current line.
func breaksLine(tag string) bool {
switch tag {
case "p", "div", "br", "li", "tr", "section", "article", "header", "footer",
"h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre":
return true
default:
return false
}
}
// collapseBlankLines trims each line and squeezes runs of blank lines, which
// nested markup produces in quantity.
func collapseBlankLines(s string) string {
lines := strings.Split(s, "\n")
out := make([]string, 0, len(lines))
blank := false
for _, line := range lines {
line = strings.Join(strings.Fields(line), " ")
if line == "" {
if blank {
continue
}
blank = true
} else {
blank = false
}
out = append(out, line)
}
return strings.TrimSpace(strings.Join(out, "\n"))
}
+272
View File
@@ -0,0 +1,272 @@
package webfetch
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// testConfig is the base every case starts from. Private networks are allowed
// because httptest binds loopback; the cases that exercise the SSRF control
// override it explicitly.
func testConfig() Config {
return Config{
Enabled: true,
Timeout: 5 * time.Second,
MaxBytes: 1 << 20,
AllowPrivateNetworks: true,
}
}
func TestFetchExtractsContent(t *testing.T) {
tests := []struct {
name string
contentType string
body string
raw bool
wantContain []string
wantAbsent []string
}{
{
name: "html is reduced to readable text",
contentType: "text/html; charset=utf-8",
body: `<html><head><title>T</title>
<style>body{color:red}</style>
<script>var x = "should not appear";</script></head>
<body><h1>Heading</h1><p>Body text here.</p></body></html>`,
wantContain: []string{"Heading", "Body text here."},
wantAbsent: []string{"should not appear", "color:red", "<p>"},
},
{
name: "raw returns the html unmodified",
contentType: "text/html",
body: `<p>markup</p>`,
raw: true,
wantContain: []string{"<p>markup</p>"},
},
{
name: "json passes through untouched",
contentType: "application/json",
body: `{"key":"value"}`,
wantContain: []string{`{"key":"value"}`},
},
{
name: "plain text passes through untouched",
contentType: "text/plain",
body: "just words",
wantContain: []string{"just words"},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", tc.contentType)
fmt.Fprint(w, tc.body)
}))
defer srv.Close()
got, err := New(testConfig()).Fetch(context.Background(), srv.URL, tc.raw)
if err != nil {
t.Fatal(err)
}
for _, want := range tc.wantContain {
if !strings.Contains(got, want) {
t.Errorf("result %q does not contain %q", got, want)
}
}
for _, absent := range tc.wantAbsent {
if strings.Contains(got, absent) {
t.Errorf("result %q should not contain %q", got, absent)
}
}
})
}
}
func TestFetchRejectsUnsupportedContentType(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
fmt.Fprint(w, "\x89PNG\r\n\x1a\n")
}))
defer srv.Close()
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
if err == nil {
t.Fatal("Fetch() error = nil, want a refusal naming the content type")
}
if !strings.Contains(err.Error(), "image/png") {
t.Errorf("error = %v, want it to name the content type", err)
}
}
func TestFetchCapsBodySize(t *testing.T) {
const limit = 512
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, strings.Repeat("a", limit*10))
}))
defer srv.Close()
cfg := testConfig()
cfg.MaxBytes = limit
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
if err != nil {
t.Fatal(err)
}
if len(got) > limit*2 { // body plus a truncation notice, nowhere near 10x
t.Errorf("result is %d bytes, want it bounded near the %d-byte limit", len(got), limit)
}
if !strings.Contains(got, "truncated") {
t.Errorf("result %q should say it was truncated", got)
}
}
func TestFetchReportsHTTPStatus(t *testing.T) {
tests := []struct {
name string
status int
body string
}{
{name: "not found", status: http.StatusNotFound, body: "no such page"},
{name: "forbidden", status: http.StatusForbidden, body: "denied"},
{name: "rate limited", status: http.StatusTooManyRequests, body: "slow down"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(tc.status)
fmt.Fprint(w, tc.body)
}))
defer srv.Close()
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
if err == nil {
t.Fatalf("Fetch() error = nil, want the %d reported", tc.status)
}
// The model has to tell 404 from 403 from a rate limit to decide
// whether retrying or rewording the URL is worth it.
if !strings.Contains(err.Error(), fmt.Sprint(tc.status)) {
t.Errorf("error = %v, want it to carry status %d", err, tc.status)
}
if !strings.Contains(err.Error(), tc.body) {
t.Errorf("error = %v, want it to carry a body excerpt", err)
}
})
}
}
func TestFetchCapsRedirects(t *testing.T) {
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, srv.URL+"/next", http.StatusFound)
}))
defer srv.Close()
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
if err == nil {
t.Fatal("Fetch() error = nil, want a redirect-limit refusal")
}
if !strings.Contains(err.Error(), "redirect") {
t.Errorf("error = %v, want it to name the redirect limit", err)
}
}
func TestFetchRejectsUnsupportedSchemes(t *testing.T) {
tests := []string{
"file:///etc/passwd",
"ftp://example.com/x",
"gopher://example.com",
"data:text/plain,hello",
"not-a-url",
}
for _, target := range tests {
t.Run(target, func(t *testing.T) {
_, err := New(testConfig()).Fetch(context.Background(), target, false)
if err == nil {
t.Fatalf("Fetch(%q) error = nil, want a scheme refusal", target)
}
})
}
}
// TestFetchBlocksPrivateAddresses is the SSRF control. archied runs on a host
// where the Docker API, NATS and its own dashboard are reachable on private
// addresses, so a model that can be talked into fetching one of those is a
// real hole. httptest binds loopback, which makes it exactly the case to
// assert against.
func TestFetchBlocksPrivateAddresses(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "internal service")
}))
defer srv.Close()
t.Run("blocked by default", func(t *testing.T) {
cfg := testConfig()
cfg.AllowPrivateNetworks = false
_, err := New(cfg).Fetch(context.Background(), srv.URL, false)
if err == nil {
t.Fatal("Fetch() reached a loopback address, want a refusal")
}
if !strings.Contains(err.Error(), "private") && !strings.Contains(err.Error(), "loopback") {
t.Errorf("error = %v, want it to explain the address was refused", err)
}
})
t.Run("allowed when configured", func(t *testing.T) {
cfg := testConfig() // AllowPrivateNetworks is true
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
if err != nil {
t.Fatalf("Fetch() with private networks allowed: %v", err)
}
if !strings.Contains(got, "internal service") {
t.Errorf("result = %q, want the body", got)
}
})
}
// TestFetchBlocksAtDialTime proves the check is on the resolved address rather
// than on the URL string. A hostname that looks public but resolves to a
// private address must still be refused, which a pre-flight URL check cannot
// do and which is how DNS-rebinding defeats one.
func TestFetchBlocksAtDialTime(t *testing.T) {
cfg := testConfig()
cfg.AllowPrivateNetworks = false
// localtest.me and its subdomains are a public DNS name resolving to
// 127.0.0.1. Resolution may be unavailable in a sandbox, so a lookup
// failure is not a test failure -- but a success must be a refusal.
_, err := New(cfg).Fetch(context.Background(), "http://localtest.me/", false)
if err == nil {
t.Fatal("Fetch() reached a public name resolving to loopback, want a refusal")
}
if strings.Contains(err.Error(), "scheme") {
t.Errorf("error = %v, want an address refusal rather than a scheme refusal", err)
}
}
func TestToolDisabledReturnsNil(t *testing.T) {
cfg := testConfig()
cfg.Enabled = false
if Tool(cfg) != nil {
t.Error("Tool() returned an entry while disabled, want nil so it is not advertised")
}
}
func TestToolRejectsMissingURL(t *testing.T) {
entry := Tool(testConfig())
if entry == nil {
t.Fatal("Tool() = nil, want an entry when enabled")
}
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
t.Error("Handler() error = nil, want a refusal when url is absent")
}
}