From 03059997fe1972f3280c3bcd29e7ecc4afcca432 Mon Sep 17 00:00:00 2001 From: ordinary being Date: Fri, 16 Oct 2026 17:16:15 +0800 Subject: [PATCH] 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. --- internal/im/dingtalk/adapter.go | 1 + internal/im/feishu/adapter.go | 3 + internal/im/mattermost/adapter.go | 2 + .../im/mattermost/webhook_body_limit_test.go | 92 ++++++++++++ internal/im/qqbot/adapter.go | 1 + internal/im/slack/adapter.go | 3 + internal/im/telegram/adapter.go | 1 + internal/im/webhook_body.go | 36 +++++ internal/im/webhook_body_test.go | 132 ++++++++++++++++++ internal/im/wecom/webhook_adapter.go | 2 + internal/im/yunzhijia/adapter.go | 2 + 11 files changed, 275 insertions(+) create mode 100644 internal/im/mattermost/webhook_body_limit_test.go create mode 100644 internal/im/webhook_body.go create mode 100644 internal/im/webhook_body_test.go diff --git a/internal/im/dingtalk/adapter.go b/internal/im/dingtalk/adapter.go index af31192d..c881fd5a 100644 --- a/internal/im/dingtalk/adapter.go +++ b/internal/im/dingtalk/adapter.go @@ -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) diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go index 32b3b461..e6af8e40 100644 --- a/internal/im/feishu/adapter.go +++ b/internal/im/feishu/adapter.go @@ -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) diff --git a/internal/im/mattermost/adapter.go b/internal/im/mattermost/adapter.go index bec87fb4..562d84cb 100644 --- a/internal/im/mattermost/adapter.go +++ b/internal/im/mattermost/adapter.go @@ -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) diff --git a/internal/im/mattermost/webhook_body_limit_test.go b/internal/im/mattermost/webhook_body_limit_test.go new file mode 100644 index 00000000..df397d33 --- /dev/null +++ b/internal/im/mattermost/webhook_body_limit_test.go @@ -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 +} diff --git a/internal/im/qqbot/adapter.go b/internal/im/qqbot/adapter.go index 65c649e8..686fc573 100644 --- a/internal/im/qqbot/adapter.go +++ b/internal/im/qqbot/adapter.go @@ -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) diff --git a/internal/im/slack/adapter.go b/internal/im/slack/adapter.go index 20eff432..7800b21b 100644 --- a/internal/im/slack/adapter.go +++ b/internal/im/slack/adapter.go @@ -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 diff --git a/internal/im/telegram/adapter.go b/internal/im/telegram/adapter.go index 690e2bd2..9bda8b2c 100644 --- a/internal/im/telegram/adapter.go +++ b/internal/im/telegram/adapter.go @@ -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) diff --git a/internal/im/webhook_body.go b/internal/im/webhook_body.go new file mode 100644 index 00000000..53579e4a --- /dev/null +++ b/internal/im/webhook_body.go @@ -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) +} diff --git a/internal/im/webhook_body_test.go b/internal/im/webhook_body_test.go new file mode 100644 index 00000000..791aac23 --- /dev/null +++ b/internal/im/webhook_body_test.go @@ -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 +} diff --git a/internal/im/wecom/webhook_adapter.go b/internal/im/wecom/webhook_adapter.go index 634559f7..59fea79e 100644 --- a/internal/im/wecom/webhook_adapter.go +++ b/internal/im/wecom/webhook_adapter.go @@ -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) diff --git a/internal/im/yunzhijia/adapter.go b/internal/im/yunzhijia/adapter.go index cb086546..84545a31 100644 --- a/internal/im/yunzhijia/adapter.go +++ b/internal/im/yunzhijia/adapter.go @@ -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)