Fix unbounded memory usage in matrix media download (#1405)
This commit is contained in:
parent
b4d00c631d
commit
882a3e1b87
1 changed files with 13 additions and 1 deletions
|
|
@ -12,6 +12,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
"io"
|
||||||
|
|
||||||
"github.com/gomarkdown/markdown"
|
"github.com/gomarkdown/markdown"
|
||||||
mdhtml "github.com/gomarkdown/markdown/html"
|
mdhtml "github.com/gomarkdown/markdown/html"
|
||||||
|
|
@ -726,11 +727,22 @@ func (c *MatrixChannel) downloadMedia(
|
||||||
reqCtx, cancel := context.WithTimeout(dlCtx, 20*time.Second)
|
reqCtx, cancel := context.WithTimeout(dlCtx, 20*time.Second)
|
||||||
defer cancel()
|
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 {
|
if err != nil {
|
||||||
return "", err
|
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.
|
// Encrypted attachments put URL in msgEvt.File and require client-side decryption.
|
||||||
if msgEvt != nil && msgEvt.File != nil && msgEvt.URL == "" {
|
if msgEvt != nil && msgEvt.File != nil && msgEvt.URL == "" {
|
||||||
err = msgEvt.File.DecryptInPlace(data)
|
err = msgEvt.File.DecryptInPlace(data)
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue