diff --git a/internal/infrastructure/docparser/image_resolver.go b/internal/infrastructure/docparser/image_resolver.go index 59ff6ae8..e8db4297 100644 --- a/internal/infrastructure/docparser/image_resolver.go +++ b/internal/infrastructure/docparser/image_resolver.go @@ -4,7 +4,9 @@ import ( "bytes" "context" "encoding/base64" + "errors" "fmt" + "html" "image" _ "image/gif" _ "image/jpeg" @@ -21,6 +23,7 @@ import ( "strings" "time" + "github.com/Tencent/WeKnora/internal/searchutil" secutils "github.com/Tencent/WeKnora/internal/utils" "github.com/Tencent/WeKnora/internal/types" @@ -333,9 +336,15 @@ var imgHTMLDataURI = regexp.MustCompile( `(?i)]*?src\s*=\s*["'](data:image/[^;]+;base64,[^"']+)["'][^>]*?/?\s*>`, ) -var imgHTMLRelativeSrc = regexp.MustCompile( - `(?i)]*?)\bsrc\s*=\s*['"]([^'"]+)['"]([^>]*)>`, -) +// imgHTMLSrc matches an HTML tag carrying a quoted src attribute. It does +// not care what the src points at — callers select the references they handle by +// inspecting the scheme, which is how the relative and the remote paths divide +// the same tags between them. +// +// Shared with the search layer so that an image stored here can always be +// matched back to the tag it came from. See searchutil.HTMLImageSrcRegex for +// the submatch layout and the known limits. +var imgHTMLSrc = searchutil.HTMLImageSrcRegex // ResolveHTMLDataURIImages finds tags in markdown, // decodes the images, stores them via fileSvc, and replaces each tag with a markdown @@ -410,7 +419,7 @@ func (r *ImageResolver) ResolveRelativeHTMLImages( refMap map[string]types.ImageRef, savedRefs map[string]StoredImage, ) (updatedMarkdown string, images []StoredImage, err error) { - matches := imgHTMLRelativeSrc.FindAllStringSubmatchIndex(markdown, -1) + matches := imgHTMLSrc.FindAllStringSubmatchIndex(markdown, -1) if len(matches) == 0 { return markdown, nil, nil } @@ -738,15 +747,218 @@ func (r *ImageResolver) ResolveDataURIImages( return markdown, images, nil } -// ResolveRemoteImages scans a Markdown string for image references whose URL -// is http:// or https://, downloads each one through an SSRF-safe HTTP client, -// uploads the bytes via fileSvc, and replaces the original URL with the -// provider:// serving URL. +// errRemoteImageIsIcon marks the one skip reason worth aggregating: a page can +// carry hundreds of tracking pixels and spacer GIFs, and a line for each would +// drown the reasons an operator actually needs to see. +var errRemoteImageIsIcon = errors.New("filtered out as icon") + +// remoteImageResult describes one image that was fetched successfully. +type remoteImageResult struct { + // ServingURL is empty when KeepOriginalURL is set. The caller fills it in + // with the normalized request URL — NOT the raw document bytes. Later stages + // both search the document for this string and fetch it, so a padded or + // entity-encoded value satisfies neither. + ServingURL string + MimeType string + // KeepOriginalURL marks a whitelisted host. Its bytes are downloaded so that + // OCR/caption analysis can run, but it is not uploaded: the image keeps being + // served from its original host, reached through the normalized URL. + KeepOriginalURL bool +} + +// fetchAndStoreRemoteImage applies the SSRF policy, downloads the image, +// rejects icons and uploads the bytes to storage. // -// Images that fail SSRF validation, exceed size limits, or cannot be downloaded -// are left unchanged (the original URL is preserved). +// Both the Markdown and the HTML scan go through here so that the SSRF check, +// the icon filter and the whitelist behaviour cannot drift apart between the +// two syntaxes. +func fetchAndStoreRemoteImage( + ctx context.Context, + client *http.Client, + fileSvc interfaces.FileService, + tenantID uint64, + imgURL string, +) (*remoteImageResult, error) { + whitelisted := isWhitelistedImageHost(imgURL) + + if !whitelisted { + if err := secutils.ValidateURLForSSRF(imgURL); err != nil { + return nil, fmt.Errorf("blocked by SSRF policy: %w", err) + } + } + + data, mimeType, err := downloadImage(ctx, client, imgURL) + if err != nil { + return nil, fmt.Errorf("download: %w", err) + } + + if isIconImage(data) { + return nil, errRemoteImageIsIcon + } + + if whitelisted { + return &remoteImageResult{MimeType: mimeType, KeepOriginalURL: true}, nil + } + + ext := extFromMime(mimeType) + if ext == "" { + ext = extFromURLPath(imgURL) + } + if ext == "" { + ext = ".png" // safe default + } + servingURL, err := fileSvc.SaveBytes(ctx, data, tenantID, uuid.New().String()+ext, false) + if err != nil { + return nil, fmt.Errorf("save: %w", err) + } + return &remoteImageResult{ServingURL: servingURL, MimeType: mimeType}, nil +} + +// isRemoteHTTPURL reports whether raw is an absolute http(s) URL. // -// Returns the updated Markdown and a list of successfully stored images. +// The comparison is deliberately byte-exact. Downstream fetchers compare the +// scheme the same way, so anything accepted here has to be spelled the way they +// expect; per-syntax normalization belongs in the SrcOf of the scan that needs +// it, not in this predicate. +func isRemoteHTTPURL(raw string) bool { + return strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") +} + +// remotePassSpec describes one scan of a document: which references it matches, +// where the URL sits inside a match, and how to turn the raw document bytes into +// the URL to request. +type remotePassSpec struct { + Pattern *regexp.Regexp + URLGroup int + Syntax string + SrcOf func(string) string +} + +// remotePassStats accumulates the reasons a scan passed a reference over, so +// that a partially resolved document can be explained afterwards. +type remotePassStats struct { + resolved int + iconSkips int + overBudget int +} + +func (s *remotePassStats) report(syntax string) { + if s.iconSkips > 0 { + log.Printf("INFO: skipped %d %s remote image(s) as icons", s.iconSkips, syntax) + } + if s.overBudget > 0 { + log.Printf( + "WARN: remote image limit of %d reached for %s images; %d reference(s) left unresolved", + maxRemoteImages, syntax, s.overBudget, + ) + } +} + +// resolveRemoteImagePass rewrites every remote http(s) reference matched by +// spec.Pattern, replacing the span of its URL capture group with the URL the +// image will be served from: the storage URL, or the normalized original for a +// whitelisted host. Matches are walked in reverse so the spans still to be +// processed stay valid after each replacement. +func resolveRemoteImagePass( + ctx context.Context, + markdown string, + spec remotePassSpec, + client func() *http.Client, + fileSvc interfaces.FileService, + tenantID uint64, +) (string, []StoredImage) { + matches := spec.Pattern.FindAllStringSubmatchIndex(markdown, -1) + if len(matches) == 0 { + return markdown, nil + } + + var ( + images []StoredImage + stats remotePassStats + ) + + for i := len(matches) - 1; i >= 0; i-- { + m := matches[i] + start, end := m[2*spec.URLGroup], m[2*spec.URLGroup+1] + if start < 0 { + continue + } + imgURL := spec.SrcOf(markdown[start:end]) + if !isRemoteHTTPURL(imgURL) { + continue + } + + if ctx.Err() != nil { + log.Printf("WARN: remote image resolution cancelled: %v", ctx.Err()) + break + } + + if stats.resolved >= maxRemoteImages { + stats.overBudget++ + continue + } + + res, err := fetchAndStoreRemoteImage(ctx, client(), fileSvc, tenantID, imgURL) + if err != nil { + if errors.Is(err, errRemoteImageIsIcon) { + stats.iconSkips++ + } else { + log.Printf("WARN: skipped %s remote image %s: %v", spec.Syntax, imgURL, err) + } + continue + } + stats.resolved++ + + // A whitelisted host is served from where it already lives, so the + // document keeps pointing there. The span is still rewritten with the + // normalized URL: later stages both locate the image by searching the + // document for its ServingURL and fetch that same string, so the two have + // to agree, and an entity-encoded or padded attribute value satisfies + // neither. + servingURL := res.ServingURL + if res.KeepOriginalURL { + servingURL = imgURL + } + + images = append(images, StoredImage{ + OriginalRef: imgURL, + ServingURL: servingURL, + MimeType: res.MimeType, + }) + markdown = markdown[:start] + servingURL + markdown[end:] + } + + stats.report(spec.Syntax) + return markdown, images +} + +// htmlAttrSrc normalizes an HTML src attribute value into the URL to request. +// +// Three things are HTML-specific. An attribute value may be padded, so it is +// trimmed — on both sides of the decode, because an entity can itself expand to +// whitespace. It may carry entities, and `&` is the correct spelling of a +// query separator, so it is unescaped. And the scheme may be written in any +// case, while every fetcher downstream compares it byte-for-byte, so it is +// lowercased. +// +// Markdown targets get none of this: they are handed through unchanged so that +// existing documents resolve exactly the references they resolve today. +func htmlAttrSrc(raw string) string { + src := strings.TrimSpace(html.UnescapeString(strings.TrimSpace(raw))) + if i := strings.Index(src, "://"); i > 0 { + src = strings.ToLower(src[:i]) + src[i:] + } + return src +} + +// markdownSrc hands a Markdown image target through untouched. Markdown has no +// attribute quoting or entity encoding to undo, and leaving it alone is what +// keeps existing documents resolving exactly what they resolve today. +func markdownSrc(raw string) string { return raw } + +// ResolveRemoteImages downloads remote http(s) images into storage and points +// the document at the stored copies. Both Markdown image syntax and HTML +// tags with a quoted src are covered. func (r *ImageResolver) ResolveRemoteImages( ctx context.Context, markdown string, @@ -755,101 +967,38 @@ func (r *ImageResolver) ResolveRemoteImages( ) (updatedMarkdown string, images []StoredImage, err error) { markdown = UnwrapLinkedImages(markdown) - matches := imgMarkdownPattern.FindAllStringSubmatchIndex(markdown, -1) - if len(matches) == 0 { - return markdown, nil, nil + // The client owns a dedicated transport, so it is built only once a scan + // actually has something to fetch. + var httpClient *http.Client + client := func() *http.Client { + if httpClient == nil { + httpClient = secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{ + Timeout: remoteImageFetchTimeout, + MaxRedirects: 5, + }) + } + return httpClient } - // Build a shared SSRF-safe HTTP client for all downloads. - httpClient := secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{ - Timeout: remoteImageFetchTimeout, - MaxRedirects: 5, - }) + // Two scans, each with its own budget. Sharing one would let HTML images eat + // into the number of Markdown images a document already gets resolved today. + markdown, mdImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{ + Pattern: imgMarkdownPattern, + // Group 2 of imgMarkdownPattern is the target; group 1 is the alt text. + URLGroup: 2, + Syntax: "markdown", + SrcOf: markdownSrc, + }, client, fileSvc, tenantID) - processed := 0 - - // Process in reverse order so that earlier indices stay valid after replacements. - for i := len(matches) - 1; i >= 0; i-- { - if processed >= maxRemoteImages { - break - } - m := matches[i] - imgURL := markdown[m[4]:m[5]] // group 2: the URL - - // Only process remote http(s) URLs. - if !strings.HasPrefix(imgURL, "http://") && !strings.HasPrefix(imgURL, "https://") { - continue - } - - // Already a provider scheme — skip. - if isProviderScheme(imgURL) { - continue - } - - // For whitelisted hosts: download to validate (mime type, icon check), - // create StoredImage for downstream OCR/caption analysis, but do NOT - // upload to storage and keep the original URL in markdown. - // The multimodal service will download from the original URL later. - whitelisted := isWhitelistedImageHost(imgURL) - - // --- SSRF check (skip for whitelisted) --- - if !whitelisted { - if err := secutils.ValidateURLForSSRF(imgURL); err != nil { - log.Printf("WARN: remote image blocked by SSRF check (%v): %s", err, imgURL) - continue - } - } - - // --- Download --- - data, mimeType, dlErr := downloadImage(ctx, httpClient, imgURL) - if dlErr != nil { - log.Printf("WARN: failed to download remote image %s: %v", imgURL, dlErr) - continue - } - - // Filter out icons / tiny decorative images. - if isIconImage(data) { - continue - } - - // Determine file extension. - ext := extFromMime(mimeType) - if ext == "" { - ext = extFromURLPath(imgURL) - } - if ext == "" { - ext = ".png" // safe default - } - - var servingURL string - if whitelisted { - // Keep the original URL — ImageMultimodalService will download it - // directly for OCR/caption analysis. - servingURL = imgURL - } else { - // --- Upload to storage --- - fileName := uuid.New().String() + ext - var saveErr error - servingURL, saveErr = fileSvc.SaveBytes(ctx, data, tenantID, fileName, false) - if saveErr != nil { - log.Printf("WARN: failed to save remote image %s: %v", imgURL, saveErr) - continue - } - } - - images = append(images, StoredImage{ - OriginalRef: imgURL, - ServingURL: servingURL, - MimeType: mimeType, - }) - - if !whitelisted { - // Replace URL in markdown. - markdown = markdown[:m[4]] + servingURL + markdown[m[5]:] - } - processed++ - } + markdown, htmlImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{ + Pattern: imgHTMLSrc, + URLGroup: searchutil.HTMLImageSrcURLGroup, + Syntax: "html", + SrcOf: htmlAttrSrc, + }, client, fileSvc, tenantID) + images = append(images, mdImages...) + images = append(images, htmlImages...) return markdown, images, nil } diff --git a/internal/infrastructure/docparser/mineru_converter.go b/internal/infrastructure/docparser/mineru_converter.go index 5117810a..b2e6cf10 100644 --- a/internal/infrastructure/docparser/mineru_converter.go +++ b/internal/infrastructure/docparser/mineru_converter.go @@ -373,7 +373,7 @@ func extractImageRefsFromContent(content string) []string { refs = append(refs, strings.TrimSpace(match[2])) } } - for _, match := range imgHTMLRelativeSrc.FindAllStringSubmatch(content, -1) { + for _, match := range imgHTMLSrc.FindAllStringSubmatch(content, -1) { if len(match) >= 3 { refs = append(refs, match[2]) } diff --git a/internal/infrastructure/docparser/resolve_remote_html_images_test.go b/internal/infrastructure/docparser/resolve_remote_html_images_test.go new file mode 100644 index 00000000..6b6ee55e --- /dev/null +++ b/internal/infrastructure/docparser/resolve_remote_html_images_test.go @@ -0,0 +1,406 @@ +package docparser + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + secutils "github.com/Tencent/WeKnora/internal/utils" +) + +// remoteImageServer serves a valid PNG for every request and counts the hits so +// that budget and dedup behaviour can be asserted directly. +func remoteImageServer(t *testing.T) (*httptest.Server, *int64) { + t.Helper() + var hits int64 + png := createTestPNG(200, 200) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt64(&hits, 1) + w.Header().Set("Content-Type", "image/png") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(png) + })) + t.Cleanup(ts.Close) + return ts, &hits +} + +func allowLocalhost(t *testing.T) { + t.Helper() + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + secutils.ResetSSRFWhitelistForTest() +} + +func resolve(t *testing.T, markdown string) (string, []StoredImage, *mockFileService) { + t.Helper() + fSvc := &mockFileService{} + updated, images, err := NewImageResolver().ResolveRemoteImages( + context.Background(), markdown, fSvc, 42) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + return updated, images, fSvc +} + +func TestResolveRemoteImages_HTMLTagRewritesSrcAndKeepsTag(t *testing.T) { + allowLocalhost(t) + ts, _ := remoteImageServer(t) + + markdown := fmt.Sprintf( + `

login screen

`, ts.URL) + + updated, images, _ := resolve(t, markdown) + + if len(images) != 1 { + t.Fatalf("expected 1 stored image, got %d", len(images)) + } + if strings.Contains(updated, ts.URL) { + t.Errorf("original URL still present: %s", updated) + } + if !strings.Contains(updated, images[0].ServingURL) { + t.Errorf("serving URL missing from output: %s", updated) + } + // The surrounding markup is the reason these documents use HTML at all. + for _, want := range []string{``} { + if !strings.Contains(updated, want) { + t.Errorf("tag structure lost, %q missing from: %s", want, updated) + } + } + if strings.Contains(updated, "![") { + t.Errorf("tag was converted to markdown syntax: %s", updated) + } +} + +func TestResolveRemoteImages_MarkdownAndHTMLBothResolved(t *testing.T) { + allowLocalhost(t) + ts, _ := remoteImageServer(t) + + markdown := fmt.Sprintf("![md](%s/md.png)\n\n", ts.URL, ts.URL) + + updated, images, _ := resolve(t, markdown) + + if len(images) != 2 { + t.Fatalf("expected 2 stored images, got %d", len(images)) + } + if strings.Contains(updated, ts.URL) { + t.Errorf("a remote URL survived: %s", updated) + } +} + +func TestResolveRemoteImages_IndependentBudgetPerSyntax(t *testing.T) { + allowLocalhost(t) + ts, _ := remoteImageServer(t) + + // Adding HTML support must not reduce how many Markdown images a document + // already gets resolved: each syntax carries its own budget. + var b strings.Builder + for i := 0; i < maxRemoteImages; i++ { + fmt.Fprintf(&b, "![md%d](%s/md%d.png)\n\n", i, ts.URL, i) + } + for i := 0; i < 5; i++ { + fmt.Fprintf(&b, "\n\n", ts.URL, i) + } + + updated, images, _ := resolve(t, b.String()) + + if len(images) != maxRemoteImages+5 { + t.Fatalf("expected %d stored images, got %d", maxRemoteImages+5, len(images)) + } + if strings.Contains(updated, ts.URL) { + t.Errorf("a remote URL survived: %s", updated) + } +} + +func TestResolveRemoteImages_HTMLSrcNormalization(t *testing.T) { + allowLocalhost(t) + ts, _ := remoteImageServer(t) + + t.Run("uppercase scheme", func(t *testing.T) { + upper := strings.Replace(ts.URL, "http://", "HTTP://", 1) + updated, images, _ := resolve(t, fmt.Sprintf(``, upper)) + if len(images) != 1 { + t.Fatalf("expected uppercase scheme to be fetched, got %d", len(images)) + } + // The scheme is normalized because every fetcher downstream compares it + // byte-for-byte; an image counted as resolved but unfetchable is worse + // than one left alone. + if strings.Contains(images[0].OriginalRef, "HTTP://") { + t.Errorf("scheme was not normalized: %q", images[0].OriginalRef) + } + if strings.Contains(updated, "HTTP://") { + t.Errorf("document still carries the uppercase scheme: %s", updated) + } + }) + + t.Run("markdown uppercase scheme is left alone", func(t *testing.T) { + // Markdown targets are handed through unchanged, so a document that + // upstream leaves untouched stays untouched. + upper := strings.Replace(ts.URL, "http://", "HTTP://", 1) + markdown := fmt.Sprintf("![x](%s/md-up.png)", upper) + updated, images, _ := resolve(t, markdown) + if len(images) != 0 { + t.Errorf("expected no markdown behaviour change, got %d image(s)", len(images)) + } + if updated != markdown { + t.Errorf("markdown content changed:\n got %q\nwant %q", updated, markdown) + } + }) + + t.Run("padded src", func(t *testing.T) { + _, images, _ := resolve(t, fmt.Sprintf(``, ts.URL)) + if len(images) != 1 { + t.Fatalf("expected padded src to be fetched, got %d", len(images)) + } + }) + + t.Run("entity encoded query", func(t *testing.T) { + var got string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r.URL.RawQuery + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(createTestPNG(200, 200)) + })) + defer srv.Close() + + _, images, _ := resolve(t, fmt.Sprintf(``, srv.URL)) + if len(images) != 1 { + t.Fatalf("expected 1 stored image, got %d", len(images)) + } + if got != "a=1&b=2" { + t.Errorf("entities were not decoded before the request: raw query %q", got) + } + }) +} + +func TestResolveRemoteImages_HTMLSrcFormsOutOfScope(t *testing.T) { + allowLocalhost(t) + ts, hits := remoteImageServer(t) + + cases := map[string]string{ + "unquoted src": fmt.Sprintf(``, ts.URL), + "srcset only": fmt.Sprintf(``, ts.URL), + "relative src": ``, + "data uri src": ``, + "provider src": ``, + "non-img tag": fmt.Sprintf(`