fix(im): cap IM callback bodies before any adapter reads them (#4369)

Every IM platform calls a public, unauthenticated endpoint - the callback URL
cannot carry a bearer token - and each platform's signature is computed over the
request body, so the bytes have to be read before the request can be
authenticated at all. Each adapter read c.Request.Body with an unbounded
io.ReadAll, so a single unauthenticated POST decided how much memory the
process would allocate.

Add LimitWebhookBody to the shared internal/im package, mirroring how
internal/handler caps uploads and JSON bodies on the authenticated routes, and
call it ahead of all fifteen reads across the eight adapters. Nine of those
reads sit in VerifyCallback or HandleURLVerification, ahead of the credential
check; the rest parse the payload afterwards.

The cap is 4 MiB, far above any real callback: chat messages, interactive cards
and block payloads are kilobytes, and attachments travel as URLs the server
fetches separately under maxIMAttachmentBytes.
main
ordinary being 2026-10-16 17:16:15 +08:00 committed by GitHub
parent 973d9d051f
commit 03059997fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 275 additions and 0 deletions

View File

@ -120,6 +120,7 @@ type atUser struct {
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -197,6 +197,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("webhook verification secret is required")
}
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read body: %w", err)
@ -236,6 +237,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
// HandleURLVerification handles the Feishu URL verification challenge.
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return false
@ -311,6 +313,7 @@ type feishuSenderID struct {
// ParseCallback parses a Feishu event callback into a unified IncomingMessage.
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -68,6 +68,7 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
}
func (a *Adapter) VerifyCallback(c *gin.Context) error {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read body: %w", err)
@ -87,6 +88,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -0,0 +1,92 @@
package mattermost
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// countingBody reports how many bytes a handler actually pulled off the wire,
// so a test can tell "rejected the oversized callback" apart from "buffered all
// of it and then failed for some other reason".
type countingBody struct {
src io.Reader
n int64
}
func (b *countingBody) Read(p []byte) (int, error) {
n, err := b.src.Read(p)
b.n += int64(n)
return n, err
}
func (b *countingBody) Close() error { return nil }
// repeatReader yields size bytes of filler without allocating size bytes.
type repeatReader struct {
remaining int64
}
// The IM callback endpoint is public and the Mattermost outgoing-webhook token
// is compared against the body, so the body has to be read before the request is
// authenticated. Without a cap, one unauthenticated POST decides how much memory
// the process allocates.
func TestVerifyCallbackRejectsOversizedBody(t *testing.T) {
const payloadSize = 64 << 20
body := &countingBody{src: &repeatReader{remaining: payloadSize}}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/im/callback/1", nil)
c.Request.Body = body
c.Request.Header.Set("Content-Type", "application/json")
a := NewAdapter(nil, "expected-token", "bot-user-id", false)
err := a.VerifyCallback(c)
if err == nil {
t.Fatal("expected an oversized callback to be rejected")
}
var tooLarge *http.MaxBytesError
if !errors.As(err, &tooLarge) {
t.Fatalf("err = %v, want an *http.MaxBytesError: the body was not capped", err)
}
if body.n >= payloadSize {
t.Errorf("handler read %d bytes of a %d byte body; the cap never fired",
body.n, payloadSize)
}
}
// A callback well inside the cap still verifies, so the bound rejects only what
// it is meant to.
func TestVerifyCallbackAcceptsNormalBody(t *testing.T) {
payload := `{"token":"expected-token","channel_id":"c1","user_id":"u1","text":"hi"}`
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/im/callback/1",
strings.NewReader(payload))
c.Request.Header.Set("Content-Type", "application/json")
a := NewAdapter(nil, "expected-token", "bot-user-id", false)
if err := a.VerifyCallback(c); err != nil {
t.Fatalf("VerifyCallback() = %v, want nil for a %d byte body", err, len(payload))
}
}
func (r *repeatReader) Read(p []byte) (int, error) {
if r.remaining <= 0 {
return 0, io.EOF
}
if int64(len(p)) > r.remaining {
p = p[:r.remaining]
}
for i := range p {
p[i] = 'a'
}
r.remaining -= int64(len(p))
return len(p), nil
}

View File

@ -36,6 +36,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -103,6 +103,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("webhook verification secret is required")
}
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read body: %w", err)
@ -124,6 +125,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
@ -172,6 +174,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
}
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return false

View File

@ -114,6 +114,7 @@ type telegramPhoto struct {
}
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -0,0 +1,36 @@
package im
import (
"net/http"
"github.com/gin-gonic/gin"
)
// maxWebhookBodyBytes caps an inbound IM callback body.
//
// The callback endpoints are public: a platform cannot present a bearer token,
// so every request reaches the adapters before any credential is checked. Each
// platform's signature is computed over the body itself, which means the bytes
// have to be read before the request can be authenticated at all. An unbounded
// read therefore lets one unauthenticated POST ask the process to buffer as much
// memory as it is willing to surrender.
//
// 4 MiB sits far above any real callback - chat messages, interactive cards and
// block payloads are kilobytes, and attachments travel as URLs the server
// fetches separately under maxIMAttachmentBytes - while still bounding what a
// single request can allocate.
const maxWebhookBodyBytes = 4 << 20
// LimitWebhookBody caps the callback body before an adapter reads it, matching
// how internal/handler caps uploads and JSON bodies on the authenticated
// routes.
//
// Call it ahead of any read of c.Request.Body. Calling it more than once per
// request is harmless: adapters that buffer the bytes replace c.Request.Body
// with an in-memory copy, so a later cap simply wraps that copy.
func LimitWebhookBody(c *gin.Context) {
if c.Request == nil || c.Request.Body == nil {
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxWebhookBodyBytes)
}

View File

@ -0,0 +1,132 @@
package im
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// The cap is the only thing standing between a public callback endpoint and an
// arbitrarily large allocation, so pin that it bounds the read rather than
// relying on the caller's body size.
func TestLimitWebhookBodyBoundsTheRead(t *testing.T) {
const payloadSize = 32 << 20
src := &repeatReader{remaining: payloadSize}
body := &countingBody{src: src}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/im/callback/1", nil)
c.Request.Body = body
LimitWebhookBody(c)
if _, err := io.ReadAll(c.Request.Body); err == nil {
t.Fatal("expected the cap to fire on an oversized callback body")
} else {
var tooLarge *http.MaxBytesError
if !errors.As(err, &tooLarge) {
t.Fatalf("err = %v, want an *http.MaxBytesError", err)
}
}
if body.n >= payloadSize {
t.Errorf("read %d bytes of a %d byte body; the cap never fired", body.n, payloadSize)
}
if body.n > maxWebhookBodyBytes+1 {
t.Errorf("read %d bytes, want at most the %d byte cap plus the probe read",
body.n, maxWebhookBodyBytes)
}
}
// A body inside the cap reads through untouched.
func TestLimitWebhookBodyAllowsNormalBody(t *testing.T) {
payload := []byte(`{"event":"message","text":"hello"}`)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/im/callback/1",
bytes.NewReader(payload))
LimitWebhookBody(c)
got, err := io.ReadAll(c.Request.Body)
if err != nil {
t.Fatalf("ReadAll() = %v, want nil for a %d byte body", err, len(payload))
}
if string(got) != string(payload) {
t.Errorf("body = %q, want %q", got, payload)
}
}
// Limiting twice must not corrupt the body: adapters that buffer the bytes
// replace c.Request.Body with an in-memory copy, and the next cap wraps that.
func TestLimitWebhookBodyIsIdempotentAcrossReads(t *testing.T) {
payload := []byte(`{"event":"message","text":"hello"}`)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/im/callback/1",
bytes.NewReader(payload))
LimitWebhookBody(c)
first, err := io.ReadAll(c.Request.Body)
if err != nil {
t.Fatalf("first ReadAll() = %v", err)
}
c.Request.Body = io.NopCloser(bytes.NewReader(first))
LimitWebhookBody(c)
second, err := io.ReadAll(c.Request.Body)
if err != nil {
t.Fatalf("second ReadAll() = %v", err)
}
if string(second) != string(payload) {
t.Errorf("body after re-cap = %q, want %q", second, payload)
}
}
// A request with no body must not panic.
func TestLimitWebhookBodyHandlesNilBody(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/im/callback/1", nil)
c.Request.Body = nil
LimitWebhookBody(c)
if c.Request.Body != nil {
t.Error("LimitWebhookBody replaced a nil body")
}
}
type countingBody struct {
src io.Reader
n int64
}
func (b *countingBody) Read(p []byte) (int, error) {
n, err := b.src.Read(p)
b.n += int64(n)
return n, err
}
func (b *countingBody) Close() error { return nil }
type repeatReader struct {
remaining int64
}
func (r *repeatReader) Read(p []byte) (int, error) {
if r.remaining <= 0 {
return 0, io.EOF
}
if int64(len(p)) > r.remaining {
p = p[:r.remaining]
}
for i := range p {
p[i] = 'a'
}
r.remaining -= int64(len(p))
return len(p), nil
}

View File

@ -161,6 +161,7 @@ func (a *WebhookAdapter) VerifyCallback(c *gin.Context) error {
encrypt = c.Query("echostr")
} else {
var body callbackRequestBody
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read request body: %w", err)
@ -204,6 +205,7 @@ func (a *WebhookAdapter) HandleURLVerification(c *gin.Context) bool {
// ParseCallback parses a WeCom callback into a unified IncomingMessage.
func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)

View File

@ -114,6 +114,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("webhook verification secret is required")
}
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return fmt.Errorf("read body: %w", err)
@ -148,6 +149,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
// ParseCallback parses a Yunzhijia webhook callback into an IncomingMessage.
// Returns nil for non-text messages or empty content.
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
im.LimitWebhookBody(c)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)