chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,616 @@
|
||||
// Package web_fetch provides a public URL content fetcher with SSRF protection.
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/utils"
|
||||
"github.com/chromedp/chromedp"
|
||||
"golang.org/x/net/html/charset"
|
||||
"golang.org/x/text/encoding"
|
||||
)
|
||||
|
||||
const (
|
||||
// Bound interactive reads; explicit environment overrides remain supported.
|
||||
defaultPageFetchTimeout = 30 * time.Second
|
||||
pipelineFetchTimeout = 15 * time.Second
|
||||
maxBodySize = 100 * 1024
|
||||
maxAgentBodySize = 2 * 1024 * 1024
|
||||
)
|
||||
|
||||
// PageFetchTimeout is the shared budget for one agent web_fetch page read.
|
||||
// The HTTP client, the fetch context, and chromedp all use this value.
|
||||
// Chromedp's deadline is a child of the fetch context, so the budgets do not add.
|
||||
//
|
||||
// ACADEMY_WEB_FETCH_TIMEOUT accepts a Go duration (150s, 3m) or a bare positive
|
||||
// number of seconds (180), the same pattern as ACADEMY_AGENT_LLM_TIMEOUT.
|
||||
// Empty, invalid, and non-positive values use defaultPageFetchTimeout.
|
||||
func PageFetchTimeout() time.Duration {
|
||||
value := strings.TrimSpace(os.Getenv("ACADEMY_WEB_FETCH_TIMEOUT"))
|
||||
if value == "" {
|
||||
return defaultPageFetchTimeout
|
||||
}
|
||||
timeout, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
// Bare number of seconds, for example "180".
|
||||
timeout, err = time.ParseDuration(value + "s")
|
||||
}
|
||||
if err != nil || timeout <= 0 {
|
||||
return defaultPageFetchTimeout
|
||||
}
|
||||
return timeout
|
||||
}
|
||||
|
||||
// ErrorCode identifies the stage and class of a fetch failure.
|
||||
type ErrorCode string
|
||||
|
||||
// Fetch failure codes distinguish retryable network errors from permanent failures.
|
||||
const (
|
||||
ErrorInvalidURL ErrorCode = "invalid_url"
|
||||
ErrorDNS ErrorCode = "dns_failed"
|
||||
ErrorTimeout ErrorCode = "connection_timeout"
|
||||
ErrorTLS ErrorCode = "tls_failed"
|
||||
ErrorHTTP403 ErrorCode = "http_403"
|
||||
ErrorHTTP429 ErrorCode = "http_429"
|
||||
ErrorHTTP5xx ErrorCode = "http_5xx"
|
||||
ErrorHTTPStatus ErrorCode = "http_status"
|
||||
ErrorSSRFRejected ErrorCode = "ssrf_rejected"
|
||||
ErrorRedirectRejected ErrorCode = "redirect_rejected"
|
||||
ErrorRead ErrorCode = "read_failed"
|
||||
ErrorHTMLParse ErrorCode = "html_parse_failed"
|
||||
ErrorEmptyContent ErrorCode = "empty_content"
|
||||
ErrorConnection ErrorCode = "connection_failed"
|
||||
ErrorBodyTooLarge ErrorCode = "body_too_large"
|
||||
ErrorUnsupportedContent ErrorCode = "unsupported_content"
|
||||
ErrorSnapshotExpired ErrorCode = "snapshot_expired"
|
||||
)
|
||||
|
||||
// FetchError carries stable, machine-readable failure details.
|
||||
type FetchError struct {
|
||||
Code ErrorCode
|
||||
Retryable bool
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *FetchError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.Err == nil {
|
||||
return string(e.Code)
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *FetchError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// ErrorDetails returns stable fields suitable for tool responses and logs.
|
||||
func ErrorDetails(err error) (ErrorCode, bool, string) {
|
||||
if err == nil {
|
||||
return "", false, ""
|
||||
}
|
||||
var fetchErr *FetchError
|
||||
if errors.As(err, &fetchErr) {
|
||||
return fetchErr.Code, fetchErr.Retryable, fetchErr.Error()
|
||||
}
|
||||
return ErrorConnection, true, err.Error()
|
||||
}
|
||||
|
||||
// Fetcher fetches and extracts public web pages through an SSRF-safe client.
|
||||
type Fetcher struct {
|
||||
markdown bool
|
||||
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
|
||||
contentType string
|
||||
}
|
||||
|
||||
// NewFetcher creates a production fetcher with DNS and redirect SSRF guards.
|
||||
func NewFetcher() *Fetcher {
|
||||
f := newFetcher(PageFetchTimeout(), renderWithChromium)
|
||||
f.markdown = true
|
||||
f.maxBodySize = maxAgentBodySize
|
||||
return f
|
||||
}
|
||||
|
||||
// NewPipelineFetcher creates an HTTP-only fetcher for the chat pipeline.
|
||||
// It keeps the pre-refactor 15s timeout and does not launch Chromium.
|
||||
func NewPipelineFetcher() *Fetcher {
|
||||
return newFetcher(pipelineFetchTimeout, nil)
|
||||
}
|
||||
|
||||
func newFetcher(timeout time.Duration, renderBrowser func(context.Context, pinnedTarget) (string, error)) *Fetcher {
|
||||
config := utils.SSRFSafeHTTPClientConfig{
|
||||
Timeout: timeout,
|
||||
MaxRedirects: 10,
|
||||
}
|
||||
fetcher := &Fetcher{
|
||||
timeout: timeout,
|
||||
maxBodySize: maxBodySize,
|
||||
validateURL: utils.ValidateURLForSSRF,
|
||||
resolveIPs: lookupPublicDNS,
|
||||
renderBrowser: renderBrowser,
|
||||
}
|
||||
transport := utils.NewSSRFSafeTransport(config)
|
||||
transport.DialContext = fetcher.pinnedDialContext()
|
||||
fetcher.client = utils.NewSSRFSafeHTTPClientWithTransport(config, transport)
|
||||
return fetcher
|
||||
}
|
||||
|
||||
// FetchURLContent preserves the existing package-level API for the chat pipeline.
|
||||
func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
|
||||
return NewPipelineFetcher().Fetch(ctx, rawURL)
|
||||
}
|
||||
|
||||
// Fetch downloads a page and returns clean text content.
|
||||
func (f *Fetcher) Fetch(ctx context.Context, rawURL string) (string, error) {
|
||||
if strings.TrimSpace(rawURL) == "" {
|
||||
return "", newFetchError(ErrorInvalidURL, false, "url is empty")
|
||||
}
|
||||
parsedURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return "", newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
|
||||
}
|
||||
if (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") || parsedURL.Hostname() == "" {
|
||||
return "", newFetchError(ErrorInvalidURL, false, "invalid URL format")
|
||||
}
|
||||
if err := f.validateURL(rawURL); err != nil {
|
||||
return "", classifyValidationError(err)
|
||||
}
|
||||
|
||||
requestCtx, cancel := context.WithTimeout(ctx, f.timeout)
|
||||
defer cancel()
|
||||
httpResult, httpErr := f.fetchHTTP(requestCtx, rawURL, parsedURL)
|
||||
if httpErr == nil {
|
||||
content, parseErr := f.extractContent(httpResult)
|
||||
if parseErr != nil && f.markdown {
|
||||
return "", parseErr
|
||||
}
|
||||
requiresBrowser := parseErr == nil && (!f.markdown || isHTMLContent(httpResult.contentType)) &&
|
||||
needsBrowserFallback(content, httpResult.body)
|
||||
if parseErr == nil && strings.TrimSpace(content) != "" && !requiresBrowser {
|
||||
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 := f.extractContent(&httpFetchResult{
|
||||
body: []byte(rendered), finalURL: browserURL, contentType: "text/html",
|
||||
})
|
||||
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) == "" || requiresBrowser {
|
||||
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 := f.extractContent(&httpFetchResult{
|
||||
body: []byte(rendered), finalURL: rawURL, contentType: "text/html",
|
||||
})
|
||||
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 nil, newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
|
||||
}
|
||||
setBrowserHeaders(req, parsedURL)
|
||||
resp, err := f.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, classifyRequestError(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
success := resp.StatusCode == http.StatusOK
|
||||
if f.markdown {
|
||||
success = resp.StatusCode >= 200 && resp.StatusCode < 300
|
||||
}
|
||||
if !success {
|
||||
return nil, classifyHTTPStatus(resp.StatusCode, resp.Status)
|
||||
}
|
||||
readLimit := f.maxBodySize
|
||||
if f.markdown {
|
||||
readLimit++
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, readLimit))
|
||||
if err != nil {
|
||||
return nil, newFetchError(ErrorRead, true, "read failed: %v", err)
|
||||
}
|
||||
if f.markdown && int64(len(body)) > f.maxBodySize {
|
||||
return nil, newFetchError(ErrorBodyTooLarge, false, "page exceeds the %d byte download limit", f.maxBodySize)
|
||||
}
|
||||
rawContentType := resp.Header.Get("Content-Type")
|
||||
contentType, _, _ := mime.ParseMediaType(rawContentType)
|
||||
if contentType == "" {
|
||||
contentType, _, _ = mime.ParseMediaType(http.DetectContentType(body))
|
||||
}
|
||||
if isHTMLContent(contentType) {
|
||||
body = decodeHTMLBody(body, rawContentType)
|
||||
}
|
||||
finalURL := rawURL
|
||||
if resp.Request != nil && resp.Request.URL != nil {
|
||||
finalURL = resp.Request.URL.String()
|
||||
}
|
||||
return &httpFetchResult{body: body, finalURL: finalURL, contentType: contentType}, nil
|
||||
}
|
||||
|
||||
// decodeHTMLBody converts an HTML body to UTF-8 when the page declares a
|
||||
// different charset through a BOM, the Content-Type header, or a <meta> tag.
|
||||
// Valid UTF-8 and undeclared bodies are returned unchanged: the HTML default
|
||||
// (windows-1252) would corrupt undeclared UTF-8 pages with an ASCII-only head.
|
||||
func decodeHTMLBody(body []byte, contentType string) []byte {
|
||||
if utf8.Valid(body) {
|
||||
return body
|
||||
}
|
||||
enc, name, certain := charset.DetermineEncoding(body, contentType)
|
||||
if enc == encoding.Nop || (!certain && name == "windows-1252") {
|
||||
return body
|
||||
}
|
||||
decoded, err := enc.NewDecoder().Bytes(body)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
// Whitelist-only mode refuses a non-whitelisted name before the
|
||||
// lookup (#3378).
|
||||
if err := utils.CheckDialWhitelistOnly(host); err != nil {
|
||||
return nil, fmt.Errorf("connection blocked: %w", err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
// Try validated addresses without a second DNS lookup. A broken IPv6 route
|
||||
// must not prevent reaching the same public host over IPv4.
|
||||
var lastErr error
|
||||
for _, ip := range ips {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
dialCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
dial := f.dialContext
|
||||
if dial == nil {
|
||||
dial = (&net.Dialer{KeepAlive: 30 * time.Second}).DialContext
|
||||
}
|
||||
conn, err := dial(dialCtx, network, net.JoinHostPort(ip.String(), port))
|
||||
cancel()
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Fetcher) fetchWithBrowser(ctx context.Context, rawURL string) (string, error) {
|
||||
target, err := f.resolvePinnedTarget(ctx, rawURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return f.renderBrowser(ctx, target)
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
// Whitelist-only mode refuses a host outside the whitelist before the
|
||||
// lookup (#3378); a whitelisted one is still resolved to pin the render.
|
||||
if err := utils.CheckSSRFWhitelistOnly(parsedURL.Hostname()); err != nil {
|
||||
return pinnedTarget{}, newFetchError(ErrorSSRFRejected, false, "%w", err)
|
||||
}
|
||||
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()
|
||||
// Child of the fetch context: a full PageFetchTimeout here cannot outlive
|
||||
// the parent budget, so HTTP and chromedp share one deadline instead of stacking.
|
||||
browserCtx, cancelTimeout := context.WithTimeout(browserCtx, PageFetchTimeout())
|
||||
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)
|
||||
}
|
||||
if len(html) > maxAgentBodySize {
|
||||
return "", newFetchError(ErrorBodyTooLarge, false, "rendered page exceeds download limit")
|
||||
}
|
||||
return html, nil
|
||||
}
|
||||
|
||||
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) {
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
req.Header.Set("Pragma", "no-cache")
|
||||
req.Header.Set("Sec-Ch-Ua", `"Chromium";v="131", "Not_A Brand";v="24"`)
|
||||
req.Header.Set("Sec-Ch-Ua-Mobile", "?0")
|
||||
req.Header.Set("Sec-Ch-Ua-Platform", `"macOS"`)
|
||||
req.Header.Set("Sec-Fetch-Dest", "document")
|
||||
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
req.Header.Set("Sec-Fetch-Site", "none")
|
||||
req.Header.Set("Sec-Fetch-User", "?1")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
req.Header.Set("Referer", parsedURL.Scheme+"://"+parsedURL.Hostname()+"/")
|
||||
}
|
||||
|
||||
func classifyHTTPStatus(statusCode int, status string) error {
|
||||
switch {
|
||||
case statusCode == http.StatusForbidden:
|
||||
return newFetchError(ErrorHTTP403, false, "HTTP %s", status)
|
||||
case statusCode == http.StatusTooManyRequests:
|
||||
return newFetchError(ErrorHTTP429, true, "HTTP %s", status)
|
||||
case statusCode >= http.StatusInternalServerError:
|
||||
return newFetchError(ErrorHTTP5xx, true, "HTTP %s", status)
|
||||
default:
|
||||
return newFetchError(ErrorHTTPStatus, false, "HTTP %s", status)
|
||||
}
|
||||
}
|
||||
|
||||
func classifyValidationError(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)
|
||||
}
|
||||
return newFetchError(ErrorSSRFRejected, false, "URL rejected: %v", err)
|
||||
}
|
||||
|
||||
func classifyRequestError(err error) error {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return newFetchError(ErrorTimeout, true, "fetch timed out: %v", err)
|
||||
}
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
return newFetchError(ErrorDNS, true, "DNS lookup failed: %v", err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
return newFetchError(ErrorTimeout, true, "fetch timed out: %v", err)
|
||||
}
|
||||
var unknownAuthority x509.UnknownAuthorityError
|
||||
var certificateInvalid x509.CertificateInvalidError
|
||||
var hostnameError x509.HostnameError
|
||||
var recordHeaderError tls.RecordHeaderError
|
||||
if errors.As(err, &unknownAuthority) || errors.As(err, &certificateInvalid) ||
|
||||
errors.As(err, &hostnameError) || errors.As(err, &recordHeaderError) {
|
||||
return newFetchError(ErrorTLS, false, "TLS validation failed: %v", err)
|
||||
}
|
||||
if errors.Is(err, utils.ErrSSRFRedirectBlocked) {
|
||||
return newFetchError(ErrorRedirectRejected, false, "redirect rejected: %v", err)
|
||||
}
|
||||
var urlErr *url.Error
|
||||
if errors.As(err, &urlErr) {
|
||||
redirectMessage := strings.ToLower(urlErr.Err.Error())
|
||||
if strings.Contains(redirectMessage, "redirect") || strings.Contains(redirectMessage, "stopped after") {
|
||||
return newFetchError(ErrorRedirectRejected, false, "redirect rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
if strings.Contains(message, "certificate") || strings.Contains(message, "tls") {
|
||||
return newFetchError(ErrorTLS, false, "TLS validation failed: %v", err)
|
||||
}
|
||||
return newFetchError(ErrorConnection, true, "fetch failed: %v", err)
|
||||
}
|
||||
|
||||
func newFetchError(code ErrorCode, retryable bool, format string, args ...interface{}) error {
|
||||
return &FetchError{Code: code, Retryable: retryable, Err: fmt.Errorf(format, args...)}
|
||||
}
|
||||
|
||||
func htmlToText(html string) (string, error) {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
|
||||
if err != nil {
|
||||
fallback := stripTags(html)
|
||||
if fallback == "" {
|
||||
return "", newFetchError(ErrorHTMLParse, false, "HTML parse failed: %v", err)
|
||||
}
|
||||
return fallback, nil
|
||||
}
|
||||
doc.Find("script, style, nav, footer, header, iframe, noscript, svg, img").Remove()
|
||||
|
||||
var builder strings.Builder
|
||||
doc.Find("body").Each(func(_ int, selection *goquery.Selection) {
|
||||
builder.WriteString(selection.Text())
|
||||
})
|
||||
lines := strings.Split(builder.String(), "\n")
|
||||
cleaned := make([]string, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" {
|
||||
cleaned = append(cleaned, line)
|
||||
}
|
||||
}
|
||||
return strings.Join(cleaned, "\n"), nil
|
||||
}
|
||||
|
||||
func stripTags(html string) string {
|
||||
var builder strings.Builder
|
||||
inTag := false
|
||||
for _, char := range html {
|
||||
switch char {
|
||||
case '<':
|
||||
inTag = true
|
||||
case '>':
|
||||
inTag = false
|
||||
default:
|
||||
if !inTag {
|
||||
builder.WriteRune(char)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(builder.String())
|
||||
}
|
||||
|
||||
func isHTMLContent(contentType string) bool {
|
||||
return contentType == "text/html" || contentType == "application/xhtml+xml"
|
||||
}
|
||||
|
||||
func (f *Fetcher) extractContent(result *httpFetchResult) (string, error) {
|
||||
if !f.markdown {
|
||||
return htmlToText(string(result.body))
|
||||
}
|
||||
if isHTMLContent(result.contentType) {
|
||||
return htmlToMarkdown(string(result.body), result.finalURL)
|
||||
}
|
||||
if strings.HasPrefix(result.contentType, "text/") ||
|
||||
result.contentType == "application/json" || result.contentType == "application/xml" ||
|
||||
strings.HasSuffix(result.contentType, "+json") || strings.HasSuffix(result.contentType, "+xml") {
|
||||
if !utf8.Valid(result.body) || strings.ContainsRune(string(result.body), 0) {
|
||||
return "", newFetchError(ErrorUnsupportedContent, false, "page is not UTF-8 text")
|
||||
}
|
||||
return strings.TrimSpace(string(result.body)), nil
|
||||
}
|
||||
return "", newFetchError(ErrorUnsupportedContent, false,
|
||||
"unsupported page content type: %s; use an appropriate document reader", result.contentType)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
)
|
||||
|
||||
func TestFetcherDecodesHTMLCharset(t *testing.T) {
|
||||
const text = "腾讯知识库网页正文"
|
||||
gbk := func(html string) []byte {
|
||||
encoded, err := simplifiedchinese.GBK.NewEncoder().String(html)
|
||||
require.NoError(t, err)
|
||||
return []byte(encoded)
|
||||
}
|
||||
// An ASCII-only first KB with no declared charset must still be read as UTF-8.
|
||||
asciiPrefix := "<!-- " + strings.Repeat("x", 1100) + " -->"
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
contentType string
|
||||
body []byte
|
||||
}{
|
||||
{
|
||||
name: "gbk header",
|
||||
contentType: "text/html; charset=gbk",
|
||||
body: gbk("<html><body><main>" + text + "</main></body></html>"),
|
||||
},
|
||||
{
|
||||
name: "gbk meta only",
|
||||
contentType: "text/html",
|
||||
body: gbk(`<html><head><meta charset="gbk"></head><body><main>` + text + "</main></body></html>"),
|
||||
},
|
||||
{
|
||||
name: "utf-8 header",
|
||||
contentType: "text/html; charset=utf-8",
|
||||
body: []byte("<html><body><main>" + text + "</main></body></html>"),
|
||||
},
|
||||
{
|
||||
name: "undeclared utf-8",
|
||||
contentType: "text/html",
|
||||
body: []byte("<html>" + asciiPrefix + "<body><main>" + text + "</main></body></html>"),
|
||||
},
|
||||
} {
|
||||
for _, markdown := range []bool{false, true} {
|
||||
name := tc.name + "/pipeline"
|
||||
if markdown {
|
||||
name = tc.name + "/agent"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.Header().Set("Content-Type", tc.contentType)
|
||||
_, _ = writer.Write(tc.body)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
fetcher := newTestFetcher(server.Client())
|
||||
if markdown {
|
||||
fetcher.markdown = true
|
||||
fetcher.maxBodySize = maxAgentBodySize
|
||||
}
|
||||
content, err := fetcher.Fetch(context.Background(), server.URL)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, content, text)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFetchURLContentBlocksRedirectToLoopback(t *testing.T) {
|
||||
internalHit := make(chan struct{}, 1)
|
||||
internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
internalHit <- struct{}{}
|
||||
fmt.Fprint(w, "<html><body>ACADEMY_INTERNAL_CANARY_178193</body></html>")
|
||||
}))
|
||||
defer internal.Close()
|
||||
|
||||
if _, err := FetchURLContent(context.Background(), internal.URL); err == nil {
|
||||
t.Fatal("direct loopback URL was not rejected")
|
||||
}
|
||||
|
||||
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, internal.URL, http.StatusFound)
|
||||
}))
|
||||
defer attacker.Close()
|
||||
|
||||
got, err := FetchURLContent(context.Background(), attacker.URL+"/entry")
|
||||
if err == nil {
|
||||
if strings.Contains(got, "ACADEMY_INTERNAL_CANARY_178193") {
|
||||
t.Fatalf("redirect followed to loopback, got %q", got)
|
||||
}
|
||||
t.Fatal("expected redirect to loopback to be blocked")
|
||||
}
|
||||
select {
|
||||
case <-internalHit:
|
||||
t.Fatal("internal loopback server was reached via redirect")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
return function(request)
|
||||
}
|
||||
|
||||
func TestFetcherFetchSuccess(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte("<html><body><main>official specifications</main></body></html>"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
fetcher := newTestFetcher(server.Client())
|
||||
content, err := fetcher.Fetch(context.Background(), server.URL)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, content, "official specifications")
|
||||
}
|
||||
|
||||
func TestFetcherClassifiesHTTPStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
code ErrorCode
|
||||
retryable bool
|
||||
}{
|
||||
{name: "forbidden", status: http.StatusForbidden, code: ErrorHTTP403, retryable: false},
|
||||
{name: "rate limited", status: http.StatusTooManyRequests, code: ErrorHTTP429, retryable: true},
|
||||
{name: "server error", status: http.StatusServiceUnavailable, code: ErrorHTTP5xx, retryable: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(test.status)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := newTestFetcher(server.Client()).Fetch(context.Background(), server.URL)
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
assert.Equal(t, test.code, code)
|
||||
assert.Equal(t, test.retryable, retryable)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetcherClassifiesNetworkFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
code ErrorCode
|
||||
retryable bool
|
||||
}{
|
||||
{name: "dns", err: &net.DNSError{Err: "no such host", Name: "invalid.example"}, code: ErrorDNS, retryable: true},
|
||||
{name: "timeout", err: context.DeadlineExceeded, code: ErrorTimeout, retryable: true},
|
||||
{name: "tls", err: x509.HostnameError{Host: "example.com"}, code: ErrorTLS, retryable: false},
|
||||
{name: "redirect", err: errors.New("redirect blocked by SSRF private address"), code: ErrorRedirectRejected, retryable: false},
|
||||
{name: "dial-time SSRF", err: errors.New("connection blocked: host resolves to restricted IP"), code: ErrorSSRFRejected, retryable: false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return nil, test.err
|
||||
})}
|
||||
_, err := newTestFetcher(client).Fetch(context.Background(), "https://example.com")
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
assert.Equal(t, test.code, code)
|
||||
assert.Equal(t, test.retryable, retryable)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetcherClassifiesDNSFailureDuringSSRFValidation(t *testing.T) {
|
||||
fetcher := newTestFetcher(&http.Client{})
|
||||
fetcher.validateURL = func(string) error {
|
||||
return errors.New("SSRF validation failed: DNS resolution failed for hostname unavailable.example")
|
||||
}
|
||||
|
||||
_, err := fetcher.Fetch(context.Background(), "https://unavailable.example")
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
|
||||
assert.Equal(t, ErrorDNS, code)
|
||||
assert.True(t, retryable)
|
||||
}
|
||||
|
||||
func TestFetcherRejectsEmptyContent(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte("<html><body><script>ignored()</script></body></html>"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := newTestFetcher(server.Client()).Fetch(context.Background(), server.URL)
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
assert.Equal(t, ErrorEmptyContent, code)
|
||||
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) {
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "")
|
||||
assert.Equal(t, 30*time.Second, NewFetcher().timeout)
|
||||
assert.Equal(t, PageFetchTimeout(), NewFetcher().timeout)
|
||||
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "150s")
|
||||
assert.Equal(t, 150*time.Second, NewFetcher().timeout)
|
||||
}
|
||||
|
||||
func TestNewPipelineFetcherUsesHTTPOnlyAndLegacyTimeout(t *testing.T) {
|
||||
fetcher := NewPipelineFetcher()
|
||||
assert.Equal(t, 15*time.Second, fetcher.timeout)
|
||||
assert.Nil(t, fetcher.renderBrowser)
|
||||
}
|
||||
|
||||
func TestPipelineFetcherIgnoresWebFetchToolTimeout(t *testing.T) {
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "180")
|
||||
fetcher := NewPipelineFetcher()
|
||||
assert.Equal(t, 15*time.Second, fetcher.timeout)
|
||||
assert.Nil(t, fetcher.renderBrowser)
|
||||
assert.Equal(t, 180*time.Second, PageFetchTimeout())
|
||||
}
|
||||
|
||||
func TestPageFetchTimeout(t *testing.T) {
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "")
|
||||
assert.Equal(t, 30*time.Second, PageFetchTimeout())
|
||||
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "150s")
|
||||
assert.Equal(t, 150*time.Second, PageFetchTimeout())
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "3m")
|
||||
assert.Equal(t, 3*time.Minute, PageFetchTimeout())
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", "180")
|
||||
assert.Equal(t, 180*time.Second, PageFetchTimeout())
|
||||
|
||||
for _, raw := range []string{"", "0", "-1", "0s", "-5s", "nope", " "} {
|
||||
t.Run("fallback_"+raw, func(t *testing.T) {
|
||||
t.Setenv("ACADEMY_WEB_FETCH_TIMEOUT", raw)
|
||||
assert.Equal(t, 30*time.Second, PageFetchTimeout())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetcherReturnsErrorWhenBrowserFallbackFailsOnSPA(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 "", errors.New("browser unavailable")
|
||||
}
|
||||
|
||||
_, err := fetcher.Fetch(context.Background(), server.URL)
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
assert.Equal(t, ErrorEmptyContent, code)
|
||||
assert.False(t, retryable)
|
||||
}
|
||||
|
||||
func TestFetcherClassifiesInvalidAndSSRFURLs(t *testing.T) {
|
||||
fetcher := NewFetcher()
|
||||
_, invalidErr := fetcher.Fetch(context.Background(), "not-a-url")
|
||||
invalidCode, invalidRetryable, _ := ErrorDetails(invalidErr)
|
||||
assert.Equal(t, ErrorInvalidURL, invalidCode)
|
||||
assert.False(t, invalidRetryable)
|
||||
|
||||
_, ssrfErr := fetcher.Fetch(context.Background(), "http://127.0.0.1:1/private")
|
||||
ssrfCode, ssrfRetryable, _ := ErrorDetails(ssrfErr)
|
||||
assert.Equal(t, ErrorSSRFRejected, ssrfCode)
|
||||
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,
|
||||
timeout: time.Second,
|
||||
maxBodySize: maxBodySize,
|
||||
validateURL: func(string) error { return nil },
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedDialFallsBackToAnotherValidatedAddress(t *testing.T) {
|
||||
var addresses []string
|
||||
expected, peer := net.Pipe()
|
||||
defer func() { _ = expected.Close() }()
|
||||
defer func() { _ = peer.Close() }()
|
||||
f := &Fetcher{
|
||||
resolveIPs: func(context.Context, string) ([]net.IP, error) {
|
||||
return []net.IP{net.ParseIP("2606:4700:4700::1111"), net.ParseIP("1.1.1.1")}, nil
|
||||
},
|
||||
dialContext: func(_ context.Context, _ string, address string) (net.Conn, error) {
|
||||
addresses = append(addresses, address)
|
||||
if len(addresses) == 1 {
|
||||
return nil, errors.New("IPv6 route unavailable")
|
||||
}
|
||||
return expected, nil
|
||||
},
|
||||
}
|
||||
conn, err := f.pinnedDialContext()(t.Context(), "tcp", "example.com:443")
|
||||
require.NoError(t, err)
|
||||
require.Same(t, expected, conn)
|
||||
require.Equal(t, []string{"[2606:4700:4700::1111]:443", "1.1.1.1:443"}, addresses)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
func whitelistOnly(t *testing.T, whitelist, only string) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", whitelist)
|
||||
t.Setenv("SSRF_WHITELIST_EXTRA", "")
|
||||
t.Setenv("SSRF_DNS_WHITELIST_ONLY", only)
|
||||
utils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(utils.ResetSSRFWhitelistForTest)
|
||||
}
|
||||
|
||||
// countingResolver stands in for DNS so a test can prove the lookup never ran.
|
||||
func countingResolver(ips ...string) (func(context.Context, string) ([]net.IP, error), *int) {
|
||||
calls := 0
|
||||
return func(context.Context, string) ([]net.IP, error) {
|
||||
calls++
|
||||
parsed := make([]net.IP, 0, len(ips))
|
||||
for _, ip := range ips {
|
||||
parsed = append(parsed, net.ParseIP(ip))
|
||||
}
|
||||
return parsed, nil
|
||||
}, &calls
|
||||
}
|
||||
|
||||
func TestResolvePinnedTargetRefusesNonWhitelistedHostWithoutDNS(t *testing.T) {
|
||||
whitelistOnly(t, "docs.internal", "true")
|
||||
resolve, calls := countingResolver("93.184.216.34")
|
||||
f := &Fetcher{resolveIPs: resolve}
|
||||
|
||||
_, err := f.resolvePinnedTarget(context.Background(), "https://outside.invalid/page")
|
||||
|
||||
if !errors.Is(err, utils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("expected the whitelist refusal, got %v", err)
|
||||
}
|
||||
var fetchErr *FetchError
|
||||
if !errors.As(err, &fetchErr) || fetchErr.Code != ErrorSSRFRejected {
|
||||
t.Fatalf("the refusal must be classified as an SSRF rejection, got %v", err)
|
||||
}
|
||||
if fetchErr.Retryable {
|
||||
t.Fatal("a whitelist refusal is permanent, not retryable")
|
||||
}
|
||||
if *calls != 0 {
|
||||
t.Fatalf("the host must not be resolved at all, got %d lookups", *calls)
|
||||
}
|
||||
}
|
||||
|
||||
// The dialer behind the fetch client is a second entry point into DNS.
|
||||
func TestPinnedDialContextRefusesNonWhitelistedHostWithoutDNS(t *testing.T) {
|
||||
whitelistOnly(t, "docs.internal", "true")
|
||||
resolve, calls := countingResolver("93.184.216.34")
|
||||
f := &Fetcher{resolveIPs: resolve}
|
||||
|
||||
_, err := f.pinnedDialContext()(context.Background(), "tcp", "outside.invalid:443")
|
||||
|
||||
if !errors.Is(err, utils.ErrSSRFHostNotWhitelisted) {
|
||||
t.Fatalf("expected the whitelist refusal, got %v", err)
|
||||
}
|
||||
if *calls != 0 {
|
||||
t.Fatalf("the host must not be resolved at all, got %d lookups", *calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePinnedTargetStillResolvesWhitelistedAndOrdinaryHosts(t *testing.T) {
|
||||
whitelistOnly(t, "docs.internal", "true")
|
||||
resolve, calls := countingResolver("93.184.216.34")
|
||||
f := &Fetcher{resolveIPs: resolve}
|
||||
|
||||
// A whitelisted host is still resolved: the render pins one address.
|
||||
if _, err := f.resolvePinnedTarget(context.Background(), "https://docs.internal/page"); err != nil {
|
||||
t.Fatalf("a whitelisted host must be fetchable: %v", err)
|
||||
}
|
||||
if *calls != 1 {
|
||||
t.Fatalf("expected one lookup for the whitelisted host, got %d", *calls)
|
||||
}
|
||||
|
||||
whitelistOnly(t, "docs.internal", "false")
|
||||
if _, err := f.resolvePinnedTarget(context.Background(), "https://outside.invalid/page"); err != nil {
|
||||
t.Fatalf("with the mode off an ordinary public host must still fetch: %v", err)
|
||||
}
|
||||
if *calls != 2 {
|
||||
t.Fatalf("expected the ordinary host to be resolved, got %d lookups", *calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
readability "codeberg.org/readeck/go-readability/v2"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
// Prefer Readability, then main/article/body, and preserve
|
||||
// source structure with Markdown. All downloads still use the shared SSRF guard.
|
||||
func htmlToMarkdown(source, rawURL string) (string, error) {
|
||||
pageURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(source))
|
||||
if err != nil {
|
||||
return "", newFetchError(ErrorHTMLParse, false, "HTML parse failed: %v", err)
|
||||
}
|
||||
title := strings.TrimSpace(doc.Find("title").First().Text())
|
||||
extractedArticle := false
|
||||
article, readErr := readability.FromReader(strings.NewReader(source), pageURL)
|
||||
if readErr == nil && article.Node != nil {
|
||||
var buf bytes.Buffer
|
||||
if article.RenderHTML(&buf) == nil && strings.TrimSpace(buf.String()) != "" {
|
||||
if extracted, parseErr := goquery.NewDocumentFromReader(&buf); parseErr == nil {
|
||||
doc = extracted
|
||||
extractedArticle = true
|
||||
if article.Title() != "" {
|
||||
title = article.Title()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Go Readability port can retain nav nodes that Mozilla removes.
|
||||
doc.Find("script, style, noscript, nav, footer, aside, iframe, svg, form").Remove()
|
||||
if !extractedArticle {
|
||||
// Apply fallback cleanup only when Readability fails. Re-selecting a
|
||||
// nested .content element after successful extraction discards sibling sections.
|
||||
doc.Find("script, style, noscript, nav, header, footer, aside").Remove()
|
||||
}
|
||||
// Resolve links against the final redirected URL; never fetch embedded resources.
|
||||
doc.Find("a[href], img[src]").Each(func(_ int, node *goquery.Selection) {
|
||||
attr := "href"
|
||||
if goquery.NodeName(node) == "img" {
|
||||
attr = "src"
|
||||
}
|
||||
raw, _ := node.Attr(attr)
|
||||
target, parseErr := url.Parse(strings.TrimSpace(raw))
|
||||
if parseErr != nil {
|
||||
node.RemoveAttr(attr)
|
||||
return
|
||||
}
|
||||
target = pageURL.ResolveReference(target)
|
||||
if target.Scheme != "http" && target.Scheme != "https" {
|
||||
node.RemoveAttr(attr)
|
||||
return
|
||||
}
|
||||
node.SetAttr(attr, target.String())
|
||||
})
|
||||
main := doc.Find("body")
|
||||
if !extractedArticle {
|
||||
if candidate := doc.Find("main, article, [role='main'], .content, #content").First(); candidate.Length() != 0 {
|
||||
main = candidate
|
||||
}
|
||||
}
|
||||
main.Find("a").Each(func(_ int, link *goquery.Selection) {
|
||||
if strings.TrimSpace(link.Text()) == "" {
|
||||
link.Remove()
|
||||
}
|
||||
})
|
||||
html, err := main.Html()
|
||||
if err != nil {
|
||||
return "", newFetchError(ErrorHTMLParse, false, "HTML extraction failed: %v", err)
|
||||
}
|
||||
conv := converter.NewConverter(converter.WithPlugins(
|
||||
base.NewBasePlugin(), commonmark.NewCommonmarkPlugin(), table.NewTablePlugin(),
|
||||
))
|
||||
markdown, err := conv.ConvertString(html)
|
||||
if err != nil {
|
||||
return "", newFetchError(ErrorHTMLParse, false, "Markdown conversion failed: %v", err)
|
||||
}
|
||||
markdown = strings.TrimSpace(markdown)
|
||||
if markdown == "" {
|
||||
return "", nil
|
||||
}
|
||||
if title != "" {
|
||||
markdown = "# " + title + "\n\n" + markdown
|
||||
}
|
||||
return markdown, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package web_fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAgentMarkdownPreservesStructureAndResolvesLinks(t *testing.T) {
|
||||
source := `<html><head><title>Reference</title></head>
|
||||
<body><nav>NOISE</nav>
|
||||
<main><h1>Guide</h1><p>Read <a href="../next">next page</a>.</p>
|
||||
<ul><li>First</li><li>Second</li></ul>
|
||||
<pre><code>if (a < b) { return a; }</code></pre>
|
||||
<table><tr><th>Name</th><th>Value</th></tr><tr><td>Count</td><td>2</td></tr></table>
|
||||
</main></body></html>`
|
||||
content, err := htmlToMarkdown(source, "https://example.com/docs/guide")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, content, "# Guide")
|
||||
assert.Contains(t, content, "[next page](https://example.com/next)")
|
||||
assert.Contains(t, content, "- First")
|
||||
assert.Contains(t, content, "if (a < b)")
|
||||
assert.Contains(t, content, "```")
|
||||
assert.Contains(t, content, "| Name")
|
||||
assert.NotContains(t, content, "NOISE")
|
||||
}
|
||||
|
||||
func TestAgentFetchContentTypesAndSizeLimit(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, contentType, body string
|
||||
code ErrorCode
|
||||
}{
|
||||
{"plain", "text/plain", "if (a < b)\n<available_files>keep me</available_files>", ""},
|
||||
{"json", "application/json", `{"value":"<tag>"}`, ""},
|
||||
{"pdf", "application/pdf", "%PDF-1.7 binary", ErrorUnsupportedContent},
|
||||
{"oversize", "text/plain", strings.Repeat("x", 1025), ErrorBodyTooLarge},
|
||||
{"binary", "text/plain", "a\x00b", ErrorUnsupportedContent},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: 200, Header: http.Header{"Content-Type": []string{tc.contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(tc.body)), Request: req,
|
||||
}, nil
|
||||
})}
|
||||
f := newTestFetcher(client)
|
||||
f.markdown, f.maxBodySize = true, 1024
|
||||
content, err := f.Fetch(context.Background(), "https://example.com/file")
|
||||
if tc.code == "" {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.body, content)
|
||||
} else {
|
||||
code, retryable, _ := ErrorDetails(err)
|
||||
assert.Equal(t, tc.code, code)
|
||||
assert.False(t, retryable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentFetchAcceptsSuccessfulHTTPStatuses(t *testing.T) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: 201, Header: http.Header{"Content-Type": []string{"text/plain"}},
|
||||
Body: io.NopCloser(strings.NewReader("created page")), Request: req,
|
||||
}, nil
|
||||
})}
|
||||
f := newTestFetcher(client)
|
||||
f.markdown = true
|
||||
content, err := f.Fetch(t.Context(), "https://example.com/page")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "created page", content)
|
||||
f.markdown = false
|
||||
_, err = f.Fetch(t.Context(), "https://example.com/page")
|
||||
require.Error(t, err, "quick-answer status behavior stays unchanged")
|
||||
}
|
||||
|
||||
// Check preservation of article sections, links, lists, tables and code.
|
||||
func TestMarkdownExtractionFixtures(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
markers []string
|
||||
}{
|
||||
{"article", []string{"FIRST_SECTION", "SECOND_SECTION", "FINAL_SECTION", "https://example.com/reference"}},
|
||||
{"structure", []string{
|
||||
"Guide", "next page", "https://example.com/next", "First item", "Second item", "if (a < b)", "Count",
|
||||
}},
|
||||
{"fallback", []string{
|
||||
"REFERENCE_DIRECTORY", "Reference entry 0", "Reference entry 11", "https://example.com/item/11",
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
source, err := os.ReadFile(filepath.Join("testdata", "extraction", tc.name+".html"))
|
||||
require.NoError(t, err)
|
||||
actual, err := htmlToMarkdown(string(source), "https://example.com/docs/guide")
|
||||
require.NoError(t, err)
|
||||
for _, marker := range tc.markers {
|
||||
require.Contains(t, strings.ReplaceAll(actual, "\\", ""), marker)
|
||||
}
|
||||
require.NotContains(t, actual, "Navigation noise")
|
||||
require.NotContains(t, actual, "Footer noise")
|
||||
if tc.name == "structure" {
|
||||
require.Contains(t, actual, " return a;", "preserve code indentation")
|
||||
require.NotContains(t, actual, "https://example.com/empty")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# Markdown extraction fixtures
|
||||
|
||||
These HTML fixtures are authored for the extraction regression tests:
|
||||
|
||||
- `article.html`: retains sibling sections around a nested `.content` element after
|
||||
successful Readability extraction.
|
||||
- `structure.html`: preserves links, lists, tables and code indentation while
|
||||
removing empty anchors and navigation noise.
|
||||
- `fallback.html`: retains directory entries and resolves relative links when
|
||||
article extraction falls back to document content.
|
||||
|
||||
Run the fixture tests from the repository root:
|
||||
|
||||
```sh
|
||||
go test ./internal/infrastructure/web_fetch -run TestMarkdownExtractionFixtures
|
||||
```
|
||||
|
||||
The tests assert content and structural preservation independently of incidental
|
||||
Markdown spacing and list marker choices.
|
||||
@@ -0,0 +1 @@
|
||||
<html><head><title>Article extraction fixture</title></head><body><nav>Navigation noise</nav><article><h1>Complete article</h1><div class="content"><p>FIRST_SECTION This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. </p></div><section><h2>Additional context</h2><p>SECOND_SECTION This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. This section describes the behavior of the public interface. It includes detailed explanations, examples, and constraints that should remain visible when the entire article is extracted. </p><p>FINAL_SECTION: See <a href="/reference">the reference</a>.</p></section></article><footer>Footer noise</footer></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
<html><head><title>Directory</title></head><body><header>Header noise</header><main><h2>REFERENCE_DIRECTORY</h2><ul><li><a href="/item/0">Reference entry 0</a></li><li><a href="/item/1">Reference entry 1</a></li><li><a href="/item/2">Reference entry 2</a></li><li><a href="/item/3">Reference entry 3</a></li><li><a href="/item/4">Reference entry 4</a></li><li><a href="/item/5">Reference entry 5</a></li><li><a href="/item/6">Reference entry 6</a></li><li><a href="/item/7">Reference entry 7</a></li><li><a href="/item/8">Reference entry 8</a></li><li><a href="/item/9">Reference entry 9</a></li><li><a href="/item/10">Reference entry 10</a></li><li><a href="/item/11">Reference entry 11</a></li></ul></main><footer>Footer noise</footer></body></html>
|
||||
@@ -0,0 +1,3 @@
|
||||
<html><head><title>Structured reference</title></head><body><main><h1>Guide</h1><p>Read <a href="../next">next page</a>. <a href="/empty"></a></p><ul><li>First item</li><li>Second item</li></ul><pre><code class="language-js">if (a < b) {
|
||||
return a;
|
||||
}</code></pre><table><tr><th>Name</th><th>Value</th></tr><tr><td>Count</td><td>2</td></tr></table></main></body></html>
|
||||
Reference in new issue
Block a user