From 882a3e1b87dc1ae959007450368c80c696f7656f Mon Sep 17 00:00:00 2001 From: Tejas1Koli Date: Thu, 12 Mar 2026 13:51:20 +0530 Subject: [PATCH] Fix unbounded memory usage in matrix media download (#1405) --- pkg/channels/matrix/matrix.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/pkg/channels/matrix/matrix.go b/pkg/channels/matrix/matrix.go index a45207f12..f602cff09 100644 --- a/pkg/channels/matrix/matrix.go +++ b/pkg/channels/matrix/matrix.go @@ -12,6 +12,7 @@ import ( "strings" "sync" "time" + "io" "github.com/gomarkdown/markdown" mdhtml "github.com/gomarkdown/markdown/html" @@ -726,10 +727,21 @@ func (c *MatrixChannel) downloadMedia( reqCtx, cancel := context.WithTimeout(dlCtx, 20*time.Second) defer cancel() - data, err := c.client.DownloadBytes(reqCtx, parsed) + const maxMediaSize = 100 * 1024 * 1024 // 100MB cap + resp, err := c.client.Download(reqCtx, parsed) if err != nil { return "", err } + + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, int64(maxMediaSize)+1)) + if err != nil { + return "", fmt.Errorf("read matrix media: %w", err) + } + + if len(data) > maxMediaSize { + return "", fmt.Errorf("media exceeds size limit of %d bytes", maxMediaSize) + } // Encrypted attachments put URL in msgEvt.File and require client-side decryption. if msgEvt != nil && msgEvt.File != nil && msgEvt.URL == "" {