fix(agent): restore safe rendered web fetch fallback

main
langcaiye 2026-07-27 15:28:47 +08:00 committed by lyingbug
parent a3da5cb57a
commit 75a2eabe20
4 changed files with 381 additions and 37 deletions

View File

@ -17,10 +17,11 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/chromedp/chromedp"
)
const (
fetchTimeout = 15 * time.Second
fetchTimeout = 60 * time.Second
maxBodySize = 100 * 1024
)
@ -82,23 +83,44 @@ func ErrorDetails(err error) (ErrorCode, bool, string) {
// Fetcher fetches and extracts public web pages through an SSRF-safe client.
type Fetcher struct {
client *http.Client
timeout time.Duration
maxBodySize int64
validateURL func(string) error
client *http.Client
timeout time.Duration
maxBodySize int64
validateURL func(string) error
resolveIPs func(context.Context, string) ([]net.IP, error)
dialContext func(context.Context, string, string) (net.Conn, error)
renderBrowser func(context.Context, pinnedTarget) (string, error)
}
type pinnedTarget struct {
URL *url.URL
Host string
Port string
IP net.IP
}
type httpFetchResult struct {
body []byte
finalURL string
}
// NewFetcher creates a production fetcher with DNS and redirect SSRF guards.
func NewFetcher() *Fetcher {
return &Fetcher{
client: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: fetchTimeout,
MaxRedirects: 10,
}),
timeout: fetchTimeout,
maxBodySize: maxBodySize,
validateURL: utils.ValidateURLForSSRF,
config := utils.SSRFSafeHTTPClientConfig{
Timeout: fetchTimeout,
MaxRedirects: 10,
}
fetcher := &Fetcher{
timeout: fetchTimeout,
maxBodySize: maxBodySize,
validateURL: utils.ValidateURLForSSRF,
resolveIPs: lookupPublicDNS,
renderBrowser: renderWithChromium,
}
transport := utils.NewSSRFSafeTransport(config)
transport.DialContext = fetcher.pinnedDialContext()
fetcher.client = utils.NewSSRFSafeHTTPClientWithTransport(config, transport)
return fetcher
}
// FetchURLContent preserves the existing package-level API.
@ -124,40 +146,199 @@ func (f *Fetcher) Fetch(ctx context.Context, rawURL string) (string, error) {
requestCtx, cancel := context.WithTimeout(ctx, f.timeout)
defer cancel()
req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, rawURL, nil)
httpResult, httpErr := f.fetchHTTP(requestCtx, rawURL, parsedURL)
if httpErr == nil {
content, parseErr := htmlToText(string(httpResult.body))
if parseErr == nil && strings.TrimSpace(content) != "" && !needsBrowserFallback(content, httpResult.body) {
logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(content))
return content, nil
}
if f.renderBrowser != nil {
browserURL := firstNonEmpty(httpResult.finalURL, rawURL)
if rendered, browserErr := f.fetchWithBrowser(requestCtx, browserURL); browserErr == nil {
content, browserParseErr := htmlToText(rendered)
if browserParseErr == nil && strings.TrimSpace(content) != "" {
logger.Infof(ctx, "[WebFetch] rendered %s → %d chars", rawURL, len(content))
return content, nil
}
}
}
if parseErr != nil {
return "", parseErr
}
if strings.TrimSpace(content) == "" {
return "", newFetchError(ErrorEmptyContent, false, "page contains no readable text")
}
return content, nil
}
if f.renderBrowser != nil && canRenderAfterHTTPError(httpErr) {
if rendered, browserErr := f.fetchWithBrowser(requestCtx, rawURL); browserErr == nil {
content, browserParseErr := htmlToText(rendered)
if browserParseErr == nil && strings.TrimSpace(content) != "" {
logger.Infof(ctx, "[WebFetch] rendered %s → %d chars", rawURL, len(content))
return content, nil
}
}
}
return "", httpErr
}
func (f *Fetcher) fetchHTTP(ctx context.Context, rawURL string, parsedURL *url.URL) (*httpFetchResult, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return "", newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
return nil, newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
}
setBrowserHeaders(req, parsedURL)
resp, err := f.client.Do(req)
if err != nil {
return "", classifyRequestError(err)
return nil, classifyRequestError(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", classifyHTTPStatus(resp.StatusCode, resp.Status)
return nil, classifyHTTPStatus(resp.StatusCode, resp.Status)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, f.maxBodySize))
if err != nil {
return "", newFetchError(ErrorRead, true, "read failed: %v", err)
return nil, newFetchError(ErrorRead, true, "read failed: %v", err)
}
if len(body) == 0 {
return "", newFetchError(ErrorEmptyContent, false, "page body is empty")
finalURL := rawURL
if resp.Request != nil && resp.Request.URL != nil {
finalURL = resp.Request.URL.String()
}
return &httpFetchResult{body: body, finalURL: finalURL}, nil
}
content, err := htmlToText(string(body))
func (f *Fetcher) pinnedDialContext() func(context.Context, string, string) (net.Conn, error) {
return func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, fmt.Errorf("invalid address %s: %w", address, err)
}
if utils.IsSystemProxy(address) || utils.IsSSRFWhitelisted(host) {
return (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext(ctx, network, address)
}
ips, err := f.resolveIPs(ctx, host)
if err != nil {
return nil, fmt.Errorf("DNS resolution failed for %s: %w", host, err)
}
if len(ips) == 0 {
return nil, fmt.Errorf("DNS resolution failed: no addresses for %s", host)
}
for _, ip := range ips {
if !utils.IsPublicIP(ip) {
return nil, fmt.Errorf("connection blocked: %s resolves to restricted IP %s", host, ip)
}
}
pinnedAddress := net.JoinHostPort(ips[0].String(), port)
if f.dialContext != nil {
return f.dialContext(ctx, network, pinnedAddress)
}
return (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext(ctx, network, pinnedAddress)
}
}
func (f *Fetcher) fetchWithBrowser(ctx context.Context, rawURL string) (string, error) {
target, err := f.resolvePinnedTarget(ctx, rawURL)
if err != nil {
return "", err
}
if strings.TrimSpace(content) == "" {
return "", newFetchError(ErrorEmptyContent, false, "page contains no readable text")
}
return f.renderBrowser(ctx, target)
}
logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(content))
return content, nil
func (f *Fetcher) resolvePinnedTarget(ctx context.Context, rawURL string) (pinnedTarget, error) {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return pinnedTarget{}, newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
}
port := parsedURL.Port()
if port == "" {
port = "443"
if parsedURL.Scheme == "http" {
port = "80"
}
}
ips, err := f.resolveIPs(ctx, parsedURL.Hostname())
if err != nil {
return pinnedTarget{}, newFetchError(ErrorDNS, true, "DNS lookup failed for %s: %v", parsedURL.Hostname(), err)
}
if len(ips) == 0 {
return pinnedTarget{}, newFetchError(ErrorDNS, true, "DNS lookup returned no addresses for %s", parsedURL.Hostname())
}
if !utils.IsSSRFWhitelisted(parsedURL.Hostname()) {
for _, ip := range ips {
if !utils.IsPublicIP(ip) {
return pinnedTarget{}, newFetchError(ErrorSSRFRejected, false, "host resolves to restricted IP %s", ip)
}
}
}
return pinnedTarget{URL: parsedURL, Host: parsedURL.Hostname(), Port: port, IP: ips[0]}, nil
}
func lookupPublicDNS(ctx context.Context, host string) ([]net.IP, error) {
return net.DefaultResolver.LookupIP(ctx, "ip", host)
}
func renderWithChromium(ctx context.Context, target pinnedTarget) (string, error) {
hostRule := fmt.Sprintf("MAP %s %s, MAP * ~NOTFOUND", target.Host, target.IP.String())
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("host-resolver-rules", hostRule),
chromedp.Flag("headless", true),
chromedp.Flag("disable-setuid-sandbox", true),
chromedp.Flag("disable-dev-shm-usage", true),
chromedp.Flag("disable-gpu", true),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
)
allocatorCtx, cancelAllocator := chromedp.NewExecAllocator(ctx, opts...)
defer cancelAllocator()
browserCtx, cancelBrowser := chromedp.NewContext(allocatorCtx)
defer cancelBrowser()
browserCtx, cancelTimeout := context.WithTimeout(browserCtx, fetchTimeout)
defer cancelTimeout()
var html string
if err := chromedp.Run(browserCtx,
chromedp.Navigate(target.URL.String()),
chromedp.WaitReady("body", chromedp.ByQuery),
chromedp.OuterHTML("html", &html),
); err != nil {
return "", fmt.Errorf("chromium render failed: %w", err)
}
return string(limitBytes([]byte(html), maxBodySize)), nil
}
func limitBytes(value []byte, max int64) []byte {
if int64(len(value)) <= max {
return value
}
return value[:max]
}
func needsBrowserFallback(content string, html []byte) bool {
trimmed := strings.TrimSpace(strings.ToLower(content))
if trimmed == "" || strings.Contains(trimmed, "enable javascript") || strings.Contains(trimmed, "loading...") {
return true
}
if len([]rune(trimmed)) >= 200 {
return false
}
lowerHTML := strings.ToLower(string(html))
hasAppRoot := strings.Contains(lowerHTML, `id="app"`) || strings.Contains(lowerHTML, `id='app'`) ||
strings.Contains(lowerHTML, `id="root"`) || strings.Contains(lowerHTML, `id='root'`)
return hasAppRoot && strings.Contains(lowerHTML, "<script")
}
func canRenderAfterHTTPError(err error) bool {
code, _, _ := ErrorDetails(err)
return code == ErrorHTTP403 || code == ErrorEmptyContent
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}
func setBrowserHeaders(req *http.Request, parsedURL *url.URL) {
@ -231,6 +412,9 @@ func classifyRequestError(err error) error {
}
message := strings.ToLower(err.Error())
if strings.Contains(message, "dns resolution failed") || strings.Contains(message, "dns lookup failed") {
return newFetchError(ErrorDNS, true, "DNS lookup failed: %v", err)
}
if strings.Contains(message, "connection blocked:") {
return newFetchError(ErrorSSRFRejected, false, "URL rejected: %v", err)
}

View File

@ -112,6 +112,30 @@ func TestFetcherRejectsEmptyContent(t *testing.T) {
assert.False(t, retryable)
}
func TestFetcherUsesBrowserFallbackForClientRenderedPage(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte(`<html><body><div id="app">Loading...</div><script>render()</script></body></html>`))
}))
defer server.Close()
fetcher := newTestFetcher(server.Client())
fetcher.resolveIPs = func(context.Context, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("93.184.216.34")}, nil
}
fetcher.renderBrowser = func(context.Context, pinnedTarget) (string, error) {
return `<html><body><main>rendered product specifications</main></body></html>`, nil
}
content, err := fetcher.Fetch(context.Background(), server.URL)
require.NoError(t, err)
assert.Contains(t, content, "rendered product specifications")
}
func TestNewFetcherKeepsAgentCompatibleTimeout(t *testing.T) {
assert.Equal(t, 60*time.Second, NewFetcher().timeout)
}
func TestFetcherClassifiesInvalidAndSSRFURLs(t *testing.T) {
fetcher := NewFetcher()
_, invalidErr := fetcher.Fetch(context.Background(), "not-a-url")
@ -125,6 +149,64 @@ func TestFetcherClassifiesInvalidAndSSRFURLs(t *testing.T) {
assert.False(t, ssrfRetryable)
}
func TestPinnedDialUsesValidatedIPAndPreservesPort(t *testing.T) {
var dialedAddress string
fetcher := &Fetcher{
resolveIPs: func(context.Context, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("93.184.216.34")}, nil
},
dialContext: func(_ context.Context, _, address string) (net.Conn, error) {
dialedAddress = address
return nil, errors.New("stop dial")
},
}
_, err := fetcher.pinnedDialContext()(context.Background(), "tcp", "example.com:443")
assert.Equal(t, "93.184.216.34:443", dialedAddress)
assert.EqualError(t, err, "stop dial")
}
func TestPinnedDialRejectsRebindingToRestrictedIP(t *testing.T) {
dialCalled := false
fetcher := &Fetcher{
resolveIPs: func(context.Context, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("127.0.0.1")}, nil
},
dialContext: func(context.Context, string, string) (net.Conn, error) {
dialCalled = true
return nil, nil
},
}
_, err := fetcher.pinnedDialContext()(context.Background(), "tcp", "example.com:443")
require.Error(t, err)
assert.Contains(t, err.Error(), "connection blocked")
assert.False(t, dialCalled)
}
func TestFetcherKeepsOriginalHostForTLSAndHTTPRouting(t *testing.T) {
var requestURL string
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
requestURL = request.URL.Host
return &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Body: http.NoBody,
Request: request,
}, nil
})}
fetcher := newTestFetcher(client)
fetcher.validateURL = func(string) error { return nil }
_, err := fetcher.Fetch(context.Background(), "https://example.com/specs")
require.Error(t, err)
assert.Equal(t, "example.com", requestURL)
assert.Contains(t, err.Error(), "no readable text")
}
func newTestFetcher(client *http.Client) *Fetcher {
return &Fetcher{
client: client,

View File

@ -9,6 +9,13 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
const (
modelWebSearchEvidenceMaxRunes = 500
modelWebFetchSummaryMaxRunes = 4000
modelWebFetchContentMaxRunes = 8000
modelWebFetchTotalMaxRunes = 16000
)
// ModelOutput returns a compact, source-centric representation for the LLM.
// The canonical ToolResult.Output remains untouched for UI, logs and storage.
func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string {
@ -350,10 +357,10 @@ func (r *sourceRegistry) modelWebSearchOutput(rows []map[string]interface{}, fal
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", handle, escapeAttr(stringValue(row, "title")))
b.WriteString(" <evidence type=\"search_summary\" verified=\"false\" />\n")
if snippet := stringValue(row, "snippet"); snippet != "" {
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(snippet))
writeLimitedWebEvidence(&b, "match", snippet, modelWebSearchEvidenceMaxRunes, nil)
}
if content := stringValue(row, "content"); content != "" && content != stringValue(row, "snippet") {
fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
writeLimitedWebEvidence(&b, "content", content, modelWebSearchEvidenceMaxRunes, nil)
}
if published := stringValue(row, "published_at"); published != "" {
fmt.Fprintf(&b, " <published>%s</published>\n", escapeText(published))
@ -375,6 +382,7 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
var b strings.Builder
b.WriteString("<retrieval type=\"web\" mode=\"fetch\">\n")
count, successCount, failedCount := 0, 0, 0
remainingEvidence := modelWebFetchTotalMaxRunes
for _, row := range rows {
rawURL := stringValue(row, "url")
if rawURL == "" {
@ -394,14 +402,14 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
b.WriteString(" view=\"full\">\n")
successCount++
if summary := stringValue(row, "summary"); summary != "" {
fmt.Fprintf(&b, " <summary>%s</summary>\n", escapeText(summary))
writeLimitedWebEvidence(&b, "summary", summary, modelWebFetchSummaryMaxRunes, &remainingEvidence)
}
if summaryStatus := stringValue(row, "summary_status"); summaryStatus == "failed" {
fmt.Fprintf(&b, " <summary_error code=\"%s\">%s</summary_error>\n",
escapeAttr(stringValue(row, "summary_error_code")), escapeText(stringValue(row, "summary_error_message")))
}
if content := stringValue(row, "raw_content"); content != "" {
fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
writeLimitedWebEvidence(&b, "content", content, modelWebFetchContentMaxRunes, &remainingEvidence)
}
} else {
fmt.Fprintf(&b, " retryable=\"%t\"", boolValue(row, "retryable"))
@ -436,6 +444,39 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
return b.String()
}
func writeLimitedWebEvidence(builder *strings.Builder, tag, value string, maxRunes int, remaining *int) {
if value == "" {
return
}
limit := maxRunes
if remaining != nil && *remaining < limit {
limit = *remaining
}
limited, truncated := truncateModelEvidence(value, limit)
if remaining != nil {
*remaining -= len([]rune(limited))
if *remaining < 0 {
*remaining = 0
}
}
fmt.Fprintf(builder, " <%s", tag)
if truncated {
builder.WriteString(" truncated=\"true\"")
}
fmt.Fprintf(builder, ">%s</%s>\n", escapeText(limited), tag)
}
func truncateModelEvidence(value string, maxRunes int) (string, bool) {
runes := []rune(value)
if len(runes) <= maxRunes {
return value, false
}
if maxRunes <= 0 {
return "", true
}
return string(runes[:maxRunes]), true
}
func mapsValue(value interface{}) []map[string]interface{} {
if value == nil {
return nil

View File

@ -281,7 +281,7 @@ func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
}
func TestModelOutputWebSearchRetainsContentOnlyEvidence(t *testing.T) {
registry := NewRegistry()
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
@ -300,8 +300,27 @@ func TestModelOutputWebSearchRetainsContentOnlyEvidence(t *testing.T) {
require.Contains(t, output, `<evidence type="search_summary" verified="false" />`)
}
func TestModelOutputWebSearchLimitsProviderContent(t *testing.T) {
registry := newSourceRegistry()
content := strings.Repeat("provider evidence ", 1000)
output := registry.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
"display_type": "web_search_results",
"results": []map[string]interface{}{{
"title": "Long provider result",
"url": "https://example.com/long",
"content": content,
}},
},
})
require.Contains(t, output, `<content truncated="true">`)
require.NotContains(t, output, content)
}
func TestModelOutputWebFetchPreservesPartialFailureStatus(t *testing.T) {
registry := NewRegistry()
registry := newSourceRegistry()
registry.RegisterWeb("https://example.com/verified", "Verified")
registry.RegisterWeb("https://example.com/forbidden", "Forbidden")
@ -335,7 +354,7 @@ func TestModelOutputWebFetchPreservesPartialFailureStatus(t *testing.T) {
}
func TestModelOutputWebFetchAllFailuresIncludeSearchFallback(t *testing.T) {
registry := NewRegistry()
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
@ -358,7 +377,7 @@ func TestModelOutputWebFetchAllFailuresIncludeSearchFallback(t *testing.T) {
}
func TestModelOutputWebFetchKeepsContentWhenSummaryFails(t *testing.T) {
registry := NewRegistry()
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
@ -380,6 +399,24 @@ func TestModelOutputWebFetchKeepsContentWhenSummaryFails(t *testing.T) {
require.Contains(t, output, `<content>official specifications</content>`)
}
func TestModelOutputWebFetchLimitsRawContentAcrossPages(t *testing.T) {
registry := newSourceRegistry()
pageContent := strings.Repeat("verified page content ", 1000)
output := registry.ModelOutput(&types.ToolResult{
Success: true,
Data: map[string]interface{}{
"display_type": "web_fetch_results",
"results": []map[string]interface{}{
{"url": "https://example.com/one", "status": "success", "raw_content": pageContent},
{"url": "https://example.com/two", "status": "success", "raw_content": pageContent},
},
},
})
require.Contains(t, output, `truncated="true"`)
require.Less(t, len([]rune(output)), modelWebFetchTotalMaxRunes+3000)
}
func TestModelOutputDocumentInfoUsesDocumentAndFAQAliases(t *testing.T) {
registry := newSourceRegistry()
result := &types.ToolResult{