Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix: bound untrusted media decoding and block private url fetches (#923)

Aldino Kemal3af52ad6f3c1
diff --git a/src/.env.example b/src/.env.example
index 8d4299e2..64bf5dc6 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -80,6 +80,9 @@ WHATSAPP_CHAT_STORAGE=true
# Supports SOCKS5/HTTP/HTTPS schemes. Empty = direct connection.
# Example: WHATSAPP_PROXY=socks5://user:[email protected]:1080
WHATSAPP_PROXY=
+# Media, document, and link-preview URLs passed to the send API are fetched
+# directly, without HTTP(S)_PROXY, so the private-address check applies to the
+# address that is actually dialed.
# Chatwoot Integration
CHATWOOT_ENABLED=false
diff --git a/src/go.mod b/src/go.mod
index 47dcd032..d01448a0 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -25,6 +25,7 @@ require (
go.mau.fi/libsignal v0.2.2
go.mau.fi/whatsmeow v0.0.0-20261015105041-df33a485cc46
golang.org/x/image v0.44.0
+ golang.org/x/net v0.59.0
google.golang.org/protobuf v1.36.12
modernc.org/sqlite v1.53.0
)
@@ -67,7 +68,6 @@ require (
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
- golang.org/x/net v0.59.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
diff --git a/src/infrastructure/chatwoot/url_validation.go b/src/infrastructure/chatwoot/url_validation.go
index 8aa89ae2..124f790e 100644
--- a/src/infrastructure/chatwoot/url_validation.go
+++ b/src/infrastructure/chatwoot/url_validation.go
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
)
// maxChatwootURLLen caps the stored Chatwoot URL length.
@@ -76,12 +77,12 @@ func chatwootHostAllowlisted(host string) bool {
}
// isDisallowedSSRFIP reports whether an IP is one we refuse to let a per-device
-// Chatwoot client talk to: loopback, RFC1918/ULA private, link-local (which
-// includes the cloud metadata address 169.254.169.254), or the unspecified
-// address.
+// Chatwoot client talk to. It uses the same non-public list as caller-selected
+// media and preview fetches: loopback, private, link-local (including
+// 169.254.169.254), CGNAT (including 100.100.100.200), reserved ranges, and
+// IPv6 forms that embed those addresses.
func isDisallowedSSRFIP(ip net.IP) bool {
- return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
- ip.IsLinkLocalMulticast() || ip.IsUnspecified()
+ return utils.IsBlockedFetchIP(ip)
}
// ValidateChatwootURL canonicalizes the URL and rejects it on SSRF grounds.
diff --git a/src/infrastructure/chatwoot/url_validation_ssrf_test.go b/src/infrastructure/chatwoot/url_validation_ssrf_test.go
new file mode 100644
index 00000000..dd76f4aa
--- /dev/null
+++ b/src/infrastructure/chatwoot/url_validation_ssrf_test.go
@@ -0,0 +1,31 @@
+package chatwoot
+
+import (
+ "net"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// The per-device guard shares the media-fetch list, so ranges such as CGNAT
+// (Alibaba's 100.100.100.200 metadata) are refused like RFC1918.
+func TestValidateChatwootURLRejectsSharedNonPublicRanges(t *testing.T) {
+ origHosts := config.ChatwootAllowedHosts
+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })
+ config.ChatwootAllowedHosts = nil
+
+ for _, raw := range []string{
+ "http://100.100.100.200",
+ "http://100.64.0.1",
+ "http://198.18.0.1",
+ "http://192.0.0.1",
+ "http://[64:ff9b::a00:1]",
+ } {
+ if err := ValidateChatwootURL(raw); err == nil {
+ t.Errorf("ValidateChatwootURL(%q) = nil, want SSRF rejection", raw)
+ }
+ }
+ if !isDisallowedSSRFIP(net.ParseIP("100.100.100.200")) {
+ t.Error("isDisallowedSSRFIP(100.100.100.200) = false, want true")
+ }
+}
diff --git a/src/pkg/utils/business_message.go b/src/pkg/utils/business_message.go
index bb637161..ca03994e 100644
--- a/src/pkg/utils/business_message.go
+++ b/src/pkg/utils/business_message.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"strings"
+ "unicode/utf8"
"go.mau.fi/whatsmeow/proto/waE2E"
)
@@ -390,56 +391,134 @@ func joinNonEmptyLines(values ...string) string {
// buttonParamsJSON as a per-button-type JSON blob (undocumented,
// reverse-engineered from traffic), so only the fields relevant to rendering
// are decoded and anything unrecognized still shows the button's raw name.
+const (
+ // interactiveSummaryMaxDepth stops nested carousels from walking a compact
+ // message forever. Real carousels are one level deep.
+ interactiveSummaryMaxDepth = 5
+ // interactiveSummaryMaxBytes caps the rendered summary so a wide or deep
+ // carousel cannot multiply a leaf into an unbounded allocation.
+ interactiveSummaryMaxBytes = 16 * 1024
+)
+
func FormatInteractiveMessageSummary(im *waE2E.InteractiveMessage) string {
- var parts []string
+ var b strings.Builder
+ writeInteractiveSummary(&b, im, 0, "")
+ if b.Len() == 0 {
+ return "Interactive message"
+ }
+ return b.String()
+}
- if header := im.GetHeader(); header != nil {
- if title := header.GetTitle(); title != "" {
- parts = append(parts, title)
+// writeInteractiveSummary appends into one builder. Nested card text is written
+// once, with the "Card N: " prefix on its first line, instead of being copied
+// into a new string at every ancestor.
+func writeInteractiveSummary(b *strings.Builder, im *waE2E.InteractiveMessage, depth int, firstPrefix string) {
+ if im == nil || depth >= interactiveSummaryMaxDepth || b.Len() >= interactiveSummaryMaxBytes {
+ return
+ }
+ first := true
+ writePart := func(text string) {
+ if text == "" || b.Len() >= interactiveSummaryMaxBytes {
+ return
}
- if subtitle := header.GetSubtitle(); subtitle != "" {
- parts = append(parts, subtitle)
+ if first {
+ first = false
+ appendBoundedSummary(b, firstPrefix)
+ appendBoundedSummary(b, text)
+ return
}
+ appendBoundedSummary(b, "\n")
+ appendBoundedSummary(b, text)
+ }
+
+ if header := im.GetHeader(); header != nil {
+ writePart(header.GetTitle())
+ writePart(header.GetSubtitle())
// ExtractMediaCaption only handles top-level Get*Message() cases, not
// InteractiveMessage.Header — surface header captions here, since
// collectInteractiveMedia forwards the file itself but nothing else
// carries the caption text.
- if caption := interactiveHeaderMediaCaption(header); caption != "" {
- parts = append(parts, caption)
- }
+ writePart(interactiveHeaderMediaCaption(header))
}
if body := im.GetBody(); body != nil {
- if text := body.GetText(); text != "" {
- parts = append(parts, text)
- }
+ writePart(body.GetText())
}
if footer := im.GetFooter(); footer != nil {
- if text := footer.GetText(); text != "" {
- parts = append(parts, text)
- }
+ writePart(footer.GetText())
}
-
for _, button := range im.GetNativeFlowMessage().GetButtons() {
- if line := formatNativeFlowButton(button); line != "" {
- parts = append(parts, line)
+ if b.Len() >= interactiveSummaryMaxBytes {
+ break
}
+ writePart(formatNativeFlowButton(button))
}
// Carousels put their CTA/quick-reply buttons on each card rather than on
// the top-level NativeFlowMessage, so the loop above sees none of them —
// summarize each card (itself a full InteractiveMessage) separately.
+ carousel := im.GetCarouselMessage()
+ if carousel == nil {
+ return
+ }
+ for i, card := range carousel.GetCards() {
+ if b.Len() >= interactiveSummaryMaxBytes || !interactiveSummaryHasContent(card, depth+1) {
+ continue
+ }
+ cardPrefix := fmt.Sprintf("Card %d: ", i+1)
+ if first {
+ first = false
+ writeInteractiveSummary(b, card, depth+1, firstPrefix+cardPrefix)
+ continue
+ }
+ appendBoundedSummary(b, "\n")
+ writeInteractiveSummary(b, card, depth+1, cardPrefix)
+ }
+}
+
+func interactiveSummaryHasContent(im *waE2E.InteractiveMessage, depth int) bool {
+ if im == nil || depth >= interactiveSummaryMaxDepth {
+ return false
+ }
+ if header := im.GetHeader(); header != nil {
+ if header.GetTitle() != "" || header.GetSubtitle() != "" || interactiveHeaderMediaCaption(header) != "" {
+ return true
+ }
+ }
+ if im.GetBody().GetText() != "" || im.GetFooter().GetText() != "" {
+ return true
+ }
+ // formatNativeFlowButton renders every non-nil button, so checking for one
+ // avoids parsing its params here.
+ for _, button := range im.GetNativeFlowMessage().GetButtons() {
+ if button != nil {
+ return true
+ }
+ }
if carousel := im.GetCarouselMessage(); carousel != nil {
- for i, card := range carousel.GetCards() {
- if cardSummary := FormatInteractiveMessageSummary(card); cardSummary != "" && cardSummary != "Interactive message" {
- parts = append(parts, fmt.Sprintf("Card %d: %s", i+1, cardSummary))
+ for _, card := range carousel.GetCards() {
+ if interactiveSummaryHasContent(card, depth+1) {
+ return true
}
}
}
+ return false
+}
- if len(parts) == 0 {
- return "Interactive message"
+func appendBoundedSummary(b *strings.Builder, text string) {
+ if text == "" || b.Len() >= interactiveSummaryMaxBytes {
+ return
+ }
+ remain := interactiveSummaryMaxBytes - b.Len()
+ if len(text) > remain {
+ // Back the cut up to a rune start so a multi-byte rune is not split.
+ // An invalid byte earlier in text does not move the cut.
+ cut := remain
+ for i := 0; i < utf8.UTFMax-1 && cut > 0 && !utf8.RuneStart(text[cut]); i++ {
+ cut--
+ }
+ text = text[:cut]
}
- return strings.Join(parts, "\n")
+ b.WriteString(text)
}
// interactiveHeaderMediaCaption returns the caption on whichever media type
diff --git a/src/pkg/utils/business_message_test.go b/src/pkg/utils/business_message_test.go
index bbab7364..2957afdc 100644
--- a/src/pkg/utils/business_message_test.go
+++ b/src/pkg/utils/business_message_test.go
@@ -2,7 +2,10 @@ package utils
import (
"reflect"
+ "strings"
"testing"
+ "time"
+ "unicode/utf8"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
@@ -477,3 +480,89 @@ func TestBuildButtonsPayloadTopLevelInteractive(t *testing.T) {
t.Fatalf("interactive without buttons should not produce a payload: %+v", got)
}
}
+
+func nestCarouselSummary(body string, levels int) *waE2E.InteractiveMessage {
+ msg := &waE2E.InteractiveMessage{Body: &waE2E.InteractiveMessage_Body{Text: proto.String(body)}}
+ for i := 0; i < levels; i++ {
+ msg = &waE2E.InteractiveMessage{
+ InteractiveMessage: &waE2E.InteractiveMessage_CarouselMessage_{
+ CarouselMessage: &waE2E.InteractiveMessage_CarouselMessage{
+ Cards: []*waE2E.InteractiveMessage{msg},
+ },
+ },
+ }
+ }
+ return msg
+}
+
+func TestFormatInteractiveMessageSummaryBoundsNestedCarousel(t *testing.T) {
+ leaf := strings.Repeat("LeafText", 40)
+ deep := nestCarouselSummary(leaf, 12)
+ start := time.Now()
+ got := FormatInteractiveMessageSummary(deep)
+ if time.Since(start) > time.Second {
+ t.Fatalf("nested summary took %s", time.Since(start))
+ }
+ if strings.Contains(got, "LeafText") {
+ t.Fatalf("depth limit kept the leaf: %q", got)
+ }
+ if len(got) > interactiveSummaryMaxBytes {
+ t.Fatalf("len %d exceeds budget %d", len(got), interactiveSummaryMaxBytes)
+ }
+
+ shallow := nestCarouselSummary("Shoes", 1)
+ got = FormatInteractiveMessageSummary(shallow)
+ if got != "Card 1: Shoes" {
+ t.Fatalf("shallow carousel = %q", got)
+ }
+
+ huge := strings.Repeat("B", interactiveSummaryMaxBytes*3)
+ got = FormatInteractiveMessageSummary(&waE2E.InteractiveMessage{
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String(huge)},
+ })
+ if len(got) > interactiveSummaryMaxBytes {
+ t.Fatalf("output %d exceeds %d", len(got), interactiveSummaryMaxBytes)
+ }
+ if !strings.HasPrefix(got, "BBB") {
+ t.Fatalf("truncated summary lost the body: %q", got)
+ }
+}
+
+func TestFormatInteractiveMessageSummaryCutsAtRuneBoundary(t *testing.T) {
+ summarize := func(body string) string {
+ return FormatInteractiveMessageSummary(&waE2E.InteractiveMessage{
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String(body)},
+ })
+ }
+
+ got := summarize("\xff" + strings.Repeat("A", 20000))
+ if len(got) != interactiveSummaryMaxBytes || !strings.HasPrefix(got, "\xffAAA") {
+ t.Fatalf("an invalid byte before the cut dropped the text: len %d, prefix %q", len(got), got[:min(len(got), 8)])
+ }
+
+ got = summarize("A" + strings.Repeat("é", interactiveSummaryMaxBytes))
+ if !utf8.ValidString(got) || len(got) != interactiveSummaryMaxBytes-1 {
+ t.Fatalf("cut split a rune: len %d, valid %v", len(got), utf8.ValidString(got))
+ }
+}
+
+func TestFormatInteractiveMessageSummaryFullBodyDropsButtons(t *testing.T) {
+ body := strings.Repeat("B", interactiveSummaryMaxBytes)
+ button := &waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{
+ Name: proto.String("cta_url"),
+ ButtonParamsJSON: proto.String(`{"display_text":"` + strings.Repeat("L", 4096) + `","url":"https://acme.example/track"}`),
+ }
+ buttons := make([]*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton, 1000)
+ for i := range buttons {
+ buttons[i] = button
+ }
+ got := FormatInteractiveMessageSummary(&waE2E.InteractiveMessage{
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String(body)},
+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
+ Buttons: buttons,
+ }},
+ })
+ if got != body {
+ t.Fatalf("summary after a full body = len %d, want the body alone (len %d)", len(got), len(body))
+ }
+}
diff --git a/src/pkg/utils/general.go b/src/pkg/utils/general.go
index dd27746a..d7805619 100644
--- a/src/pkg/utils/general.go
+++ b/src/pkg/utils/general.go
@@ -2,6 +2,7 @@ package utils
import (
"bytes"
+ "context"
"fmt"
"image"
"image/color"
@@ -91,6 +92,10 @@ const (
linkPreviewMaxJPEGDimension = 400
linkPreviewImageQuality = 85
linkPreviewJPEGQuality = 80
+ // MaxPreviewHTMLBytes caps the decompressed preview document; only that
+ // prefix is parsed. Go's HTTP client gunzips before Body is read, so this
+ // limit applies to the decoded stream.
+ MaxPreviewHTMLBytes = 2 * 1024 * 1024
)
func resizeWithinBounds(src image.Image, maxDimension int) image.Image {
@@ -170,16 +175,9 @@ func isRetryableStatus(statusCode int) bool {
}
func GetMetaDataFromURL(urlStr string) (meta Metadata, err error) {
- // Create HTTP client with timeout
- client := &http.Client{
- Timeout: 15 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return fmt.Errorf("too many redirects")
- }
- return nil
- },
- }
+ // Caller-selected preview URLs cannot target loopback, private, or
+ // link-local addresses. The same client is used for the metadata image.
+ client := newUntrustedHTTPClient(15 * time.Second)
// Parse the base URL for resolving relative URLs later
baseURL, err := url.Parse(urlStr)
@@ -195,7 +193,7 @@ func GetMetaDataFromURL(urlStr string) (meta Metadata, err error) {
if err != nil {
return meta, err
}
- response, err = client.Do(req)
+ response, err = doUntrusted(client, req)
if err != nil {
return meta, err
}
@@ -215,8 +213,10 @@ func GetMetaDataFromURL(urlStr string) (meta Metadata, err error) {
return meta, fmt.Errorf("HTTP request failed with status: %s", response.Status)
}
- // Parse the HTML document
- document, err := goquery.NewDocumentFromReader(response.Body)
+ // Parse only a prefix of the decompressed body. The HTTP transport gunzips
+ // before this read, so a small gzip payload cannot expand into an unbounded
+ // token, and the og: and title tags in <head> still yield a preview.
+ document, err := goquery.NewDocumentFromReader(io.LimitReader(response.Body, MaxPreviewHTMLBytes))
if err != nil {
return meta, err
}
@@ -272,7 +272,7 @@ func GetMetaDataFromURL(urlStr string) (meta Metadata, err error) {
logrus.Warnf("Failed to create image request: %v", err)
} else {
imgReq.Header.Set("Accept", "image/avif,image/webp,image/png,image/jpeg,*/*;q=0.8")
- imgResponse, err := client.Do(imgReq)
+ imgResponse, err := doUntrusted(client, imgReq)
if err != nil {
logrus.Warnf("Failed to download image: %v", err)
} else {
@@ -300,9 +300,8 @@ func GetMetaDataFromURL(urlStr string) (meta Metadata, err error) {
} else if int64(len(imageData)) > maxImageSize {
logrus.Warnf("Downloaded image exceeds max size: %d > %d", len(imageData), maxImageSize)
} else {
- // Validate image by decoding it
- imageReader := bytes.NewReader(imageData)
- img, _, err := image.Decode(imageReader)
+ // Header dimensions are checked before the raster is allocated.
+ img, _, err := DecodeImageWithinBudget(bytes.NewReader(imageData))
if err != nil {
logrus.Warnf("Failed to decode image: %v", err)
} else {
@@ -344,17 +343,13 @@ func ContainsMention(message string) []string {
return phoneNumbers
}
-func DownloadImageFromURL(url string) ([]byte, string, error) {
- client := &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return fmt.Errorf("too many redirects")
- }
- return nil
- },
+func DownloadImageFromURL(ctx context.Context, url string) ([]byte, string, error) {
+ client := newUntrustedHTTPClient(30 * time.Second)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return nil, "", err
}
- response, err := client.Get(url)
+ response, err := doUntrusted(client, req)
if err != nil {
return nil, "", err
}
@@ -400,18 +395,13 @@ func DownloadImageFromURL(url string) ([]byte, string, error) {
// It validates that the content-type returned by the server starts with "audio/" and that the size is below
// WhatsappSettingMaxDownloadSize limit to avoid memory exhaustion. Only the MIME types defined in audio validation
// are allowed to ensure WhatsApp compatibility.
-func DownloadAudioFromURL(audioURL string) ([]byte, string, error) {
- client := &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return fmt.Errorf("too many redirects")
- }
- return nil
- },
+func DownloadAudioFromURL(ctx context.Context, audioURL string) ([]byte, string, error) {
+ client := newUntrustedHTTPClient(30 * time.Second)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, audioURL, nil)
+ if err != nil {
+ return nil, "", err
}
-
- resp, err := client.Get(audioURL)
+ resp, err := doUntrusted(client, req)
if err != nil {
return nil, "", err
}
@@ -491,18 +481,13 @@ func DownloadAudioFromURL(audioURL string) ([]byte, string, error) {
// DownloadVideoFromURL downloads a video file from the provided URL and returns the bytes and sanitized filename.
// It validates that the content-type returned by the server is one of the supported WhatsApp video formats and
// that the size does not exceed WhatsappSettingMaxDownloadSize to avoid memory exhaustion.
-func DownloadVideoFromURL(videoURL string) ([]byte, string, error) {
- client := &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return fmt.Errorf("too many redirects")
- }
- return nil
- },
+func DownloadVideoFromURL(ctx context.Context, videoURL string) ([]byte, string, error) {
+ client := newUntrustedHTTPClient(30 * time.Second)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, videoURL, nil)
+ if err != nil {
+ return nil, "", err
}
-
- resp, err := client.Get(videoURL)
+ resp, err := doUntrusted(client, req)
if err != nil {
return nil, "", err
}
@@ -607,18 +592,13 @@ func UniqueStrings(input []string) []string {
// DownloadFileFromURL downloads a file from the provided URL and returns the bytes and sanitized filename.
// It enforces max file size limit.
-func DownloadFileFromURL(fileURL string) ([]byte, string, error) {
- client := &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return fmt.Errorf("too many redirects")
- }
- return nil
- },
+func DownloadFileFromURL(ctx context.Context, fileURL string) ([]byte, string, error) {
+ client := newUntrustedHTTPClient(30 * time.Second)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileURL, nil)
+ if err != nil {
+ return nil, "", err
}
-
- resp, err := client.Get(fileURL)
+ resp, err := doUntrusted(client, req)
if err != nil {
return nil, "", err
}
diff --git a/src/pkg/utils/general_test.go b/src/pkg/utils/general_test.go
index abfe0ef1..c84ffdfc 100644
--- a/src/pkg/utils/general_test.go
+++ b/src/pkg/utils/general_test.go
@@ -2,6 +2,7 @@ package utils_test
import (
"bytes"
+ "context"
"fmt"
"image"
"image/color"
@@ -95,7 +96,12 @@ func (suite *UtilsTestSuite) TestStrToFloat64() {
assert.Equal(suite.T(), 0.0, utils.StrToFloat64(""))
}
+func (suite *UtilsTestSuite) allowLoopbackFetch() {
+ suite.T().Cleanup(utils.AllowUntrustedLoopbackForTest())
+}
+
func (suite *UtilsTestSuite) TestGetMetaDataFromURL() {
+ suite.allowLoopbackFetch()
// Use httptest.NewServer to mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<!DOCTYPE html><html><head><title>Test Title</title><meta name='description' content='Test Description'><meta property='og:image' content='http://example.com/image.jpg'></head><body></body></html>`))
@@ -110,6 +116,7 @@ func (suite *UtilsTestSuite) TestGetMetaDataFromURL() {
}
func (suite *UtilsTestSuite) TestGetMetaDataFromURLSendsBrowserHeaders() {
+ suite.allowLoopbackFetch()
// assertBrowserHeaders verifies that a request carries the full set of browser-like headers.
assertBrowserHeaders := func(t *testing.T, r *http.Request, label string) {
assert.Contains(t, r.Header.Get("User-Agent"), "Mozilla", label+": User-Agent should look browser-like")
@@ -143,6 +150,7 @@ func (suite *UtilsTestSuite) TestGetMetaDataFromURLSendsBrowserHeaders() {
}
func (suite *UtilsTestSuite) TestGetMetaDataFromURLEdgeCases() {
+ suite.allowLoopbackFetch()
// Test with OG title and Twitter image
server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<!DOCTYPE html><html><head><meta property='og:title' content='OG Title'><meta name='twitter:image' content='relative-image.jpg'></head><body></body></html>`))
@@ -198,7 +206,8 @@ func (suite *UtilsTestSuite) TestGetMetaDataFromURLEdgeCases() {
_, err = utils.GetMetaDataFromURL(slowServer.URL)
assert.Error(suite.T(), err)
- assert.Contains(suite.T(), err.Error(), "deadline exceeded")
+ errText := strings.ToLower(err.Error())
+ assert.True(suite.T(), strings.Contains(errText, "timeout") || strings.Contains(errText, "deadline exceeded"), err.Error())
// Test too many redirects
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -232,6 +241,7 @@ func (suite *UtilsTestSuite) TestGetMetaDataFromURLEdgeCases() {
}
func (suite *UtilsTestSuite) TestGetMetaDataFromURLNormalizesLinkPreviewThumbnails() {
+ suite.allowLoopbackFetch()
source := image.NewRGBA(image.Rect(0, 0, 1200, 800))
for y := 0; y < source.Bounds().Dy(); y++ {
for x := 0; x < source.Bounds().Dx(); x++ {
@@ -275,6 +285,7 @@ func (suite *UtilsTestSuite) TestGetMetaDataFromURLNormalizesLinkPreviewThumbnai
}
func (suite *UtilsTestSuite) TestDownloadImageFromURL() {
+ suite.allowLoopbackFetch()
// Use httptest.NewServer to mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/image.jpg" {
@@ -286,7 +297,7 @@ func (suite *UtilsTestSuite) TestDownloadImageFromURL() {
}))
defer server.Close() // Ensure the server is closed when the test ends
- imageData, fileName, err := utils.DownloadImageFromURL(server.URL + "/image.jpg")
+ imageData, fileName, err := utils.DownloadImageFromURL(context.Background(), server.URL+"/image.jpg")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), []byte("image data"), imageData)
assert.Equal(suite.T(), "image.jpg", fileName)
@@ -413,6 +424,7 @@ func (suite *UtilsTestSuite) TestStrToFloat64EdgeCases() {
}
func (suite *UtilsTestSuite) TestDownloadImageFromURLEdgeCases() {
+ suite.allowLoopbackFetch()
// Test non-image content type
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
@@ -420,7 +432,7 @@ func (suite *UtilsTestSuite) TestDownloadImageFromURLEdgeCases() {
}))
defer server.Close()
- _, _, err := utils.DownloadImageFromURL(server.URL)
+ _, _, err := utils.DownloadImageFromURL(context.Background(), server.URL)
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "invalid content type")
@@ -430,7 +442,7 @@ func (suite *UtilsTestSuite) TestDownloadImageFromURLEdgeCases() {
}))
defer errorServer.Close()
- _, _, err = utils.DownloadImageFromURL(errorServer.URL)
+ _, _, err = utils.DownloadImageFromURL(context.Background(), errorServer.URL)
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "HTTP request failed")
@@ -443,7 +455,7 @@ func (suite *UtilsTestSuite) TestDownloadImageFromURLEdgeCases() {
}))
defer extServer.Close()
- _, _, err = utils.DownloadImageFromURL(extServer.URL + "/image.gif")
+ _, _, err = utils.DownloadImageFromURL(context.Background(), extServer.URL+"/image.gif")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "unsupported file type")
@@ -462,28 +474,29 @@ func (suite *UtilsTestSuite) TestDownloadImageFromURLEdgeCases() {
defer validExtServer.Close()
// Test .jpg
- data, filename, err := utils.DownloadImageFromURL(validExtServer.URL + "/test.jpg")
+ data, filename, err := utils.DownloadImageFromURL(context.Background(), validExtServer.URL+"/test.jpg")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.jpg", filename)
assert.Equal(suite.T(), []byte("valid image data"), data)
// Test .png
- data, filename, err = utils.DownloadImageFromURL(validExtServer.URL + "/test.png")
+ data, filename, err = utils.DownloadImageFromURL(context.Background(), validExtServer.URL+"/test.png")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.png", filename)
// Test .webp
- data, filename, err = utils.DownloadImageFromURL(validExtServer.URL + "/test.webp")
+ data, filename, err = utils.DownloadImageFromURL(context.Background(), validExtServer.URL+"/test.webp")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.webp", filename)
// Test filename extraction with query parameters
- data, filename, err = utils.DownloadImageFromURL(validExtServer.URL + "/test.jpg?v=1&size=large")
+ data, filename, err = utils.DownloadImageFromURL(context.Background(), validExtServer.URL+"/test.jpg?v=1&size=large")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.jpg", filename)
}
func (suite *UtilsTestSuite) TestDownloadAudioFromURL() {
+ suite.allowLoopbackFetch()
// Mock original config values
origMaxSize := config.WhatsappSettingMaxDownloadSize
config.WhatsappSettingMaxDownloadSize = 1024 * 1024 // 1MB for testing
@@ -521,33 +534,33 @@ func (suite *UtilsTestSuite) TestDownloadAudioFromURL() {
defer server.Close()
// Test valid MP3 download
- data, filename, err := utils.DownloadAudioFromURL(server.URL + "/test.mp3")
+ data, filename, err := utils.DownloadAudioFromURL(context.Background(), server.URL+"/test.mp3")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.mp3", filename)
assert.Equal(suite.T(), []byte("audio data"), data)
// Test valid WAV download
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/test.wav")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/test.wav")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.wav", filename)
// Test valid OGG download
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/test.ogg")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/test.ogg")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.ogg", filename)
// Test valid M4A download
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/test.m4a")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/test.m4a")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.m4a", filename)
// Test invalid content type - should now warn but still proceed (changed behavior for Chatwoot compatibility)
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/invalid.mp3")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/invalid.mp3")
assert.NoError(suite.T(), err) // Now proceeds with warning instead of error
assert.NotEmpty(suite.T(), data)
// Test file too large by content length
- _, _, err = utils.DownloadAudioFromURL(server.URL + "/large.mp3")
+ _, _, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/large.mp3")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "exceeds maximum allowed size")
@@ -557,23 +570,23 @@ func (suite *UtilsTestSuite) TestDownloadAudioFromURL() {
}))
defer errorServer.Close()
- _, _, err = utils.DownloadAudioFromURL(errorServer.URL + "/error.mp3")
+ _, _, err = utils.DownloadAudioFromURL(context.Background(), errorServer.URL+"/error.mp3")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "HTTP request failed")
// Test filename without extension (should generate timestamp-based name)
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/no-filename/")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/no-filename/")
assert.NoError(suite.T(), err)
assert.Contains(suite.T(), filename, "audio_")
assert.Equal(suite.T(), []byte("audio without filename"), data)
// Test URL with query parameters
- data, filename, err = utils.DownloadAudioFromURL(server.URL + "/test.mp3?v=1&quality=high")
+ data, filename, err = utils.DownloadAudioFromURL(context.Background(), server.URL+"/test.mp3?v=1&quality=high")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.mp3", filename)
// Test invalid URL
- _, _, err = utils.DownloadAudioFromURL("not-a-valid-url")
+ _, _, err = utils.DownloadAudioFromURL(context.Background(), "not-a-valid-url")
assert.Error(suite.T(), err)
// Test too many redirects
@@ -582,12 +595,13 @@ func (suite *UtilsTestSuite) TestDownloadAudioFromURL() {
}))
defer redirectServer.Close()
- _, _, err = utils.DownloadAudioFromURL(redirectServer.URL + "/redirect.mp3")
+ _, _, err = utils.DownloadAudioFromURL(context.Background(), redirectServer.URL+"/redirect.mp3")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "too many redirects")
}
func (suite *UtilsTestSuite) TestDownloadVideoFromURL() {
+ suite.allowLoopbackFetch()
// Mock original config values
origMaxSize := config.WhatsappSettingMaxDownloadSize
config.WhatsappSettingMaxDownloadSize = 1024 * 1024 // 1MB for testing
@@ -622,28 +636,28 @@ func (suite *UtilsTestSuite) TestDownloadVideoFromURL() {
defer server.Close()
// Test valid MP4 download
- data, filename, err := utils.DownloadVideoFromURL(server.URL + "/test.mp4")
+ data, filename, err := utils.DownloadVideoFromURL(context.Background(), server.URL+"/test.mp4")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.mp4", filename)
assert.Equal(suite.T(), []byte("video data"), data)
// Test valid MKV download
- data, filename, err = utils.DownloadVideoFromURL(server.URL + "/test.mkv")
+ data, filename, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/test.mkv")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.mkv", filename)
// Test valid AVI download
- data, filename, err = utils.DownloadVideoFromURL(server.URL + "/test.avi")
+ data, filename, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/test.avi")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.avi", filename)
// Test invalid content type
- _, _, err = utils.DownloadVideoFromURL(server.URL + "/invalid.mp4")
+ _, _, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/invalid.mp4")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "invalid content type")
// Test file too large by content length
- _, _, err = utils.DownloadVideoFromURL(server.URL + "/large.mp4")
+ _, _, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/large.mp4")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "exceeds maximum allowed size")
@@ -653,24 +667,24 @@ func (suite *UtilsTestSuite) TestDownloadVideoFromURL() {
}))
defer errorServer.Close()
- _, _, err = utils.DownloadVideoFromURL(errorServer.URL + "/error.mp4")
+ _, _, err = utils.DownloadVideoFromURL(context.Background(), errorServer.URL+"/error.mp4")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "HTTP request failed")
// Test filename without extension (should generate timestamp-based name)
- data, filename, err = utils.DownloadVideoFromURL(server.URL + "/no-filename/")
+ data, filename, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/no-filename/")
assert.NoError(suite.T(), err)
assert.Contains(suite.T(), filename, "video_")
assert.True(suite.T(), strings.HasSuffix(filename, ".mp4"))
assert.Equal(suite.T(), []byte("video without filename"), data)
// Test URL with query parameters
- data, filename, err = utils.DownloadVideoFromURL(server.URL + "/test.mp4?v=1&quality=hd")
+ data, filename, err = utils.DownloadVideoFromURL(context.Background(), server.URL+"/test.mp4?v=1&quality=hd")
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.mp4", filename)
// Test invalid URL
- _, _, err = utils.DownloadVideoFromURL("not-a-valid-url")
+ _, _, err = utils.DownloadVideoFromURL(context.Background(), "not-a-valid-url")
assert.Error(suite.T(), err)
// Test too many redirects
@@ -679,7 +693,7 @@ func (suite *UtilsTestSuite) TestDownloadVideoFromURL() {
}))
defer redirectServer.Close()
- _, _, err = utils.DownloadVideoFromURL(redirectServer.URL + "/redirect.mp4")
+ _, _, err = utils.DownloadVideoFromURL(context.Background(), redirectServer.URL+"/redirect.mp4")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), "too many redirects")
}
diff --git a/src/pkg/utils/image_bounds.go b/src/pkg/utils/image_bounds.go
new file mode 100644
index 00000000..effe84f4
--- /dev/null
+++ b/src/pkg/utils/image_bounds.go
@@ -0,0 +1,322 @@
+package utils
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "image"
+ "io"
+ "math"
+ "os"
+
+ "github.com/disintegration/imaging"
+)
+
+const (
+ // MaxImageEdge is the longest side accepted before a full raster decode.
+ // 32768 admits long screenshots and panoramas and still bounds imaging's
+ // per-axis resize weight tables.
+ MaxImageEdge = 32768
+ // MaxImagePixels is the decoded pixel budget for every format but JPEG,
+ // about 40 megapixels. Width and height are also rejected when their
+ // product would overflow. Original mode SendImage still sends an image
+ // past these budgets, without a thumbnail.
+ MaxImagePixels = 40_000_000
+ // ThumbnailMaxWidth is the target width for a normal send thumbnail.
+ ThumbnailMaxWidth = 100
+ // ThumbnailMaxHeight stops a very narrow source from being stretched into
+ // a tall thumbnail when the width is fixed and the height is derived.
+ ThumbnailMaxHeight = 512
+ // maxJPEGPixels replaces MaxImagePixels for JPEG, so 48, 50 and 64 MP
+ // phone photos decode. The NRGBA copy made to rotate or crop the largest
+ // one still fits in maxJPEGDecodeBytes.
+ maxJPEGPixels = 80_000_000
+ // maxJPEGDecodeBytes bounds what image/jpeg allocates for one decode. It
+ // admits a 40 MP progressive or an 80 MP baseline 4:2:0 photo, and refuses
+ // a 40 MP progressive CMYK JPEG, which needs about 900 MiB.
+ maxJPEGDecodeBytes = 320 << 20
+)
+
+// ErrImageTooLarge is returned when width, height, or pixel count is outside
+// the decode budget.
+var ErrImageTooLarge = errors.New("image exceeds dimension or pixel budget")
+
+// ValidateImageDimensions rejects non-positive sizes, edges above MaxImageEdge,
+// pixel counts above MaxImagePixels, and sizes whose product overflows.
+func ValidateImageDimensions(width, height int) error {
+ return validateImageDimensions("", width, height)
+}
+
+// validateImageDimensions is ValidateImageDimensions for a decoded format. A
+// JPEG is held to maxJPEGPixels instead of MaxImagePixels.
+func validateImageDimensions(format string, width, height int) error {
+ if width <= 0 || height <= 0 {
+ return fmt.Errorf("%w: non-positive dimensions %dx%d", ErrImageTooLarge, width, height)
+ }
+ w := int64(width)
+ h := int64(height)
+ if w > math.MaxInt64/h {
+ return fmt.Errorf("%w: dimensions %dx%d overflow pixel count", ErrImageTooLarge, width, height)
+ }
+ if w > MaxImageEdge || h > MaxImageEdge {
+ return fmt.Errorf("%w: dimensions %dx%d exceed maximum edge %d", ErrImageTooLarge, width, height, MaxImageEdge)
+ }
+ limit := int64(MaxImagePixels)
+ if format == "jpeg" {
+ limit = maxJPEGPixels
+ }
+ if w*h > limit {
+ return fmt.Errorf("%w: dimensions %dx%d exceed maximum pixel count %d", ErrImageTooLarge, width, height, limit)
+ }
+ return nil
+}
+
+// ThumbnailSize fits srcW x srcH inside the thumbnail box without upscaling.
+// The result never exceeds ThumbnailMaxWidth, ThumbnailMaxHeight, or their product.
+func ThumbnailSize(srcW, srcH int) (int, int) {
+ return FitBoxSize(srcW, srcH, ThumbnailMaxWidth, ThumbnailMaxHeight)
+}
+
+// FitBoxSize fits srcW x srcH inside maxW x maxH without upscaling.
+// Neither returned edge exceeds its cap, and the product stays within maxW*maxH.
+// A zero requested dimension is not used to derive an unbounded edge.
+func FitBoxSize(srcW, srcH, maxW, maxH int) (int, int) {
+ if srcW <= 0 || srcH <= 0 || maxW <= 0 || maxH <= 0 {
+ return 0, 0
+ }
+ dstW := int64(srcW)
+ dstH := int64(srcH)
+ limitW := int64(maxW)
+ limitH := int64(maxH)
+ if dstW > limitW {
+ dstH = dstH * limitW / dstW
+ if dstH < 1 {
+ dstH = 1
+ }
+ dstW = limitW
+ }
+ if dstH > limitH {
+ dstW = dstW * limitH / dstH
+ if dstW < 1 {
+ dstW = 1
+ }
+ dstH = limitH
+ }
+ if dstW < 1 {
+ dstW = 1
+ }
+ if dstH < 1 {
+ dstH = 1
+ }
+ maxPixels := limitW * limitH
+ if dstH > 0 && dstW > maxPixels/dstH {
+ dstW = maxPixels / dstH
+ if dstW < 1 {
+ dstW = 1
+ }
+ }
+ return int(dstW), int(dstH)
+}
+
+// FitBox scales src down so both edges stay inside the box. It does not
+// enlarge a smaller image and does not derive an unbounded height from a
+// fixed width.
+func FitBox(src image.Image, maxW, maxH int) image.Image {
+ if src == nil {
+ return nil
+ }
+ bounds := src.Bounds()
+ dstW, dstH := FitBoxSize(bounds.Dx(), bounds.Dy(), maxW, maxH)
+ if dstW <= 0 || dstH <= 0 {
+ return src
+ }
+ if dstW == bounds.Dx() && dstH == bounds.Dy() {
+ return src
+ }
+ return imaging.Resize(src, dstW, dstH, imaging.Lanczos)
+}
+
+// FitThumbnail scales src down into the thumbnail box. It does not enlarge a
+// small image, and it does not derive an unbounded height from a fixed width.
+func FitThumbnail(src image.Image) image.Image {
+ return FitBox(src, ThumbnailMaxWidth, ThumbnailMaxHeight)
+}
+
+// DecodeImageWithinBudget reads image dimensions before allocating the raster.
+// Formats that cannot report a header are rejected instead of fully decoded.
+// A JPEG is also rejected when its estimated decoder memory exceeds
+// maxJPEGDecodeBytes.
+func DecodeImageWithinBudget(r io.Reader, opts ...imaging.DecodeOption) (image.Image, string, error) {
+ seeker, err := imageReaderAtStart(r)
+ if err != nil {
+ return nil, "", err
+ }
+ cfg, format, err := image.DecodeConfig(seeker)
+ if err != nil {
+ return nil, "", err
+ }
+ if err := validateImageDimensions(format, cfg.Width, cfg.Height); err != nil {
+ return nil, format, err
+ }
+ if format == "jpeg" {
+ if _, err := seeker.Seek(0, io.SeekStart); err != nil {
+ return nil, format, err
+ }
+ need, err := jpegDecodeBytes(seeker)
+ if err != nil {
+ return nil, format, err
+ }
+ if need > maxJPEGDecodeBytes {
+ return nil, format, fmt.Errorf("%w: JPEG decode needs about %d bytes, budget %d", ErrImageTooLarge, need, maxJPEGDecodeBytes)
+ }
+ }
+ if _, err := seeker.Seek(0, io.SeekStart); err != nil {
+ return nil, format, err
+ }
+ img, err := imaging.Decode(seeker, opts...)
+ if err != nil {
+ return nil, format, err
+ }
+ decoded := img.Bounds()
+ if err := validateImageDimensions(format, decoded.Dx(), decoded.Dy()); err != nil {
+ return nil, format, err
+ }
+ return img, format, nil
+}
+
+// DecodeImageFileWithinBudget opens path and decodes it only after the header
+// passes the DecodeImageWithinBudget checks.
+func DecodeImageFileWithinBudget(path string, opts ...imaging.DecodeOption) (image.Image, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ img, _, err := DecodeImageWithinBudget(file, opts...)
+ return img, err
+}
+
+// jpegDecodeBytes estimates what image/jpeg allocates from the first SOF
+// segment: one byte per component sample for the output planes, four more per
+// sample for progressive coefficient buffers, and four bytes per pixel to
+// convert a 4-component image to CMYK or an RGB-tagged 3-component image to
+// RGBA. image/jpeg reads the RGB tag from APP0 and APP14 segments anywhere
+// before EOI, so the whole stream is scanned.
+func jpegDecodeBytes(r io.Reader) (int64, error) {
+ br := bufio.NewReader(r)
+ if _, err := br.Discard(2); err != nil { // SOI
+ return 0, err
+ }
+ need := int64(-1) // set by the first SOF
+ var pixels int64
+ var comps int
+ var rgbIDs, jfif, adobeRGB bool
+ var err error
+scan:
+ for {
+ // A marker is 0xff plus optional 0xff fill bytes. Other bytes between
+ // segments, entropy-coded data included, are skipped, as image/jpeg does.
+ var b byte
+ if b, err = br.ReadByte(); err != nil {
+ break
+ }
+ if b != 0xff {
+ continue
+ }
+ marker := b
+ for marker == 0xff && err == nil {
+ marker, err = br.ReadByte()
+ }
+ switch {
+ case err != nil:
+ break scan
+ case marker == 0x00 || (marker >= 0xd0 && marker <= 0xd7):
+ continue // stuffed byte or RSTn, neither has a length
+ case marker == 0xd9: // EOI
+ break scan
+ }
+ var size [2]byte
+ if _, err = io.ReadFull(br, size[:]); err != nil {
+ break
+ }
+ n := int(binary.BigEndian.Uint16(size[:])) - 2
+ switch {
+ case marker == 0xe0 && n >= 5: // APP0; the last one decides JFIF
+ var id [5]byte
+ if _, err = io.ReadFull(br, id[:]); err != nil {
+ break scan
+ }
+ n -= 5
+ jfif = string(id[:]) == "JFIF\x00"
+ case marker == 0xee && n >= 12: // APP14
+ var app [12]byte
+ if _, err = io.ReadFull(br, app[:]); err != nil {
+ break scan
+ }
+ n -= 12
+ if string(app[:5]) == "Adobe" {
+ adobeRGB = app[11] == 0 // transform 0 is RGB
+ }
+ case need < 0 && marker&0xf0 == 0xc0 && marker != 0xc4 && marker != 0xc8 && marker != 0xcc:
+ // SOF: precision, height, width, component count, then id, HiVi,
+ // and Tq for each of at most 4 components.
+ var sof [6 + 3*4]byte
+ if n < 6+3 || n > len(sof) {
+ return 0, fmt.Errorf("unsupported JPEG SOF length %d", n)
+ }
+ if _, err = io.ReadFull(br, sof[:n]); err != nil {
+ break scan
+ }
+ height := int64(binary.BigEndian.Uint16(sof[1:3]))
+ width := int64(binary.BigEndian.Uint16(sof[3:5]))
+ comps = (n - 6) / 3
+ // Component i holds width*height*h_i*v_i/(hMax*vMax) samples.
+ var sumHV int64
+ hMax, vMax := int64(1), int64(1)
+ for i := 0; i < comps; i++ {
+ h, v := int64(sof[7+3*i]>>4), int64(sof[7+3*i]&0x0f)
+ sumHV += h * v
+ hMax, vMax = max(hMax, h), max(vMax, v)
+ }
+ samples := width * height * sumHV / (hMax * vMax)
+ need = samples
+ if marker&0x03 == 2 { // SOF2, SOF6, SOF10, and SOF14 are progressive
+ need += 4 * samples
+ }
+ pixels = width * height
+ rgbIDs = comps == 3 && sof[6] == 'R' && sof[9] == 'G' && sof[12] == 'B'
+ n = 0
+ }
+ if _, err = br.Discard(n); err != nil {
+ break
+ }
+ }
+ // Once the frame header is known, a stream may end without EOI.
+ if err != nil && (need < 0 || !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF)) {
+ return 0, err
+ }
+ if need < 0 {
+ return 0, errors.New("JPEG has no SOF segment")
+ }
+ if comps == 4 || comps == 3 && !jfif && (adobeRGB || rgbIDs) {
+ need += 4 * pixels
+ }
+ return need, nil
+}
+
+// imageReaderAtStart returns a seeker positioned for DecodeConfig.
+// Callers that already hold a size-capped byte slice pass a *bytes.Reader.
+// A non-seeker is buffered; those callers must already have capped the
+// compressed length.
+func imageReaderAtStart(r io.Reader) (io.ReadSeeker, error) {
+ if seeker, ok := r.(io.ReadSeeker); ok {
+ return seeker, nil
+ }
+ data, err := io.ReadAll(r)
+ if err != nil {
+ return nil, err
+ }
+ return bytes.NewReader(data), nil
+}
diff --git a/src/pkg/utils/image_bounds_internal_test.go b/src/pkg/utils/image_bounds_internal_test.go
new file mode 100644
index 00000000..0cfedfcb
--- /dev/null
+++ b/src/pkg/utils/image_bounds_internal_test.go
@@ -0,0 +1,46 @@
+package utils
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestJPEGDecodeBytesCountsRGBConversion(t *testing.T) {
+ // 7500x8000 4:4:4 needs 180,000,000 bytes of planes. image/jpeg converts an
+ // RGB-tagged one to RGBA as well, 240,000,000 bytes more.
+ soi := []byte{0xff, 0xd8}
+ sof := func(ids ...byte) []byte {
+ out := []byte{0xff, 0xc0, 0, 17, 8, 0x1f, 0x40, 0x1d, 0x4c, 3}
+ for _, id := range ids {
+ out = append(out, id, 0x11, 0)
+ }
+ return out
+ }
+ sos := []byte{0xff, 0xda, 0, 8, 1, 1, 0, 0, 63, 0}
+ scanData := []byte{0x12, 0x34}
+ jfif := []byte{0xff, 0xe0, 0, 7, 'J', 'F', 'I', 'F', 0}
+ adobeRGB := []byte{0xff, 0xee, 0, 14, 'A', 'd', 'o', 'b', 'e', 0, 100, 0, 0, 0, 0, 0}
+ for _, tt := range []struct {
+ name string
+ parts [][]byte
+ want int64
+ }{
+ {"YCbCr component ids", [][]byte{soi, sof(1, 2, 3), sos, scanData}, 180_000_000},
+ {"RGB component ids", [][]byte{soi, sof('R', 'G', 'B'), sos, scanData}, 420_000_000},
+ {"Adobe RGB after the first scan", [][]byte{soi, sof(1, 2, 3), sos, scanData, adobeRGB}, 420_000_000},
+ {"JFIF keeps YCbCr", [][]byte{soi, jfif, sof(1, 2, 3), sos, scanData, adobeRGB}, 180_000_000},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := jpegDecodeBytes(bytes.NewReader(bytes.Join(tt.parts, nil)))
+ require.NoError(t, err)
+ require.Equal(t, tt.want, got)
+ })
+ }
+
+ // An RGB-tagged 60 MP JPEG fits the pixel cap but not the decode budget.
+ rgb := bytes.Join([][]byte{soi, sof('R', 'G', 'B'), sos}, nil)
+ _, _, err := DecodeImageWithinBudget(bytes.NewReader(rgb))
+ require.ErrorIs(t, err, ErrImageTooLarge)
+}
diff --git a/src/pkg/utils/image_bounds_test.go b/src/pkg/utils/image_bounds_test.go
new file mode 100644
index 00000000..1da27ef0
--- /dev/null
+++ b/src/pkg/utils/image_bounds_test.go
@@ -0,0 +1,197 @@
+package utils_test
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "image"
+ "image/png"
+ "math"
+ "mime/multipart"
+ "net/textproto"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/stretchr/testify/require"
+)
+
+func pngWithIHDR(width, height uint32) []byte {
+ ihdr := make([]byte, 13)
+ binary.BigEndian.PutUint32(ihdr[0:4], width)
+ binary.BigEndian.PutUint32(ihdr[4:8], height)
+ ihdr[8] = 8
+ ihdr[9] = 2
+ payload := append([]byte("IHDR"), ihdr...)
+ var chunk bytes.Buffer
+ _ = binary.Write(&chunk, binary.BigEndian, uint32(len(ihdr)))
+ chunk.Write(payload)
+ _ = binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(payload))
+ out := []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}
+ return append(out, chunk.Bytes()...)
+}
+
+type seekCountReader struct {
+ *bytes.Reader
+ seeks int
+}
+
+func (s *seekCountReader) Seek(offset int64, whence int) (int64, error) {
+ s.seeks++
+ return s.Reader.Seek(offset, whence)
+}
+
+func TestValidateImageDimensions(t *testing.T) {
+ require.NoError(t, utils.ValidateImageDimensions(8000, 5000))
+ require.NoError(t, utils.ValidateImageDimensions(utils.MaxImageEdge, 1220))
+ require.ErrorIs(t, utils.ValidateImageDimensions(utils.MaxImageEdge+1, 1), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(1, utils.MaxImageEdge+1), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(8000, 5001), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(utils.MaxImageEdge, utils.MaxImageEdge), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(0, 10), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(math.MaxInt, 2), utils.ErrImageTooLarge)
+ require.ErrorIs(t, utils.ValidateImageDimensions(math.MaxInt, math.MaxInt), utils.ErrImageTooLarge)
+}
+
+func TestDecodeImageWithinBudgetRejectsOversizedHeaderBeforeDecode(t *testing.T) {
+ header := pngWithIHDR(20000, 20000)
+ reader := &seekCountReader{Reader: bytes.NewReader(header)}
+ img, _, err := utils.DecodeImageWithinBudget(reader)
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+ require.Zero(t, reader.seeks, "full decode seeks back to the start; rejection must happen first")
+}
+
+// jpegHeader is SOI, a JFIF APP0 (so DecodeConfig stops at SOF), and one SOF
+// segment with the given sampling factor byte per component. It carries no
+// scan data.
+func jpegHeader(sofMarker byte, width, height uint16, sampling ...byte) []byte {
+ out := []byte{0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 'J', 'F', 'I', 'F', 0x00, 1, 1, 0, 0, 1, 0, 1, 0, 0}
+ sof := []byte{8, byte(height >> 8), byte(height), byte(width >> 8), byte(width), byte(len(sampling))}
+ for i, hv := range sampling {
+ sof = append(sof, byte(i+1), hv, 0)
+ }
+ out = append(out, 0xff, sofMarker, 0, byte(len(sof)+2))
+ return append(out, sof...)
+}
+
+func TestDecodeImageWithinBudgetRejectsJPEGOverDecoderMemoryBudget(t *testing.T) {
+ // 6000x6600 is under the pixel budget, but a progressive CMYK decode
+ // allocates about 900 MiB.
+ cmyk := jpegHeader(0xc2, 6000, 6600, 0x11, 0x11, 0x11, 0x11)
+ img, _, err := utils.DecodeImageWithinBudget(bytes.NewReader(cmyk))
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+
+ // A 40 MP progressive 4:2:0 photo stays inside the budget; the header-only
+ // fixture then fails in the decoder for lack of scan data.
+ photo := jpegHeader(0xc2, 8000, 5000, 0x22, 0x11, 0x11)
+ _, _, err = utils.DecodeImageWithinBudget(bytes.NewReader(photo))
+ require.Error(t, err)
+ require.NotErrorIs(t, err, utils.ErrImageTooLarge)
+}
+
+func TestDecodeImageWithinBudgetGivesJPEGItsOwnPixelCap(t *testing.T) {
+ // A 48 MP baseline 4:2:0 phone photo is past MaxImagePixels but needs about
+ // 70 MiB to decode, so it passes the header checks.
+ phone := jpegHeader(0xc0, 8064, 6048, 0x22, 0x11, 0x11)
+ _, _, err := utils.DecodeImageWithinBudget(bytes.NewReader(phone))
+ require.Error(t, err)
+ require.NotErrorIs(t, err, utils.ErrImageTooLarge)
+ require.NoError(t, utils.ValidateGroupPhotoFormat(multipartImage(t, "phone.jpg", "image/jpeg", phone)))
+
+ // A 96 MP grayscale JPEG decodes in about 92 MiB, but rotating or cropping
+ // it would copy 384 MB, so the JPEG pixel cap refuses it.
+ _, _, err = utils.DecodeImageWithinBudget(bytes.NewReader(jpegHeader(0xc0, 16000, 6000, 0x11)))
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+
+ // Other formats keep the pixel cap; a long screenshot fits the edge cap.
+ _, _, err = utils.DecodeImageWithinBudget(bytes.NewReader(pngWithIHDR(8064, 6048)))
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ _, _, err = utils.DecodeImageWithinBudget(bytes.NewReader(pngWithIHDR(1080, 16000)))
+ require.Error(t, err)
+ require.NotErrorIs(t, err, utils.ErrImageTooLarge)
+}
+
+func TestDecodeImageWithinBudgetDecodesAcceptedImage(t *testing.T) {
+ var encoded bytes.Buffer
+ require.NoError(t, png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 3, 2))))
+ img, format, err := utils.DecodeImageWithinBudget(bytes.NewReader(encoded.Bytes()))
+ require.NoError(t, err)
+ require.Equal(t, "png", format)
+ require.Equal(t, 3, img.Bounds().Dx())
+ require.Equal(t, 2, img.Bounds().Dy())
+}
+
+func TestThumbnailSizeDoesNotUpscaleOrExplode(t *testing.T) {
+ tests := []struct {
+ name string
+ srcW, srcH int
+ maxW, maxH int
+ }{
+ {name: "landscape photo", srcW: 4000, srcH: 3000, maxW: 100, maxH: 75},
+ {name: "portrait photo", srcW: 3024, srcH: 4032, maxW: 100, maxH: 133},
+ {name: "small image is not upscaled", srcW: 20, srcH: 20, maxW: 20, maxH: 20},
+ {name: "narrow source keeps a short height", srcW: 1, srcH: 8192, maxW: utils.ThumbnailMaxWidth, maxH: utils.ThumbnailMaxHeight},
+ {name: "wide source keeps a short height", srcW: 8192, srcH: 1, maxW: utils.ThumbnailMaxWidth, maxH: 1},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotW, gotH := utils.ThumbnailSize(tt.srcW, tt.srcH)
+ require.LessOrEqual(t, gotW, tt.maxW)
+ require.LessOrEqual(t, gotH, tt.maxH)
+ require.LessOrEqual(t, gotW, utils.ThumbnailMaxWidth)
+ require.LessOrEqual(t, gotH, utils.ThumbnailMaxHeight)
+ require.LessOrEqual(t, int64(gotW)*int64(gotH), int64(utils.ThumbnailMaxWidth)*int64(utils.ThumbnailMaxHeight))
+ require.Greater(t, gotW, 0)
+ require.Greater(t, gotH, 0)
+ })
+ }
+}
+
+func TestFitThumbnailCapsNarrowImage(t *testing.T) {
+ src := image.NewNRGBA(image.Rect(0, 0, 1, 8192))
+ got := utils.FitThumbnail(src)
+ require.LessOrEqual(t, got.Bounds().Dx(), utils.ThumbnailMaxWidth)
+ require.LessOrEqual(t, got.Bounds().Dy(), utils.ThumbnailMaxHeight)
+ require.Less(t, got.Bounds().Dy(), 1000)
+}
+
+func multipartImage(t *testing.T, filename, contentType string, data []byte) *multipart.FileHeader {
+ t.Helper()
+ body := &bytes.Buffer{}
+ writer := multipart.NewWriter(body)
+ header := make(textproto.MIMEHeader)
+ header.Set("Content-Disposition", fmt.Sprintf(`form-data; name="photo"; filename="%s"`, filename))
+ header.Set("Content-Type", contentType)
+ part, err := writer.CreatePart(header)
+ require.NoError(t, err)
+ _, err = part.Write(data)
+ require.NoError(t, err)
+ require.NoError(t, writer.Close())
+
+ form, err := multipart.NewReader(body, writer.Boundary()).ReadForm(int64(len(data)) + 4096)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = form.RemoveAll() })
+ files := form.File["photo"]
+ require.NotEmpty(t, files)
+ return files[0]
+}
+
+func TestProcessGroupPhotoRejectsOversizedHeader(t *testing.T) {
+ file := multipartImage(t, "big.png", "image/png", pngWithIHDR(20000, 20000))
+ require.ErrorIs(t, utils.ValidateGroupPhotoFormat(file), utils.ErrImageTooLarge)
+ _, err := utils.ProcessGroupPhoto(file)
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+}
+
+func TestProcessGroupPhotoAcceptsSmallPNG(t *testing.T) {
+ var encoded bytes.Buffer
+ require.NoError(t, png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 16, 8))))
+ file := multipartImage(t, "ok.png", "image/png", encoded.Bytes())
+ require.NoError(t, utils.ValidateGroupPhotoFormat(file))
+ buf, err := utils.ProcessGroupPhoto(file)
+ require.NoError(t, err)
+ require.GreaterOrEqual(t, buf.Len(), 3)
+ require.Equal(t, []byte{0xff, 0xd8, 0xff}, buf.Bytes()[:3])
+}
diff --git a/src/pkg/utils/image_utils.go b/src/pkg/utils/image_utils.go
index f84264ed..58cfc2e6 100644
--- a/src/pkg/utils/image_utils.go
+++ b/src/pkg/utils/image_utils.go
@@ -31,8 +31,8 @@ func ProcessGroupPhoto(file *multipart.FileHeader) (*bytes.Buffer, error) {
}
defer src.Close()
- // Decode the image
- img, format, err := image.Decode(src)
+ // Header dimensions are checked before the raster is allocated.
+ img, format, err := DecodeImageWithinBudget(src)
if err != nil {
return nil, fmt.Errorf("failed to decode image: %w", err)
}
@@ -166,11 +166,14 @@ func ValidateGroupPhotoFormat(file *multipart.FileHeader) error {
return fmt.Errorf("failed to reset file position: %w", err)
}
- // Detect image format from header
- _, format, err := image.DecodeConfig(src)
+ // Detect image format from header and reject oversized rasters before use.
+ cfg, format, err := image.DecodeConfig(src)
if err != nil {
return fmt.Errorf("invalid image file: %w", err)
}
+ if err := validateImageDimensions(format, cfg.Width, cfg.Height); err != nil {
+ return fmt.Errorf("invalid image file: %w", err)
+ }
if format != "jpeg" && format != "png" && format != "webp" {
return fmt.Errorf("unsupported image format detected: %s", format)
diff --git a/src/pkg/utils/preview_limit_test.go b/src/pkg/utils/preview_limit_test.go
new file mode 100644
index 00000000..d717d505
--- /dev/null
+++ b/src/pkg/utils/preview_limit_test.go
@@ -0,0 +1,59 @@
+package utils_test
+
+import (
+ "bytes"
+ "compress/gzip"
+ "net/http"
+ "net/http/httptest"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetMetaDataFromURLParsesCappedPrefixOfDecompressedHTML(t *testing.T) {
+ t.Cleanup(utils.AllowUntrustedLoopbackForTest())
+ payload := []byte(`<html><head><title>Long page</title></head><body><!--` +
+ strings.Repeat("x", 32*utils.MaxPreviewHTMLBytes) +
+ `--><meta name="description" content="past the cap"></body></html>`)
+ var compressed bytes.Buffer
+ zw, err := gzip.NewWriterLevel(&compressed, gzip.BestSpeed)
+ require.NoError(t, err)
+ _, err = zw.Write(payload)
+ require.NoError(t, err)
+ require.NoError(t, zw.Close())
+ require.Less(t, compressed.Len(), utils.MaxPreviewHTMLBytes, "fixture must be small on the wire")
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
+ http.Error(w, "client did not ask for gzip", http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Encoding", "gzip")
+ _, _ = w.Write(compressed.Bytes())
+ }))
+ t.Cleanup(server.Close)
+
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ meta, err := utils.GetMetaDataFromURL(server.URL)
+ runtime.ReadMemStats(&after)
+ require.NoError(t, err)
+ require.Equal(t, "Long page", meta.Title)
+ require.Empty(t, meta.Description, "bytes past the cap must not be parsed")
+ require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(len(payload)/2), "the decoded body must not be buffered")
+}
+
+func TestGetMetaDataFromURLAcceptsHTMLUnderCap(t *testing.T) {
+ t.Cleanup(utils.AllowUntrustedLoopbackForTest())
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`<html><head><title>Short</title></head><body>ok</body></html>`))
+ }))
+ t.Cleanup(server.Close)
+
+ meta, err := utils.GetMetaDataFromURL(server.URL)
+ require.NoError(t, err)
+ require.Equal(t, "Short", meta.Title)
+}
diff --git a/src/pkg/utils/safe_http.go b/src/pkg/utils/safe_http.go
new file mode 100644
index 00000000..9363e949
--- /dev/null
+++ b/src/pkg/utils/safe_http.go
@@ -0,0 +1,414 @@
+package utils
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "mime"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+ "unicode/utf8"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "golang.org/x/net/idna"
+)
+
+const maxUntrustedRedirects = 10
+
+var errNonPublicAddress = errors.New("refusing to fetch non-public address")
+
+// untrustedFetchHooks is the test seam for caller-selected preview, document,
+// and media fetches. Production leaves it zero, which resolves through the
+// default resolver and refuses non-public addresses. Operator-configured
+// Chatwoot base URLs do not use this client.
+type untrustedFetchHooks struct {
+ lookup func(context.Context, string) ([]net.IP, error)
+ dial func(context.Context, string, string) (net.Conn, error)
+ skip bool
+}
+
+var (
+ untrustedFetchMu sync.Mutex
+ untrustedFetch untrustedFetchHooks
+)
+
+func snapshotUntrustedFetchHooks() untrustedFetchHooks {
+ untrustedFetchMu.Lock()
+ defer untrustedFetchMu.Unlock()
+ return untrustedFetch
+}
+
+// SetUntrustedFetchTestHooks overrides DNS lookup and dialing for caller-selected
+// preview, document, and media fetches. A nil lookup or dial keeps the current function.
+// skipAddressCheck lets tests reach httptest loopback servers. Production code
+// must not call this.
+func SetUntrustedFetchTestHooks(
+ lookup func(context.Context, string) ([]net.IP, error),
+ dial func(context.Context, string, string) (net.Conn, error),
+ skipAddressCheck bool,
+) (restore func()) {
+ untrustedFetchMu.Lock()
+ prev := untrustedFetch
+ next := prev
+ if lookup != nil {
+ next.lookup = lookup
+ }
+ if dial != nil {
+ next.dial = dial
+ }
+ next.skip = skipAddressCheck
+ untrustedFetch = next
+ untrustedFetchMu.Unlock()
+ return func() {
+ untrustedFetchMu.Lock()
+ untrustedFetch = prev
+ untrustedFetchMu.Unlock()
+ }
+}
+
+// AllowUntrustedLoopbackForTest disables the public-address check so tests can
+// use httptest servers. Production defaults are unchanged when the returned
+// function runs.
+func AllowUntrustedLoopbackForTest() (restore func()) {
+ return SetUntrustedFetchTestHooks(nil, nil, true)
+}
+
+// untrustedTransport is shared so keep-alive connections are pooled and expire.
+// It keeps the default HTTP/2 and idle-connection settings, replaces dialing,
+// and connects directly: a proxy would resolve the destination again after it
+// was checked, so HTTP(S)_PROXY is not used for these fetches.
+var untrustedTransport = func() *http.Transport {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.DialContext = dialUntrusted
+ return transport
+}()
+
+type chatwootAttachmentFetchKey struct{}
+
+// WithChatwootAttachmentFetch marks ctx as fetching a Chatwoot attachment. Only
+// such fetches may reach the operator-configured Chatwoot hosts, which can be
+// private; every other caller-selected URL keeps the public-address check.
+func WithChatwootAttachmentFetch(ctx context.Context) context.Context {
+ return context.WithValue(ctx, chatwootAttachmentFetchKey{}, true)
+}
+
+func newUntrustedHTTPClient(timeout time.Duration) *http.Client {
+ return &http.Client{
+ Timeout: timeout,
+ Transport: untrustedTransport,
+ CheckRedirect: untrustedCheckRedirect,
+ }
+}
+
+func doUntrusted(client *http.Client, req *http.Request) (*http.Response, error) {
+ if err := validateUntrustedURL(req.Context(), req.URL.String()); err != nil {
+ // gowa's own file URLs (from /message/:id/download or webhook media
+ // paths) point at a loopback or private address in default deployments.
+ // Serve those from disk; /statics is already public, so nothing new is
+ // exposed.
+ if errors.Is(err, errNonPublicAddress) {
+ if resp, ok := localStaticResponse(req); ok {
+ return resp, nil
+ }
+ }
+ return nil, err
+ }
+ return client.Do(req)
+}
+
+// localStaticResponse answers a GET for a gowa /statics URL from the stored
+// file. os.Root keeps the lookup inside the statics directory, whatever
+// separators or symlinks the path holds.
+func localStaticResponse(req *http.Request) (*http.Response, bool) {
+ rel, ok := strings.CutPrefix(req.URL.Path, config.AppBasePath+"/statics/")
+ if !ok || req.Method != http.MethodGet {
+ return nil, false
+ }
+ root, err := os.OpenRoot("statics")
+ if err != nil {
+ return nil, false
+ }
+ defer root.Close()
+ file, err := root.Open(filepath.FromSlash(path.Clean(rel)))
+ if err != nil {
+ return nil, false
+ }
+ info, err := file.Stat()
+ if err != nil || !info.Mode().IsRegular() {
+ _ = file.Close()
+ return nil, false
+ }
+ header := http.Header{}
+ if contentType := mime.TypeByExtension(filepath.Ext(rel)); contentType != "" {
+ header.Set("Content-Type", contentType)
+ }
+ return &http.Response{
+ Status: "200 OK",
+ StatusCode: http.StatusOK,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: header,
+ Body: file,
+ ContentLength: info.Size(),
+ Request: req,
+ }, true
+}
+
+func untrustedCheckRedirect(req *http.Request, via []*http.Request) error {
+ if len(via) >= maxUntrustedRedirects {
+ return fmt.Errorf("too many redirects")
+ }
+ return validateUntrustedURL(req.Context(), req.URL.String())
+}
+
+func validateUntrustedURL(ctx context.Context, raw string) error {
+ parsed, err := url.Parse(raw)
+ if err != nil {
+ return fmt.Errorf("invalid URL: %w", err)
+ }
+ if parsed.Scheme != "http" && parsed.Scheme != "https" {
+ return fmt.Errorf("unsupported protocol scheme %q", parsed.Scheme)
+ }
+ host := normalizeFetchHost(parsed.Hostname())
+ if host == "" {
+ return fmt.Errorf("missing host")
+ }
+ // net/http dials the punycode form of a non-ASCII host, so resolve and
+ // check that same name.
+ if strings.ContainsFunc(host, func(r rune) bool { return r >= utf8.RuneSelf }) {
+ if host, err = idna.Lookup.ToASCII(host); err != nil {
+ return fmt.Errorf("invalid host: %w", err)
+ }
+ }
+ hooks := snapshotUntrustedFetchHooks()
+ if hooks.skip || operatorTrustedHost(ctx, host, urlPort(parsed)) {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ ips, err := resolveUntrustedHost(ctx, host, hooks)
+ if err != nil {
+ return err
+ }
+ return rejectBlockedIPs(host, ips)
+}
+
+// operatorTrustedHost reports whether a Chatwoot attachment fetch (see
+// WithChatwootAttachmentFetch) targets the CHATWOOT_URL host and port, or a
+// host listed in CHATWOOT_ALLOWED_HOSTS, matched case-insensitively as the
+// chatwoot package does. Chatwoot serves attachments from these
+// operator-configured hosts, which may be private, so those fetches skip the
+// public-address check.
+func operatorTrustedHost(ctx context.Context, host, port string) bool {
+ if ctx.Value(chatwootAttachmentFetchKey{}) == nil {
+ return false
+ }
+ if base, err := url.Parse(strings.TrimSpace(config.ChatwootURL)); err == nil && strings.EqualFold(base.Hostname(), host) && urlPort(base) == port {
+ return true
+ }
+ for _, allowed := range config.ChatwootAllowedHosts {
+ if strings.EqualFold(strings.TrimSpace(allowed), host) {
+ return true
+ }
+ }
+ return false
+}
+
+// urlPort returns u's port, defaulting to the scheme's port.
+func urlPort(u *url.URL) string {
+ if port := u.Port(); port != "" {
+ return port
+ }
+ if strings.EqualFold(u.Scheme, "https") {
+ return "443"
+ }
+ return "80"
+}
+
+func normalizeFetchHost(host string) string {
+ host = strings.TrimSpace(host)
+ if zone := strings.IndexByte(host, '%'); zone >= 0 {
+ host = host[:zone]
+ }
+ return host
+}
+
+func resolveUntrustedHost(ctx context.Context, host string, hooks untrustedFetchHooks) ([]net.IP, error) {
+ if ip := net.ParseIP(host); ip != nil {
+ return []net.IP{ip}, nil
+ }
+ if hooks.lookup != nil {
+ ips, err := hooks.lookup(ctx, host)
+ if err != nil {
+ return nil, err
+ }
+ if len(ips) == 0 {
+ return nil, fmt.Errorf("no addresses for host %s", host)
+ }
+ return ips, nil
+ }
+ addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
+ if err != nil {
+ return nil, err
+ }
+ ips := make([]net.IP, 0, len(addrs))
+ for _, addr := range addrs {
+ if addr.IP != nil {
+ ips = append(ips, addr.IP)
+ }
+ }
+ if len(ips) == 0 {
+ return nil, fmt.Errorf("no addresses for host %s", host)
+ }
+ return ips, nil
+}
+
+func rejectBlockedIPs(host string, ips []net.IP) error {
+ if len(ips) == 0 {
+ return fmt.Errorf("no addresses for host %s", host)
+ }
+ for _, ip := range ips {
+ if IsBlockedFetchIP(ip) {
+ return fmt.Errorf("%w %s", errNonPublicAddress, ip)
+ }
+ }
+ return nil
+}
+
+// IPv6 transition prefixes. NAT64 well-known, IPv4-compatible, SIIT, and 6to4
+// embed an IPv4 address; local-use NAT64, Teredo, and deprecated site-local are
+// refused outright.
+var (
+ nat64WellKnown = netip.MustParsePrefix("64:ff9b::/96")
+ nat64LocalUse = netip.MustParsePrefix("64:ff9b:1::/48")
+ ipv4Compatible = netip.MustParsePrefix("::/96")
+ siit = netip.MustParsePrefix("::ffff:0:0:0/96")
+ sixToFour = netip.MustParsePrefix("2002::/16")
+ teredo = netip.MustParsePrefix("2001::/32")
+ siteLocal = netip.MustParsePrefix("fec0::/10")
+)
+
+// IsBlockedFetchIP reports whether ip is not publicly routable and must not be
+// reached by a caller-selected URL. The Chatwoot per-device guard shares it.
+func IsBlockedFetchIP(ip net.IP) bool {
+ if len(ip) == 0 || ip == nil {
+ return true
+ }
+ if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsUnspecified() {
+ return true
+ }
+ // To4 also matches IPv4-mapped IPv6, so the ranges below cover both forms.
+ v4 := ip.To4()
+ if v4 == nil {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return false
+ }
+ b := addr.As16()
+ switch {
+ case nat64LocalUse.Contains(addr), teredo.Contains(addr), siteLocal.Contains(addr):
+ return true
+ case nat64WellKnown.Contains(addr), ipv4Compatible.Contains(addr), siit.Contains(addr):
+ // These carry an IPv4 address in the last four bytes. NAT64 also
+ // maps public IPv4 for DNS64, so the prefix is not refused outright.
+ return IsBlockedFetchIP(net.IP(b[12:]))
+ case sixToFour.Contains(addr):
+ return IsBlockedFetchIP(net.IP(b[2:6]))
+ default:
+ return false
+ }
+ }
+ switch {
+ case v4[0] == 0:
+ // 0.0.0.0/8, including "this host" and 0.0.0.1.
+ return true
+ case v4[0] == 100 && v4[1]&0xc0 == 64:
+ // 100.64.0.0/10 carrier-grade NAT, including Alibaba metadata 100.100.100.200.
+ return true
+ case v4[0] == 192 && v4[1] == 0 && v4[2] == 0:
+ // 192.0.0.0/24 IETF protocol assignments.
+ return true
+ case v4[0] == 198 && (v4[1] == 18 || v4[1] == 19):
+ // 198.18.0.0/15 network benchmark tests.
+ return true
+ case v4[0] >= 240:
+ // 240.0.0.0/4 reserved (includes limited broadcast).
+ return true
+ default:
+ return false
+ }
+}
+
+// dialUntrusted lets net.Dialer resolve the dial address and race its IPs with
+// the usual IPv6/IPv4 fallback, while rejectBlockedConnect refuses every
+// non-public IP it is about to connect to. Checking each connect covers DNS
+// rebinding between the request check and the connection. Operator-trusted
+// hosts are dialed as given. Test lookup and dial hooks resolve, check, and
+// then dial the checked IP.
+func dialUntrusted(ctx context.Context, network, address string) (net.Conn, error) {
+ hooks := snapshotUntrustedFetchHooks()
+ host, port, err := net.SplitHostPort(address)
+ if err != nil {
+ return nil, err
+ }
+ host = normalizeFetchHost(host)
+ if hooks.skip || operatorTrustedHost(ctx, host, port) {
+ if hooks.dial != nil {
+ return hooks.dial(ctx, network, address)
+ }
+ var dialer net.Dialer
+ return dialer.DialContext(ctx, network, address)
+ }
+ if hooks.lookup == nil && hooks.dial == nil {
+ dialer := net.Dialer{Timeout: 10 * time.Second, Control: rejectBlockedConnect}
+ return dialer.DialContext(ctx, network, address)
+ }
+ ips, err := resolveUntrustedHost(ctx, host, hooks)
+ if err != nil {
+ return nil, err
+ }
+ if err := rejectBlockedIPs(host, ips); err != nil {
+ return nil, err
+ }
+ if hooks.dial != nil {
+ return hooks.dial(ctx, network, net.JoinHostPort(ips[0].String(), port))
+ }
+ var dialer net.Dialer
+ dialer.Timeout = 10 * time.Second
+ var last error
+ for _, ip := range ips {
+ conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
+ if err == nil {
+ return conn, nil
+ }
+ last = err
+ }
+ if last == nil {
+ last = fmt.Errorf("no route to %s", address)
+ }
+ return nil, last
+}
+
+// rejectBlockedConnect is the net.Dialer Control for untrusted fetches. It
+// receives each resolved IP and port just before the connect.
+func rejectBlockedConnect(_, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return err
+ }
+ if IsBlockedFetchIP(net.ParseIP(host)) {
+ return fmt.Errorf("%w %s", errNonPublicAddress, host)
+ }
+ return nil
+}
diff --git a/src/pkg/utils/safe_http_internal_test.go b/src/pkg/utils/safe_http_internal_test.go
new file mode 100644
index 00000000..126e1d1c
--- /dev/null
+++ b/src/pkg/utils/safe_http_internal_test.go
@@ -0,0 +1,16 @@
+package utils
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestRejectBlockedConnectChecksEachDialedAddress(t *testing.T) {
+ for _, address := range []string{"10.0.0.8:80", "169.254.169.254:80", "[::1]:443", "[::ffff:127.0.0.1]:80"} {
+ require.ErrorIs(t, rejectBlockedConnect("tcp", address, nil), errNonPublicAddress, address)
+ }
+ for _, address := range []string{"1.1.1.1:443", "[2606:4700:4700::1111]:443"} {
+ require.NoError(t, rejectBlockedConnect("tcp", address, nil), address)
+ }
+}
diff --git a/src/pkg/utils/safe_http_test.go b/src/pkg/utils/safe_http_test.go
new file mode 100644
index 00000000..97a23ddc
--- /dev/null
+++ b/src/pkg/utils/safe_http_test.go
@@ -0,0 +1,405 @@
+package utils_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/stretchr/testify/require"
+)
+
+func TestUntrustedFetchBlocksPrivateAndNonHTTPDestinations(t *testing.T) {
+ targets := []string{
+ "http://127.0.0.1/",
+ "http://127.0.0.1:9/secret",
+ "http://localhost/secret",
+ "http://169.254.169.254/latest/meta-data",
+ "http://169.254.1.1/",
+ "http://10.1.2.3/doc",
+ "http://192.168.1.20/doc",
+ "http://172.16.0.5/doc",
+ "http://0.0.0.0/",
+ "http://[::1]/",
+ "http://[::]/",
+ "http://[fd00::1]/",
+ "http://[fe80::1]/",
+ "http://[::ffff:127.0.0.1]/",
+ "http://[::ffff:169.254.169.254]/latest/meta-data",
+ "http://224.0.0.1/",
+ "http://255.255.255.255/",
+ "http://100.100.100.200/latest/meta-data",
+ "http://[::ffff:100.100.100.200]/",
+ "http://198.18.0.1/",
+ "http://192.0.0.1/",
+ "http://240.0.0.1/",
+ "http://0.0.0.1/",
+ "http://[64:ff9b::a00:1]/",
+ "http://[64:ff9b::a9fe:a9fe]/latest/meta-data",
+ "http://[64:ff9b:1::808:808]/",
+ "http://[::a9fe:a9fe]/",
+ "http://[::7f00:1]/",
+ "http://[::ffff:0:a9fe:a9fe]/",
+ "http://[2002:a9fe:a9fe::1]/",
+ "http://[2001:0:808:808::1]/",
+ "http://[fec0::1]/",
+ "ftp://example.com/file",
+ "file:///etc/passwd",
+ "gopher://example.com/",
+ }
+ for _, raw := range targets {
+ t.Run(raw, func(t *testing.T) {
+ dialed := false
+ restore := utils.SetUntrustedFetchTestHooks(nil, func(context.Context, string, string) (net.Conn, error) {
+ dialed = true
+ return nil, errors.New("dialed")
+ }, false)
+ t.Cleanup(restore)
+
+ _, _, fileErr := utils.DownloadFileFromURL(context.Background(), raw)
+ require.Error(t, fileErr)
+ _, metaErr := utils.GetMetaDataFromURL(raw)
+ require.Error(t, metaErr)
+ _, _, imageErr := utils.DownloadImageFromURL(context.Background(), raw)
+ require.Error(t, imageErr)
+ _, _, audioErr := utils.DownloadAudioFromURL(context.Background(), raw)
+ require.Error(t, audioErr)
+ _, _, videoErr := utils.DownloadVideoFromURL(context.Background(), raw)
+ require.Error(t, videoErr)
+ require.False(t, dialed)
+ })
+ }
+}
+
+func TestUntrustedFetchAllowsOrdinaryPublicLiteral(t *testing.T) {
+ for _, raw := range []string{
+ "http://1.1.1.1/status",
+ "http://8.8.8.8/status",
+ "http://[::ffff:8.8.8.8]/status",
+ "http://[64:ff9b::808:808]/status",
+ "http://[2002:808:808::1]/status",
+ } {
+ t.Run(raw, func(t *testing.T) {
+ dialed := false
+ restore := utils.SetUntrustedFetchTestHooks(nil, func(context.Context, string, string) (net.Conn, error) {
+ dialed = true
+ return nil, errors.New("stopped after allow")
+ }, false)
+ t.Cleanup(restore)
+
+ _, _, err := utils.DownloadFileFromURL(context.Background(), raw)
+ require.Error(t, err)
+ require.NotContains(t, err.Error(), "non-public")
+ require.True(t, dialed)
+ })
+ }
+}
+
+func TestUntrustedFetchBlocksNameThatResolvesPrivate(t *testing.T) {
+ dialed := false
+ restore := utils.SetUntrustedFetchTestHooks(
+ func(context.Context, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("10.0.0.8")}, nil
+ },
+ func(context.Context, string, string) (net.Conn, error) {
+ dialed = true
+ return nil, errors.New("dialed")
+ },
+ false,
+ )
+ t.Cleanup(restore)
+
+ _, _, err := utils.DownloadFileFromURL(context.Background(), "http://internal.example/secret")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "10.0.0.8")
+ require.False(t, dialed)
+}
+
+func TestUntrustedDialRechecksAddressAfterInitialLookup(t *testing.T) {
+ calls := 0
+ dialed := false
+ restore := utils.SetUntrustedFetchTestHooks(
+ func(context.Context, string) ([]net.IP, error) {
+ calls++
+ if calls == 1 {
+ return []net.IP{net.ParseIP("1.1.1.1")}, nil
+ }
+ return []net.IP{net.ParseIP("10.9.8.7")}, nil
+ },
+ func(context.Context, string, string) (net.Conn, error) {
+ dialed = true
+ return nil, errors.New("should not dial")
+ },
+ false,
+ )
+ t.Cleanup(restore)
+
+ _, _, err := utils.DownloadFileFromURL(context.Background(), "http://rebind.example/secret")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "10.9.8.7")
+ require.False(t, dialed)
+ require.GreaterOrEqual(t, calls, 2)
+}
+
+func TestUntrustedFetchAllowsPublicURLWithStubbedDialer(t *testing.T) {
+ var gotHost string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotHost = r.Host
+ fmt.Fprint(w, `<html><head><title>Public</title></head></html>`)
+ }))
+ t.Cleanup(server.Close)
+
+ var dialed []string
+ restore := utils.SetUntrustedFetchTestHooks(
+ func(_ context.Context, host string) ([]net.IP, error) {
+ if host == "public.example" {
+ return []net.IP{net.ParseIP("1.1.1.1")}, nil
+ }
+ return nil, fmt.Errorf("unexpected host %s", host)
+ },
+ func(ctx context.Context, network, address string) (net.Conn, error) {
+ dialed = append(dialed, address)
+ if !strings.HasPrefix(address, "1.1.1.1:") {
+ return nil, fmt.Errorf("unexpected dial %s", address)
+ }
+ var dialer net.Dialer
+ return dialer.DialContext(ctx, network, server.Listener.Addr().String())
+ },
+ false,
+ )
+ t.Cleanup(restore)
+
+ meta, err := utils.GetMetaDataFromURL("http://public.example/page")
+ require.NoError(t, err)
+ require.Equal(t, "Public", meta.Title)
+ require.NotEmpty(t, dialed)
+ require.True(t, strings.HasPrefix(dialed[0], "1.1.1.1:"))
+ require.Equal(t, "public.example", gotHost)
+
+ body, name, err := utils.DownloadFileFromURL(context.Background(), "http://public.example/file.bin")
+ require.NoError(t, err)
+ require.Equal(t, "file.bin", name)
+ require.Contains(t, string(body), "Public")
+}
+
+func TestUntrustedFetchBlocksRedirectToPrivateAddress(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", http.StatusFound)
+ }))
+ t.Cleanup(server.Close)
+
+ var dialed []string
+ restore := stubPublicDialer(t, server, &dialed)
+ t.Cleanup(restore)
+
+ _, err := utils.GetMetaDataFromURL("http://public.example/page")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "169.254.169.254")
+ _, _, fileErr := utils.DownloadFileFromURL(context.Background(), "http://public.example/doc")
+ require.Error(t, fileErr)
+ require.Contains(t, fileErr.Error(), "169.254.169.254")
+ _, _, audioErr := utils.DownloadAudioFromURL(context.Background(), "http://public.example/a.mp3")
+ require.Error(t, audioErr)
+ require.Contains(t, audioErr.Error(), "169.254.169.254")
+ for _, address := range dialed {
+ require.NotContains(t, address, "169.254")
+ require.NotContains(t, address, "127.")
+ }
+}
+
+func TestPreviewImageURLCannotTargetMetadataAddress(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `<html><head><title>Page</title><meta property="og:image" content="http://169.254.169.254/latest/meta-data/x.jpg"></head></html>`)
+ }))
+ t.Cleanup(server.Close)
+
+ var dialed []string
+ t.Cleanup(stubPublicDialer(t, server, &dialed))
+
+ meta, err := utils.GetMetaDataFromURL("http://public.example/page")
+ require.NoError(t, err)
+ require.Equal(t, "Page", meta.Title)
+ require.Contains(t, meta.Image, "169.254.169.254")
+ require.Empty(t, meta.ImageThumb)
+ for _, address := range dialed {
+ require.NotContains(t, address, "169.254")
+ require.NotContains(t, address, "127.")
+ }
+}
+
+func TestPreviewImageRedirectCannotTargetPrivateAddress(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/img.jpg" {
+ http.Redirect(w, r, "http://10.2.3.4/secret.jpg", http.StatusFound)
+ return
+ }
+ fmt.Fprint(w, `<html><head><title>Redirected image</title><meta property="og:image" content="http://public.example/img.jpg"></head></html>`)
+ }))
+ t.Cleanup(server.Close)
+
+ var dialed []string
+ t.Cleanup(stubPublicDialer(t, server, &dialed))
+
+ meta, err := utils.GetMetaDataFromURL("http://public.example/page")
+ require.NoError(t, err)
+ require.Equal(t, "Redirected image", meta.Title)
+ require.Empty(t, meta.ImageThumb)
+ for _, address := range dialed {
+ require.NotContains(t, address, "10.2.3.4")
+ require.NotContains(t, address, "127.")
+ }
+}
+
+func TestUntrustedFetchAllowsOperatorChatwootHosts(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/png")
+ fmt.Fprint(w, "attachment")
+ }))
+ t.Cleanup(server.Close)
+
+ prevURL, prevHosts := config.ChatwootURL, config.ChatwootAllowedHosts
+ config.ChatwootURL = "http://chatwoot.internal:3000"
+ config.ChatwootAllowedHosts = []string{"Storage.Internal"}
+ t.Cleanup(func() { config.ChatwootURL, config.ChatwootAllowedHosts = prevURL, prevHosts })
+
+ var dialed []string
+ t.Cleanup(utils.SetUntrustedFetchTestHooks(
+ func(context.Context, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("192.168.1.20")}, nil
+ },
+ func(ctx context.Context, network, address string) (net.Conn, error) {
+ dialed = append(dialed, address)
+ var dialer net.Dialer
+ return dialer.DialContext(ctx, network, server.Listener.Addr().String())
+ },
+ false,
+ ))
+
+ attachment := utils.WithChatwootAttachmentFetch(context.Background())
+ _, _, err := utils.DownloadFileFromURL(attachment, "http://chatwoot.internal:3000/rails/active_storage/blobs/report.pdf")
+ require.NoError(t, err)
+ _, _, err = utils.DownloadImageFromURL(attachment, "http://storage.internal/bucket/photo.png")
+ require.NoError(t, err)
+ require.Equal(t, []string{"chatwoot.internal:3000", "storage.internal:80"}, dialed)
+
+ _, _, err = utils.DownloadFileFromURL(attachment, "http://other.internal/report.pdf")
+ require.ErrorContains(t, err, "192.168.1.20")
+ _, _, err = utils.DownloadFileFromURL(attachment, "http://chatwoot.internal:6379/")
+ require.ErrorContains(t, err, "192.168.1.20")
+
+ // A caller-selected URL outside the Chatwoot attachment flow gets no exemption.
+ _, _, err = utils.DownloadFileFromURL(context.Background(), "http://chatwoot.internal:3000/rails/active_storage/blobs/report.pdf")
+ require.ErrorContains(t, err, "192.168.1.20")
+ _, _, err = utils.DownloadAudioFromURL(context.Background(), "http://storage.internal:6379/")
+ require.ErrorContains(t, err, "192.168.1.20")
+}
+
+func TestUntrustedFetchChecksPunycodeFormOfIDNHost(t *testing.T) {
+ var looked []string
+ var dialed string
+ t.Cleanup(utils.SetUntrustedFetchTestHooks(
+ func(_ context.Context, host string) ([]net.IP, error) {
+ looked = append(looked, host)
+ if host == "xn--bcher-kva.de" {
+ return []net.IP{net.ParseIP("1.1.1.1")}, nil
+ }
+ return nil, fmt.Errorf("unexpected host %s", host)
+ },
+ func(_ context.Context, _, address string) (net.Conn, error) {
+ dialed = address
+ return nil, errors.New("stopped after allow")
+ },
+ false,
+ ))
+
+ _, _, err := utils.DownloadFileFromURL(context.Background(), "http://bücher.de/doc.pdf")
+ require.ErrorContains(t, err, "stopped after allow")
+ require.Equal(t, []string{"xn--bcher-kva.de", "xn--bcher-kva.de"}, looked)
+ require.Equal(t, "1.1.1.1:80", dialed)
+}
+
+func TestUntrustedFetchReusesPooledConnections(t *testing.T) {
+ t.Cleanup(utils.AllowUntrustedLoopbackForTest())
+ var conns atomic.Int32
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "file")
+ }))
+ server.Config.ConnState = func(_ net.Conn, state http.ConnState) {
+ if state == http.StateNew {
+ conns.Add(1)
+ }
+ }
+ server.Start()
+ t.Cleanup(server.Close)
+
+ for range 5 {
+ _, _, err := utils.DownloadFileFromURL(context.Background(), server.URL+"/doc.pdf")
+ require.NoError(t, err)
+ }
+ require.EqualValues(t, 1, conns.Load(), "each fetch must not open its own transport")
+}
+
+func stubPublicDialer(t *testing.T, server *httptest.Server, dialed *[]string) func() {
+ t.Helper()
+ return utils.SetUntrustedFetchTestHooks(
+ func(_ context.Context, host string) ([]net.IP, error) {
+ if host == "public.example" {
+ return []net.IP{net.ParseIP("1.1.1.1")}, nil
+ }
+ return nil, fmt.Errorf("unexpected host %s", host)
+ },
+ func(ctx context.Context, network, address string) (net.Conn, error) {
+ *dialed = append(*dialed, address)
+ if !strings.HasPrefix(address, "1.1.1.1:") {
+ return nil, fmt.Errorf("unexpected dial %s", address)
+ }
+ var dialer net.Dialer
+ return dialer.DialContext(ctx, network, server.Listener.Addr().String())
+ },
+ false,
+ )
+}
+
+func TestUntrustedFetchServesOwnStaticsFromDisk(t *testing.T) {
+ t.Chdir(t.TempDir())
+ require.NoError(t, os.MkdirAll("statics/media", 0o755))
+ require.NoError(t, os.WriteFile("statics/media/a b.pdf", []byte("%PDF-1.4"), 0o644))
+ require.NoError(t, os.MkdirAll("storages", 0o755))
+ require.NoError(t, os.WriteFile("storages/whatsapp.db", []byte("secret"), 0o644))
+
+ var dialed atomic.Int32
+ t.Cleanup(utils.SetUntrustedFetchTestHooks(
+ func(context.Context, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("172.18.0.5")}, nil
+ },
+ func(context.Context, string, string) (net.Conn, error) {
+ dialed.Add(1)
+ return nil, errors.New("unexpected dial")
+ },
+ false,
+ ))
+
+ data, name, err := utils.DownloadFileFromURL(context.Background(), "http://gowa:3000/statics/media/a%20b.pdf")
+ require.NoError(t, err)
+ require.Equal(t, "%PDF-1.4", string(data))
+ require.Equal(t, "a%20b.pdf", name)
+
+ for _, target := range []string{
+ "http://gowa:3000/statics/../storages/whatsapp.db",
+ "http://gowa:3000/statics/media/missing.pdf",
+ "http://gowa:3000/app/devices",
+ "http://gowa:3000/statics/..%5c..%5cstorages%5cwhatsapp.db",
+ } {
+ _, _, err = utils.DownloadFileFromURL(context.Background(), target)
+ require.ErrorContains(t, err, "non-public address", target)
+ }
+ require.Zero(t, dialed.Load())
+}
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index ae84e132..9c1781d4 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -844,6 +844,8 @@ func (h *ChatwootHandler) notifySendFailure(payload chatwoot.WebhookPayload, rou
}
func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, att chatwoot.Attachment, caption string) (domainSend.GenericResponse, error) {
+ // Chatwoot serves attachments from its own, possibly private, host.
+ ctx = utils.WithChatwootAttachmentFetch(ctx)
switch att.FileType {
case "image":
req := domainSend.ImageRequest{
diff --git a/src/usecase/message_update_link_test.go b/src/usecase/message_update_link_test.go
index ec73304e..9464ffe3 100644
--- a/src/usecase/message_update_link_test.go
+++ b/src/usecase/message_update_link_test.go
@@ -7,6 +7,7 @@ import (
"testing"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mau.fi/whatsmeow"
@@ -16,6 +17,9 @@ import (
func newLinkPreviewPage(t *testing.T) string {
t.Helper()
+ // Preview fetches refuse loopback. This fixture is an httptest server, so
+ // the address check is disabled for the test and restored afterward.
+ t.Cleanup(utils.AllowUntrustedLoopbackForTest())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(`<html><head><title>Countdown</title><meta property="og:title" content="Countdown"><meta name="description" content="Live timer"></head><body></body></html>`))
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 1c4e7670..1d99a07a 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"image"
+ "io"
"math"
"mime"
"net/http"
@@ -42,6 +43,14 @@ var webpCanvasSizeRegex = regexp.MustCompile(`Canvas size:\s*(\d+)\s*x\s*(\d+)`)
const hdImageMaxEdge = 2560
+// compressedImageMaxEdge is the width of the legacy compress=true send. The
+// derived height is capped at hdImageMaxEdge so a narrow source cannot grow a
+// fixed width into a multi-megapixel height.
+const compressedImageMaxEdge = 600
+
+// stickerMaxEdge is the longest side of a static sticker before WebP conversion.
+const stickerMaxEdge = 512
+
type videoMetadata struct {
Width uint32
Height uint32
@@ -57,13 +66,42 @@ func prepareImageForSend(src image.Image, compress, hd bool) (image.Image, bool)
return resizeImageForHD(src), true
}
if compress {
- return imaging.Resize(src, 600, 0, imaging.Lanczos), true
+ return utils.FitBox(src, compressedImageMaxEdge, hdImageMaxEdge), true
}
return src, false
}
func openImageForSend(imagePath string, hd bool) (image.Image, error) {
- return imaging.Open(imagePath, imaging.AutoOrientation(hd))
+ return utils.DecodeImageFileWithinBudget(imagePath, imaging.AutoOrientation(hd))
+}
+
+// videoThumbnailFFmpegArgs extracts one frame already fitted inside the
+// 100x512 thumbnail box. force_original_aspect_ratio=decrease does not
+// enlarge a short edge to fill the box.
+func videoThumbnailFFmpegArgs(inputPath, outputPath string) []string {
+ return []string{
+ "-i", inputPath,
+ "-ss", "00:00:01.000",
+ "-vframes", "1",
+ "-vf", "scale=100:512:force_original_aspect_ratio=decrease",
+ outputPath,
+ }
+}
+
+// openVideoThumbnail decodes a frame only after its header fits the shared
+// pixel budget, then fits it inside the thumbnail box.
+func openVideoThumbnail(path string) (image.Image, error) {
+ img, err := utils.DecodeImageFileWithinBudget(path)
+ if err != nil {
+ return nil, err
+ }
+ return utils.FitThumbnail(img), nil
+}
+
+// openStickerImage decodes a sticker only after its header fits the shared
+// pixel budget.
+func openStickerImage(path string) (image.Image, error) {
+ return utils.DecodeImageFileWithinBudget(path)
}
func saveProcessedImage(src image.Image, directory, imageName string, hd bool) (string, error) {
@@ -389,12 +427,12 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
// Prefix every temp file with a UUID, as the video path already does.
// Without it two concurrent sends of the same filename share one path on
- // disk and the async cleanup below deletes the other request's files.
+ // disk and the deferred cleanup below deletes the other request's files.
generateUUID := fiberUtils.UUIDv4()
if request.ImageURL != nil && *request.ImageURL != "" {
// Download image from URL
- imageData, fileName, err := utils.DownloadImageFromURL(*request.ImageURL)
+ imageData, fileName, err := utils.DownloadImageFromURL(ctx, *request.ImageURL)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to download image from URL %v", err))
}
@@ -403,7 +441,7 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
mimeType := http.DetectContentType(imageData)
if mimeType == "image/webp" {
// Convert WebP to PNG
- webpImage, err := imaging.Decode(bytes.NewReader(imageData))
+ webpImage, _, err := utils.DecodeImageWithinBudget(bytes.NewReader(imageData))
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to decode WebP image %v", err))
}
@@ -440,21 +478,33 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
}
}
deletedItems = append(deletedItems, oriImagePath)
+ // Remove the temp files on every return, including the early errors below.
+ defer func() {
+ errDelete := utils.RemoveFile(0, deletedItems...)
+ if errDelete != nil {
+ fmt.Println("error when deleting picture: ", errDelete)
+ }
+ }()
/* Generate thumbnail with smalled image size */
srcImage, err := openImageForSend(oriImagePath, request.HD)
- if err != nil {
+ switch {
+ case err == nil:
+ // Resize thumbnail within a fixed box. A fixed width with a derived height
+ // would upscale a very narrow image into a tall raster.
+ resizedImage := utils.FitThumbnail(srcImage)
+ imageThumbnail = fmt.Sprintf("%s/thumbnails-%s", config.PathSendItems, imageName)
+ if err = imaging.Save(resizedImage, imageThumbnail); err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to save thumbnail %v", err))
+ }
+ deletedItems = append(deletedItems, imageThumbnail)
+ case !request.Compress && !request.HD && errors.Is(err, utils.ErrImageTooLarge):
+ // Original mode uploads the file unchanged and decodes it only for the
+ // thumbnail, so an image past the decode budget is sent without one.
+ default:
return response, pkgError.InternalServerError(fmt.Sprintf("Failed to open image file '%s' for thumbnail generation: %v. Possible causes: file not found, unsupported format, or permission denied.", oriImagePath, err))
}
- // Resize Thumbnail
- resizedImage := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
- imageThumbnail = fmt.Sprintf("%s/thumbnails-%s", config.PathSendItems, imageName)
- if err = imaging.Save(resizedImage, imageThumbnail); err != nil {
- return response, pkgError.InternalServerError(fmt.Sprintf("failed to save thumbnail %v", err))
- }
- deletedItems = append(deletedItems, imageThumbnail)
-
preparedImage, processed := prepareImageForSend(srcImage, request.Compress, request.HD)
if processed {
processedImagePath, saveErr := saveProcessedImage(preparedImage, config.PathSendItems, imageName, request.HD)
@@ -482,9 +532,12 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
fmt.Printf("failed to upload file: %v", err)
return response, err
}
- dataWaThumbnail, err := os.ReadFile(imageThumbnail)
- if err != nil {
- return response, pkgError.InternalServerError(fmt.Sprintf("failed to read thumbnail %v", err))
+ var dataWaThumbnail []byte
+ if imageThumbnail != "" {
+ dataWaThumbnail, err = os.ReadFile(imageThumbnail)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to read thumbnail %v", err))
+ }
}
msg := &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
@@ -530,12 +583,6 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
caption = request.Caption
}
ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, caption)
- go func() {
- errDelete := utils.RemoveFile(0, deletedItems...)
- if errDelete != nil {
- fmt.Println("error when deleting picture: ", errDelete)
- }
- }()
if err != nil {
return response, err
}
@@ -567,7 +614,7 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
)
if request.FileURL != nil && *request.FileURL != "" {
- fileBytes, fileName, err = utils.DownloadFileFromURL(*request.FileURL)
+ fileBytes, fileName, err = utils.DownloadFileFromURL(ctx, *request.FileURL)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to download file from URL: %v", err))
}
@@ -675,13 +722,19 @@ func generatePDFThumbnail(pdfBytes []byte, uuid string) []byte {
return nil
}
- // Try pdftoppm first (poppler-utils) — widely available, no Ghostscript needed
+ pxW, pxH, ok := pdfApprovedRasterPixels(tempPDF)
+ if !ok {
+ logrus.Warnf("skipping PDF thumbnail: page exceeds render budget or size is unknown")
+ return nil
+ }
+
+ // pdftoppm is pinned to the approved pixel size. A missing or failed
+ // pdfinfo measurement never reaches this command.
pngGenerated := false
pdftoppmOut := fmt.Sprintf("%s/thumb_%s", config.PathSendItems, uuid)
cmdCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- cmd := exec.CommandContext(cmdCtx, "pdftoppm", "-png", "-f", "1", "-l", "1", "-r", "150", "-singlefile", tempPDF, pdftoppmOut)
- if err := cmd.Run(); err == nil {
+ if err := runExternal(cmdCtx, "pdftoppm", pdfPopplerArgs(tempPDF, pdftoppmOut, pxW, pxH)...); err == nil {
// pdftoppm with -singlefile outputs to {prefix}.png
actualOut := pdftoppmOut + ".png"
if _, statErr := os.Stat(actualOut); statErr == nil {
@@ -690,20 +743,21 @@ func generatePDFThumbnail(pdfBytes []byte, uuid string) []byte {
}
}
- // Fallback to ImageMagick convert
+ // Fallback to ImageMagick convert. Density and a shrink-only geometry keep
+ // the fallback from expanding a narrow page into a tall raster.
if !pngGenerated {
- cmd = exec.CommandContext(cmdCtx, "convert", tempPDF+"[0]", "-resize", "300x", "-quality", "85", tempPNG)
- if err := cmd.Run(); err != nil {
+ if err := runExternal(cmdCtx, "convert", "-density", "72", "-limit", "width", "8192", "-limit", "height", "8192", tempPDF+"[0]", "-resize", "100x512>", "-quality", "85", tempPNG); err != nil {
return nil
}
}
- // Resize to thumbnail
- srcImage, err := imaging.Open(tempPNG)
+ // Resize to thumbnail. Reject a render that exceeds the shared pixel budget
+ // instead of allocating it.
+ srcImage, err := utils.DecodeImageFileWithinBudget(tempPNG)
if err != nil {
return nil
}
- resized := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
+ resized := utils.FitThumbnail(srcImage)
if err = imaging.Save(resized, thumbPath); err != nil {
return nil
}
@@ -729,12 +783,12 @@ func generateImageDocThumbnail(imageBytes []byte, fileName string, uuid string)
return nil
}
- srcImage, err := imaging.Open(tempPath)
+ srcImage, err := utils.DecodeImageFileWithinBudget(tempPath)
if err != nil {
return nil
}
- resized := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
+ resized := utils.FitThumbnail(srcImage)
if err = imaging.Save(resized, thumbPath); err != nil {
return nil
}
@@ -830,23 +884,39 @@ func getAudioDuration(audioPath string) uint32 {
// generateWaveform generates a waveform visualization for voice notes using ffmpeg.
// Returns a []byte with 64 amplitude samples (0-100) for WhatsApp UI visualization.
-func generateWaveform(audioPath string) []byte {
- // Extract audio samples as signed 8-bit PCM
- // -ac 1: mono, -ar 8000: 8kHz sample rate, -f s8: signed 8-bit output
- output, err := runFFMpeg(
- "-i", audioPath,
- "-ac", "1",
- "-ar", "8000",
- "-f", "s8",
- "-acodec", "pcm_s8",
- "pipe:1",
- )
+func generateWaveform(audioPath string, durationSeconds uint32) []byte {
+ // Extract signed 8-bit PCM sized to span the whole note. The reader keeps
+ // at most waveformMaxPCMBytes so a highly compressed recording cannot
+ // expand into an unbounded buffer.
+ if _, err := exec.LookPath("ffmpeg"); err != nil {
+ logrus.Warnf("Failed to generate waveform: %v", err)
+ return generateDefaultWaveform()
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "ffmpeg", waveformFFmpegArgs(audioPath, durationSeconds)...)
+ cmd.Stderr = io.Discard
+ stdout, err := cmd.StdoutPipe()
if err != nil {
logrus.Warnf("Failed to generate waveform: %v", err)
return generateDefaultWaveform()
}
+ if err := cmd.Start(); err != nil {
+ logrus.Warnf("Failed to generate waveform: %v", err)
+ return generateDefaultWaveform()
+ }
+ samples, readErr := readWaveformPCM(stdout, waveformMaxPCMBytes)
+ _ = stdout.Close()
+ if cmd.Process != nil {
+ _ = cmd.Process.Kill()
+ }
+ waitErr := cmd.Wait()
+ if len(samples) == 0 {
+ logrus.Warnf("Failed to generate waveform: read=%v wait=%v", readErr, waitErr)
+ return generateDefaultWaveform()
+ }
- return downsampleToWaveform(output, 64)
+ return downsampleToWaveform(samples, 64)
}
// downsampleToWaveform converts raw PCM samples to a fixed number of amplitude peaks.
@@ -951,7 +1021,7 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
// Determine source of video (URL or uploaded file)
if request.VideoURL != nil && *request.VideoURL != "" {
// Download video bytes
- videoBytes, fileName, errDownload := utils.DownloadVideoFromURL(*request.VideoURL)
+ videoBytes, fileName, errDownload := utils.DownloadVideoFromURL(ctx, *request.VideoURL)
if errDownload != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to download video from URL %v", errDownload))
}
@@ -978,22 +1048,23 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
return response, pkgError.InternalServerError("ffmpeg not installed")
}
- // Generate thumbnail using ffmpeg
+ // Generate thumbnail using ffmpeg. The scale filter fits the frame inside
+ // the thumbnail box without stretching a tiny edge into a tall raster.
thumbnailVideoPath := fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+".png")
- cmdThumbnail := exec.Command("ffmpeg", "-i", oriVideoPath, "-ss", "00:00:01.000", "-vframes", "1", thumbnailVideoPath)
+ cmdThumbnail := exec.Command("ffmpeg", videoThumbnailFFmpegArgs(oriVideoPath, thumbnailVideoPath)...)
err = cmdThumbnail.Run()
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to create thumbnail %v", err))
}
- // Resize Thumbnail
- srcImage, err := imaging.Open(thumbnailVideoPath)
+ // Reject an extracted frame that still exceeds the shared pixel budget
+ // before imaging fully decodes it, then keep the preview inside 100x512.
+ srcImage, err := openVideoThumbnail(thumbnailVideoPath)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("Failed to open generated video thumbnail image '%s': %v. Possible causes: file not found, unsupported format, or permission denied.", thumbnailVideoPath, err))
}
- resizedImage := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
thumbnailResizeVideoPath := fmt.Sprintf("%s/thumbnails-%s", config.PathSendItems, generateUUID+".png")
- if err = imaging.Save(resizedImage, thumbnailResizeVideoPath); err != nil {
+ if err = imaging.Save(srcImage, thumbnailResizeVideoPath); err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to save thumbnail %v", err))
}
@@ -1344,7 +1415,7 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
// Handle audio from URL or file
if request.AudioURL != nil && *request.AudioURL != "" {
- audioBytes, audioFilename, err = utils.DownloadAudioFromURL(*request.AudioURL)
+ audioBytes, audioFilename, err = utils.DownloadAudioFromURL(ctx, *request.AudioURL)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to download audio from URL %v", err))
}
@@ -1382,7 +1453,7 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
// Generate waveform for PTT voice notes
var waveformData []byte
if request.PTT && tempAudioPath != "" {
- waveformData = generateWaveform(tempAudioPath)
+ waveformData = generateWaveform(tempAudioPath, audioDuration)
}
// If PTT is requested, convert audio to OGG Opus format for WhatsApp voice note compatibility
@@ -1749,7 +1820,7 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
// Handle sticker from URL or file
if request.StickerURL != nil && *request.StickerURL != "" {
// Download sticker from URL
- imageData, _, err := utils.DownloadImageFromURL(*request.StickerURL)
+ imageData, _, err := utils.DownloadImageFromURL(ctx, *request.StickerURL)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to download sticker from URL: %v", err))
}
@@ -1865,11 +1936,15 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
return response, nil
}
- // Convert image to WebP format for sticker (512x512 max size)
- srcImage, err := imaging.Open(stickerPath)
+ // Convert image to WebP format for sticker (512x512 max size).
+ // Header dimensions are checked before the raster is allocated.
+ srcImage, err := openStickerImage(stickerPath)
if err != nil {
- // Fallback for animated WebP (imaging.Open doesn't support animated WebP)
- logrus.Warnf("imaging.Open failed for %s: %v. Trying animated WebP fallback...", stickerPath, err)
+ if errors.Is(err, utils.ErrImageTooLarge) {
+ return response, pkgError.InternalServerError(fmt.Sprintf("sticker image exceeds pixel budget: %v", err))
+ }
+ // Fallback for animated WebP (the still decoder does not support it).
+ logrus.Warnf("sticker decode failed for %s: %v. Trying animated WebP fallback...", stickerPath, err)
fallbackPngPath := filepath.Join(absBaseDir, fmt.Sprintf("fallback_%s.png", fiberUtils.UUIDv4()))
deletedItems = append(deletedItems, fallbackPngPath)
@@ -1915,25 +1990,16 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
return response, pkgError.InternalServerError(fmt.Sprintf("failed to open image for sticker conversion: %v (animated WebP requires webpmux and dwebp tools)", err))
}
- srcImage, err = imaging.Open(fallbackPngPath)
+ srcImage, err = openStickerImage(fallbackPngPath)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("failed to open fallback PNG image: %v", err))
}
logrus.Info("Fallback conversion successful")
}
- // Resize image to max 512x512 maintaining aspect ratio
- bounds := srcImage.Bounds()
- width := bounds.Dx()
- height := bounds.Dy()
-
- if width > 512 || height > 512 {
- if width > height {
- srcImage = imaging.Resize(srcImage, 512, 0, imaging.Lanczos)
- } else {
- srcImage = imaging.Resize(srcImage, 0, 512, imaging.Lanczos)
- }
- }
+ // Fit inside 512x512. Both edges are capped; a narrow source is not
+ // stretched by deriving an unbounded height from a fixed width.
+ srcImage = utils.FitBox(srcImage, stickerMaxEdge, stickerMaxEdge)
// Convert to WebP using external command (ffmpeg or cwebp)
webpPath := filepath.Join(absBaseDir, fmt.Sprintf("sticker_%s.webp", fiberUtils.UUIDv4()))
diff --git a/src/usecase/send_limits.go b/src/usecase/send_limits.go
new file mode 100644
index 00000000..445ddbc8
--- /dev/null
+++ b/src/usecase/send_limits.go
@@ -0,0 +1,171 @@
+package usecase
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "math"
+ "os/exec"
+ "regexp"
+ "strconv"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+)
+
+const (
+ pdfThumbnailDPI = 150
+
+ // waveformSampleRate is the PCM rate used to build a 64-point voice waveform.
+ waveformSampleRate = 8000
+ // waveformMaxSeconds is the longest note decoded at waveformSampleRate.
+ // Longer notes are decoded at a lower rate within waveformMaxPCMBytes.
+ waveformMaxSeconds = 120
+ // waveformMaxPCMBytes is the decoded s8 mono prefix kept in memory.
+ waveformMaxPCMBytes = waveformSampleRate * waveformMaxSeconds
+)
+
+// runExternal and runExternalOutput are replaceable so tests can prove an
+// oversized PDF never reaches a rasterizer.
+var runExternal = func(ctx context.Context, name string, args ...string) error {
+ return exec.CommandContext(ctx, name, args...).Run()
+}
+
+var runExternalOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return exec.CommandContext(ctx, name, args...).Output()
+}
+
+var pdfInfoPageSizePattern = regexp.MustCompile(`Page(?:\s+\d+)?\s+size:\s+([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s+x\s+([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s+pts`)
+
+// pdfRasterWithinBudget reports whether a page of the given size in points
+// stays inside the shared image budget when rasterized at pdfThumbnailDPI.
+func pdfRasterWithinBudget(widthPts, heightPts float64) bool {
+ widthPx := ceilPDFPixels(widthPts)
+ heightPx := ceilPDFPixels(heightPts)
+ if widthPx <= 0 || heightPx <= 0 {
+ return false
+ }
+ return utils.ValidateImageDimensions(widthPx, heightPx) == nil
+}
+
+// ceilPDFPixels is ceil(points * 150 / 72) in integer arithmetic so a page
+// that lands on a whole pixel is not rounded up by float error.
+func ceilPDFPixels(pts float64) int {
+ if math.IsNaN(pts) || math.IsInf(pts, 0) || pts <= 0 || pts > 1e12 {
+ return 0
+ }
+ milli := int64(math.Round(pts * 1000))
+ if milli <= 0 {
+ return 0
+ }
+ den := int64(1000 * 72)
+ num := milli * int64(pdfThumbnailDPI)
+ if num/milli != int64(pdfThumbnailDPI) {
+ return 0
+ }
+ px := (num + den - 1) / den
+ if px > int64(math.MaxInt32) {
+ return 0
+ }
+ return int(px)
+}
+
+// pdfApprovedRasterPixels returns the pixel size pdfinfo measured for page 1
+// when that size fits the shared image budget. If pdfinfo is missing, errors,
+// or does not report an in-budget size, ok is false and the caller must not
+// rasterize.
+func pdfApprovedRasterPixels(path string) (width, height int, ok bool) {
+ infoW, infoH, infoOK := pdfInfoPagePoints(path)
+ if !infoOK {
+ return 0, 0, false
+ }
+ return pdfRasterPixels(infoW, infoH)
+}
+
+// pdfPopplerArgs renders a page to an exact pixel size already accepted by
+// pdfApprovedRasterPixels. It does not use an uncapped DPI flag. -cropbox
+// renders the CropBox that pdfinfo measured, so the pinned size keeps the
+// page's aspect ratio.
+func pdfPopplerArgs(pdfPath, outPrefix string, pxW, pxH int) []string {
+ if pxW < 1 {
+ pxW = 1
+ }
+ if pxH < 1 {
+ pxH = 1
+ }
+ return []string{
+ "-png",
+ "-f", "1",
+ "-l", "1",
+ "-cropbox",
+ "-scale-to-x", strconv.Itoa(pxW),
+ "-scale-to-y", strconv.Itoa(pxH),
+ "-singlefile",
+ pdfPath,
+ outPrefix,
+ }
+}
+
+func pdfRasterPixels(widthPts, heightPts float64) (int, int, bool) {
+ if !pdfRasterWithinBudget(widthPts, heightPts) {
+ return 0, 0, false
+ }
+ return ceilPDFPixels(widthPts), ceilPDFPixels(heightPts), true
+}
+
+func pdfInfoPagePoints(path string) (float64, float64, bool) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ out, err := runExternalOutput(ctx, "pdfinfo", "-f", "1", "-l", "1", path)
+ if err != nil {
+ return 0, 0, false
+ }
+ return parsePDFInfoPageSize(out)
+}
+
+func parsePDFInfoPageSize(output []byte) (float64, float64, bool) {
+ match := pdfInfoPageSizePattern.FindSubmatch(output)
+ if len(match) < 3 {
+ return 0, 0, false
+ }
+ width, errW := strconv.ParseFloat(string(match[1]), 64)
+ height, errH := strconv.ParseFloat(string(match[2]), 64)
+ if errW != nil || errH != nil {
+ return 0, 0, false
+ }
+ return width, height, true
+}
+
+// waveformFFmpegArgs decodes mono s8 PCM for the waveform. A note longer than
+// waveformMaxSeconds is decoded whole at a rate that fits waveformMaxPCMBytes,
+// so the bars span the full note; a shorter or unknown duration keeps the
+// waveformSampleRate prefix.
+func waveformFFmpegArgs(audioPath string, durationSeconds uint32) []string {
+ args := []string{"-hide_banner", "-loglevel", "error", "-i", audioPath, "-ac", "1"}
+ if durationSeconds > waveformMaxSeconds {
+ args = append(args, "-ar", strconv.Itoa(max(64, waveformMaxPCMBytes/int(durationSeconds))))
+ } else {
+ args = append(args, "-ar", strconv.Itoa(waveformSampleRate), "-t", strconv.Itoa(waveformMaxSeconds))
+ }
+ return append(args, "-f", "s8", "-acodec", "pcm_s8", "pipe:1")
+}
+
+// readWaveformPCM keeps at most max decoded PCM bytes. A longer stream is
+// truncated to that prefix so the waveform can be built without buffering it.
+func readWaveformPCM(r io.Reader, max int) ([]byte, error) {
+ if max <= 0 {
+ return nil, fmt.Errorf("invalid pcm cap")
+ }
+ buf := make([]byte, max)
+ n, err := io.ReadFull(r, buf)
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ return buf[:n], nil
+ }
+ if err != nil {
+ if n > 0 {
+ return buf[:n], nil
+ }
+ return nil, err
+ }
+ return buf[:n], nil
+}
diff --git a/src/usecase/send_limits_test.go b/src/usecase/send_limits_test.go
new file mode 100644
index 00000000..87f6e450
--- /dev/null
+++ b/src/usecase/send_limits_test.go
@@ -0,0 +1,269 @@
+package usecase
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "image"
+ "image/jpeg"
+ "image/png"
+ "math"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/stretchr/testify/require"
+)
+
+func pngWithIHDR(width, height uint32) []byte {
+ ihdr := make([]byte, 13)
+ binary.BigEndian.PutUint32(ihdr[0:4], width)
+ binary.BigEndian.PutUint32(ihdr[4:8], height)
+ ihdr[8] = 8
+ ihdr[9] = 2
+ payload := append([]byte("IHDR"), ihdr...)
+ var chunk bytes.Buffer
+ _ = binary.Write(&chunk, binary.BigEndian, uint32(len(ihdr)))
+ chunk.Write(payload)
+ _ = binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(payload))
+ out := []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}
+ return append(out, chunk.Bytes()...)
+}
+
+func pdfWithMediaBox(width, height int) []byte {
+ return []byte(fmt.Sprintf("%%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 %d %d]>>endobj\ntrailer<</Root 1 0 R>>\n%%%%EOF\n", width, height))
+}
+
+func withSendItemsDir(t *testing.T) {
+ t.Helper()
+ orig := config.PathSendItems
+ config.PathSendItems = t.TempDir()
+ t.Cleanup(func() { config.PathSendItems = orig })
+}
+
+func TestOpenImageForSendRejectsOversizedDimensions(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "huge.png")
+ require.NoError(t, os.WriteFile(path, pngWithIHDR(20000, 20000), 0600))
+ img, err := openImageForSend(path, false)
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+}
+
+func TestOpenImageForSendStillDecodesSmallImage(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "small.png")
+ var encoded bytes.Buffer
+ require.NoError(t, png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 4, 5))))
+ require.NoError(t, os.WriteFile(path, encoded.Bytes(), 0600))
+ img, err := openImageForSend(path, false)
+ require.NoError(t, err)
+ require.Equal(t, 4, img.Bounds().Dx())
+ require.Equal(t, 5, img.Bounds().Dy())
+}
+
+func TestGenerateImageDocThumbnailRejectsOversizedImage(t *testing.T) {
+ withSendItemsDir(t)
+ got := generateImageDocThumbnail(pngWithIHDR(9000, 9000), "big.png", "oversize")
+ require.Nil(t, got)
+}
+
+func TestGenerateImageDocThumbnailKeepsSmallImage(t *testing.T) {
+ withSendItemsDir(t)
+ var encoded bytes.Buffer
+ require.NoError(t, jpeg.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 32, 16)), &jpeg.Options{Quality: 80}))
+ got := generateImageDocThumbnail(encoded.Bytes(), "photo.jpg", "small")
+ require.NotEmpty(t, got)
+ require.Equal(t, "image/jpeg", httpContentType(got))
+}
+
+func httpContentType(data []byte) string {
+ if len(data) >= 3 && data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff {
+ return "image/jpeg"
+ }
+ return ""
+}
+
+func TestPDFRasterBudget(t *testing.T) {
+ require.True(t, pdfRasterWithinBudget(612, 792))
+ require.False(t, pdfRasterWithinBudget(200000, 200000))
+ require.False(t, pdfRasterWithinBudget(1, 200000))
+ require.False(t, pdfRasterWithinBudget(math.Inf(1), 10))
+}
+
+func TestParsePDFInfoPageSize(t *testing.T) {
+ width, height, ok := parsePDFInfoPageSize([]byte("Page 1 size: 612 x 792 pts (letter)\n"))
+ require.True(t, ok)
+ require.Equal(t, 612.0, width)
+ require.Equal(t, 792.0, height)
+}
+
+func TestGeneratePDFThumbnailDoesNotRenderOversizedPage(t *testing.T) {
+ withSendItemsDir(t)
+ var rendered []string
+ origRun := runExternal
+ origOut := runExternalOutput
+ runExternal = func(ctx context.Context, name string, args ...string) error {
+ rendered = append(rendered, name)
+ return fmt.Errorf("render should not be called")
+ }
+ runExternalOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if name == "pdfinfo" {
+ return []byte("Page 1 size: 200000 x 200000 pts\n"), nil
+ }
+ return nil, fmt.Errorf("unexpected %s", name)
+ }
+ t.Cleanup(func() {
+ runExternal = origRun
+ runExternalOutput = origOut
+ })
+
+ got := generatePDFThumbnail(pdfWithMediaBox(200000, 200000), "huge")
+ require.Nil(t, got)
+ require.NotContains(t, rendered, "pdftoppm")
+ require.NotContains(t, rendered, "convert")
+}
+
+func TestGeneratePDFThumbnailRejectsWhenPDFInfoDisagrees(t *testing.T) {
+ withSendItemsDir(t)
+ var rendered []string
+ origRun := runExternal
+ origOut := runExternalOutput
+ runExternal = func(ctx context.Context, name string, args ...string) error {
+ rendered = append(rendered, name)
+ return nil
+ }
+ runExternalOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return []byte("Page 1 size: 200000 x 200000 pts\n"), nil
+ }
+ t.Cleanup(func() {
+ runExternal = origRun
+ runExternalOutput = origOut
+ })
+
+ got := generatePDFThumbnail(pdfWithMediaBox(612, 792), "lie")
+ require.Nil(t, got)
+ require.NotContains(t, rendered, "pdftoppm")
+ require.NotContains(t, rendered, "convert")
+}
+
+func TestGeneratePDFThumbnailAttemptsRenderForLetterPage(t *testing.T) {
+ withSendItemsDir(t)
+ var rendered []string
+ origRun := runExternal
+ origOut := runExternalOutput
+ runExternal = func(ctx context.Context, name string, args ...string) error {
+ rendered = append(rendered, name)
+ rendered = append(rendered, args...)
+ return fmt.Errorf("stub")
+ }
+ runExternalOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return []byte("Page 1 size: 612 x 792 pts\n"), nil
+ }
+ t.Cleanup(func() {
+ runExternal = origRun
+ runExternalOutput = origOut
+ })
+
+ // Only page 1 is measured, so a later oversized page does not block it.
+ pdf := append(pdfWithMediaBox(612, 792), "4 0 obj<</Type/Page/MediaBox[0 0 14400 14400]>>endobj\n"...)
+ got := generatePDFThumbnail(pdf, "letter")
+ require.Nil(t, got)
+ require.Contains(t, rendered, "pdftoppm")
+ require.Contains(t, rendered, "-cropbox")
+ require.Contains(t, rendered, "-scale-to-x")
+ require.Contains(t, rendered, "-scale-to-y")
+ require.Contains(t, rendered, "1275")
+ require.Contains(t, rendered, "1650")
+ require.NotContains(t, rendered, "-r")
+}
+
+func TestGeneratePDFThumbnailDoesNotRasterizeWhenPDFInfoFails(t *testing.T) {
+ withSendItemsDir(t)
+ var rendered []string
+ origRun := runExternal
+ origOut := runExternalOutput
+ runExternal = func(ctx context.Context, name string, args ...string) error {
+ rendered = append(rendered, name)
+ return nil
+ }
+ runExternalOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return nil, fmt.Errorf("pdfinfo failed")
+ }
+ t.Cleanup(func() {
+ runExternal = origRun
+ runExternalOutput = origOut
+ })
+
+ // A decoy small MediaBox must not authorize pdftoppm when pdfinfo errors.
+ got := generatePDFThumbnail(pdfWithMediaBox(612, 792), "decoy")
+ require.Nil(t, got)
+ require.NotContains(t, rendered, "pdftoppm")
+ require.NotContains(t, rendered, "convert")
+}
+
+func TestOpenVideoThumbnailRejectsExtremeFrameBeforeDecode(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "frame.png")
+ require.NoError(t, os.WriteFile(path, pngWithIHDR(2, 65535), 0600))
+ img, err := openVideoThumbnail(path)
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+}
+
+func TestOpenStickerImageRejectsHugeHeaderBeforeDecode(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sticker.png")
+ require.NoError(t, os.WriteFile(path, pngWithIHDR(30000, 30000), 0600))
+ img, err := openStickerImage(path)
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+}
+
+type infiniteByteReader struct{ b byte }
+
+func (r infiniteByteReader) Read(p []byte) (int, error) {
+ for i := range p {
+ p[i] = r.b
+ }
+ return len(p), nil
+}
+
+func TestReadWaveformPCMCapsDecodedBytes(t *testing.T) {
+ const max = 4096
+ samples, err := readWaveformPCM(infiniteByteReader{b: 80}, max)
+ require.NoError(t, err)
+ require.Len(t, samples, max)
+ require.Equal(t, waveformSampleRate*waveformMaxSeconds, waveformMaxPCMBytes)
+
+ waveform := downsampleToWaveform(samples, 64)
+ require.Len(t, waveform, 64)
+ for _, value := range waveform {
+ require.LessOrEqual(t, value, byte(100))
+ }
+}
+
+func TestWaveformFFmpegArgsSpanWholeNote(t *testing.T) {
+ flagValue := func(args []string, flag string) string {
+ for i := 0; i+1 < len(args); i++ {
+ if args[i] == flag {
+ return args[i+1]
+ }
+ }
+ return ""
+ }
+
+ // Short or unknown durations keep the 8 kHz prefix capped by -t.
+ for _, seconds := range []uint32{0, 30, waveformMaxSeconds} {
+ args := waveformFFmpegArgs("note.ogg", seconds)
+ require.Equal(t, "8000", flagValue(args, "-ar"))
+ require.Equal(t, "120", flagValue(args, "-t"))
+ require.Equal(t, "pipe:1", args[len(args)-1])
+ }
+
+ // Longer notes are decoded whole at a rate that fits waveformMaxPCMBytes.
+ args := waveformFFmpegArgs("note.ogg", 300)
+ require.NotContains(t, args, "-t")
+ require.Equal(t, "3200", flagValue(args, "-ar"))
+ require.Equal(t, "64", flagValue(waveformFFmpegArgs("note.ogg", 100000), "-ar"))
+}
diff --git a/src/usecase/send_test.go b/src/usecase/send_test.go
index 5b2d2a25..6a66c3a5 100644
--- a/src/usecase/send_test.go
+++ b/src/usecase/send_test.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "strings"
"testing"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
@@ -118,6 +119,36 @@ func TestPrepareImageForSendSelectsRequestedQuality(t *testing.T) {
}
}
+func TestPrepareImageForSendCompressCapsNarrowSource(t *testing.T) {
+ narrow := image.NewRGBA(image.Rect(0, 0, 1, 8192))
+ got, processed := prepareImageForSend(narrow, true, false)
+ require.True(t, processed)
+ require.LessOrEqual(t, got.Bounds().Dx(), compressedImageMaxEdge)
+ require.LessOrEqual(t, got.Bounds().Dy(), hdImageMaxEdge)
+ require.LessOrEqual(t, got.Bounds().Dx()*got.Bounds().Dy(), compressedImageMaxEdge*hdImageMaxEdge)
+
+ photo := image.NewRGBA(image.Rect(0, 0, 3000, 1500))
+ got, processed = prepareImageForSend(photo, true, false)
+ require.True(t, processed)
+ assert.Equal(t, 600, got.Bounds().Dx())
+ assert.Equal(t, 300, got.Bounds().Dy())
+
+ // A portrait screenshot keeps the 600 px width, as the fixed-width resize did.
+ portrait := image.NewRGBA(image.Rect(0, 0, 1080, 2340))
+ got, processed = prepareImageForSend(portrait, true, false)
+ require.True(t, processed)
+ assert.Equal(t, 600, got.Bounds().Dx())
+ assert.Equal(t, 1300, got.Bounds().Dy())
+}
+
+func TestVideoThumbnailFFmpegArgsFitInsideBox(t *testing.T) {
+ args := videoThumbnailFFmpegArgs("clip.mp4", "frame.png")
+ assert.Contains(t, args, "scale=100:512:force_original_aspect_ratio=decrease")
+ assert.NotContains(t, args, "scale=100:-1")
+ joined := strings.Join(args, " ")
+ assert.NotContains(t, joined, "100:0")
+}
+
func TestBuildHDVideoFFmpegArgsUses1280BoundingBoxWithoutUpscaling(t *testing.T) {
want := []string{
"-i", "input.mp4",
diff --git a/src/usecase/user.go b/src/usecase/user.go
index fd81048a..6dc48e71 100644
--- a/src/usecase/user.go
+++ b/src/usecase/user.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"image"
+ "io"
"sync"
"time"
@@ -327,8 +328,8 @@ func (service serviceUser) ChangeAvatar(ctx context.Context, request domainUser.
}
defer file.Close()
- // Read original image
- srcImage, err := imaging.Decode(file)
+ // Read original image. Dimensions are checked before the raster is allocated.
+ srcImage, err := decodeAvatarImage(file)
if err != nil {
return fmt.Errorf("failed to decode image: %v", err)
}
@@ -372,6 +373,13 @@ func (service serviceUser) ChangeAvatar(ctx context.Context, request domainUser.
return nil
}
+// decodeAvatarImage decodes an uploaded avatar only after its header dimensions
+// pass the shared pixel budget.
+func decodeAvatarImage(r io.Reader) (image.Image, error) {
+ img, _, err := utils.DecodeImageWithinBudget(r)
+ return img, err
+}
+
func (service serviceUser) ChangePushName(ctx context.Context, request domainUser.ChangePushNameRequest) (err error) {
client := whatsapp.ClientFromContext(ctx)
if client == nil {
diff --git a/src/usecase/user_test.go b/src/usecase/user_test.go
index ccbf197b..114b38c7 100644
--- a/src/usecase/user_test.go
+++ b/src/usecase/user_test.go
@@ -1,11 +1,31 @@
package usecase
import (
+ "bytes"
+ "image"
+ "image/png"
"testing"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/stretchr/testify/require"
"go.mau.fi/whatsmeow/types"
)
+func TestDecodeAvatarImageRejectsOversizedHeaderBeforeDecode(t *testing.T) {
+ img, err := decodeAvatarImage(bytes.NewReader(pngWithIHDR(20000, 20000)))
+ require.ErrorIs(t, err, utils.ErrImageTooLarge)
+ require.Nil(t, img)
+}
+
+func TestDecodeAvatarImageAcceptsSmallPNG(t *testing.T) {
+ var encoded bytes.Buffer
+ require.NoError(t, png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 8, 8))))
+ img, err := decodeAvatarImage(bytes.NewReader(encoded.Bytes()))
+ require.NoError(t, err)
+ require.Equal(t, 8, img.Bounds().Dx())
+ require.Equal(t, 8, img.Bounds().Dy())
+}
+
func TestContactDisplayName(t *testing.T) {
tests := []struct {
name string